diff --git a/Code/Mantid/Build/CMake/CommonSetup.cmake b/Code/Mantid/Build/CMake/CommonSetup.cmake index e185358b4f15..10625001e3b6 100644 --- a/Code/Mantid/Build/CMake/CommonSetup.cmake +++ b/Code/Mantid/Build/CMake/CommonSetup.cmake @@ -305,29 +305,7 @@ endif() # External Data for testing ########################################################################### if ( CXXTEST_FOUND OR PYUNITTEST_FOUND ) - include ( MantidExternalData ) - -# None of our tests reference files directly as arguments so we have to manually -# call ExternalData_Expand_Arguments to register the files with the ExternalData -# mechanism -get_filename_component ( EXTERNALDATATEST_SOURCE_DIR ${PROJECT_SOURCE_DIR} ABSOLUTE ) -file( GLOB_RECURSE doctest_content_links - RELATIVE "${EXTERNALDATATEST_SOURCE_DIR}" "Testing/Data/DocTest/*.md5" ) -file( GLOB_RECURSE unittest_content_links - RELATIVE "${EXTERNALDATATEST_SOURCE_DIR}" "Testing/Data/UnitTest/*.md5" ) -set ( content_links "${doctest_content_links};${unittest_content_links}" ) -foreach(link ${content_links}) - string( REGEX REPLACE "\\.md5$" "" link ${link} ) - ExternalData_Expand_Arguments( StandardTestData - link_location - DATA{${link}} - ) -endforeach() - -# Create target to download data from the StandardTestData group. This must come after -# all tests have been added that reference the group, so we put it last. -ExternalData_Add_Target(StandardTestData) -set_target_properties(StandardTestData PROPERTIES EXCLUDE_FROM_ALL TRUE) + include( SetupDataTargets ) endif() ########################################################################### diff --git a/Code/Mantid/Build/CMake/CppCheck_Suppressions.txt b/Code/Mantid/Build/CMake/CppCheck_Suppressions.txt index 16965a971a8b..c808e945f406 100644 --- a/Code/Mantid/Build/CMake/CppCheck_Suppressions.txt +++ b/Code/Mantid/Build/CMake/CppCheck_Suppressions.txt @@ -4,6 +4,6 @@ // suppress in all files - BE CAREFULL not to leave trailing spaces after the rule id. or empty lines // For a library this is not a problem per se -unusedFunction +// unusedFunction // cppcheck has problems handling the number of pre-processor definitions used in the DLL_EXPORTs -class_X_Y \ No newline at end of file +class_X_Y diff --git a/Code/Mantid/Build/CMake/EmbeddedGTest.cmake b/Code/Mantid/Build/CMake/EmbeddedGTest.cmake index 25e55227cd58..545837105cc1 100644 --- a/Code/Mantid/Build/CMake/EmbeddedGTest.cmake +++ b/Code/Mantid/Build/CMake/EmbeddedGTest.cmake @@ -3,8 +3,8 @@ # GTEST_FOUND If false, do not try to use Google Test find_path ( GTEST_INCLUDE_DIR gtest/gtest.h - PATHS ${PROJECT_SOURCE_DIR}/TestingTools/gmock-${GMOCK_VERSION}/gtest/include - ${PROJECT_SOURCE_DIR}/../TestingTools/gmock-${GMOCK_VERSION}/gtest/include + PATHS ${PROJECT_SOURCE_DIR}/Testing/Tools/gmock-${GMOCK_VERSION}/gtest/include + ${PROJECT_SOURCE_DIR}/../Testing/Tools/gmock-${GMOCK_VERSION}/gtest/include NO_DEFAULT_PATH ) # handle the QUIETLY and REQUIRED arguments and set GTEST_FOUND to TRUE if diff --git a/Code/Mantid/Build/CMake/FindCxxTest.cmake b/Code/Mantid/Build/CMake/FindCxxTest.cmake index cc9a5cb40c3b..8aaeadbb37fd 100644 --- a/Code/Mantid/Build/CMake/FindCxxTest.cmake +++ b/Code/Mantid/Build/CMake/FindCxxTest.cmake @@ -194,8 +194,8 @@ endmacro(CXXTEST_ADD_TEST) #============================================================= find_path(CXXTEST_INCLUDE_DIR cxxtest/TestSuite.h - PATHS ${PROJECT_SOURCE_DIR}/TestingTools/cxxtest - ${PROJECT_SOURCE_DIR}/../TestingTools/cxxtest ) + PATHS ${PROJECT_SOURCE_DIR}/Testing/Tools/cxxtest + ${PROJECT_SOURCE_DIR}/../Testing/Tools/cxxtest ) find_program(CXXTEST_TESTGEN_EXECUTABLE python/scripts/cxxtestgen PATHS ${CXXTEST_INCLUDE_DIR}) diff --git a/Code/Mantid/Build/CMake/FindGMock.cmake b/Code/Mantid/Build/CMake/FindGMock.cmake index e540e5a18af2..a611ce2fb73d 100644 --- a/Code/Mantid/Build/CMake/FindGMock.cmake +++ b/Code/Mantid/Build/CMake/FindGMock.cmake @@ -17,8 +17,8 @@ ENDIF() set (GMOCK_VERSION ${GMOCK_VERSION} CACHE INTERNAL "") find_path ( GMOCK_INCLUDE_DIR gmock/gmock.h - PATHS ${PROJECT_SOURCE_DIR}/TestingTools/gmock-${GMOCK_VERSION}/include - ${PROJECT_SOURCE_DIR}/../TestingTools/gmock-${GMOCK_VERSION}/include + PATHS ${PROJECT_SOURCE_DIR}/Testing/Tools/gmock-${GMOCK_VERSION}/include + ${PROJECT_SOURCE_DIR}/../Testing/Tools/gmock-${GMOCK_VERSION}/include NO_DEFAULT_PATH ) SET(GMOCK_LIB gmock) diff --git a/Code/Mantid/Build/CMake/FindMatlab.cmake b/Code/Mantid/Build/CMake/FindMatlab.cmake deleted file mode 100644 index 685006f10be6..000000000000 --- a/Code/Mantid/Build/CMake/FindMatlab.cmake +++ /dev/null @@ -1,57 +0,0 @@ -# Based upon FindMatlab.cmake from the CMake 2.8.3 distribution -# The script included with the distribution fails to find Matlab as it contains references -# to paths that no longer exist within Matlab - -# NOTE: Unsupported on Linux/Mac as I can't get a working version there to test it. Plus it was never built there before ... - -# Defines: -# MATLAB_INCLUDE_DIR: include path for mex.h, engine.h -# MATLAB_LIBRARIES: required libraries: libmex, etc -# MATLAB_MEX_LIBRARY: path to libmex.lib -# MATLAB_MX_LIBRARY: path to libmx.lib -# MATLAB_ENG_LIBRARY: path to libeng.lib - -if ( MATLAB_INCLUDE_DIR AND MATLAB_LIBRARIES ) - # Already in cache, be silent - set ( MATLAB_FOUND TRUE ) -endif () - -set ( MATLAB_FOUND FALSE ) -if ( WIN32 ) - # There seems to be know better way of querying the keys in the registry so we'll have to assume that all of the versions are 7.XX and search for these - set ( MATLAB_MAJOR_VERSION "7" ) - set ( REGISTRY_ROOT "HKEY_LOCAL_MACHINE\\SOFTWARE\\MathWorks\\MATLAB" ) - set ( REGISTRY_KEY "MATLABROOT" ) - set ( EXTERN_INCLUDE "/extern/include") - set ( EXTERN_SRC "/extern/src") - if( CMAKE_CL_64 ) - set( EXTERN_LIB "/extern/lib/win64/microsoft/" ) - else () - set( EXTERN_LIB "/extern/lib/win32/microsoft/" ) - endif () - # We'll assume we want to link to the oldest version so that it is most likely to be forward compatible. - # 2010 = 7.11 so stop at 15? - foreach ( MATLAB_MINOR_VERSION RANGE 1 15 ) - find_library ( MATLAB_MEX_LIBRARY libmex "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_LIB}" ) - find_library ( MATLAB_MX_LIBRARY libmx "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_LIB}" ) - find_library ( MATLAB_ENG_LIBRARY libeng "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_LIB}" ) - find_library ( MATLAB_MAT_LIBRARY libmat "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_LIB}" ) - set ( MATLAB_LIBRARIES ${MATLAB_MEX_LIBRARY} ${MATLAB_MX_LIBRARY} ${MATLAB_ENG_LIBRARY} ${MATLAB_MAT_LIBRARY} ) - find_path( MATLAB_INCLUDE_DIR "mex.h" "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_INCLUDE}" ) - find_path( MATLAB_EXTERN_SRC "mwdebug.c" "[${REGISTRY_ROOT}\\${MATLAB_MAJOR_VERSION}.${MATLAB_MINOR_VERSION};${REGISTRY_KEY}]${EXTERN_SRC}" ) - if ( MATLAB_INCLUDE_DIR AND MATLAB_LIBRARIES AND MATLAB_EXTERN_SRC ) - if ( NOT MATLAB_FIND_QUIETLY ) - message ( STATUS "Found Matlab: ${MATLAB_INCLUDE_DIR}" ) - endif () - set ( MATLAB_FOUND 1 ) - break () - endif () - endforeach ( MATLAB_MINOR_VERSION ) - - # Clean up temporary variables - set ( MATLAB_MAJOR_VERSION ) - set ( REGISTRY_ROOT ) - set ( REGISTRY_KEY ) - set ( EXTERN_INCLUDE ) - -endif () diff --git a/Code/Mantid/Build/CMake/FindOpenCascade.cmake b/Code/Mantid/Build/CMake/FindOpenCascade.cmake index aefa011416e1..ed88d20d029c 100644 --- a/Code/Mantid/Build/CMake/FindOpenCascade.cmake +++ b/Code/Mantid/Build/CMake/FindOpenCascade.cmake @@ -60,7 +60,7 @@ find_library ( OPENCASCADE_LIB_TKGEOMBASE NAMES TKGeomBase ) -find_library ( OPENCASCADE_LIB_TKGEOMAlgo +find_library ( OPENCASCADE_LIB_TKGEOMALGO NAMES TKGeomAlgo ) diff --git a/Code/Mantid/Build/CMake/FindPoco.cmake b/Code/Mantid/Build/CMake/FindPoco.cmake index 63c811ccf494..978e770fa8c8 100644 --- a/Code/Mantid/Build/CMake/FindPoco.cmake +++ b/Code/Mantid/Build/CMake/FindPoco.cmake @@ -61,14 +61,14 @@ if( POCO_INCLUDE_DIR ) file ( STRINGS ${VERSION_FILE} POCO_VERSION REGEX ${VERS_REGEX} ) # pull out just the part after the 0x string( REGEX REPLACE ${VERS_REGEX} "\\1" POCO_VERSION ${POCO_VERSION} ) + # Pretty format string( SUBSTRING ${POCO_VERSION} 0 2 POCO_VERSION_MAJOR ) - string( REGEX REPLACE "^0" "" POCO_VERSION_MAJOR ${POCO_VERSION_MAJOR} ) + string( REGEX REPLACE "^0\(.\)" "\\1" POCO_VERSION_MAJOR ${POCO_VERSION_MAJOR} ) string( SUBSTRING ${POCO_VERSION} 2 2 POCO_VERSION_MINOR ) - string( REGEX REPLACE "^0" "" POCO_VERSION_MINOR ${POCO_VERSION_MINOR} ) + string( REGEX REPLACE "^0\(.\)" "\\1" POCO_VERSION_MINOR ${POCO_VERSION_MINOR} ) string( SUBSTRING ${POCO_VERSION} 4 2 POCO_VERSION_PATCH ) - string( REGEX REPLACE "^0" "" POCO_VERSION_PATCH ${POCO_VERSION_PATCH} ) - + string( REGEX REPLACE "^0\(.\)" "\\1" POCO_VERSION_PATCH ${POCO_VERSION_PATCH} ) set ( POCO_VERSION "${POCO_VERSION_MAJOR}.${POCO_VERSION_MINOR}.${POCO_VERSION_PATCH}" ) endif() diff --git a/Code/Mantid/Build/CMake/FindPyUnitTest.cmake b/Code/Mantid/Build/CMake/FindPyUnitTest.cmake index 893cb5b392a5..bd6c3661633b 100644 --- a/Code/Mantid/Build/CMake/FindPyUnitTest.cmake +++ b/Code/Mantid/Build/CMake/FindPyUnitTest.cmake @@ -59,13 +59,13 @@ endmacro ( PYUNITTEST_ADD_TEST ) # find the driver script find_program ( PYUNITTEST_GEN_EXEC pyunit_gen.py - PATHS ${PROJECT_SOURCE_DIR}/TestingTools/pyunit_gen - ${PROJECT_SOURCE_DIR}/../TestingTools/pyunit_gen ) + PATHS ${PROJECT_SOURCE_DIR}/Testing/Tools/pyunit_gen + ${PROJECT_SOURCE_DIR}/../Testing/Tools/pyunit_gen ) # determine where the xmlrunner lives find_path ( PYUNITTEST_XMLRUNNER xmlrunner/__init__.py - PATHS ${PROJECT_SOURCE_DIR}/TestingTools/unittest-xml-reporting/src/ - ${PROJECT_SOURCE_DIR}/../TestingTools/unittest-xml-reporting/src/ ) + PATHS ${PROJECT_SOURCE_DIR}/Testing/Tools/unittest-xml-reporting/src/ + ${PROJECT_SOURCE_DIR}/../Testing/Tools/unittest-xml-reporting/src/ ) # let people know whether or not it was found if (PYUNITTEST_GEN_EXEC) diff --git a/Code/Mantid/Build/CMake/FindPythonLibs.cmake b/Code/Mantid/Build/CMake/FindPythonLibs.cmake deleted file mode 100644 index acd7ff4ba5c3..000000000000 --- a/Code/Mantid/Build/CMake/FindPythonLibs.cmake +++ /dev/null @@ -1,218 +0,0 @@ -# Taken from the CMake 2.8.3 distribution -# Contains a fix to find the shared library on Linux, which isn't present -# in default Redhat CMake version (2.6.4) - -# - Find python libraries -# This module finds if Python is installed and determines where the -# include files and libraries are. It also determines what the name of -# the library is. This code sets the following variables: -# -# PYTHONLIBS_FOUND - have the Python libs been found -# PYTHON_LIBRARIES - path to the python library -# PYTHON_INCLUDE_PATH - path to where Python.h is found (deprecated) -# PYTHON_INCLUDE_DIRS - path to where Python.h is found -# PYTHON_DEBUG_LIBRARIES - path to the debug library -# - -#============================================================================= -# CMake - Cross Platform Makefile Generator -# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium -# All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# * Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# -# * Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# -# * Neither the names of Kitware, Inc., the Insight Software Consortium, -# nor the names of their contributors may be used to endorse or promote -# products derived from this software without specific prior written -# permission. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -#============================================================================= - -INCLUDE(CMakeFindFrameworks) -# Search for the python framework on Apple. -CMAKE_FIND_FRAMEWORKS(Python) - -FOREACH(_CURRENT_VERSION 2.7 2.6 2.5 2.4 2.3 2.2 2.1 2.0 1.6 1.5) - STRING(REPLACE "." "" _CURRENT_VERSION_NO_DOTS ${_CURRENT_VERSION}) - IF(WIN32) - FIND_LIBRARY(PYTHON_DEBUG_LIBRARY - NAMES python${_CURRENT_VERSION_NO_DOTS}_d python - PATHS - [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs/Debug - [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs - [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs/Debug - [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs"${CMAKE_LIBRARY_PATH}/Python"${_CURRENT_VERSION_NO_DOTS}) - ENDIF(WIN32) - - FIND_LIBRARY(PYTHON_LIBRARY - NAMES python${_CURRENT_VERSION_NO_DOTS} python${_CURRENT_VERSION} - PATHS - [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs - [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/libs - # Avoid finding the .dll in the PATH. We want the .lib. - NO_SYSTEM_ENVIRONMENT_PATH - ) - # Look for the static library in the Python config directory - FIND_LIBRARY(PYTHON_LIBRARY - NAMES python${_CURRENT_VERSION_NO_DOTS} python${_CURRENT_VERSION} - # Avoid finding the .dll in the PATH. We want the .lib. - NO_SYSTEM_ENVIRONMENT_PATH - # This is where the static library is usually located - PATH_SUFFIXES python${_CURRENT_VERSION}/config - ) - - # For backward compatibility, honour value of PYTHON_INCLUDE_PATH, if - # PYTHON_INCLUDE_DIR is not set. - IF(DEFINED PYTHON_INCLUDE_PATH AND NOT DEFINED PYTHON_INCLUDE_DIR) - SET(PYTHON_INCLUDE_DIR "${PYTHON_INCLUDE_PATH}" CACHE PATH - "Path to where Python.h is found" FORCE) - ENDIF(DEFINED PYTHON_INCLUDE_PATH AND NOT DEFINED PYTHON_INCLUDE_DIR) - - SET(PYTHON_FRAMEWORK_INCLUDES) - IF(Python_FRAMEWORKS AND NOT PYTHON_INCLUDE_DIR) - FOREACH(dir ${Python_FRAMEWORKS}) - SET(PYTHON_FRAMEWORK_INCLUDES ${PYTHON_FRAMEWORK_INCLUDES} - ${dir}/Versions/${_CURRENT_VERSION}/include/python${_CURRENT_VERSION}) - ENDFOREACH(dir) - ENDIF(Python_FRAMEWORKS AND NOT PYTHON_INCLUDE_DIR) - - FIND_PATH(PYTHON_INCLUDE_DIR - NAMES Python.h - PATHS - ${PYTHON_FRAMEWORK_INCLUDES} - [HKEY_LOCAL_MACHINE\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/include - [HKEY_CURRENT_USER\\SOFTWARE\\Python\\PythonCore\\${_CURRENT_VERSION}\\InstallPath]/include - PATH_SUFFIXES - python${_CURRENT_VERSION} - ) - - # For backward compatibility, set PYTHON_INCLUDE_PATH, but make it internal. - SET(PYTHON_INCLUDE_PATH "${PYTHON_INCLUDE_DIR}" CACHE INTERNAL - "Path to where Python.h is found (deprecated)") - -ENDFOREACH(_CURRENT_VERSION) - -MARK_AS_ADVANCED( - PYTHON_DEBUG_LIBRARY - PYTHON_LIBRARY - PYTHON_INCLUDE_DIR -) - -# We use PYTHON_INCLUDE_DIR, PYTHON_LIBRARY and PYTHON_DEBUG_LIBRARY for the -# cache entries because they are meant to specify the location of a single -# library. We now set the variables listed by the documentation for this -# module. -SET(PYTHON_INCLUDE_DIRS "${PYTHON_INCLUDE_DIR}") -SET(PYTHON_LIBRARIES "${PYTHON_LIBRARY}") -SET(PYTHON_DEBUG_LIBRARIES "${PYTHON_DEBUG_LIBRARY}") - - -INCLUDE(FindPackageHandleStandardArgs) -FIND_PACKAGE_HANDLE_STANDARD_ARGS(PythonLibs DEFAULT_MSG PYTHON_LIBRARIES PYTHON_INCLUDE_DIRS) - - -# PYTHON_ADD_MODULE( src1 src2 ... srcN) is used to build modules for python. -# PYTHON_WRITE_MODULES_HEADER() writes a header file you can include -# in your sources to initialize the static python modules -FUNCTION(PYTHON_ADD_MODULE _NAME ) - GET_PROPERTY(_TARGET_SUPPORTS_SHARED_LIBS - GLOBAL PROPERTY TARGET_SUPPORTS_SHARED_LIBS) - OPTION(PYTHON_ENABLE_MODULE_${_NAME} "Add module ${_NAME}" TRUE) - OPTION(PYTHON_MODULE_${_NAME}_BUILD_SHARED - "Add module ${_NAME} shared" ${_TARGET_SUPPORTS_SHARED_LIBS}) - - # Mark these options as advanced - MARK_AS_ADVANCED(PYTHON_ENABLE_MODULE_${_NAME} - PYTHON_MODULE_${_NAME}_BUILD_SHARED) - - IF(PYTHON_ENABLE_MODULE_${_NAME}) - IF(PYTHON_MODULE_${_NAME}_BUILD_SHARED) - SET(PY_MODULE_TYPE MODULE) - ELSE(PYTHON_MODULE_${_NAME}_BUILD_SHARED) - SET(PY_MODULE_TYPE STATIC) - SET_PROPERTY(GLOBAL APPEND PROPERTY PY_STATIC_MODULES_LIST ${_NAME}) - ENDIF(PYTHON_MODULE_${_NAME}_BUILD_SHARED) - - SET_PROPERTY(GLOBAL APPEND PROPERTY PY_MODULES_LIST ${_NAME}) - ADD_LIBRARY(${_NAME} ${PY_MODULE_TYPE} ${ARGN}) -# TARGET_LINK_LIBRARIES(${_NAME} ${PYTHON_LIBRARIES}) - - IF(PYTHON_MODULE_${_NAME}_BUILD_SHARED) - SET_TARGET_PROPERTIES(${_NAME} PROPERTIES PREFIX "${PYTHON_MODULE_PREFIX}") - IF(WIN32 AND NOT CYGWIN) - SET_TARGET_PROPERTIES(${_NAME} PROPERTIES SUFFIX ".pyd") - ENDIF(WIN32 AND NOT CYGWIN) - ENDIF(PYTHON_MODULE_${_NAME}_BUILD_SHARED) - - ENDIF(PYTHON_ENABLE_MODULE_${_NAME}) -ENDFUNCTION(PYTHON_ADD_MODULE) - -FUNCTION(PYTHON_WRITE_MODULES_HEADER _filename) - - GET_PROPERTY(PY_STATIC_MODULES_LIST GLOBAL PROPERTY PY_STATIC_MODULES_LIST) - - GET_FILENAME_COMPONENT(_name "${_filename}" NAME) - STRING(REPLACE "." "_" _name "${_name}") - STRING(TOUPPER ${_name} _nameUpper) - - SET(_filenameTmp "${_filename}.in") - FILE(WRITE ${_filenameTmp} "/*Created by cmake, do not edit, changes will be lost*/\n") - FILE(APPEND ${_filenameTmp} -"#ifndef ${_nameUpper} -#define ${_nameUpper} - -#include - -#ifdef __cplusplus -extern \"C\" { -#endif /* __cplusplus */ - -") - - FOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - FILE(APPEND ${_filenameTmp} "extern void init${PYTHON_MODULE_PREFIX}${_currentModule}(void);\n\n") - ENDFOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - - FILE(APPEND ${_filenameTmp} -"#ifdef __cplusplus -} -#endif /* __cplusplus */ - -") - - - FOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - FILE(APPEND ${_filenameTmp} "int ${_name}_${_currentModule}(void) \n{\n static char name[]=\"${PYTHON_MODULE_PREFIX}${_currentModule}\"; return PyImport_AppendInittab(name, init${PYTHON_MODULE_PREFIX}${_currentModule});\n}\n\n") - ENDFOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - - FILE(APPEND ${_filenameTmp} "void ${_name}_LoadAllPythonModules(void)\n{\n") - FOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - FILE(APPEND ${_filenameTmp} " ${_name}_${_currentModule}();\n") - ENDFOREACH(_currentModule ${PY_STATIC_MODULES_LIST}) - FILE(APPEND ${_filenameTmp} "}\n\n") - FILE(APPEND ${_filenameTmp} "#ifndef EXCLUDE_LOAD_ALL_FUNCTION\nvoid CMakeLoadAllPythonModules(void)\n{\n ${_name}_LoadAllPythonModules();\n}\n#endif\n\n#endif\n") - -# with CONFIGURE_FILE() cmake complains that you may not use a file created using FILE(WRITE) as input file for CONFIGURE_FILE() - EXECUTE_PROCESS(COMMAND ${CMAKE_COMMAND} -E copy_if_different "${_filenameTmp}" "${_filename}" OUTPUT_QUIET ERROR_QUIET) - -ENDFUNCTION(PYTHON_WRITE_MODULES_HEADER) diff --git a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake index b3c39effafcc..760ecee5a349 100644 --- a/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake +++ b/Code/Mantid/Build/CMake/LinuxPackageScripts.cmake @@ -22,6 +22,10 @@ endif() set ( CMAKE_INSTALL_RPATH ${CMAKE_INSTALL_PREFIX}/${LIB_DIR};${CMAKE_INSTALL_PREFIX}/${PLUGINS_DIR};${CMAKE_INSTALL_PREFIX}/${PVPLUGINS_DIR} ) +# Tell rpm that this package does not own /opt /usr/share/{applications,pixmaps} +# Required for Fedora >= 18 and RHEL >= 7 +set ( CPACK_RPM_EXCLUDE_FROM_AUTO_FILELIST_ADDITION /opt /usr/share/applications /usr/share/pixmaps ) + ########################################################################### # LD_PRELOAD TCMalloc ########################################################################### @@ -93,7 +97,8 @@ set ( PRE_UNINSTALL_FILE ${CMAKE_CURRENT_BINARY_DIR}/prerm ) set ( POST_UNINSTALL_FILE ${CMAKE_CURRENT_BINARY_DIR}/postrm ) if ( "${UNIX_DIST}" MATCHES "RedHatEnterprise" OR "${UNIX_DIST}" MATCHES "^Fedora" ) # RHEL/Fedora - if ( "${UNIX_CODENAME}" MATCHES "Santiago" ) # el6 + if ( "${UNIX_CODENAME}" MATCHES "Santiago" OR + "${UNIX_CODENAME}" MATCHES "Maipo" ) set ( WRAPPER_PREFIX "scl enable mantidlibs \"" ) set ( WRAPPER_POSTFIX "\"" ) set ( EXTRA_LDPATH "/usr/lib64/paraview" ) diff --git a/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in b/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in index 94ac4695d25a..33556e1b1c79 100644 --- a/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in +++ b/Code/Mantid/Build/CMake/Packaging/launch_mantidplot.sh.in @@ -21,4 +21,4 @@ else fi # Launch -LD_PRELOAD=${LOCAL_PRELOAD} TCMALLOC_RELEASE_RATE=${TCM_RELEASE} LD_LIBRARY_PATH=${LOCAL_LDPATH} @WRAPPER_PREFIX@$INSTALLDIR/@MANTIDPLOT_EXEC@ $*@WRAPPER_POSTFIX@ +LD_PRELOAD=${LOCAL_PRELOAD} TCMALLOC_RELEASE_RATE=${TCM_RELEASE} LD_LIBRARY_PATH=${LOCAL_LDPATH} QT_API=pyqt @WRAPPER_PREFIX@$INSTALLDIR/@MANTIDPLOT_EXEC@ $*@WRAPPER_POSTFIX@ diff --git a/Code/Mantid/Build/CMake/SetupDataTargets.cmake b/Code/Mantid/Build/CMake/SetupDataTargets.cmake new file mode 100644 index 000000000000..8f8a87e1e291 --- /dev/null +++ b/Code/Mantid/Build/CMake/SetupDataTargets.cmake @@ -0,0 +1,32 @@ +########################################################################### +# Define targets to download the data +########################################################################### +include ( MantidExternalData ) + +# None of our tests reference files directly as arguments so we have to manually +# call ExternalData_Expand_Arguments to register the files with the ExternalData +# mechanism +function(_create_data_target _targetname _content_link_patterns) + get_filename_component ( EXTERNALDATATEST_SOURCE_DIR ${PROJECT_SOURCE_DIR} ABSOLUTE ) + foreach(_pattern ${_content_link_patterns}) + file( GLOB_RECURSE _content_links + RELATIVE "${EXTERNALDATATEST_SOURCE_DIR}" ${_pattern} ) + foreach(link ${_content_links}) + string( REGEX REPLACE "\\.md5$" "" link ${link} ) + ExternalData_Expand_Arguments( ${_targetname} + link_location + DATA{${link}} + ) + endforeach() + endforeach() + # Create target to download data from the StandardTestData group. This must come after + # all tests have been added that reference the group, so we put it last. + ExternalData_Add_Target(${_targetname}) + set_target_properties(${_targetname} PROPERTIES EXCLUDE_FROM_ALL TRUE) +endfunction() + +# We'll create two targets: +# - StandardTestData: data required by the unit tests and documentation tests +# - SystemTestData: data required for the system tests +_create_data_target(StandardTestData "Testing/Data/DocTest/*.md5;Testing/Data/UnitTest/*.md5") +_create_data_target(SystemTestData "Testing/Data/SystemTest/*.md5;Testing/SystemTests/tests/analysis/reference/*.md5") diff --git a/Code/Mantid/Build/Jenkins/buildscript b/Code/Mantid/Build/Jenkins/buildscript index 61417dc99d96..461364befab4 100755 --- a/Code/Mantid/Build/Jenkins/buildscript +++ b/Code/Mantid/Build/Jenkins/buildscript @@ -4,10 +4,12 @@ # # Notes: # -# WORKSPACE, JOB_NAME & NODE_LABEL are environment variables that are set by -# Jenkins. The last one corresponds to any labels set on a slave. -# BUILD_THREADS & PARAVIEW_DIR should be set in the configuration of each slave. +# WORKSPACE, JOB_NAME, NODE_LABEL GIT_COMMIT are environment variables that +# are set by Jenkins. The last one corresponds to any labels set on a slave. +# BUILD_THREADS & PARAVIEW_DIR should be set in the configuration of each +# slave. ############################################################################### +SCRIPT_DIR=$(dirname "$0") ############################################################################### # Print out the versions of things we are using @@ -15,7 +17,18 @@ cmake --version echo "SHA1=${sha1}" +############################################################################### +# Setup clang +############################################################################### if [[ ${JOB_NAME} == *clang* ]]; then + USE_CLANG=true +elif [[ $(uname) == 'Darwin' ]] ; then + if [[ ! $(command -v icpc) ]] ; then + USE_CLANG=true + fi +fi + +if [[ $USE_CLANG ]]; then # Assuming we are using the clang compiler echo "Using clang/llvm compiler." clang --version @@ -35,7 +48,7 @@ fi ############################################################################### # OS X 10.8 setup steps ############################################################################### -if [[ $(uname) == 'Darwin' ]] && [[ ${JOB_NAME} != *clang* ]]; then +if [[ $(uname) == 'Darwin' ]] && [[ ! $USE_CLANG ]]; then # Assuming we are using the Intel compiler cd $WORKSPACE/Code ./fetch_Third_Party.sh @@ -53,30 +66,56 @@ fi ############################################################################### # Set up the location for the local object store outside of the build and # source tree, which can be shared by multiple builds. -# It defaults to the parent directory of the workspace but can be overridden -# by setting the MANTID_DATA_STORE environment variable. +# It defaults to a MantidExternalData directory within the HOME directory. +# It can be overridden by setting the MANTID_DATA_STORE environment variable. ############################################################################### if [ -z "$MANTID_DATA_STORE" ]; then - export MANTID_DATA_STORE=$(dirname $WORKSPACE) + export MANTID_DATA_STORE=$HOME/MantidExternalData +fi + +############################################################################### +# RHEL6 setup steps - nodes must have a "rhel6" label set (in lowercase) +############################################################################### +if [[ ${NODE_LABELS} == *rhel6* ]]; then + SCL_ON_RHEL6="scl enable mantidlibs" + ON_RHEL6=true +else + SCL_ON_RHEL6="eval" fi ############################################################################### -# Check whether this is a clean build (must have 'clean' in the job name) +# Check job requirements from the name ############################################################################### if [[ ${JOB_NAME} == *clean* ]]; then CLEANBUILD=true - # Removing the build directory entirely guarantees a completely clean build - rm -rf $WORKSPACE/build + BUILDPKG=true +fi + +if [[ -e $WORKSPACE/build/CMakeCache.txt ]]; then + # Temporary while the builds flick between old & new TestingTools locations + TESTINGTOOLS_DIR=$(grep 'Code/Mantid/TestingTools/cxxtest' $WORKSPACE/build/CMakeCache.txt || true) + if [ ! -z "$TESTINGTOOLS_DIR" ]; then + rm -fr $WORKSPACE/build + fi +fi + +if [[ ${JOB_NAME} == *pull_requests* ]]; then + BUILDPKG=true +fi - # Set some variables relating to the linux packages created from clean builds +############################################################################### +# Packaging options +############################################################################### +if [[ "$BUILDPKG" == true ]]; then + # Set some variables relating to the linux packages if [[ $(uname) != 'Darwin' ]]; then # Use different suffix for linux builds - if [[ ${JOB_NAME} == *master* ]]; then + if [[ ${JOB_NAME} == *release* ]]; then + PACKAGINGVARS="-DENVVARS_ON_INSTALL=True -DCPACK_SET_DESTDIR=ON -DPACKAGE_DOCS=ON" + elif [[ ${JOB_NAME} == *master* ]]; then PACKAGINGVARS="-DENVVARS_ON_INSTALL=False -DCMAKE_INSTALL_PREFIX=/opt/mantidnightly -DCPACK_PACKAGE_SUFFIX=nightly -DCPACK_SET_DESTDIR=OFF -DPACKAGE_DOCS=ON" - elif [[ ${JOB_NAME} == *develop* ]]; then + else PACKAGINGVARS="-DENVVARS_ON_INSTALL=False -DCMAKE_INSTALL_PREFIX=/opt/mantidunstable -DCPACK_PACKAGE_SUFFIX=unstable -DCPACK_SET_DESTDIR=OFF -DPACKAGE_DOCS=ON" - elif [[ ${JOB_NAME} == *release* ]]; then - PACKAGINGVARS="-DENVVARS_ON_INSTALL=True -DCPACK_SET_DESTDIR=ON -DPACKAGE_DOCS=ON" fi else # Mac packaging @@ -85,20 +124,19 @@ if [[ ${JOB_NAME} == *clean* ]]; then fi ############################################################################### -# RHEL6 setup steps - nodes must have a "rhel6" label set (in lowercase) +# Setup the build directory ############################################################################### -if [[ ${NODE_LABELS} == *rhel6* ]]; then - SCL_ON_RHEL6="scl enable mantidlibs" - ON_RHEL6=true -else - SCL_ON_RHEL6="eval" +if [[ "$CLEANBUILD" == true ]]; then + rm -rf $WORKSPACE/build fi +[ -d $WORKSPACE/build ] || mkdir $WORKSPACE/build +cd $WORKSPACE/build ############################################################################### -# Create the build directory if it doesn't exist +# Clean up any artifacts from last build so that if it fails +# they don't get archived again ############################################################################### -[ -d $WORKSPACE/build ] || mkdir $WORKSPACE/build -cd $WORKSPACE/build +rm -f *.dmg *.rpm *.deb *.tar.gz ############################################################################### ## Check the required build configuration @@ -144,45 +182,39 @@ $SCL_ON_RHEL6 "cmake --build . --target AllTests -- -j$BUILD_THREADS" # Run the tests ############################################################################### # Remove any Mantid.user.properties file -rm -f ~/.mantid/Mantid.user.properties +userprops=~/.mantid/Mantid.user.properties +rm -f $userprops $SCL_ON_RHEL6 "ctest -j$BUILD_THREADS --schedule-random --output-on-failure" ############################################################################### -# Documentation -# Build Qt help on all platforms for a clean build so that it can be packaged +# Create the install kit if required. This includes building the Qt help +# documentation ############################################################################### -if [[ "$CLEANBUILD" == true ]]; then +if [[ "$BUILDPKG" == true ]]; then # Workaround so that the target can find the properties file # CMake doesn't easily allow environment variables on custom targets if [[ $(uname) == 'Darwin' ]]; then export MANTIDPATH=$PWD/bin fi $SCL_ON_RHEL6 "cmake --build . --target docs-qthelp" -fi - -############################################################################### -# Create the install kit if this is a clean or non-Mac build -############################################################################### -rm -f *.dmg *.rpm *.deb *.tar.gz -# Always build a package on linux -if [[ $(uname) != 'Darwin' ]]; then $SCL_ON_RHEL6 "cpack" -fi -if [[ "$CLEANBUILD" == true ]]; then - # On the Mac, only create a package for clean builds - if [[ $(uname) == 'Darwin' ]]; then - $SCL_ON_RHEL6 "cpack" - fi - - # We could build the source tarball anywhere, but we choose to do it on RHEL6 - # We also parcel up the documentation into a tar file that is easier to move around + # Source tarball on clean build (arbitrarily choose rhel6) + # Also, parcel up the documentation into a tar file that is easier to move around # and labelled by the commit id it was built with. This assumes the Jenkins git plugin # has set the GIT_COMMIT environment variable - if [[ "$ON_RHEL6" == true ]]; then + if [[ "$CLEANBUILD" == true && "$ON_RHEL6" == true ]]; then $SCL_ON_RHEL6 "cmake --build . --target docs-html" tar -cjf mantiddocs-g${GIT_COMMIT:0:7}.tar.bz2 --exclude='*.buildinfo' --exclude="MantidProject.q*" docs/html # The ..._PREFIX argument avoids opt/Mantid directories at the top of the tree $SCL_ON_RHEL6 "cpack --config CPackSourceConfig.cmake -D CPACK_PACKAGING_INSTALL_PREFIX=" fi fi + +############################################################################### +# Run the system tests on RHEL6 when doing a pull request build. Run +# from a package to have at least one Linux checks it install okay +############################################################################### +if [[ "${ON_RHEL6}" == true ]] && [[ ${JOB_NAME} == *pull_requests* ]]; then + $SCRIPT_DIR/systemtests +fi diff --git a/Code/Mantid/Build/Jenkins/buildscript.bat b/Code/Mantid/Build/Jenkins/buildscript.bat index f861162c87c9..ce0d2ca69f03 100755 --- a/Code/Mantid/Build/Jenkins/buildscript.bat +++ b/Code/Mantid/Build/Jenkins/buildscript.bat @@ -1,3 +1,4 @@ +setlocal enableextensions enabledelayedexpansion ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: WINDOWS SCRIPT TO DRIVE THE JENKINS BUILDS OF MANTID. :: @@ -6,23 +7,10 @@ :: WORKSPACE & JOB_NAME are environment variables that are set by Jenkins. :: BUILD_THREADS & PARAVIEW_DIR should be set in the configuration of each slave. ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: - -"C:\Program Files (x86)\CMake 2.8\bin\cmake.exe" --version +set CMAKE_BIN_DIR=C:\Program Files (x86)\CMake 2.8\bin +"%CMAKE_BIN_DIR%\cmake.exe" --version echo %sha1% -::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -:: Check the required build configuration -::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -set BUILD_CONFIG= -if not "%JOB_NAME%"=="%JOB_NAME:debug=%" ( - set BUILD_CONFIG=Debug -) else ( -if not "%JOB_NAME%"=="%JOB_NAME:relwithdbg=%" ( - set BUILD_CONFIG=RelWithDbg -) else ( - set BUILD_CONFIG=Release - )) - ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Get or update the third party dependencies ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: @@ -30,40 +18,81 @@ cd %WORKSPACE%\Code call fetch_Third_Party win64 cd %WORKSPACE% -set PATH=%WORKSPACE%\Code\Third_Party\lib\win64;%WORKSPACE%\Code\Third_Party\lib\win64\Python27;%PARAVIEW_DIR%\bin\%BUILD_CONFIG%;%PATH% - ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Set up the location for local object store outside of the build and source :: tree, which can be shared by multiple builds. -:: It defaults to the parent directory of the workspace but can be overridden -:: by setting the MANTID_DATA_STORE environment variable. +:: It defaults to a MantidExternalData directory within the USERPROFILE +:: directory. It can be overridden by setting the MANTID_DATA_STORE environment +:: variable. ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if NOT DEFINED MANTID_DATA_STORE ( - for %%F in ("%WORKSPACE%") do set MANTID_DATA_STORE=%%~dpF + set MANTID_DATA_STORE=%USERPROFILE%\MantidExternalData +) + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Check job requirements from the name +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +set CLEANBUILD= +set BUILDPKG= +if not "%JOB_NAME%" == "%JOB_NAME:clean=%" ( + set CLEANBUILD=yes + set BUILDPKG=yes +) + +if EXIST %WORKSPACE%\build\CMakeCache.txt ( + FINDSTR "Code/Mantid/TestingTools/cxxtest" %WORKSPACE%\build\CMakeCache.txt && ( + rmdir /S /Q %WORKSPACE%\build + ) +) + +if not "%JOB_NAME%" == "%JOB_NAME:pull_requests=%" ( + set BUILDPKG=yes ) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -:: Check whether this is a clean build (must have 'clean' in the job name) +:: Packaging options ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: set PACKAGE_DOCS= -if "%JOB_NAME%"=="%JOB_NAME:clean=%" ( - set CLEANBUILD=no -) else ( - set CLEANBUILD=yes - set PACKAGE_DOCS=-DPACKAGE_DOCS=True - rmdir /S /Q build +if "%BUILDPKG%" == "yes" ( + set PACKAGE_DOCS=-DPACKAGE_DOCS=ON ) ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -:: Create the build directory if it doesn't exist +:: Setup the build directory ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +if "%CLEANBUILD%" == "yes" ( + rmdir /S /Q %WORKSPACE%\build +) md %WORKSPACE%\build cd %WORKSPACE%\build +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Clean up any artifacts from last build so that if it fails +:: they don't get archived again. +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +del /Q *.exe + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Check the required build configuration +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +set BUILD_CONFIG= +if not "%JOB_NAME%"=="%JOB_NAME:debug=%" ( + set BUILD_CONFIG=Debug +) else ( +if not "%JOB_NAME%"=="%JOB_NAME:relwithdbg=%" ( + set BUILD_CONFIG=RelWithDbg +) else ( + set BUILD_CONFIG=Release + )) +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Update the PATH so that we can find everything +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +set PATH=%WORKSPACE%\Code\Third_Party\lib\win64;%WORKSPACE%\Code\Third_Party\lib\win64\Python27;%PARAVIEW_DIR%\bin\%BUILD_CONFIG%;%PATH% + ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: CMake configuration ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -"C:\Program Files (x86)\CMake 2.8\bin\cmake.exe" -G "Visual Studio 11 Win64" -DCONSOLE=OFF -DENABLE_CPACK=ON -DMAKE_VATES=ON -DParaView_DIR=%PARAVIEW_DIR% -DMANTID_DATA_STORE=%MANTID_DATA_STORE% -DUSE_PRECOMPILED_HEADERS=ON %PACKAGE_DOCS% ..\Code\Mantid +"%CMAKE_BIN_DIR%\cmake.exe" -G "Visual Studio 11 Win64" -DCONSOLE=OFF -DENABLE_CPACK=ON -DMAKE_VATES=ON -DParaView_DIR=%PARAVIEW_DIR% -DMANTID_DATA_STORE=!MANTID_DATA_STORE! -DUSE_PRECOMPILED_HEADERS=ON %PACKAGE_DOCS% ..\Code\Mantid if ERRORLEVEL 1 exit /B %ERRORLEVEL% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: @@ -75,17 +104,53 @@ if ERRORLEVEL 1 exit /B %ERRORLEVEL% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: :: Run the tests ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -"C:\Program Files (x86)\CMake 2.8\bin\ctest.exe" -C %BUILD_CONFIG% -j%BUILD_THREADS% --schedule-random --output-on-failure +:: Remove the user properties file just in case anything polluted it +set USERPROPS=bin\%BUILD_CONFIG%\Mantid.user.properties +del %USERPROPS% +"%CMAKE_BIN_DIR%\ctest.exe" -C %BUILD_CONFIG% -j%BUILD_THREADS% --schedule-random --output-on-failure if ERRORLEVEL 1 exit /B %ERRORLEVEL% ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -:: Create the install kit if this is a clean build +:: Create the install kit if required +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +if "%BUILDPKG%" == "yes" ( + echo Building package + :: Build offline documentation + msbuild /nologo /nr:false /p:Configuration=%BUILD_CONFIG% docs/docs-qthelp.vcxproj + + :: Ignore errors as the exit code of msbuild is wrong here. + :: It always marks the build as a failure even thought the MantidPlot exit + :: code is correct! + ::if ERRORLEVEL 1 exit /B %ERRORLEVEL% + "%CMAKE_BIN_DIR%\cpack.exe" -C %BUILD_CONFIG% --config CPackConfig.cmake +) + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Run the doc tests when doing a pull request build. Run from a package +:: from a package to have at least one Linux checks it install okay ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: -if "%CLEANBUILD%" EQU "yes" ( - :: Build offline documentation - msbuild /nologo /nr:false /p:Configuration=%BUILD_CONFIG% docs/docs-qthelp.vcxproj +if not "%JOB_NAME%"=="%JOB_NAME:pull_requests=%" ( + :: Install package + set SYSTEMTESTS_DIR=%WORKSPACE%\Code\Mantid\Testing\SystemTests + python !SYSTEMTESTS_DIR!\scripts\mantidinstaller.py install %WORKSPACE%\build - :: ignore errors as the exit code of the build isn't correct - ::if ERRORLEVEL 1 exit /B %ERRORLEVEL% - cpack -C %BUILD_CONFIG% --config CPackConfig.cmake + ::Remove user properties, disable instrument updating & usage reports and add data paths + del /Q C:\MantidInstall\bin\Mantid.user.properties + echo UpdateInstrumentDefinitions.OnStartup = 0 > C:\MantidInstall\bin\Mantid.user.properties + echo usagereports.enabled = 0 >> C:\MantidInstall\bin\Mantid.user.properties + :: User properties file cannot contain backslash characters + set WORKSPACE_UNIX_STYLE=%WORKSPACE:\=/% + set DATA_ROOT=!WORKSPACE_UNIX_STYLE!/build/ExternalData/Testing/Data + echo datasearch.directories = !DATA_ROOT!/UnitTest;!DATA_ROOT!/DocTest;!WORKSPACE_UNIX_STYLE!/Code/Mantid/instrument >> C:\MantidInstall\bin\Mantid.user.properties + + :: Run tests + cd %WORKSPACE%\build\docs + C:\MantidInstall\bin\MantidPlot.exe -xq runsphinx_doctest.py + set RETCODE=!ERRORLEVEL! + + :: Remove Mantid + cd %WORKSPACE%\build + python !SYSTEMTESTS_DIR!\scripts\mantidinstaller.py uninstall %WORKSPACE%\build + if !RETCODE! NEQ 0 exit /B 1 ) + diff --git a/Code/Mantid/Build/Jenkins/jenkins-slave.sh b/Code/Mantid/Build/Jenkins/jenkins-slave.sh index 02596bb47456..b728187b1cc7 100755 --- a/Code/Mantid/Build/Jenkins/jenkins-slave.sh +++ b/Code/Mantid/Build/Jenkins/jenkins-slave.sh @@ -7,7 +7,9 @@ # The settings at the top must be filled in for each slave. ##################################################################### # Crontab setting should be something like -# 0,30 * * * * /home/builder/jenkins-linode nodename secret +# 0,30 * * * * /home/builder/jenkins-linode/jenkins-slave.sh nodename secret +# or (on mac) +# 0,30 * * * * /Users/builder/jenkins-linode/jenkins-slave.sh nodename secret ##################################################################### # User configuration ##################################################################### diff --git a/Code/Mantid/Build/Jenkins/systemtests b/Code/Mantid/Build/Jenkins/systemtests new file mode 100755 index 000000000000..16f29a98e56b --- /dev/null +++ b/Code/Mantid/Build/Jenkins/systemtests @@ -0,0 +1,73 @@ +#!/bin/bash -ex +############################################################################### +# LINUX/MAC SCRIPT TO DRIVE THE SYSTEM TESTS OF MANTID +# +# Notes: +# +# WORKSPACE, JOB_NAME, NODE_LABEL GIT_COMMIT are environment variables that +# are set by Jenkins. The last one corresponds to any labels set on a slave. +############################################################################### + +############################################################################### +# Print out the versions of things we are using +############################################################################### +cmake --version +echo "SHA1=${sha1}" + +############################################################################### +# Set up the location for the local object store outside of the build and +# source tree, which can be shared by multiple builds. +# It defaults to the parent directory of the workspace but can be overridden +# by setting the MANTID_DATA_STORE environment variable. +############################################################################### +if [ -z "$MANTID_DATA_STORE" ]; then + export MANTID_DATA_STORE=$(dirname $WORKSPACE) +fi + +############################################################################### +# RHEL6 setup steps - nodes must have a "rhel6" label set (in lowercase) +############################################################################### +if [[ ${NODE_LABELS} == *rhel6* ]]; then + SCL_ON_RHEL6="scl enable mantidlibs" + ON_RHEL6=true +else + SCL_ON_RHEL6="eval" +fi + +############################################################################### +# Create the build directory if it doesn't exist +############################################################################### +[ -d $WORKSPACE/build ] || mkdir $WORKSPACE/build +cd $WORKSPACE/build + +############################################################################### +# CMake configuration if it has not already been configured. +# We use the special flag that only creates the targets for the data +############################################################################### +if [[ ! -e $WORKSPACE/build/CMakeCache.txt ]]; then + $SCL_ON_RHEL6 "cmake -DMANTID_DATA_STORE=${MANTID_DATA_STORE} -DDATA_TARGETS_ONLY=ON ../Code/Mantid" +else + $SCL_ON_RHEL6 "cmake ." +fi + +############################################################################### +# Build step +############################################################################### +$SCL_ON_RHEL6 "cmake --build . -- StandardTestData" +$SCL_ON_RHEL6 "cmake --build . -- SystemTestData" + +############################################################################### +# Run the tests +############################################################################### +# Remove any Mantid.user.properties file +userprops=~/.mantid/Mantid.user.properties +rm -f $userprops +# Turn off usage reports and instrument downloading for the mantid call +# that creates the properties file +echo "UpdateInstrumentDefinitions.OnStartup = 0" > $userprops +echo "usagereports.enabled = 0" >> $userprops + +# Run +PKGDIR=${WORKSPACE}/build +python $WORKSPACE/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py -o -d $PKGDIR + diff --git a/Code/Mantid/Build/Jenkins/systemtests.bat b/Code/Mantid/Build/Jenkins/systemtests.bat new file mode 100755 index 000000000000..3c2f3e003568 --- /dev/null +++ b/Code/Mantid/Build/Jenkins/systemtests.bat @@ -0,0 +1,66 @@ +setlocal enbaleextensions enabledelayedexpansion +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: WINDOWS SCRIPT TO DRIVE THE SYSTEM TESTS OF MANTID +:: +:: Notes: +:: +:: WORKSPACE, JOB_NAME & NODE_LABEL are environment variables that +:: are set by Jenkins. The last one corresponds to any labels set on a slave. +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Print out the versions of things we are using +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +set CMAKE_BIN_DIR=C:\Program Files (x86)\CMake 2.8\bin +"%CMAKE_BIN_DIR%\cmake" --version +echo %sha1% + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Set up the location for local object store outside of the build and source +:: tree, which can be shared by multiple builds. +:: It defaults to a MantidExternalData directory within the USERPROFILE +:: directory. It can be overridden by setting the MANTID_DATA_STORE environment +:: variable. +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +if NOT DEFINED MANTID_DATA_STORE ( + set MANTID_DATA_STORE=%USERPROFILE%\MantidExternalData +) + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Setup the build directory +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +md %WORKSPACE%\build +cd %WORKSPACE%\build + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: CMake configuration if it has not already been configured. +:: We use the special flag that only creates the targets for the data +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +if not EXIST %WORKSPACE%\build\CMakeCache.txt ( + "%CMAKE_BIN_DIR%\cmake" -DMANTID_DATA_STORE=!MANTID_DATA_STORE! -DDATA_TARGETS_ONLY=ON ..\Code\Mantid +) else ( + :: This ensures that any new data files are picked up by the cmake globbing + "%CMAKE_BIN_DIR%\cmake" . +) + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Build step +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +"%CMAKE_BIN_DIR%\cmake" --build . -- StandardTestData +"%CMAKE_BIN_DIR%\cmake" --build . -- SystemTestData + +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Run the tests +::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: +:: Remove any Mantid.user.properties file +set USERPROPS=C:\MantidInstall\bin\Mantid.user.properties +del /Q %USERPROPS% +:: Turn off usage reports and instrument downloading for the mantid call +:: that creates the properties file +echo UpdateInstrumentDefinitions.OnStartup = 0 > %USERPROPS% +echo usagereports.enabled = 0 >> %USERPROPS% + +:: Run +set PKGDIR=%WORKSPACE%\build +python %WORKSPACE%\Code\Mantid\Testing\SystemTests\scripts\InstallerTests.py -o -d %PKGDIR% + diff --git a/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.3/DEBIAN/control b/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.3/DEBIAN/control index b8a48ac71c23..5d0abce474b7 100644 --- a/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.3/DEBIAN/control +++ b/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.3/DEBIAN/control @@ -3,7 +3,7 @@ Version: 1.2.3 Section: main Priority: optional Architecture: all -Depends: git, clang, cmake-qt-gui(>=2.8.12), qt4-qmake, qt4-dev-tools, libqt4-dbg, libpoco-dev(>=1.4.2), libboost-all-dev, libboost-dbg, libnexus0-dev, libgoogle-perftools-dev, libqwt5-qt4-dev, libqwtplot3d-qt4-dev, python-qt4-dev, libgsl0-dev, liboce-visualization-dev, libmuparser-dev, python-numpy, libssl-dev, libqscintilla2-dev, texlive,texlive-latex-extra, dvipng, libhdf4-dev, doxygen, python-sphinx, python-scipy, ipython-qtconsole (>=1.2.0), libhdf5-dev, libhdf4-dev, libpococrypto11-dbg, libpocodata11-dbg, libpocofoundation11-dbg, libpocomysql11-dbg, libpoconet11-dbg, libpoconetssl11-dbg, libpocoodbc11-dbg, libpocosqlite11-dbg, libpocoutil11-dbg, libpocoxml11-dbg, libpocozip11-dbg, python-qt4-dbg, qt4-default, ninja-build, libjsoncpp-dev, python-dateutil +Depends: git, clang, cmake-qt-gui(>=2.8.12), qt4-qmake, qt4-dev-tools, libqt4-dbg, libpoco-dev(>=1.4.2), libboost-all-dev, libboost-dbg, libnexus0-dev, libgoogle-perftools-dev, libqwt5-qt4-dev, libqwtplot3d-qt4-dev, python-qt4-dev, libgsl0-dev, liboce-visualization-dev, libmuparser-dev, python-numpy, libssl-dev, libqscintilla2-dev, texlive, texlive-latex-extra, dvipng, libhdf4-dev, doxygen, python-sphinx, python-scipy, ipython-qtconsole (>=1.2.0), libhdf5-dev, libhdf4-dev, libpococrypto11-dbg, libpocodata11-dbg, libpocofoundation11-dbg, libpocomysql11-dbg, libpoconet11-dbg, libpoconetssl11-dbg, libpocoodbc11-dbg, libpocosqlite11-dbg, libpocoutil11-dbg, libpocoxml11-dbg, libpocozip11-dbg, python-qt4-dbg, qt4-default, ninja-build, libjsoncpp-dev, python-dateutil, python-sphinx-bootstrap-theme Installed-Size: 0 Maintainer: Mantid Project Description: Installs all packages required for a Mantid developer diff --git a/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.4/DEBIAN/control b/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.4/DEBIAN/control index 7eb31c754324..b9feb3ebcfd4 100644 --- a/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.4/DEBIAN/control +++ b/Code/Mantid/Build/dev-packages/deb/mantid-developer/mantid-developer-1.2.4/DEBIAN/control @@ -3,7 +3,7 @@ Version: 1.2.4 Section: main Priority: optional Architecture: all -Depends: git, clang, cmake-qt-gui(>=2.8.12), qt4-qmake, qt4-dev-tools, libqt4-dbg, libpoco-dev(>=1.4.2), libboost-all-dev, libboost-dbg, libnexus0-dev, libgoogle-perftools-dev, libqwt5-qt4-dev, libqwtplot3d-qt4-dev, python-qt4-dev, libgsl0-dev, liboce-visualization-dev, libmuparser-dev, python-numpy, libssl-dev, libqscintilla2-dev, texlive,texlive-latex-extra, dvipng, libhdf4-dev, doxygen, python-sphinx, python-scipy, ipython-qtconsole (>=1.2.0), libhdf5-dev, libhdf4-dev, libpococrypto11-dbg, libpocodata11-dbg, libpocofoundation11-dbg, libpocomysql11-dbg, libpoconet11-dbg, libpoconetssl11-dbg, libpocoodbc11-dbg, libpocosqlite11-dbg, libpocoutil11-dbg, libpocoxml11-dbg, libpocozip11-dbg, python-qt4-dbg, qt4-default, ninja-build, libjsoncpp-dev, python-dateutil, graphviz +Depends: git, clang, cmake-qt-gui(>=2.8.12), qt4-qmake, qt4-dev-tools, libqt4-dbg, libpoco-dev(>=1.4.2), libboost-all-dev, libboost-dbg, libnexus0-dev, libgoogle-perftools-dev, libqwt5-qt4-dev, libqwtplot3d-qt4-dev, python-qt4-dev, libgsl0-dev, liboce-visualization-dev, libmuparser-dev, python-numpy, libssl-dev, libqscintilla2-dev, texlive,texlive-latex-extra, dvipng, libhdf4-dev, doxygen, python-sphinx, python-scipy, ipython-qtconsole (>=1.2.0), libhdf5-dev, libhdf4-dev, libpococrypto11-dbg, libpocodata11-dbg, libpocofoundation11-dbg, libpocomysql11-dbg, libpoconet11-dbg, libpoconetssl11-dbg, libpocoodbc11-dbg, libpocosqlite11-dbg, libpocoutil11-dbg, libpocoxml11-dbg, libpocozip11-dbg, python-qt4-dbg, qt4-default, ninja-build, libjsoncpp-dev, python-dateutil, python-sphinx-bootstrap-theme, graphviz Installed-Size: 0 Maintainer: Mantid Project Description: Installs all packages required for a Mantid developer diff --git a/Code/Mantid/CMakeLists.txt b/Code/Mantid/CMakeLists.txt index 2b79286d6eb5..a055859f89e1 100644 --- a/Code/Mantid/CMakeLists.txt +++ b/Code/Mantid/CMakeLists.txt @@ -1,8 +1,8 @@ ########################################################################### # CMake version check. -# Only versions after 2.8.5 will find the HL component for HDF5 +# Only versions after 2.8.12 will find the HL component for HDF5 ########################################################################### -cmake_minimum_required ( VERSION 2.8.5 ) +cmake_minimum_required ( VERSION 2.8.12 ) # System package target is important for the windows builds as it allows us to package only the dlls and exes and exclude libs. Defaults to empty for other platforms. set ( SYSTEM_PACKAGE_TARGET "") @@ -12,6 +12,17 @@ set ( CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/Build/CMake") # Define the project name. project ( Mantid ) + +########################################################################### +# Quick exit if we only want data targets +########################################################################### +if( DATA_TARGETS_ONLY ) + include( SetupDataTargets ) + # System test config files + add_subdirectory( Testing/SystemTests/scripts ) + return() +endif() + set ( CPACK_PACKAGE_SUFFIX "" CACHE STRING "suffix used to determine the deployment type") set_property(CACHE CPACK_PACKAGE_SUFFIX PROPERTY STRINGS nightly unstable "") #empty string and release are treated as the same thing @@ -147,6 +158,9 @@ add_subdirectory ( scripts ) add_subdirectory ( docs ) +# System test data target +add_subdirectory ( Testing/SystemTests/scripts ) + ########################################################################### # Installation settings ########################################################################### diff --git a/Code/Mantid/Framework/API/CMakeLists.txt b/Code/Mantid/Framework/API/CMakeLists.txt index cc62a6115e29..c59fd55a43a5 100644 --- a/Code/Mantid/Framework/API/CMakeLists.txt +++ b/Code/Mantid/Framework/API/CMakeLists.txt @@ -93,6 +93,7 @@ set ( SRC_FILES src/ParamFunction.cpp src/ParameterReference.cpp src/ParameterTie.cpp + src/PeakFunctionIntegrator.cpp src/PeakTransform.cpp src/PeakTransformHKL.cpp src/PeakTransformQLab.cpp @@ -252,6 +253,7 @@ set ( INC_FILES inc/MantidAPI/ParamFunction.h inc/MantidAPI/ParameterReference.h inc/MantidAPI/ParameterTie.h + inc/MantidAPI/PeakFunctionIntegrator.h inc/MantidAPI/PeakTransform.h inc/MantidAPI/PeakTransformFactory.h inc/MantidAPI/PeakTransformHKL.h @@ -348,6 +350,7 @@ set ( TEST_FILES ParamFunctionAttributeHolderTest.h ParameterReferenceTest.h ParameterTieTest.h + PeakFunctionIntegratorTest.h PeakTransformHKLTest.h PeakTransformQLabTest.h PeakTransformQSampleTest.h diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h b/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h index 442f9cca369e..0ee7a8d085ff 100644 --- a/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/IPeak.h @@ -7,6 +7,7 @@ #include "MantidKernel/Matrix.h" #include "MantidKernel/V3D.h" #include "MantidKernel/PhysicalConstants.h" +#include namespace Mantid { namespace API { @@ -50,9 +51,9 @@ class MANTID_API_DLL IPeak { virtual bool findDetector() = 0; virtual void setQSampleFrame(Mantid::Kernel::V3D QSampleFrame, - double detectorDistance = 1.0) = 0; + boost::optional detectorDistance) = 0; virtual void setQLabFrame(Mantid::Kernel::V3D QLabFrame, - double detectorDistance = 1.0) = 0; + boost::optional detectorDistance) = 0; virtual void setWavelength(double wavelength) = 0; virtual double getWavelength() const = 0; diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h b/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h index 7405ca45a731..80e2899f880f 100644 --- a/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/IPeakFunction.h @@ -49,6 +49,12 @@ class MANTID_API_DLL IPeakFunction : public IFunctionWithLocation { /// Sets the parameters such that FWHM = w virtual void setFwhm(const double w) = 0; + /// Returns the integral intensity of the peak + virtual double intensity() const; + + /// Sets the integral intensity of the peak + virtual void setIntensity(const double newIntensity); + /// General implementation of the method for all peaks. void function1D(double *out, const double *xValues, const size_t nData) const; /// General implementation of the method for all peaks. diff --git a/Code/Mantid/Framework/API/inc/MantidAPI/IPeaksWorkspace.h b/Code/Mantid/Framework/API/inc/MantidAPI/IPeaksWorkspace.h index 7282be8542cc..15bd48bf8b94 100644 --- a/Code/Mantid/Framework/API/inc/MantidAPI/IPeaksWorkspace.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/IPeaksWorkspace.h @@ -7,6 +7,7 @@ #include "MantidAPI/ITableWorkspace.h" #include "MantidAPI/ExperimentInfo.h" #include "MantidKernel/SpecialCoordinateSystem.h" +#include namespace Mantid { @@ -98,12 +99,20 @@ class MANTID_API_DLL IPeaksWorkspace : public ITableWorkspace, //--------------------------------------------------------------------------------------------- /** Create an instance of a Peak - * @param QLabFrame :: Q of the center of the peak, in reciprocal space - * @param detectorDistance :: distance between the sample and the detector. + * @param QLabFrame :: Q of the center of the peak in the lab frame, in reciprocal space + * @param detectorDistance :: Optional distance between the sample and the detector. Calculated if not provided. * @return a pointer to a new Peak object. */ virtual IPeak *createPeak(Mantid::Kernel::V3D QLabFrame, - double detectorDistance = 1.0) const = 0; + boost::optional detectorDistance) const = 0; + + + /** + * Create an instance of a peak using a V3D + * @param HKL V3D + * @return a pointer to a new Peak object. + */ + virtual IPeak *createPeakHKL(Mantid::Kernel::V3D HKL) const = 0; //--------------------------------------------------------------------------------------------- /** Determine if the workspace has been integrated using a peaks integration diff --git a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h b/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h similarity index 73% rename from Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h rename to Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h index c287ca1bf842..f07e262b1843 100644 --- a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h +++ b/Code/Mantid/Framework/API/inc/MantidAPI/PeakFunctionIntegrator.h @@ -1,22 +1,25 @@ #ifndef PEAKFUNCTIONINTEGRATOR_H #define PEAKFUNCTIONINTEGRATOR_H -#include "MantidSINQ/DllConfig.h" +#include "MantidAPI/DllConfig.h" #include "MantidAPI/IPeakFunction.h" #include "gsl/gsl_integration.h" namespace Mantid { -namespace Poldi { +namespace API { /** PeakFunctionIntegrator : * General integration of peaks (in the form of IPeakFunction) by wrapping the corresponding GSL-functions. Integration with infinity limits is supported. + PeakFunctionIntegrator allocates a GSL integration workspace on construction + and frees the memory when it's destroyed. + @author Michael Wedel, Paul Scherrer Institut - SINQ @date 24/04/2014 - Copyright © 2014 PSI-MSS + Copyright © 2014,2015 PSI-MSS This file is part of Mantid. @@ -37,7 +40,7 @@ namespace Poldi { Code Documentation is available at: */ -struct MANTID_SINQ_DLL IntegrationResult { +struct MANTID_API_DLL IntegrationResult { double result; double error; size_t intervals; @@ -46,7 +49,7 @@ struct MANTID_SINQ_DLL IntegrationResult { bool success; }; -class MANTID_SINQ_DLL PeakFunctionIntegrator { +class MANTID_API_DLL PeakFunctionIntegrator { public: PeakFunctionIntegrator(double requiredRelativePrecision = 1e-8); virtual ~PeakFunctionIntegrator(); @@ -55,27 +58,26 @@ class MANTID_SINQ_DLL PeakFunctionIntegrator { double requiredRelativePrecision() const; IntegrationResult - integrateInfinity(API::IPeakFunction_const_sptr peakFunction) const; + integrateInfinity(const IPeakFunction &peakFunction) const; IntegrationResult - integratePositiveInfinity(API::IPeakFunction_const_sptr peakFunction, + integratePositiveInfinity(const IPeakFunction &peakFunction, double lowerLimit) const; IntegrationResult - integrateNegativeInfinity(API::IPeakFunction_const_sptr peakFunction, + integrateNegativeInfinity(const IPeakFunction &peakFunction, double upperLimit) const; - IntegrationResult integrate(API::IPeakFunction_const_sptr peakFunction, + IntegrationResult integrate(const IPeakFunction &peakFunction, double lowerLimit, double upperLimit) const; protected: - gsl_function getGSLFunction(API::IPeakFunction_const_sptr peakFunction) const; - void throwIfInvalid(API::IPeakFunction_const_sptr peakFunction) const; + gsl_function getGSLFunction(const IPeakFunction &peakFunction) const; gsl_integration_workspace *m_integrationWorkspace; double m_relativePrecision; }; -double MANTID_SINQ_DLL gsl_peak_wrapper(double x, void *parameters); +double MANTID_API_DLL gsl_peak_wrapper(double x, void *parameters); } } diff --git a/Code/Mantid/Framework/API/src/Algorithm.cpp b/Code/Mantid/Framework/API/src/Algorithm.cpp index e47704b9bc2c..4a41e7e1182d 100644 --- a/Code/Mantid/Framework/API/src/Algorithm.cpp +++ b/Code/Mantid/Framework/API/src/Algorithm.cpp @@ -1164,7 +1164,7 @@ bool Algorithm::checkGroups() { // Workspace groups are NOT returned by IWP->getWorkspace() most of the time // because WorkspaceProperty is templated by // and WorkspaceGroup does not subclass - if (!wsGroup && !prop->value().empty()) { + if (!wsGroup && prop && !prop->value().empty()) { // So try to use the name in the AnalysisDataService try { wsGroup = AnalysisDataService::Instance().retrieveWS( diff --git a/Code/Mantid/Framework/API/src/IPeakFunction.cpp b/Code/Mantid/Framework/API/src/IPeakFunction.cpp index 04e9b34dc2b2..07053b760fda 100644 --- a/Code/Mantid/Framework/API/src/IPeakFunction.cpp +++ b/Code/Mantid/Framework/API/src/IPeakFunction.cpp @@ -3,6 +3,7 @@ //---------------------------------------------------------------------- #include "MantidAPI/IPeakFunction.h" #include "MantidAPI/Jacobian.h" +#include "MantidAPI/PeakFunctionIntegrator.h" #include "MantidKernel/Exception.h" #include "MantidKernel/ConfigService.h" @@ -130,5 +131,43 @@ void IPeakFunction::setPeakRadius(const int &r) { } } +/// Returns the integral intensity of the peak function, using the peak radius +/// to determine integration borders. +double IPeakFunction::intensity() const { + double x0 = centre(); + double dx = fabs(s_peakRadius * fwhm()); + + PeakFunctionIntegrator integrator; + IntegrationResult result = integrator.integrate(*this, x0 - dx, x0 + dx); + + if (!result.success) { + return 0.0; + } + + return result.result; +} + +/// Sets the integral intensity of the peak by adjusting the height. +void IPeakFunction::setIntensity(const double newIntensity) { + double currentHeight = height(); + double currentIntensity = intensity(); + + if (currentIntensity == 0.0) { + // Try to set a different height first. + setHeight(2.0); + + currentHeight = height(); + currentIntensity = intensity(); + + // If the current intensity is still 0, there's nothing left to do. + if (currentIntensity == 0.0) { + throw std::invalid_argument( + "Cannot set new intensity, not enough information available."); + } + } + + setHeight(newIntensity / currentIntensity * currentHeight); +} + } // namespace API } // namespace Mantid diff --git a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PeakFunctionIntegrator.cpp b/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp similarity index 71% rename from Code/Mantid/Framework/SINQ/src/PoldiUtilities/PeakFunctionIntegrator.cpp rename to Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp index 620b41e9237a..b36896423ffc 100644 --- a/Code/Mantid/Framework/SINQ/src/PoldiUtilities/PeakFunctionIntegrator.cpp +++ b/Code/Mantid/Framework/API/src/PeakFunctionIntegrator.cpp @@ -1,4 +1,4 @@ -#include "MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h" +#include "MantidAPI/PeakFunctionIntegrator.h" #include "MantidAPI/FunctionDomain1D.h" #include "gsl/gsl_errno.h" @@ -6,15 +6,13 @@ #include namespace Mantid { -namespace Poldi { - -using namespace API; +namespace API { /** Constructor with required relative precision argument. The default is 1e-8. * See also PeakFunctionIntegrator::setRequiredRelativePrecision. * * @param requiredRelativePrecision :: Desired relative precision of the - *integral estimations. + * integral estimations. */ PeakFunctionIntegrator::PeakFunctionIntegrator(double requiredRelativePrecision) : m_integrationWorkspace(gsl_integration_workspace_alloc(1000)), @@ -31,8 +29,7 @@ PeakFunctionIntegrator::~PeakFunctionIntegrator() { } /** This method sets the desired numerical relative precision that's passed on - *to the - * GSL integration-routines. + * to the GSL integration-routines. * * @param newPrecision :: Desired relative precision for integrations. */ @@ -47,19 +44,14 @@ double PeakFunctionIntegrator::requiredRelativePrecision() const { } /** Integration of peak function on the interval [-Inf, +Inf]. Internally, - *gsl_integration_qagi is used - * for this. If a default constructed IPeakFunction_const_sptr is passed to the - *function, std::invalid_argument is thrown. - * The results are returned as IntegrationResult-struct, which contains the - *approximation of the integral along - * with other information such as an error estimate (absolute). + * gsl_integration_qagi is used for this. The results are returned as + * IntegrationResult-struct, which contains the approximation of the integral + * along with other information such as an error estimate (absolute). * * @param peakFunction :: Peak function to integrate. */ IntegrationResult PeakFunctionIntegrator::integrateInfinity( - IPeakFunction_const_sptr peakFunction) const { - throwIfInvalid(peakFunction); - + const IPeakFunction &peakFunction) const { IntegrationResult result; gsl_function f = getGSLFunction(peakFunction); @@ -74,16 +66,13 @@ IntegrationResult PeakFunctionIntegrator::integrateInfinity( } /** Integration of peak function on the interval [a, +Inf]. Internally, - *gsl_integration_qagiu is used - * for this. If a default constructed IPeakFunction_const_sptr is passed to the - *function, std::invalid_argument is thrown. + * gsl_integration_qagiu is used for this. * * @param peakFunction :: Peak function to integrate. + * @param lowerLimit :: Lower limit of the integration. */ IntegrationResult PeakFunctionIntegrator::integratePositiveInfinity( - IPeakFunction_const_sptr peakFunction, double lowerLimit) const { - throwIfInvalid(peakFunction); - + const IPeakFunction &peakFunction, double lowerLimit) const { IntegrationResult result; gsl_function f = getGSLFunction(peakFunction); @@ -98,16 +87,13 @@ IntegrationResult PeakFunctionIntegrator::integratePositiveInfinity( } /** Integration of peak function on the interval [-Inf, b]. Internally, - *gsl_integration_qagil is used - * for this. If a default constructed IPeakFunction_const_sptr is passed to the - *function, std::invalid_argument is thrown. + * gsl_integration_qagil is used for this. * * @param peakFunction :: Peak function to integrate. + * @param upperLimit :: Upper limit of the integration. */ IntegrationResult PeakFunctionIntegrator::integrateNegativeInfinity( - IPeakFunction_const_sptr peakFunction, double upperLimit) const { - throwIfInvalid(peakFunction); - + const IPeakFunction &peakFunction, double upperLimit) const { IntegrationResult result; gsl_function f = getGSLFunction(peakFunction); @@ -122,17 +108,15 @@ IntegrationResult PeakFunctionIntegrator::integrateNegativeInfinity( } /** Integration of peak function on the interval [a, b]. Internally, - *gsl_integration_qags is used - * for this. If a default constructed IPeakFunction_const_sptr is passed to the - *function, std::invalid_argument is thrown. + * gsl_integration_qags is used for this. * * @param peakFunction :: Peak function to integrate. + * @param lowerLimit :: Lower limit of the integration. + * @param upperLimit :: Upper limit of the integration. */ IntegrationResult -PeakFunctionIntegrator::integrate(IPeakFunction_const_sptr peakFunction, +PeakFunctionIntegrator::integrate(const IPeakFunction &peakFunction, double lowerLimit, double upperLimit) const { - throwIfInvalid(peakFunction); - IntegrationResult result; gsl_function f = getGSLFunction(peakFunction); @@ -151,24 +135,22 @@ PeakFunctionIntegrator::integrate(IPeakFunction_const_sptr peakFunction, * @param peakFunction :: Peak function to wrap. */ gsl_function PeakFunctionIntegrator::getGSLFunction( - IPeakFunction_const_sptr peakFunction) const { + const IPeakFunction &peakFunction) const { gsl_function f; - f.function = &Mantid::Poldi::gsl_peak_wrapper; - f.params = &peakFunction; + f.function = &Mantid::API::gsl_peak_wrapper; + f.params = + reinterpret_cast(&const_cast(peakFunction)); return f; } -void PeakFunctionIntegrator::throwIfInvalid( - IPeakFunction_const_sptr peakFunction) const { +double gsl_peak_wrapper(double x, void *parameters) { + IPeakFunction *peakFunction = reinterpret_cast(parameters); + if (!peakFunction) { - throw std::invalid_argument("Can not integrate NULL-function."); + throw std::runtime_error( + "Cannot process NULL-pointer in gsl_peak_wrapper."); } -} - -double gsl_peak_wrapper(double x, void *parameters) { - IPeakFunction_const_sptr peakFunction = - *(IPeakFunction_const_sptr *)parameters; double y; diff --git a/Code/Mantid/Framework/API/src/PropertyNexus.cpp b/Code/Mantid/Framework/API/src/PropertyNexus.cpp index 1f2aac69306c..0290d469289b 100644 --- a/Code/Mantid/Framework/API/src/PropertyNexus.cpp +++ b/Code/Mantid/Framework/API/src/PropertyNexus.cpp @@ -193,7 +193,9 @@ Property *loadProperty(::NeXus::File *file, const std::string &group) { file->closeData(); file->closeGroup(); // add units - retVal->setUnits(unitsStr); + if (retVal) + retVal->setUnits(unitsStr); + return retVal; } diff --git a/Code/Mantid/Framework/API/src/ScriptBuilder.cpp b/Code/Mantid/Framework/API/src/ScriptBuilder.cpp index 259d2848ea8a..2171a29f2486 100644 --- a/Code/Mantid/Framework/API/src/ScriptBuilder.cpp +++ b/Code/Mantid/Framework/API/src/ScriptBuilder.cpp @@ -4,6 +4,8 @@ #include "MantidAPI/AlgorithmFactory.h" #include "MantidAPI/HistoryItem.h" #include "MantidAPI/ScriptBuilder.h" +#include "MantidKernel/Property.h" +#include "MantidKernel/Logger.h" #include @@ -13,6 +15,10 @@ namespace API { using Mantid::Kernel::PropertyHistory_sptr; using Mantid::Kernel::PropertyHistory_const_sptr; +namespace { +Mantid::Kernel::Logger g_log("ScriptBuilder"); +} + ScriptBuilder::ScriptBuilder(boost::shared_ptr view, std::string versionSpecificity) : m_historyItems(view->getAlgorithmsList()), m_output(), @@ -156,13 +162,31 @@ ScriptBuilder::buildAlgorithmString(AlgorithmHistory_const_sptr algHistory) { */ const std::string ScriptBuilder::buildPropertyString(PropertyHistory_const_sptr propHistory) { + using Mantid::Kernel::Direction; + + // Create a vector of all non workspace property type names + std::vector nonWorkspaceTypes; + nonWorkspaceTypes.push_back("number"); + nonWorkspaceTypes.push_back("boolean"); + nonWorkspaceTypes.push_back("string"); + std::string prop = ""; + // No need to specify value for default properties if (!propHistory->isDefault()) { - if (propHistory->type() == "number") { + // Do not give values to output properties other than workspace properties + if (find(nonWorkspaceTypes.begin(), nonWorkspaceTypes.end(), + propHistory->type()) != nonWorkspaceTypes.end() && + propHistory->direction() == Direction::Output) { + g_log.debug() << "Ignoring property " << propHistory->name() + << " of type " << propHistory->type() << std::endl; + // Handle numerical properties + } else if (propHistory->type() == "number") { prop = propHistory->name() + "=" + propHistory->value(); + // Handle boolean properties } else if (propHistory->type() == "boolean") { std::string value = (propHistory->value() == "1" ? "True" : "False"); prop = propHistory->name() + "=" + value; + // Handle all other property types } else { std::string opener = "='"; if (propHistory->value().find('\\') != std::string::npos) { diff --git a/Code/Mantid/Framework/API/test/MockObjects.h b/Code/Mantid/Framework/API/test/MockObjects.h index a87670dc88ec..591c063b6e13 100644 --- a/Code/Mantid/Framework/API/test/MockObjects.h +++ b/Code/Mantid/Framework/API/test/MockObjects.h @@ -103,9 +103,9 @@ namespace MOCK_METHOD0(findDetector, bool()); MOCK_METHOD2(setQSampleFrame, - void(Mantid::Kernel::V3D QSampleFrame, double detectorDistance)); + void(Mantid::Kernel::V3D QSampleFrame, boost::optional detectorDistance)); MOCK_METHOD2(setQLabFrame, - void(Mantid::Kernel::V3D QLabFrame, double detectorDistance)); + void(Mantid::Kernel::V3D QLabFrame, boost::optional detectorDistance)); MOCK_METHOD1(setWavelength, void(double wavelength)); MOCK_CONST_METHOD0(getWavelength, diff --git a/Code/Mantid/Framework/SINQ/test/PeakFunctionIntegratorTest.h b/Code/Mantid/Framework/API/test/PeakFunctionIntegratorTest.h similarity index 82% rename from Code/Mantid/Framework/SINQ/test/PeakFunctionIntegratorTest.h rename to Code/Mantid/Framework/API/test/PeakFunctionIntegratorTest.h index 59b641d58fb3..49c3be3b83e4 100644 --- a/Code/Mantid/Framework/SINQ/test/PeakFunctionIntegratorTest.h +++ b/Code/Mantid/Framework/API/test/PeakFunctionIntegratorTest.h @@ -2,14 +2,12 @@ #define PEAKFUNCTIONINTEGRATORTEST_H #include -#include "MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h" - -#include "MantidCurveFitting/Gaussian.h" -#include "MantidCurveFitting/Lorentzian.h" +#include "MantidAPI/PeakFunctionIntegrator.h" +#include "MantidAPI/FrameworkManager.h" +#include "MantidAPI/FunctionFactory.h" #include "gsl/gsl_errno.h" -using namespace Mantid::Poldi; using namespace Mantid::API; using namespace Mantid::CurveFitting; @@ -30,10 +28,15 @@ class TestablePeakFunctionIntegrator : public PeakFunctionIntegrator class PeakFunctionIntegratorTest : public CxxTest::TestSuite { private: + PeakFunctionIntegratorTest() + { + FrameworkManager::Instance(); + } + IPeakFunction_sptr getGaussian(double center, double fwhm, double height) { - IPeakFunction_sptr gaussian(new Gaussian); - gaussian->initialize(); + IPeakFunction_sptr gaussian = boost::dynamic_pointer_cast( + FunctionFactory::Instance().createFunction("Gaussian")); gaussian->setCentre(center); gaussian->setFwhm(fwhm); gaussian->setHeight(height); @@ -48,8 +51,8 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite IPeakFunction_sptr getLorentzian(double center, double fwhm, double height) { - IPeakFunction_sptr lorentzian(new Lorentzian); - lorentzian->initialize(); + IPeakFunction_sptr lorentzian = boost::dynamic_pointer_cast( + FunctionFactory::Instance().createFunction("Lorentzian")); lorentzian->setCentre(center); lorentzian->setFwhm(fwhm); lorentzian->setHeight(height); @@ -96,18 +99,7 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite { IPeakFunction_sptr gaussian = getGaussian(0.0, 1.0, 2.0); - TS_ASSERT_EQUALS(gsl_peak_wrapper(0.0, &gaussian), 2.0); - } - - void testNullPointer() - { - PeakFunctionIntegrator integrator; - - TS_ASSERT_THROWS(integrator.integrateInfinity(IPeakFunction_sptr()), std::invalid_argument); - TS_ASSERT_THROWS(integrator.integratePositiveInfinity(IPeakFunction_sptr(), 0.0), std::invalid_argument); - TS_ASSERT_THROWS(integrator.integrateNegativeInfinity(IPeakFunction_sptr(), 0.0), std::invalid_argument); - TS_ASSERT_THROWS(integrator.integrate(IPeakFunction_sptr(), 0.0, 0.0), std::invalid_argument); - + TS_ASSERT_EQUALS(gsl_peak_wrapper(0.0, &(*gaussian)), 2.0); } void testIntegrateInfinityGaussian() @@ -115,13 +107,13 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite IPeakFunction_sptr gaussian = getGaussian(0.0, 1.0, 1.0); PeakFunctionIntegrator integrator; - IntegrationResult result = integrator.integrateInfinity(gaussian); + IntegrationResult result = integrator.integrateInfinity(*gaussian); TS_ASSERT_EQUALS(result.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(result.result, getGaussianAnalyticalInfiniteIntegral(gaussian), integrator.requiredRelativePrecision()); TS_ASSERT_DELTA(result.error, 0.0, integrator.requiredRelativePrecision()); integrator.setRequiredRelativePrecision(1e-14); - IntegrationResult otherResult = integrator.integrateInfinity(gaussian); + IntegrationResult otherResult = integrator.integrateInfinity(*gaussian); TS_ASSERT_EQUALS(otherResult.errorCode, static_cast(GSL_EBADTOL)); TS_ASSERT_EQUALS(otherResult.result, 0.0); TS_ASSERT_EQUALS(otherResult.error, 0.0); @@ -131,7 +123,7 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite { IPeakFunction_sptr gaussian = getGaussian(0.0, 1.0, 1.0); PeakFunctionIntegrator integrator; - IntegrationResult result = integrator.integratePositiveInfinity(gaussian, 0.0); + IntegrationResult result = integrator.integratePositiveInfinity(*gaussian, 0.0); TS_ASSERT_EQUALS(result.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(result.result, getGaussianAnalyticalInfiniteIntegral(gaussian) / 2.0, integrator.requiredRelativePrecision()); @@ -141,7 +133,7 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite { IPeakFunction_sptr gaussian = getGaussian(0.0, 1.0, 1.0); PeakFunctionIntegrator integrator; - IntegrationResult result = integrator.integrateNegativeInfinity(gaussian, 0.0); + IntegrationResult result = integrator.integrateNegativeInfinity(*gaussian, 0.0); TS_ASSERT_EQUALS(result.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(result.result, getGaussianAnalyticalInfiniteIntegral(gaussian) / 2.0, integrator.requiredRelativePrecision()); @@ -158,15 +150,15 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite IPeakFunction_sptr gaussian = getGaussian(0.0, 2.0 * sqrt(2.0 * log(2.0)), 1.0 / sqrt(2.0 * M_PI)); PeakFunctionIntegrator integrator(1e-10); - IntegrationResult rOneSigma = integrator.integrate(gaussian, -1.0, 1.0); + IntegrationResult rOneSigma = integrator.integrate(*gaussian, -1.0, 1.0); TS_ASSERT_EQUALS(rOneSigma.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(rOneSigma.result, 0.682689492137086, integrator.requiredRelativePrecision()); - IntegrationResult rTwoSigma = integrator.integrate(gaussian, -2.0, 2.0); + IntegrationResult rTwoSigma = integrator.integrate(*gaussian, -2.0, 2.0); TS_ASSERT_EQUALS(rTwoSigma.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(rTwoSigma.result, 0.954499736103642, integrator.requiredRelativePrecision()); - IntegrationResult rThreeSigma = integrator.integrate(gaussian, -3.0, 3.0); + IntegrationResult rThreeSigma = integrator.integrate(*gaussian, -3.0, 3.0); TS_ASSERT_EQUALS(rThreeSigma.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(rThreeSigma.result, 0.997300203936740, integrator.requiredRelativePrecision()); } @@ -176,7 +168,7 @@ class PeakFunctionIntegratorTest : public CxxTest::TestSuite IPeakFunction_sptr lorentzian = getLorentzian(0.0, 3.0, 8.0); PeakFunctionIntegrator integrator(1e-8); - IntegrationResult result = integrator.integrateInfinity(lorentzian); + IntegrationResult result = integrator.integrateInfinity(*lorentzian); TS_ASSERT_EQUALS(result.errorCode, static_cast(GSL_SUCCESS)); TS_ASSERT_DELTA(result.result, getLorentzianAnalyticalInfiniteIntegral(lorentzian), integrator.requiredRelativePrecision()); TS_ASSERT_LESS_THAN(result.intervals, 1000); diff --git a/Code/Mantid/Framework/API/test/PeakTransformHKLTest.h b/Code/Mantid/Framework/API/test/PeakTransformHKLTest.h index f726f3355326..20a99d8feac7 100644 --- a/Code/Mantid/Framework/API/test/PeakTransformHKLTest.h +++ b/Code/Mantid/Framework/API/test/PeakTransformHKLTest.h @@ -10,6 +10,16 @@ using namespace Mantid::API; using Mantid::Kernel::V3D; using namespace testing; +namespace boost{ + template + std::basic_ostream& operator<<(std::basic_ostream& out, optional const& maybe) + { + if (maybe) + out << maybe; + return out; + } +} + class PeakTransformHKLTest : public CxxTest::TestSuite { public: diff --git a/Code/Mantid/Framework/API/test/PeakTransformQLabTest.h b/Code/Mantid/Framework/API/test/PeakTransformQLabTest.h index b3184387f832..849824ad26cc 100644 --- a/Code/Mantid/Framework/API/test/PeakTransformQLabTest.h +++ b/Code/Mantid/Framework/API/test/PeakTransformQLabTest.h @@ -11,6 +11,16 @@ using namespace Mantid; using Mantid::Kernel::V3D; using namespace testing; +namespace boost{ + template + std::basic_ostream& operator<<(std::basic_ostream& out, optional const& maybe) + { + if (maybe) + out << maybe; + return out; + } +} + class PeakTransformQLabTest : public CxxTest::TestSuite { diff --git a/Code/Mantid/Framework/API/test/PeakTransformQSampleTest.h b/Code/Mantid/Framework/API/test/PeakTransformQSampleTest.h index f3d01c140557..9e970ba1b51a 100644 --- a/Code/Mantid/Framework/API/test/PeakTransformQSampleTest.h +++ b/Code/Mantid/Framework/API/test/PeakTransformQSampleTest.h @@ -11,6 +11,17 @@ using namespace Mantid; using Mantid::Kernel::V3D; using namespace testing; + +namespace boost{ + template + std::basic_ostream& operator<<(std::basic_ostream& out, optional const& maybe) + { + if (maybe) + out << maybe; + return out; + } +} + class PeakTransformQSampleTest : public CxxTest::TestSuite { diff --git a/Code/Mantid/Framework/API/test/ScriptBuilderTest.h b/Code/Mantid/Framework/API/test/ScriptBuilderTest.h index 8bd1da860939..f413726083e7 100644 --- a/Code/Mantid/Framework/API/test/ScriptBuilderTest.h +++ b/Code/Mantid/Framework/API/test/ScriptBuilderTest.h @@ -27,7 +27,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite const std::string workspaceMethodName() const { return "methodname"; } const std::string workspaceMethodOnTypes() const { return "MatrixWorkspace;ITableWorkspace"; } const std::string workspaceMethodInputProperty() const { return "InputWorkspace"; } - + void init() { declareProperty("PropertyA", "Hello"); @@ -52,11 +52,12 @@ class ScriptBuilderTest : public CxxTest::TestSuite const std::string workspaceMethodName() const { return "methodname"; } const std::string workspaceMethodOnTypes() const { return "MatrixWorkspace;ITableWorkspace"; } const std::string workspaceMethodInputProperty() const { return "InputWorkspace"; } - + void init() { declareProperty("PropertyA", "Hello"); declareProperty("PropertyB", "World"); + declareProperty("PropertyC", "", Direction::Output); } void exec() { @@ -65,6 +66,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite alg->initialize(); alg->setProperty("PropertyA", "I Don't exist!"); alg->execute(); + setProperty("PropertyC", "I have been set!"); } }; @@ -81,7 +83,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite const std::string workspaceMethodName() const { return "methodname"; } const std::string workspaceMethodOnTypes() const { return "MatrixWorkspace;ITableWorkspace"; } const std::string workspaceMethodInputProperty() const { return "InputWorkspace"; } - + void init() { declareProperty("PropertyA", 13); @@ -115,7 +117,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite const std::string workspaceMethodName() const { return "methodname"; } const std::string workspaceMethodOnTypes() const { return "Workspace;MatrixWorkspace;ITableWorkspace"; } const std::string workspaceMethodInputProperty() const { return "InputWorkspace"; } - + void init() { declareProperty(new WorkspaceProperty("InputWorkspace", "", Direction::Input)); @@ -137,7 +139,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite }; private: - + public: void setUp() @@ -155,7 +157,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite Mantid::API::AlgorithmFactory::Instance().unsubscribe("BasicAlgorithm",1); Mantid::API::AlgorithmFactory::Instance().unsubscribe("SubAlgorithm",1); } - + void test_Build_Simple() { std::string result[] = { @@ -220,7 +222,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite alg->setRethrows(true); alg->setProperty("InputWorkspace", input); alg->setPropertyValue("OutputWorkspace", "test_output_workspace"); - alg->execute(); + alg->execute(); auto ws = AnalysisDataService::Instance().retrieveWS("test_output_workspace"); auto wsHist = ws->getHistory(); @@ -280,7 +282,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite alg->setProperty("InputWorkspace", "test_output_workspace"); alg->setPropertyValue("OutputWorkspace", "test_output_workspace"); alg->execute(); - + auto ws = AnalysisDataService::Instance().retrieveWS("test_output_workspace"); auto wsHist = ws->getHistory(); auto view = wsHist.createView(); @@ -305,7 +307,7 @@ class ScriptBuilderTest : public CxxTest::TestSuite AnalysisDataService::Instance().remove("test_input_workspace"); } - + void test_Build_Simple_with_backslash() { //checks that property values with \ get prefixed with r, eg. filename=r'c:\test\data.txt' diff --git a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h index e1dd2d90a01b..e10891b09dc7 100644 --- a/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h +++ b/Code/Mantid/Framework/Algorithms/inc/MantidAlgorithms/PlotAsymmetryByLogValue.h @@ -69,7 +69,6 @@ class DLLExport PlotAsymmetryByLogValue : public API::Algorithm { virtual const std::string summary() const { return "Calculates asymmetry for a series of log values"; } - /// Algorithm's version for identification overriding a virtual method virtual int version() const { return 1; } /// Algorithm's category for identification overriding a virtual method @@ -79,19 +78,24 @@ class DLLExport PlotAsymmetryByLogValue : public API::Algorithm { // Overridden Algorithm methods void init(); void exec(); - + // Parse run names + void parseRunNames (std::string& firstFN, std::string& lastFN, std::string& fnBase, std::string& fnExt); + // Load dead-time corrections from specified file + void loadCorrectionsFromFile (API::Workspace_sptr &customDeadTimes, std::string deadTimeFile ); + // Apply dead-time corrections + void applyDeadtimeCorr (API::Workspace_sptr &loadedWs, API::Workspace_sptr deadTimes); + /// Group detectors from run file + void groupDetectors (API::Workspace_sptr &loadedWs, API::Workspace_sptr loadedDetGrouping); /// Calculate the integral asymmetry for a workspace (single period) void calcIntAsymmetry(API::MatrixWorkspace_sptr ws, double &Y, double &E); - /// Calculate the integral asymmetry for a workspace (red & green) - void calcIntAsymmetry(API::MatrixWorkspace_sptr ws_red, - API::MatrixWorkspace_sptr ws_geen, double &Y, - double &E); + void calcIntAsymmetry(API::MatrixWorkspace_sptr ws_red, API::MatrixWorkspace_sptr ws_geen, double &Y, double &E); /// Group detectors - void groupDetectors(API::MatrixWorkspace_sptr &ws, - const std::vector &spectraList); + void groupDetectors (API::MatrixWorkspace_sptr &ws, const std::vector &spectraList); /// Get log value - double getLogValue(API::MatrixWorkspace &ws, const std::string &logName); + double getLogValue(API::MatrixWorkspace &ws); + /// Populate output workspace with results + void populateOutputWorkspace (API::MatrixWorkspace_sptr &outWS, int nplots); /// Stores property "Int" bool m_int; @@ -101,6 +105,19 @@ class DLLExport PlotAsymmetryByLogValue : public API::Algorithm { std::vector m_backward_list; /// If true call LoadMuonNexus with Autogroup on bool m_autogroup; + // Mantid vectors to store results + // Red mantid vectors + MantidVec m_redX, m_redY, m_redE; + // Green mantid vectors + MantidVec m_greenX, m_greenY, m_greenE; + // Mantid vectors to store Red + Green + MantidVec m_sumX, m_sumY, m_sumE; + // Mantid vectors to store Red - Green + MantidVec m_diffX, m_diffY, m_diffE; + // LogValue name + std::string m_logName; + // LogValue function + std::string m_logFunc; }; } // namespace Algorithm diff --git a/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp b/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp index afa69cc2d060..5b50cd0fd5ce 100644 --- a/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp +++ b/Code/Mantid/Framework/Algorithms/src/CreateGroupingWorkspace.cpp @@ -9,6 +9,7 @@ #include #include #include "MantidAPI/FileProperty.h" +#include "MantidKernel/BoundedValidator.h" #include "MantidKernel/ListValidator.h" namespace { @@ -92,9 +93,10 @@ void CreateGroupingWorkspace::init() { declareProperty("MaxRecursionDepth", 5, "Number of levels to search into the instrument (default=5)"); - declareProperty("FixedGroupCount", 0, "Used to distribute the detectors of a " - "given component into a fixed number " - "of groups"); + declareProperty("FixedGroupCount", 0, + boost::make_shared >(0, INT_MAX), + "Used to distribute the detectors of a given component into " + "a fixed number of groups"); declareProperty("ComponentName", "", "Specify the instrument component to " "group into a fixed number of groups"); @@ -169,12 +171,18 @@ void makeGroupingByNumGroups(const std::string compName, int numGroups, // Get detectors for given instument component std::vector detectors; inst->getDetectorsInBank(detectors, compName); + size_t numDetectors = detectors.size(); + + // Sanity check for following calculation + if(numGroups > static_cast(numDetectors)) + throw std::runtime_error("Number of groups must be less than or " + "equal to number of detectors"); // Calculate number of detectors per group - int detectorsPerGroup = static_cast(detectors.size()) / numGroups; + int detectorsPerGroup = static_cast(numDetectors) / numGroups; // Map detectors to group - for (unsigned int detIndex = 0; detIndex < detectors.size(); detIndex++) { + for (unsigned int detIndex = 0; detIndex < numDetectors; detIndex++) { int detectorID = detectors[detIndex]->getID(); int groupNum = (detIndex / detectorsPerGroup) + 1; diff --git a/Code/Mantid/Framework/Algorithms/src/CreateSampleWorkspace.cpp b/Code/Mantid/Framework/Algorithms/src/CreateSampleWorkspace.cpp index f04d8ac8bb3f..99496421e98c 100644 --- a/Code/Mantid/Framework/Algorithms/src/CreateSampleWorkspace.cpp +++ b/Code/Mantid/Framework/Algorithms/src/CreateSampleWorkspace.cpp @@ -396,7 +396,7 @@ Instrument_sptr CreateSampleWorkspace::createTestInstrumentRectangular( int num_banks, int pixels, double pixelSpacing) { boost::shared_ptr testInst(new Instrument("basic_rect")); testInst->setReferenceFrame( - boost::shared_ptr(new ReferenceFrame(Y, X, Left, ""))); + boost::shared_ptr(new ReferenceFrame(Y, Z, Left, ""))); const double cylRadius(pixelSpacing / 2); const double cylHeight(0.0002); diff --git a/Code/Mantid/Framework/Algorithms/src/CreateWorkspace.cpp b/Code/Mantid/Framework/Algorithms/src/CreateWorkspace.cpp index 34109440a281..de34cb087ff5 100644 --- a/Code/Mantid/Framework/Algorithms/src/CreateWorkspace.cpp +++ b/Code/Mantid/Framework/Algorithms/src/CreateWorkspace.cpp @@ -86,12 +86,23 @@ void CreateWorkspace::exec() { const Property *const dataXprop = getProperty("DataX"); const Property *const dataYprop = getProperty("DataY"); const Property *const dataEprop = getProperty("DataE"); - const std::vector &dataX = - *dynamic_cast *>(dataXprop); - const std::vector &dataY = - *dynamic_cast *>(dataYprop); - const std::vector &dataE = - *dynamic_cast *>(dataEprop); + + const ArrayProperty *pCheck = NULL; + + pCheck = dynamic_cast *>(dataXprop); + if (!pCheck) + throw std::invalid_argument("DataX cannot be casted to a double vector"); + const std::vector &dataX = *pCheck; + + pCheck = dynamic_cast *>(dataYprop); + if (!pCheck) + throw std::invalid_argument("DataY cannot be casted to a double vector"); + const std::vector &dataY = *pCheck; + + pCheck = dynamic_cast *>(dataEprop); + if (!pCheck) + throw std::invalid_argument("DataE cannot be casted to a double vector"); + const std::vector &dataE = *pCheck; const int nSpec = getProperty("NSpec"); const std::string xUnit = getProperty("UnitX"); diff --git a/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp b/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp index c5e4e660b520..dd1f338b860c 100644 --- a/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp +++ b/Code/Mantid/Framework/Algorithms/src/GenerateEventsFilter.cpp @@ -10,6 +10,7 @@ #include "MantidAPI/WorkspaceProperty.h" #include "MantidAPI/Column.h" #include "MantidKernel/VisibleWhenProperty.h" +#include "MantidKernel/ArrayProperty.h" using namespace Mantid; using namespace Mantid::Kernel; @@ -74,8 +75,14 @@ void GenerateEventsFilter::init() { "while the relative time takes integer or float. "); // Split by time (only) in steps - declareProperty("TimeInterval", EMPTY_DBL(), - "Length of the time splices if filtered in time only."); + declareProperty(new ArrayProperty("TimeInterval"), + "Array for lengths of time intervals for splitters. " + "If the array is empty, then there will be one splitter " + "created from StartTime and StopTime. " + "If the array has one value, then all splitters will have " + "same time intervals. " + "If the size of the array is larger than one, then the " + "splitters can have various time interval values."); setPropertySettings("TimeInterval", new VisibleWhenProperty("LogName", IS_EQUAL_TO, "")); @@ -113,16 +120,6 @@ void GenerateEventsFilter::init() { setPropertySettings("LogValueInterval", new VisibleWhenProperty("LogName", IS_NOT_EQUAL_TO, "")); - /* - Documentation doesn't include property options in property descriptions or - anywhere else. - For example, FilterLogValueByChangingDirection doesn't let me know that - Increasing and Decreasing - are valid options without using the MantidPlotGui to open the algorithm - dialog. - - */ - std::vector filteroptions; filteroptions.push_back("Both"); filteroptions.push_back("Increase"); @@ -379,10 +376,10 @@ void GenerateEventsFilter::processInputTime() { /** Set splitters by time value / interval only */ void GenerateEventsFilter::setFilterByTimeOnly() { - double timeinterval = this->getProperty("TimeInterval"); + vector vec_timeintervals = this->getProperty("TimeInterval"); bool singleslot = false; - if (timeinterval == EMPTY_DBL()) + if (vec_timeintervals.size() == 0) singleslot = true; // Progress @@ -401,7 +398,8 @@ void GenerateEventsFilter::setFilterByTimeOnly() { ss << "Time Interval From " << m_startTime << " to " << m_stopTime; addNewTimeFilterSplitter(m_startTime, m_stopTime, wsindex, ss.str()); - } else { + } else if (vec_timeintervals.size() == 1) { + double timeinterval = vec_timeintervals[0]; int64_t timeslot = 0; // Explicitly N time intervals @@ -439,6 +437,67 @@ void GenerateEventsFilter::setFilterByTimeOnly() { } } // END-WHILE } // END-IF-ELSE + else + { + // Explicitly N time intervals with various interval + + // Construct a vector for time intervals in nanosecond + size_t numtimeintervals = vec_timeintervals.size(); + std::vector vec_dtimens(numtimeintervals); + for (size_t id = 0; id < numtimeintervals; ++id) + { + int64_t deltatime_ns = + static_cast(vec_timeintervals[id] * m_timeUnitConvertFactorToNS); + vec_dtimens[id] = deltatime_ns; + } + + // Build the splitters + int64_t timeslot = 0; + + int64_t curtime_ns = m_startTime.totalNanoseconds(); + int wsindex = 0; + while (curtime_ns < m_stopTime.totalNanoseconds()) { + int64_t deltatime_ns; + for (size_t id = 0; id < numtimeintervals; ++id) + { + // get next time interval value + deltatime_ns = vec_dtimens[id]; + // Calculate next.time + int64_t nexttime_ns = curtime_ns + deltatime_ns; + bool breaklater = false; + if (nexttime_ns > m_stopTime.totalNanoseconds()) + { + nexttime_ns = m_stopTime.totalNanoseconds(); + breaklater = true; + } + + // Create splitter and information + Kernel::DateAndTime t0(curtime_ns); + Kernel::DateAndTime tf(nexttime_ns); + std::stringstream ss; + ss << "Time Interval From " << t0 << " to " << tf; + + addNewTimeFilterSplitter(t0, tf, wsindex, ss.str()); + + // Update loop variable + curtime_ns = nexttime_ns; + ++wsindex; + + // Update progress + int64_t newtimeslot = + (curtime_ns - m_startTime.totalNanoseconds()) * 90 / totaltime; + if (newtimeslot > timeslot) { + // There is change and update progress + timeslot = newtimeslot; + double prog = 0.1 + double(timeslot) / 100.0; + progress(prog); + } + + if (breaklater) + break; + } // END-FOR + } // END-WHILE + } return; } diff --git a/Code/Mantid/Framework/Algorithms/src/Integration.cpp b/Code/Mantid/Framework/Algorithms/src/Integration.cpp index 1cb9afa56820..03a00b76cde2 100644 --- a/Code/Mantid/Framework/Algorithms/src/Integration.cpp +++ b/Code/Mantid/Framework/Algorithms/src/Integration.cpp @@ -121,11 +121,13 @@ void Integration::exec() { if (axisIsText) { Mantid::API::TextAxis *newAxis = dynamic_cast(outputWorkspace->getAxis(1)); - newAxis->setLabel(outWI, localworkspace->getAxis(1)->label(i)); + if (newAxis) + newAxis->setLabel(outWI, localworkspace->getAxis(1)->label(i)); } else if (axisIsNumeric) { Mantid::API::NumericAxis *newAxis = dynamic_cast(outputWorkspace->getAxis(1)); - newAxis->setValue(outWI, (*(localworkspace->getAxis(1)))(i)); + if (newAxis) + newAxis->setValue(outWI, (*(localworkspace->getAxis(1)))(i)); } // This is the output diff --git a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index c9dfec93a203..260a5244b6e2 100644 --- a/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Code/Mantid/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -8,6 +8,7 @@ #include #include "MantidAPI/FileProperty.h" +#include #include "MantidAPI/Progress.h" #include "MantidAPI/ScopedWorkspace.h" #include "MantidAPI/TableRow.h" @@ -15,11 +16,13 @@ #include "MantidAPI/AlgorithmManager.h" #include "MantidAlgorithms/PlotAsymmetryByLogValue.h" #include "MantidDataObjects/Workspace2D.h" +#include "MantidDataObjects/TableWorkspace.h" #include "MantidKernel/ArrayProperty.h" #include "MantidKernel/ListValidator.h" #include "MantidKernel/MandatoryValidator.h" #include "MantidKernel/PropertyWithValue.h" #include "MantidKernel/TimeSeriesProperty.h" +#include "Poco/File.h" #include #include @@ -36,11 +39,21 @@ namespace // anonymous */ template bool convertLogToDouble(const Mantid::Kernel::Property *property, - double &value) { + double &value, const std::string& function) { const Mantid::Kernel::TimeSeriesProperty *log = dynamic_cast *>(property); if (log) { - value = static_cast(log->lastValue()); + if (function=="Mean") { + value = static_cast(log->timeAverageValue()); + } else if (function=="First") { + value = static_cast(log->firstValue()); + } else if (function=="Min") { + value = static_cast(log->minValue()); + } else if (function=="Max") { + value = static_cast(log->maxValue()); + } else { // Default + value = static_cast(log->lastValue()); + } return true; } auto tlog = @@ -82,6 +95,17 @@ void PlotAsymmetryByLogValue::init() { boost::make_shared>(), "The name of the log values which will be used as the x-axis " "in the output workspace."); + + std::vector optionsLog; + optionsLog.push_back("Mean"); + optionsLog.push_back("Min"); + optionsLog.push_back("Max"); + optionsLog.push_back("First"); + optionsLog.push_back("Last"); + declareProperty("Function", "Last", + boost::make_shared(optionsLog), + "The function to apply: 'Mean', 'Min', 'Max', 'First' or 'Last'."); + declareProperty("Red", 1, "The period number for the 'red' data."); declareProperty("Green", EMPTY_INT(), "The period number for the 'green' data."); @@ -92,7 +116,6 @@ void PlotAsymmetryByLogValue::init() { declareProperty("Type", "Integral", boost::make_shared(options), "The calculation type: 'Integral' or 'Differential'."); - declareProperty( "TimeMin", EMPTY_DBL(), "The beginning of the time interval used in the calculations."); @@ -130,232 +153,340 @@ void PlotAsymmetryByLogValue::init() { * Executes the algorithm */ void PlotAsymmetryByLogValue::exec() { + + // Get properties + // Get grouping property m_forward_list = getProperty("ForwardSpectra"); m_backward_list = getProperty("BackwardSpectra"); m_autogroup = (m_forward_list.size() == 0 && m_backward_list.size() == 0); - - std::string logName = getProperty("LogValue"); - + // Get log value + m_logName = getPropertyValue("LogValue"); + // Get green and red periods int red = getProperty("Red"); int green = getProperty("Green"); - + // Get type of computation std::string stype = getProperty("Type"); m_int = stype == "Integral"; - + // Get type of dead-time corrections + const std::string dtcType = getPropertyValue("DeadTimeCorrType"); + // Get runs std::string firstFN = getProperty("FirstRun"); std::string lastFN = getProperty("LastRun"); + // Get function to apply to logValue + m_logFunc = getPropertyValue("Function"); - std::string ext = firstFN.substr(firstFN.find_last_of(".")); - - firstFN.erase(firstFN.size() - 4); - lastFN.erase(lastFN.size() - 4); - - std::string fnBase = firstFN; - size_t i = fnBase.size() - 1; - while (isdigit(fnBase[i])) - i--; - if (i == fnBase.size() - 1) { - g_log.error("File name must end with a number."); - throw Exception::FileError("File name must end with a number.", firstFN); - } - fnBase.erase(i + 1); - - firstFN.erase(0, fnBase.size()); - lastFN.erase(0, fnBase.size()); - + // Parse run names and get the number of runs + std::string fnBase, fnExt; + parseRunNames( firstFN, lastFN, fnBase, fnExt); size_t is = atoi(firstFN.c_str()); // starting run number size_t ie = atoi(lastFN.c_str()); // last run number int w = static_cast(firstFN.size()); - // The number of runs - size_t npoints = ie - is + 1; - - // Create the 2D workspace for the output - int nplots = green != EMPTY_INT() ? 4 : 1; - MatrixWorkspace_sptr outWS = WorkspaceFactory::Instance().create( - "Workspace2D", - nplots, // the number of plots - npoints, // the number of data points on a plot - npoints // it's not a histogram - ); - TextAxis *tAxis = new TextAxis(nplots); - if (nplots == 1) { - tAxis->setLabel(0, "Asymmetry"); - } else { - tAxis->setLabel(0, "Red-Green"); - tAxis->setLabel(1, "Red"); - tAxis->setLabel(2, "Green"); - tAxis->setLabel(3, "Red+Green"); - } - outWS->replaceAxis(1, tAxis); - - const std::string dtcType = getPropertyValue("DeadTimeCorrType"); + // Dead-time corrections: if user specifies a file, load corrections now Workspace_sptr customDeadTimes; - if (dtcType == "FromSpecifiedFile") { - IAlgorithm_sptr loadDeadTimes = createChildAlgorithm("LoadNexusProcessed"); - loadDeadTimes->initialize(); - loadDeadTimes->setPropertyValue("Filename", - getPropertyValue("DeadTimeCorrFile")); - loadDeadTimes->execute(); - - customDeadTimes = loadDeadTimes->getProperty("OutputWorkspace"); + loadCorrectionsFromFile (customDeadTimes, getPropertyValue("DeadTimeCorrFile")); } Progress progress(this, 0, 1, ie - is + 2); + + // Loop through runs for (size_t i = is; i <= ie; i++) { + + // Get complete run name std::ostringstream fn, fnn; fnn << std::setw(w) << std::setfill('0') << i; - fn << fnBase << fnn.str() << ext; + fn << fnBase << fnn.str() << fnExt; + // Load run IAlgorithm_sptr load = createChildAlgorithm("LoadMuonNexus"); - load->initialize(); load->setPropertyValue("Filename", fn.str()); load->execute(); - Workspace_sptr loadedWs = load->getProperty("OutputWorkspace"); + // Check if dead-time corrections have to be applied if (dtcType != "None") { - IAlgorithm_sptr applyCorr = - AlgorithmManager::Instance().create("ApplyDeadTimeCorr"); - applyCorr->setLogging(false); - applyCorr->setRethrows(true); - - ScopedWorkspace ws(loadedWs); - applyCorr->setPropertyValue("InputWorkspace", ws.name()); - applyCorr->setPropertyValue("OutputWorkspace", ws.name()); - - ScopedWorkspace deadTimes; - if (dtcType == "FromSpecifiedFile") { - deadTimes.set(customDeadTimes); + applyDeadtimeCorr (loadedWs, customDeadTimes); } else { - deadTimes.set(load->getProperty("DeadTimeTable")); + Workspace_sptr deadTimes = load->getProperty("DeadTimeTable"); + applyDeadtimeCorr (loadedWs, deadTimes); } - - applyCorr->setPropertyValue("DeadTimeTable", deadTimes.name()); - applyCorr->execute(); - - // Workspace should've been replaced in the ADS by ApplyDeadTimeCorr, so - // need to - // re-assign it - loadedWs = ws.retrieve(); } + // If m_autogroup, group detectors if (m_autogroup) { - Workspace_sptr loadedDetGrouping = - load->getProperty("DetectorGroupingTable"); - + Workspace_sptr loadedDetGrouping = load->getProperty("DetectorGroupingTable"); if (!loadedDetGrouping) throw std::runtime_error("No grouping info in the file.\n\nPlease " "specify grouping manually"); - - // Could be groups of workspaces, so need to work with ADS - ScopedWorkspace inWS(loadedWs); - ScopedWorkspace grouping(loadedDetGrouping); - ScopedWorkspace outWS; - - try { - IAlgorithm_sptr applyGrouping = - AlgorithmManager::Instance().create("MuonGroupDetectors"); - applyGrouping->setLogging(false); - applyGrouping->setRethrows(true); - - applyGrouping->setPropertyValue("InputWorkspace", inWS.name()); - applyGrouping->setPropertyValue("DetectorGroupingTable", - grouping.name()); - applyGrouping->setPropertyValue("OutputWorkspace", outWS.name()); - applyGrouping->execute(); - - loadedWs = outWS.retrieve(); - } catch (...) { - throw std::runtime_error( - "Unable to group detectors.\n\nPlease specify grouping manually."); - } + groupDetectors(loadedWs,loadedDetGrouping); } + // Check if workspace is a workspace group WorkspaceGroup_sptr loadedGroup = boost::dynamic_pointer_cast(loadedWs); + // If it is not, we only have 'red' data if (!loadedGroup) { Workspace2D_sptr loadedWs2D = boost::dynamic_pointer_cast(loadedWs); double Y, E; calcIntAsymmetry(loadedWs2D, Y, E); - outWS->dataY(0)[i - is] = Y; - outWS->dataX(0)[i - is] = getLogValue(*loadedWs2D, logName); - outWS->dataE(0)[i - is] = E; + m_redX.push_back(getLogValue(*loadedWs2D)); + m_redY.push_back(Y); + m_redE.push_back(E); + } else { + DataObjects::Workspace2D_sptr ws_red; DataObjects::Workspace2D_sptr ws_green; - - // Run through the periods of the loaded file and do calculations on the + // Run through the periods of the loaded file and save the // selected ones for (int mi = 0; mi < loadedGroup->getNumberOfEntries(); mi++) { + Workspace2D_sptr memberWs = boost::dynamic_pointer_cast(loadedGroup->getItem(mi)); - int period = mi + 1; - - // Do only one period - if (green == EMPTY_INT() && period == red) { + if ( period == red ){ ws_red = memberWs; - double Y, E; - calcIntAsymmetry(ws_red, Y, E); - outWS->dataY(0)[i - is] = Y; - outWS->dataX(0)[i - is] = getLogValue(*ws_red, logName); - outWS->dataE(0)[i - is] = E; - } else // red & green - { - if (period == red) - ws_red = memberWs; - if (period == green) + } + if ( green!= EMPTY_INT() ){ + if ( period == green ){ ws_green = memberWs; + } } } - // red & green claculation - if (green != EMPTY_INT()) { - if (!ws_red || !ws_green) - throw std::invalid_argument("Red or green period is out of range"); + // Check ws_red + if (!ws_red){ + throw std::invalid_argument("Red period is out of range"); + } + // Check ws_green + if ( (green!=EMPTY_INT()) && (!ws_green) ){ + throw std::invalid_argument("Green period is out of range"); + } + + if ( green==EMPTY_INT() ){ double Y, E; - double Y1, E1; - double logValue = getLogValue(*ws_red, logName); calcIntAsymmetry(ws_red, Y, E); - calcIntAsymmetry(ws_green, Y1, E1); - outWS->dataY(1)[i - is] = Y; - outWS->dataX(1)[i - is] = logValue; - outWS->dataE(1)[i - is] = E; - - outWS->dataY(2)[i - is] = Y1; - outWS->dataX(2)[i - is] = logValue; - outWS->dataE(2)[i - is] = E1; - - outWS->dataY(3)[i - is] = Y + Y1; - outWS->dataX(3)[i - is] = logValue; - outWS->dataE(3)[i - is] = sqrt(E * E + E1 * E1); - + m_redX.push_back(getLogValue(*ws_red)); + m_redY.push_back(Y); + m_redE.push_back(E); + + } else{ + + double YR, ER; + double YG, EG; + double logValue = getLogValue(*ws_red); + calcIntAsymmetry(ws_red, YR, ER); + calcIntAsymmetry(ws_green, YG, EG); + // Red data + m_redX.push_back(logValue); + m_redY.push_back(YR); + m_redE.push_back(ER); + // Green data + m_greenX.push_back(logValue); + m_greenY.push_back(YG); + m_greenE.push_back(EG); + // Sum + m_sumX.push_back(logValue); + m_sumY.push_back(YR+YG); + m_sumE.push_back(sqrt(ER * ER + EG * EG)); // move to last for safety since some grouping takes place in the // calcIntAsymmetry call below - calcIntAsymmetry(ws_red, ws_green, Y, E); - outWS->dataY(0)[i - is] = Y; - outWS->dataX(0)[i - is] = logValue; - outWS->dataE(0)[i - is] = E; - } else if (!ws_red) - throw std::invalid_argument("Red period is out of range"); - } + calcIntAsymmetry(ws_red, ws_green, YR, ER); + m_diffX.push_back(logValue); + m_diffY.push_back(YR); + m_diffE.push_back(ER); + } + } // else loadedGroup progress.report(); } - outWS->getAxis(0)->title() = logName; - outWS->setYUnitLabel("Asymmetry"); + // Create the 2D workspace for the output + int nplots = m_greenX.size() ? 4 : 1; + size_t npoints = ie - is + 1; + MatrixWorkspace_sptr outWS = WorkspaceFactory::Instance().create( + "Workspace2D", + nplots, // the number of plots + npoints, // the number of data points on a plot + npoints // it's not a histogram + ); + // Populate output workspace with data + populateOutputWorkspace(outWS,nplots); // Assign the result to the output workspace property setProperty("OutputWorkspace", outWS); } +/** Load dead-time corrections from specified file +* @param customDeadTimes :: [input/output] Output workspace to store corrections +* @param deadTimeFile :: [input] File to read corrections from +*/ +void PlotAsymmetryByLogValue::loadCorrectionsFromFile (Workspace_sptr &customDeadTimes, std::string deadTimeFile ) +{ + IAlgorithm_sptr loadDeadTimes = createChildAlgorithm("LoadNexusProcessed"); + loadDeadTimes->setPropertyValue("Filename", deadTimeFile); + loadDeadTimes->setProperty("OutputWorkspace", customDeadTimes); + loadDeadTimes->executeAsChildAlg(); + customDeadTimes = loadDeadTimes->getProperty("OutputWorkspace"); +} +/** Populate output workspace with results +* @param outWS :: [input/output] Output workspace to populate +* @param nplots :: [input] Number of histograms +*/ +void PlotAsymmetryByLogValue::populateOutputWorkspace (MatrixWorkspace_sptr &outWS, int nplots) +{ + TextAxis *tAxis = new TextAxis(nplots); + if (nplots == 1) { + tAxis->setLabel(0, "Asymmetry"); + outWS->dataX(0) = m_redX; + outWS->dataY(0) = m_redY; + outWS->dataE(0) = m_redE; + } else { + tAxis->setLabel(0, "Red-Green"); + tAxis->setLabel(1, "Red"); + tAxis->setLabel(2, "Green"); + tAxis->setLabel(3, "Red+Green"); + outWS->dataX(0) = m_diffX; + outWS->dataY(0) = m_diffY; + outWS->dataE(0) = m_diffE; + outWS->dataX(1) = m_redX; + outWS->dataY(1) = m_redY; + outWS->dataE(1) = m_redE; + outWS->dataX(2) = m_greenX; + outWS->dataY(2) = m_greenY; + outWS->dataE(2) = m_greenE; + outWS->dataX(3) = m_sumX; + outWS->dataY(3) = m_sumY; + outWS->dataE(3) = m_sumE; + } + outWS->replaceAxis(1, tAxis); + outWS->getAxis(0)->title() = m_logName; + outWS->setYUnitLabel("Asymmetry"); +} +/** Parse run names +* @param firstFN :: [input/output] First run's name +* @param lastFN :: [input/output] Last run's name +* @param fnBase :: [output] Runs base name +* @param fnExt :: [output] Runs extension +*/ +void PlotAsymmetryByLogValue::parseRunNames (std::string& firstFN, std::string& lastFN, std::string& fnBase, std::string& fnExt) +{ + + // Parse first run's name + std::string firstExt = firstFN.substr(firstFN.find_last_of(".")); + firstFN.erase(firstFN.size() - 4); + + std::string firstBase = firstFN; + size_t i = firstBase.size() - 1; + while (isdigit(firstBase[i])) + i--; + if (i == firstBase.size() - 1) { + throw Exception::FileError("File name must end with a number.", firstFN); + } + firstBase.erase(i + 1); + firstFN.erase(0, firstBase.size()); + + // Parse last run's name + std::string lastExt = lastFN.substr(lastFN.find_last_of(".")); + lastFN.erase(lastFN.size() - 4); + + std::string lastBase = lastFN; + i = lastBase.size() - 1; + while (isdigit(lastBase[i])) + i--; + if (i == lastBase.size() - 1) { + throw Exception::FileError("File name must end with a number.", lastFN); + } + lastBase.erase(i + 1); + lastFN.erase(0, lastBase.size()); + + // Compare first and last + if ( firstBase != lastBase ) { + // Runs are not in the same directory + + // First run number with last base name + std::ostringstream tempFirst; + tempFirst << lastBase << firstFN << firstExt << std::endl; + std::string pathFirst = FileFinder::Instance().getFullPath(tempFirst.str()); + // Last run number with first base name + std::ostringstream tempLast; + tempLast << firstBase << lastFN << lastExt << std::endl; + std::string pathLast = FileFinder::Instance().getFullPath(tempLast.str()); + + // Try to correct this on the fly by + // checking if the last run can be found in the first directory... + if ( Poco::File(pathLast).exists() ) { + fnBase = firstBase; + fnExt = firstExt; + g_log.warning() << "First and last run are not in the same directory. File " + << pathLast << " will be used instead." << std::endl; + } else if (Poco::File(pathFirst).exists()) { + // ...or viceversa + fnBase = lastBase; + fnExt = lastExt; + g_log.warning() << "First and last run are not in the same directory. File " + << pathFirst << " will be used instead." << std::endl; + } else { + throw std::runtime_error("First and last runs are not in the same directory."); + } + + } else { + + fnBase = firstBase; + fnExt = firstExt; + } +} + +/** Apply dead-time corrections. The calculation is done by ApplyDeadTimeCorr algorithm +* @param loadedWs :: [input/output] Workspace to apply corrections to +* @param deadTimes :: [input] Corrections to apply +*/ +void PlotAsymmetryByLogValue::applyDeadtimeCorr (Workspace_sptr &loadedWs, Workspace_sptr deadTimes) +{ + ScopedWorkspace ws(loadedWs); + ScopedWorkspace dt(deadTimes); + + IAlgorithm_sptr applyCorr = AlgorithmManager::Instance().create("ApplyDeadTimeCorr"); + applyCorr->setLogging(false); + applyCorr->setRethrows(true); + applyCorr->setPropertyValue("InputWorkspace", ws.name()); + applyCorr->setPropertyValue("OutputWorkspace", ws.name()); + applyCorr->setProperty("DeadTimeTable", dt.name()); + applyCorr->execute(); + // Workspace should've been replaced in the ADS by ApplyDeadTimeCorr, so + // need to + // re-assign it + loadedWs = ws.retrieve(); +} + +/** Group detectors from specified file +* @param loadedWs :: [input/output] Workspace to apply grouping to +* @param loadedDetGrouping :: [input] Workspace storing detectors grouping +*/ +void PlotAsymmetryByLogValue::groupDetectors (Workspace_sptr &loadedWs, Workspace_sptr loadedDetGrouping) +{ + + // Could be groups of workspaces, so need to work with ADS + ScopedWorkspace inWS(loadedWs); + ScopedWorkspace grouping(loadedDetGrouping); + ScopedWorkspace outWS; + + IAlgorithm_sptr applyGrouping = AlgorithmManager::Instance().create("MuonGroupDetectors"); + applyGrouping->setLogging(false); + applyGrouping->setRethrows(true); + + applyGrouping->setPropertyValue("InputWorkspace", inWS.name()); + applyGrouping->setPropertyValue("DetectorGroupingTable", grouping.name()); + applyGrouping->setPropertyValue("OutputWorkspace", outWS.name()); + applyGrouping->execute(); + + loadedWs = outWS.retrieve(); +} /** Calculate the integral asymmetry for a workspace. * The calculation is done by MuonAsymmetryCalc and SimpleIntegration * algorithms. @@ -539,35 +670,32 @@ PlotAsymmetryByLogValue::groupDetectors(API::MatrixWorkspace_sptr &ws, * Get log value from a workspace. Convert to double if possible. * * @param ws :: The input workspace. - * @param logName :: Name of the log file. * @return :: Log value. * @throw :: std::invalid_argument if the log cannot be converted to a double or *doesn't exist. */ -double PlotAsymmetryByLogValue::getLogValue(MatrixWorkspace &ws, - const std::string &logName) { - auto *property = ws.run().getLogData(logName); +double PlotAsymmetryByLogValue::getLogValue(MatrixWorkspace &ws) { + auto *property = ws.run().getLogData(m_logName); if (!property) { - throw std::invalid_argument("Log " + logName + " does not exist."); + throw std::invalid_argument("Log " + m_logName + " does not exist."); } - double value = 0; // try different property types - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; - if (convertLogToDouble(property, value)) + if (convertLogToDouble(property, value, m_logFunc)) return value; // try if it's a string and can be lexically cast to double auto slog = @@ -582,8 +710,11 @@ double PlotAsymmetryByLogValue::getLogValue(MatrixWorkspace &ws, } } - throw std::invalid_argument("Log " + logName + + throw std::invalid_argument("Log " + m_logName + " cannot be converted to a double type."); } + + + } // namespace Algorithm } // namespace Mantid diff --git a/Code/Mantid/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp b/Code/Mantid/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp index bd062648c9c4..6b2cb131d0ce 100644 --- a/Code/Mantid/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp +++ b/Code/Mantid/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp @@ -3,14 +3,10 @@ //---------------------------------------------------------------------- #include "MantidAlgorithms/TOFSANSResolutionByPixel.h" #include "MantidAPI/WorkspaceValidators.h" -#include "MantidDataObjects/EventWorkspace.h" -#include "MantidDataObjects/EventList.h" #include "MantidDataObjects/Workspace2D.h" -#include "MantidKernel/RebinParamsValidator.h" #include "MantidKernel/ArrayProperty.h" -#include "MantidKernel/VectorHelper.h" -#include "MantidKernel/Interpolation.h" #include "MantidKernel/BoundedValidator.h" +#include "MantidKernel/Interpolation.h" #include "boost/math/special_functions/fpclassify.hpp" @@ -28,7 +24,7 @@ using namespace DataObjects; void TOFSANSResolutionByPixel::init() { declareProperty(new WorkspaceProperty<>( - "InputWorkspace", "", Direction::InOut, + "Workspace", "", Direction::InOut, boost::make_shared("Wavelength")), "Name the workspace to calculate the resolution for, for " "each pixel and wavelenght"); @@ -55,7 +51,7 @@ double TOFSANSResolutionByPixel::getTOFResolution(double wl) { } void TOFSANSResolutionByPixel::exec() { - MatrixWorkspace_sptr inOutWS = getProperty("InputWorkspace"); + MatrixWorkspace_sptr inOutWS = getProperty("Workspace"); double deltaR = getProperty("DeltaR"); double R1 = getProperty("SourceApertureRadius"); double R2 = getProperty("SampleApertureRadius"); @@ -99,9 +95,7 @@ void TOFSANSResolutionByPixel::exec() { const int numberOfSpectra = static_cast(inOutWS->getNumberHistograms()); Progress progress(this, 0.0, 1.0, numberOfSpectra); - // PARALLEL_FOR1(inOutWS) for (int i = 0; i < numberOfSpectra; i++) { - // PARALLEL_START_INTERUPT_REGION IDetector_const_sptr det; try { det = inOutWS->getDetector(i); @@ -109,11 +103,6 @@ void TOFSANSResolutionByPixel::exec() { g_log.information() << "Spectrum index " << i << " has no detector assigned to it - discarding" << std::endl; - // Catch if no detector. Next line tests whether this happened - test - // placed - // outside here because Mac Intel compiler doesn't like 'continue' in a - // catch - // in an openmp block. } // If no detector found or if it's masked or a monitor, skip onto the next // spectrum @@ -168,7 +157,6 @@ void TOFSANSResolutionByPixel::exec() { } progress.report("Computing Q resolution"); - // PARALLEL_END_INTERUPT_REGION } } } // namespace Algorithms diff --git a/Code/Mantid/Framework/Algorithms/test/CreateGroupingWorkspaceTest.h b/Code/Mantid/Framework/Algorithms/test/CreateGroupingWorkspaceTest.h index 1c6da9d70818..b1269a78fcf5 100644 --- a/Code/Mantid/Framework/Algorithms/test/CreateGroupingWorkspaceTest.h +++ b/Code/Mantid/Framework/Algorithms/test/CreateGroupingWorkspaceTest.h @@ -174,6 +174,26 @@ class CreateGroupingWorkspaceTest : public CxxTest::TestSuite AnalysisDataService::Instance().remove(outWSName); } + void test_exec_WithFixedGroups_FailOnGroupsGreaterThanDet() + { + // Name of the output workspace. + std::string outWSName("CreateGroupingWorkspaceTest_OutputWS_fail"); + + CreateGroupingWorkspace alg; + TS_ASSERT_THROWS_NOTHING( alg.initialize() ) + TS_ASSERT( alg.isInitialized() ) + TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("InstrumentName", "IRIS") ); + TS_ASSERT_THROWS_NOTHING( alg.setProperty("FixedGroupCount", 52) ); + TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("ComponentName", "graphite") ); + TS_ASSERT_THROWS_NOTHING( alg.setPropertyValue("OutputWorkspace", outWSName) ); + TS_ASSERT_THROWS_NOTHING( alg.execute() ); + + // Should fail as IRIS graphite component has only 51 spectra + TS_ASSERT( !alg.isExecuted() ); + + AnalysisDataService::Instance().remove(outWSName); + } + }; diff --git a/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h b/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h index 33816f2d7cdf..e9715535e5cb 100644 --- a/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h +++ b/Code/Mantid/Framework/Algorithms/test/GenerateEventsFilterTest.h @@ -123,7 +123,7 @@ class GenerateEventsFilterTest : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING(alg.setProperty("InputWorkspace", eventWS)); TS_ASSERT_THROWS_NOTHING(alg.setProperty("OutputWorkspace", "Splitters01")); TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("InformationWorkspace", "InfoWS");) - TS_ASSERT_THROWS_NOTHING(alg.setProperty("TimeInterval", 15000.0)); + TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("TimeInterval", "15000.0")); TS_ASSERT_THROWS_NOTHING(alg.setProperty("UnitOfTime", "Nanoseconds")); // 3. Running and get result @@ -597,7 +597,7 @@ class GenerateEventsFilterTest : public CxxTest::TestSuite TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("OutputWorkspace", "Splitters08")); TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("InformationWorkspace", "InfoWS08")); TS_ASSERT_THROWS_NOTHING(alg.setProperty("FastLog", true)); - TS_ASSERT_THROWS_NOTHING(alg.setProperty("TimeInterval", 15000.0)); + TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("TimeInterval", "15000.0")); TS_ASSERT_THROWS_NOTHING(alg.setProperty("UnitOfTime", "Nanoseconds")); // Running and get result @@ -941,6 +941,79 @@ class GenerateEventsFilterTest : public CxxTest::TestSuite } + //---------------------------------------------------------------------------------------------- + /** Test generation of splitters by various time intervals + * (1) Multiple time interval with various time interval lengths + * (2) Default start time and stop time + */ + void test_genTimeVariousIntervalMatrixSplitter() + { + // Create input Workspace & initial setup + DataObjects::EventWorkspace_sptr eventWS = createEventWorkspace(); + AnalysisDataService::Instance().addOrReplace("TestEventWorkspace08v", eventWS); + int64_t timeinterval_ns = 15000; + + // Init and set property + GenerateEventsFilter alg; + alg.initialize(); + + std::vector vectimeintervals; + vectimeintervals.push_back(static_cast(timeinterval_ns)); + vectimeintervals.push_back(static_cast(timeinterval_ns)*2.); + vectimeintervals.push_back(static_cast(timeinterval_ns)*3.); + TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("InputWorkspace", "TestEventWorkspace08v")); + TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("OutputWorkspace", "Splitters08v")); + TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("InformationWorkspace", "InfoWS08v")); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("FastLog", true)); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("TimeInterval", vectimeintervals)); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("UnitOfTime", "Nanoseconds")); + + // Running and get result + TS_ASSERT_THROWS_NOTHING(alg.execute()); + TS_ASSERT(alg.isExecuted()); + + // Check output workspace + API::MatrixWorkspace_sptr splittersws = + boost::dynamic_pointer_cast(AnalysisDataService::Instance().retrieve("Splitters08v")); + + TS_ASSERT(splittersws); + + // Check values of output workspace + size_t numintervals = 38; + TS_ASSERT_EQUALS(splittersws->readY(0).size(), numintervals); + + std::string runstarttimestr = eventWS->run().getProperty("run_start")->value(); + Kernel::DateAndTime runstarttime(runstarttimestr); + int64_t runstarttime_ns = runstarttime.totalNanoseconds(); + + Kernel::TimeSeriesProperty *protonchargelog = + dynamic_cast* >(eventWS->run().getProperty("proton_charge")); + Kernel::DateAndTime runstoptime = Kernel::DateAndTime(protonchargelog->lastTime().totalNanoseconds() + 100000); + + // First 3 intervals + TS_ASSERT_EQUALS(static_cast(splittersws->readX(0)[0]), runstarttime_ns); + TS_ASSERT_EQUALS(static_cast(splittersws->readX(0)[1]), runstarttime_ns + timeinterval_ns); + TS_ASSERT_EQUALS(static_cast(splittersws->readY(0)[0]), 0); + + TS_ASSERT_EQUALS(static_cast(splittersws->readX(0)[2]), runstarttime_ns + timeinterval_ns*3); + TS_ASSERT_EQUALS(static_cast(splittersws->readY(0)[1]), 1); + + TS_ASSERT_EQUALS(static_cast(splittersws->readX(0)[3]), runstarttime_ns + timeinterval_ns*6); + TS_ASSERT_EQUALS(static_cast(splittersws->readY(0)[2]), 2); + + // Last interval + TS_ASSERT_EQUALS(static_cast(splittersws->readX(0).back()), runstoptime.totalNanoseconds()); + TS_ASSERT_EQUALS(static_cast(splittersws->readY(0).back()), numintervals-1); + + // Clean + AnalysisDataService::Instance().remove("Splitters08v"); + AnalysisDataService::Instance().remove("InfoWS08v"); + AnalysisDataService::Instance().remove("TestEventWorkspace08v"); + + return; + } + + //---------------------------------------------------------------------------------------------- /** Convert the splitters stored in a matrix workspace to a vector of SplittingInterval objects */ diff --git a/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h b/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h index e6bed858dac2..2ec9773aeab6 100644 --- a/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h +++ b/Code/Mantid/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h @@ -254,6 +254,44 @@ class PlotAsymmetryByLogValueTest : public CxxTest::TestSuite AnalysisDataService::Instance().remove(ws); } + void test_LogValueFunction () + { + const std::string ws = "Test_LogValueFunction"; + + PlotAsymmetryByLogValue alg; + + TS_ASSERT_THROWS_NOTHING(alg.initialize()); + + alg.setPropertyValue("FirstRun", firstRun); + alg.setPropertyValue("LastRun", lastRun); + alg.setPropertyValue("OutputWorkspace", ws); + // We use 'beamlog_current' as log value because + // we want to test the 'Mean' function below and this is + // one of the few properties that contains different values over time + alg.setPropertyValue("LogValue","beamlog_current"); + alg.setPropertyValue("Function","Mean"); + alg.setPropertyValue("DeadTimeCorrType","None"); + + TS_ASSERT_THROWS_NOTHING(alg.execute()); + TS_ASSERT(alg.isExecuted()); + + MatrixWorkspace_sptr outWs = boost::dynamic_pointer_cast( + AnalysisDataService::Instance().retrieve(ws)); + + TS_ASSERT(outWs); + TS_ASSERT_EQUALS(outWs->blocksize(), 2); + TS_ASSERT_EQUALS(outWs->getNumberHistograms(),1); + + // Now we want to test X values (log values) in the output workspace + // rather than asymmetry (Y values) + const Mantid::MantidVec& X = outWs->readX(0); + + TS_ASSERT_DELTA(X[0], 179.078620, 0.00001); + TS_ASSERT_DELTA(X[1], 178.849998, 0.00001); + + AnalysisDataService::Instance().remove(ws); + } + private: std::string firstRun,lastRun; diff --git a/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h b/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h index 078029a8e1f2..c8a27eb888e3 100644 --- a/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h +++ b/Code/Mantid/Framework/Algorithms/test/RemoveExpDecayTest.h @@ -3,124 +3,69 @@ #include -#include "MantidAPI/AnalysisDataService.h" -#include "MantidAPI/Workspace.h" #include "MantidAlgorithms/RemoveExpDecay.h" -#include "MantidDataHandling/LoadInstrument.h" -#include "MantidDataHandling/LoadMuonNexus2.h" -#include "MantidDataObjects/Workspace2D.h" #include "MantidTestHelpers/WorkspaceCreationHelper.h" -#include - using namespace Mantid::Algorithms; using namespace Mantid::API; +const std::string outputName = "MuonRemoveExpDecay_Output"; + class RemoveExpDecayTest : public CxxTest::TestSuite { public: - void testName() - { - TS_ASSERT_EQUALS( alg.name(), "RemoveExpDecay" ) - } - - void testCategory() - { - TS_ASSERT_EQUALS( alg.category(), "Muon" ) - } - void testInit() { + MuonRemoveExpDecay alg; alg.initialize(); - TS_ASSERT( alg.isInitialized() ) - } - - void testLoadNexusAndSetProperties() - { - //This test does not run on Windows64 as is does not support HDF4 files - - loader.initialize(); - loader.setPropertyValue("Filename", "emu00006473.nxs"); - loader.setPropertyValue("OutputWorkspace", "EMU6473"); - TS_ASSERT_THROWS_NOTHING( loader.execute() ); - TS_ASSERT_EQUALS(loader.isExecuted(),true); - - alg.setPropertyValue("InputWorkspace", "EMU6473"); - alg.setPropertyValue("OutputWorkspace", "Result"); - alg.setPropertyValue("Spectra", "0"); - } - - void testProperties() - { - //This test does not run on Windows64 as is does not support HDF4 files - TS_ASSERT_EQUALS( alg.getPropertyValue("Spectra"), "0"); + TS_ASSERT(alg.isInitialized()) } void testExecute() { - //This test does not run on Windows64 as is does not support HDF4 files - try - { - TS_ASSERT_EQUALS(alg.execute(),true); - } - catch(std::runtime_error & e) - { - TS_FAIL(e.what()); - } + auto ws = WorkspaceCreationHelper::Create2DWorkspace(1,1); - Workspace_const_sptr outputWS = AnalysisDataService::Instance().retrieve("Result"); + MuonRemoveExpDecay alg; + TS_ASSERT_THROWS_NOTHING(alg.initialize()); + TS_ASSERT(alg.isInitialized()); + alg.setChild(true); + alg.setProperty("InputWorkspace", ws); + alg.setPropertyValue("OutputWorkspace", outputName); + alg.setPropertyValue("Spectra", "0"); + TS_ASSERT_THROWS_NOTHING(alg.execute()); + TS_ASSERT(alg.isExecuted()) } - void testWhereOptional3rdArgNotSet() + void testExecuteWhereSepctraNotSet() { - //This test does not run on Windows64 as is does not support HDF4 files - - MuonRemoveExpDecay alg2; - alg2.initialize(); - - alg2.setPropertyValue("InputWorkspace", "EMU6473"); - alg2.setPropertyValue("OutputWorkspace", "MuonRemoveExpDecayResult"); + auto ws = WorkspaceCreationHelper::Create2DWorkspace(1,1); - try - { - TS_ASSERT_EQUALS(alg2.execute(),true); - } - catch(std::runtime_error & e) - { - TS_FAIL(e.what()); - } + MuonRemoveExpDecay alg; + TS_ASSERT_THROWS_NOTHING(alg.initialize()); + TS_ASSERT(alg.isInitialized()); + alg.setChild(true); + alg.setProperty("InputWorkspace", ws); + alg.setPropertyValue("OutputWorkspace", outputName); + TS_ASSERT_THROWS_NOTHING(alg.execute()); + TS_ASSERT(alg.isExecuted()) } void test_yUnitLabel() { - const std::string outputWSName = "RemoveExpDecayTest_yUnitLabel_OutputWS"; - auto ws = WorkspaceCreationHelper::Create2DWorkspace(1,1); MuonRemoveExpDecay alg; alg.initialize(); + alg.setChild(true); alg.setProperty("InputWorkspace", ws); - alg.setProperty("OutputWorkspace", outputWSName); + alg.setProperty("OutputWorkspace", outputName); alg.execute(); - auto result = AnalysisDataService::Instance().retrieveWS(outputWSName); - + MatrixWorkspace_sptr result = alg.getProperty("OutputWorkspace"); TS_ASSERT(result); - - if( result ) - { - TS_ASSERT_EQUALS( result->YUnitLabel(), "Asymmetry" ); - } - - AnalysisDataService::Instance().remove(outputWSName); + TS_ASSERT_EQUALS(result->YUnitLabel(), "Asymmetry"); } - - -private: - MuonRemoveExpDecay alg; - Mantid::DataHandling::LoadMuonNexus2 loader; - }; #endif /*MUONREMOVEEXPDECAYTEST_H_*/ diff --git a/Code/Mantid/Framework/CMakeLists.txt b/Code/Mantid/Framework/CMakeLists.txt index 03c5ab5792d2..aa04d1bd087c 100644 --- a/Code/Mantid/Framework/CMakeLists.txt +++ b/Code/Mantid/Framework/CMakeLists.txt @@ -1,5 +1,5 @@ # This is mainly here so you don't get a complaint when running cmake -cmake_minimum_required (VERSION 2.8.5) +cmake_minimum_required (VERSION 2.8.12) # Add the path to our custom 'find' modules set ( CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/../Build/CMake") @@ -121,9 +121,7 @@ endif () # Unit test helper packages if ( CXXTEST_FOUND ) add_subdirectory ( UserAlgorithms ) - # This needs to be here so that a Framework-only build will work. -# add_subdirectory ( ../TestingTools ${${CMAKE_PROJECT_NAME}_BINARY_DIR}/TestingTools/gmock-${GMOCK_VERSION} ) - add_subdirectory ( ../TestingTools ${${CMAKE_PROJECT_NAME}_BINARY_DIR}/TestingTools ) + add_subdirectory ( ../Testing/Tools ${${CMAKE_PROJECT_NAME}_BINARY_DIR}/Testing/Tools ) endif () add_subdirectory (MDAlgorithms) diff --git a/Code/Mantid/Framework/Crystal/CMakeLists.txt b/Code/Mantid/Framework/Crystal/CMakeLists.txt index 5498af2dfec0..24d7be132d25 100644 --- a/Code/Mantid/Framework/Crystal/CMakeLists.txt +++ b/Code/Mantid/Framework/Crystal/CMakeLists.txt @@ -1,5 +1,6 @@ set ( SRC_FILES + src/AddPeakHKL.cpp src/AnvredCorrection.cpp src/CalculatePeaksHKL.cpp src/CalculateUMatrix.cpp @@ -69,6 +70,7 @@ set ( SRC_FILES set ( SRC_UNITY_IGNORE_FILES ) set ( INC_FILES + inc/MantidCrystal/AddPeakHKL.h inc/MantidCrystal/AnvredCorrection.h inc/MantidCrystal/BackgroundStrategy.h inc/MantidCrystal/CalculatePeaksHKL.h @@ -140,6 +142,7 @@ set ( INC_FILES ) set ( TEST_FILES + AddPeakHKLTest.h AnvredCorrectionTest.h CalculatePeaksHKLTest.h CalculateUMatrixTest.h diff --git a/Code/Mantid/Framework/Crystal/inc/MantidCrystal/AddPeakHKL.h b/Code/Mantid/Framework/Crystal/inc/MantidCrystal/AddPeakHKL.h new file mode 100644 index 000000000000..055eadd3b7af --- /dev/null +++ b/Code/Mantid/Framework/Crystal/inc/MantidCrystal/AddPeakHKL.h @@ -0,0 +1,56 @@ +#ifndef MANTID_CRYSTAL_ADDPEAKHKL_H_ +#define MANTID_CRYSTAL_ADDPEAKHKL_H_ + +#include "MantidKernel/System.h" +#include "MantidAPI/Algorithm.h" + +namespace Mantid +{ +namespace Crystal +{ + + /** AddPeakHKL : Algorithm to add a peaks to a PeaksWorkspace in the HKL frame + + Copyright © 2015 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source + + This file is part of Mantid. + + Mantid is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + Mantid is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + File change history is stored at: + Code Documentation is available at: + */ + class DLLExport AddPeakHKL : public API::Algorithm + { + public: + AddPeakHKL(); + virtual ~AddPeakHKL(); + + virtual const std::string name() const; + virtual int version() const; + virtual const std::string category() const; + virtual const std::string summary() const; + + private: + void init(); + void exec(); + + + }; + + +} // namespace Crystal +} // namespace Mantid + +#endif /* MANTID_CRYSTAL_ADDPEAKHKL_H_ */ diff --git a/Code/Mantid/Framework/Crystal/inc/MantidCrystal/SaveIsawUB.h b/Code/Mantid/Framework/Crystal/inc/MantidCrystal/SaveIsawUB.h index f801c296730d..6ee866ca117f 100644 --- a/Code/Mantid/Framework/Crystal/inc/MantidCrystal/SaveIsawUB.h +++ b/Code/Mantid/Framework/Crystal/inc/MantidCrystal/SaveIsawUB.h @@ -64,7 +64,7 @@ class DLLExport SaveIsawUB : public API::Algorithm { void exec(); // Calculates the error in the volume - double getErrorVolume(Geometry::OrientedLattice lattice); + double getErrorVolume(const Geometry::OrientedLattice &lattice); }; } // namespace Mantid diff --git a/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp b/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp new file mode 100644 index 000000000000..78c563d096e9 --- /dev/null +++ b/Code/Mantid/Framework/Crystal/src/AddPeakHKL.cpp @@ -0,0 +1,74 @@ +#include "MantidCrystal/AddPeakHKL.h" +#include "MantidAPI/IPeaksWorkspace.h" +#include "MantidAPI/IPeak.h" +#include "MantidKernel/ArrayProperty.h" +#include "MantidKernel/ArrayLengthValidator.h" +#include "MantidKernel/V3D.h" + +namespace Mantid +{ +namespace Crystal +{ + + using namespace Mantid::Kernel; + using namespace Mantid::API; + + // Register the algorithm into the AlgorithmFactory + DECLARE_ALGORITHM(AddPeakHKL) + + + + //---------------------------------------------------------------------------------------------- + /** Constructor + */ + AddPeakHKL::AddPeakHKL() + { + } + + //---------------------------------------------------------------------------------------------- + /** Destructor + */ + AddPeakHKL::~AddPeakHKL() + { + } + + + //---------------------------------------------------------------------------------------------- + + /// Algorithms name for identification. @see Algorithm::name + const std::string AddPeakHKL::name() const { return "AddPeakHKL"; } + + /// Algorithm's version for identification. @see Algorithm::version + int AddPeakHKL::version() const { return 1;}; + + /// Algorithm's category for identification. @see Algorithm::category + const std::string AddPeakHKL::category() const { return "Crystal";} + + /// Algorithm's summary for use in the GUI and help. @see Algorithm::summary + const std::string AddPeakHKL::summary() const { return "Add a peak in the hkl frame";}; + + //---------------------------------------------------------------------------------------------- + /** Initialize the algorithm's properties. + */ + void AddPeakHKL::init() + { + declareProperty(new WorkspaceProperty("Workspace","",Direction::InOut), "An input workspace."); + declareProperty(new ArrayProperty("HKL", boost::make_shared > (3)), "HKL point to add"); + } + + //---------------------------------------------------------------------------------------------- + /** Execute the algorithm. + */ + void AddPeakHKL::exec() + { + IPeaksWorkspace_sptr peakWS = this->getProperty("Workspace"); + const std::vector hklValue = this->getProperty("HKL"); + IPeak * peak = peakWS->createPeakHKL(V3D(hklValue[0], hklValue[1], hklValue[2])); + peakWS->addPeak(*peak); + delete peak; + } + + + +} // namespace Crystal +} // namespace Mantid diff --git a/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp b/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp index 541403979d91..ba77553c1c38 100644 --- a/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp +++ b/Code/Mantid/Framework/Crystal/src/PredictPeaks.cpp @@ -145,7 +145,7 @@ void PredictPeaks::doHKL(const double h, const double k, const double l, PARALLEL_CRITICAL(PredictPeaks_numInRange) { numInRange++; } // Create the peak using the Q in the lab framewith all its info: - Peak p(inst, q); + Peak p(inst, q, boost::optional()); if (p.findDetector()) { // Only add peaks that hit the detector p.setGoniometerMatrix(gonio); diff --git a/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp b/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp index 4f9e74320185..a2ba70830a4f 100644 --- a/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp +++ b/Code/Mantid/Framework/Crystal/src/SaveIsawUB.cpp @@ -54,7 +54,7 @@ void SaveIsawUB::init() { "Path to an ISAW-style UB matrix text file."); } -double SaveIsawUB::getErrorVolume(OrientedLattice lattice) { +double SaveIsawUB::getErrorVolume(const OrientedLattice &lattice) { double Volume; double latticeParams[6] = {lattice.a(), lattice.b(), lattice.c(), lattice.alpha(), lattice.beta(), lattice.gamma()}; diff --git a/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h b/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h new file mode 100644 index 000000000000..0c842e3da845 --- /dev/null +++ b/Code/Mantid/Framework/Crystal/test/AddPeakHKLTest.h @@ -0,0 +1,112 @@ +#ifndef MANTID_CRYSTAL_ADDPEAKHKLTEST_H_ +#define MANTID_CRYSTAL_ADDPEAKHKLTEST_H_ + +#include +#include "MantidCrystal/AddPeakHKL.h" +#include "MantidKernel/V3D.h" +#include "MantidAPI/AnalysisDataService.h" +#include "MantidDataObjects/PeaksWorkspace.h" +#include "MantidGeometry/Crystal/OrientedLattice.h" +#include "MantidTestHelpers/ComponentCreationHelper.h" + +using Mantid::Crystal::AddPeakHKL; +using namespace Mantid::Kernel; +using namespace Mantid::API; +using namespace Mantid::DataObjects; + +class AddPeakHKLTest : public CxxTest::TestSuite +{ +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static AddPeakHKLTest *createSuite() { return new AddPeakHKLTest(); } + static void destroySuite( AddPeakHKLTest *suite ) { delete suite; } + + + void test_Init() + { + AddPeakHKL alg; + TS_ASSERT_THROWS_NOTHING( alg.initialize() ) + TS_ASSERT( alg.isInitialized() ) + } + + void test_hkl_validation() + { + AddPeakHKL alg; + alg.initialize(); + std::vector hkl_bad(4); // Too big! + TS_ASSERT_THROWS( alg.setProperty("HKL", hkl_bad), std::invalid_argument& ); + + std::vector hkl_good(3, 0); // Right size. + TS_ASSERT_THROWS_NOTHING( alg.setProperty("HKL", hkl_good) ); + } + + + void test_exec() + { + // Create simple fictional instrument + const V3D source(0,0,0); + const V3D sample(15, 0, 0); + const V3D detectorPos(20, 5, 0); + const V3D beam1 = sample - source; + const V3D beam2 = detectorPos - sample; + auto minimalInstrument = ComponentCreationHelper::createMinimalInstrument( source, sample, detectorPos ); + + // Derive distances and angles + const double l1 = beam1.norm(); + const double l2 = beam2.norm(); + const V3D qLabDir = (beam1/l1) - (beam2/l2); + + const double microSecsInSec = 1e6; + + // Derive QLab for diffraction + const double wavenumber_in_angstrom_times_tof_in_microsec = + (Mantid::PhysicalConstants::NeutronMass * (l1 + l2) * 1e-10 * microSecsInSec) / + Mantid::PhysicalConstants::h_bar; + V3D qLab = qLabDir * wavenumber_in_angstrom_times_tof_in_microsec; + + Mantid::Geometry::OrientedLattice orientedLattice(1, 1, 1, 90, 90, 90); // U is identity, real and reciprocal lattice vectors are identical. + Mantid::Geometry::Goniometer goniometer; // identity + V3D hkl = qLab / (2 * M_PI); // Given our settings above, this is the simplified relationship between qLab and hkl. + + // Now create a peaks workspace around the simple fictional instrument + PeaksWorkspace_sptr ws = boost::make_shared(); + ws->setInstrument(minimalInstrument); + ws->mutableSample().setOrientedLattice(&orientedLattice); + ws->mutableRun().setGoniometer(goniometer, false); + + AddPeakHKL alg; + alg.setChild(true); + alg.initialize(); + std::vector hklVec; + hklVec.push_back(hkl.X()); + hklVec.push_back(hkl.Y()); + hklVec.push_back(hkl.Z()); + alg.setProperty("HKL", hklVec); + alg.setProperty("Workspace", ws); + alg.execute(); + IPeaksWorkspace_sptr ws_out = alg.getProperty("Workspace"); + + // Get the peak just added. + const IPeak& peak =ws_out->getPeak(0); + + /* + Now we check we have made a self - consistent peak + */ + TSM_ASSERT_EQUALS("New peak should have HKL we demanded.", hkl, peak.getHKL()); + TSM_ASSERT_EQUALS("New peak should have QLab we expected.", qLab, peak.getQLabFrame()); + TSM_ASSERT_EQUALS("QSample and QLab should be identical given the identity goniometer settings.", peak.getQLabFrame(), peak.getQSampleFrame()); + auto detector = peak.getDetector(); + TSM_ASSERT("No detector", detector); + TSM_ASSERT_EQUALS("This detector id does not match what we expect from the instrument definition", 1, detector->getID()); + TSM_ASSERT_EQUALS("Thie detector position is wrong", detectorPos, detector->getPos()); + TSM_ASSERT_EQUALS("Goniometer has not been set properly", goniometer.getR(), peak.getGoniometerMatrix()); + + } + + + +}; + + +#endif /* MANTID_CRYSTAL_ADDPEAKHKLTEST_H_ */ diff --git a/Code/Mantid/Framework/Crystal/test/IndexSXPeaksTest.h b/Code/Mantid/Framework/Crystal/test/IndexSXPeaksTest.h index b8c4ca4a2166..a69316a8dc7d 100644 --- a/Code/Mantid/Framework/Crystal/test/IndexSXPeaksTest.h +++ b/Code/Mantid/Framework/Crystal/test/IndexSXPeaksTest.h @@ -120,7 +120,7 @@ class IndexSXPeaksTest : public CxxTest::TestSuite { IPeak& peak = m_masterPeaks->getPeak(i); Mantid::Kernel::V3D v(1, 0, 0); - peak.setQSampleFrame(v); // Overwrite all Q samples to be co-linear. + peak.setQSampleFrame(v, boost::optional()); // Overwrite all Q samples to be co-linear. } TS_ASSERT_THROWS(doTest(6, "1, 2, 3, 4, 5, 6", 14.131, 19.247, 8.606, 90.0, 105.071, 90.0), std::runtime_error); diff --git a/Code/Mantid/Framework/Crystal/test/PeaksOnSurfaceTest.h b/Code/Mantid/Framework/Crystal/test/PeaksOnSurfaceTest.h index 7e2fa007ee98..239a663dfe7e 100644 --- a/Code/Mantid/Framework/Crystal/test/PeaksOnSurfaceTest.h +++ b/Code/Mantid/Framework/Crystal/test/PeaksOnSurfaceTest.h @@ -33,7 +33,7 @@ class PeaksOnSurfaceTest : public CxxTest::TestSuite Mantid::Kernel::V3D position; if(coordFrame == "Q (lab frame)") { - peak.setQLabFrame(peakPosition); + peak.setQLabFrame(peakPosition,1/*set the detector distance explicitly*/); } else { @@ -374,4 +374,4 @@ class PeaksOnSurfaceTestPerformance : public CxxTest::TestSuite } }; -#endif /* MANTID_CRYSTAL_PEAKSONSURFACETEST_H_ */ \ No newline at end of file +#endif /* MANTID_CRYSTAL_PEAKSONSURFACETEST_H_ */ diff --git a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt index 238f3a6762bd..9b5c8ec012b8 100644 --- a/Code/Mantid/Framework/CurveFitting/CMakeLists.txt +++ b/Code/Mantid/Framework/CurveFitting/CMakeLists.txt @@ -30,6 +30,7 @@ set ( SRC_FILES src/DerivMinimizer.cpp src/DiffRotDiscreteCircle.cpp src/DiffSphere.cpp + src/DynamicKuboToyabe.cpp src/EndErfc.cpp src/ExpDecay.cpp src/ExpDecayMuon.cpp @@ -138,6 +139,7 @@ set ( INC_FILES inc/MantidCurveFitting/DiffRotDiscreteCircle.h inc/MantidCurveFitting/DiffSphere.h inc/MantidCurveFitting/DllConfig.h + inc/MantidCurveFitting/DynamicKuboToyabe.h inc/MantidCurveFitting/EndErfc.h inc/MantidCurveFitting/ExpDecay.h inc/MantidCurveFitting/ExpDecayMuon.h @@ -241,6 +243,7 @@ set ( TEST_FILES DeltaFunctionTest.h DiffRotDiscreteCircleTest.h DiffSphereTest.h + DynamicKuboToyabeTest.h EndErfcTest.h ExpDecayMuonTest.h ExpDecayOscTest.h @@ -261,6 +264,7 @@ set ( TEST_FILES GaussianTest.h GramCharlierComptonProfileTest.h IkedaCarpenterPVTest.h + IPeakFunctionIntensityTest.h LeBailFitTest.h LeBailFunctionTest.h LeastSquaresTest.h diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/BackToBackExponential.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/BackToBackExponential.h index 92713f3bd730..bdf4e79ca415 100644 --- a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/BackToBackExponential.h +++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/BackToBackExponential.h @@ -54,6 +54,8 @@ class DLLExport BackToBackExponential : public PeakParametersNumeric { public: /// Default constructor. BackToBackExponential() : PeakParametersNumeric() {} + virtual double intensity() const; + virtual void setIntensity(const double newIntensity); /// overwrite IFunction base class methods std::string name() const { return "BackToBackExponential"; } diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h new file mode 100644 index 000000000000..34f8cb9fbfbb --- /dev/null +++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/DynamicKuboToyabe.h @@ -0,0 +1,66 @@ +#ifndef MANTID_CURVEFITTING_DYNAMICKUBOTOYABE_H_ +#define MANTID_CURVEFITTING_DYNAMICKUBOTOYABE_H_ + +//---------------------------------------------------------------------- +// Includes +//---------------------------------------------------------------------- +#include "MantidAPI/IPeakFunction.h" +#include "MantidAPI/IFunctionMW.h" +#include "MantidAPI/IFunctionWithLocation.h" +#include + +namespace Mantid +{ + namespace CurveFitting + { + /** + Provide Dynamic Kubo Toyabe function interface to IFunction1D for muon scientists. + + @author Raquel Alvarez, ISIS, RAL + @date 18/02/2015 + + Copyright © 2007-2012 ISIS Rutherford Appleton Laboratory & NScD Oak Ridge National Laboratory + + This file is part of Mantid. + + Mantid is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + Mantid is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + File change history is stored at: + Code Documentation is available at: + */ + + class DLLExport DynamicKuboToyabe : public API::ParamFunction, public API::IFunction1D + { + public: + + /// Destructor + virtual ~DynamicKuboToyabe() {} + + /// overwrite base class methods + std::string name()const{return "DynamicKuboToyabe";} + virtual const std::string category() const { return "Muon";} + + protected: + virtual void function1D(double* out, const double* xValues, const size_t nData)const; + virtual void functionDeriv1D(API::Jacobian* out, const double* xValues, const size_t nData); + virtual void functionDeriv(const API::FunctionDomain& domain, API::Jacobian& jacobian); + virtual void init(); + virtual void setActiveParameter(size_t i, double value); + + }; + + } // namespace CurveFitting +} // namespace Mantid + +#endif /*MANTID_CURVEFITTING_DYNAMICKUBOTOYABE_H_*/ \ No newline at end of file diff --git a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LeBailFit.h b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LeBailFit.h index eb70dd8af7d6..6080044f484a 100644 --- a/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LeBailFit.h +++ b/Code/Mantid/Framework/CurveFitting/inc/MantidCurveFitting/LeBailFit.h @@ -253,7 +253,7 @@ class DLLExport LeBailFit : public API::Algorithm { bool prevBetterRwp); /// Limit proposed value in the specified boundary - double limitProposedValueInBound(Parameter param, double newvalue, + double limitProposedValueInBound(const Parameter ¶m, double newvalue, double direction, int choice); /// Book keep the (sopposed) best MC result diff --git a/Code/Mantid/Framework/CurveFitting/src/BackToBackExponential.cpp b/Code/Mantid/Framework/CurveFitting/src/BackToBackExponential.cpp index 5d8f182dd5a5..0d78e7deee30 100644 --- a/Code/Mantid/Framework/CurveFitting/src/BackToBackExponential.cpp +++ b/Code/Mantid/Framework/CurveFitting/src/BackToBackExponential.cpp @@ -32,9 +32,15 @@ void BackToBackExponential::init() { defineCentreParameter("X0"); defineHeightParameter("I"); - defineWidthParameter("S",Linear); - defineWidthParameter("A",Inverse); - defineWidthParameter("B",Inverse); + defineWidthParameter("S", Linear); + defineWidthParameter("A", Inverse); + defineWidthParameter("B", Inverse); +} + +double BackToBackExponential::intensity() const { return getParameter("I"); } + +void BackToBackExponential::setIntensity(const double newIntensity) { + setParameter("I", newIntensity); } void BackToBackExponential::function1D(double *out, const double *xValues, @@ -102,30 +108,23 @@ double BackToBackExponential::expWidth() const { return M_LN2 * (a + b) / (a * b); } -std::pair BackToBackExponential::getExtent() const -{ +std::pair BackToBackExponential::getExtent() const { double a = getParameter(1) / 5.0; double b = getParameter(2) / 5.0; - if ( a == 0.0 ) - { + if (a == 0.0) { a = 1.0; - } - else - { + } else { a = 1.0 / a; } - if ( b == 0.0 ) - { + if (b == 0.0) { b = 1.0; - } - else - { + } else { b = 1.0 / b; } auto c = getParameter("X0"); auto start = c - a; auto end = c + b; - return std::make_pair( start, end ); + return std::make_pair(start, end); } } // namespace CurveFitting diff --git a/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp new file mode 100644 index 000000000000..4b7bae69801a --- /dev/null +++ b/Code/Mantid/Framework/CurveFitting/src/DynamicKuboToyabe.cpp @@ -0,0 +1,151 @@ +//---------------------------------------------------------------------- +// Includes +//---------------------------------------------------------------------- +#include "MantidCurveFitting/DynamicKuboToyabe.h" +#include "MantidAPI/Jacobian.h" +#include "MantidAPI/FunctionFactory.h" +#include + +namespace Mantid +{ +namespace CurveFitting +{ + +using namespace Kernel; +using namespace API; + +DECLARE_FUNCTION(DynamicKuboToyabe) + +void DynamicKuboToyabe::init() +{ + declareParameter("Asym", 0.2, "Amplitude at time 0"); + declareParameter("Delta", 0.2, "Local field"); + declareParameter("Field", 0.0, "External field"); + declareParameter("Nu", 0.0, "Hopping rate"); +} + +// Static Zero Field Kubo Toyabe relaxation function +double ZFKT (const double x, const double G){ + + const double q = G*G*x*x; + return (0.3333333333 + 0.6666666667*exp(-0.5*q)*(1-q)); +} + +// Dynamic Kubo-Toyabe +double getDKT (double t, double G, double v){ + + const int tsmax = 656; // Length of the time axis, 32 us of valid data + const double eps = 0.05; // Bin width for calculations + + static double oldG=-1., oldV=-1.; + static std::vector gStat(tsmax), gDyn(tsmax); + + + if ( (G != oldG) || (v != oldV) ){ + + // If G or v have changed with respect to the + // previous call, we need to re-do the computations + + + if ( G != oldG ){ + + // But we only need to + // re-compute gStat if G has changed + + // Generate static Kubo-Toyabe + for (int k=0; k0; j--){ + y=y*(1-hop)+hop*gDyn[k-j]*gStat[j]; + } + gDyn[k]=y; + } + } + + // Interpolate table + // If beyond end, extrapolate + int x=int(fabs(t)/eps); + if (x>tsmax-2) + x = tsmax-2; + double xe=(fabs(t)/eps)-x; + return gDyn[x]*(1-xe)+xe*gDyn[x+1]; + +} + +// Dynamic Kubo Toyabe function +void DynamicKuboToyabe::function1D(double* out, const double* xValues, const size_t nData)const +{ + const double& A = getParameter("Asym"); + const double& G = fabs(getParameter("Delta")); + const double& F = fabs(getParameter("Field")); + const double& v = fabs(getParameter("Nu")); + + + // Zero hopping rate + if (v == 0.0) { + + // Zero external field + if ( F == 0.0 ){ + for (size_t i = 0; i < nData; i++) { + out[i] = A*ZFKT(xValues[i],G); + } + } + // Non-zero external field + else{ + throw std::runtime_error("HKT() not implemented yet"); + } + } + + // Non-zero hopping rate + else { + + if ( F==0.0 ) { + + for (size_t i = 0; i mcgroup, Rfactor r, * * @return :: new value in boundary */ -double LeBailFit::limitProposedValueInBound(Parameter param, double newvalue, +double LeBailFit::limitProposedValueInBound(const Parameter ¶m, double newvalue, double direction, int choice) { if (choice == 0) { // Half distance diff --git a/Code/Mantid/Framework/CurveFitting/test/BackToBackExponentialTest.h b/Code/Mantid/Framework/CurveFitting/test/BackToBackExponentialTest.h index 8d01288baef3..9f385263a317 100644 --- a/Code/Mantid/Framework/CurveFitting/test/BackToBackExponentialTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/BackToBackExponentialTest.h @@ -185,6 +185,25 @@ class BackToBackExponentialTest : public CxxTest::TestSuite } } + void testIntensity() + { + const double s = 4.0; + const double I = 2.1; + BackToBackExponential b2bExp; + b2bExp.initialize(); + b2bExp.setParameter("I", I); + b2bExp.setParameter("A", 6.0);// large A and B make + b2bExp.setParameter("B", 6.0);// the exponentials narrow + b2bExp.setParameter("X0",0.0); + b2bExp.setParameter("S", s); + + TS_ASSERT_EQUALS(b2bExp.intensity(), 2.1); + TS_ASSERT_THROWS_NOTHING(b2bExp.setIntensity(3.0)); + + TS_ASSERT_EQUALS(b2bExp.intensity(), 3.0); + TS_ASSERT_EQUALS(b2bExp.getParameter("I"), 3.0); + } + void test_width() { BackToBackExponential b2b; diff --git a/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h new file mode 100644 index 000000000000..74e8717d9fb9 --- /dev/null +++ b/Code/Mantid/Framework/CurveFitting/test/DynamicKuboToyabeTest.h @@ -0,0 +1,141 @@ +#ifndef DYNAMICKUBOTOYABETEST_H_ +#define DYNAMICKUBOTOYABETEST_H_ + +#include + +#include "MantidCurveFitting/DynamicKuboToyabe.h" +#include "MantidCurveFitting/StaticKuboToyabe.h" +#include "MantidAPI/FunctionDomain1D.h" +#include "MantidAPI/FunctionValues.h" + +using namespace Mantid::Kernel; +using namespace Mantid::API; +using namespace Mantid::CurveFitting; + + +class DynamicKuboToyabeTest : public CxxTest::TestSuite +{ +public: + + void testZFZNDKTFunction() + { + // Test Dynamic Kubo Toyabe (DKT) for Zero Field (ZF) and Zero Nu (ZN) + // Function values must match exactly values from the Static Kubo Toyabe + const double asym = 1.0; + const double delta = 0.39; + const double field = 0; + const double nu = 0.0; + + DynamicKuboToyabe dkt; + dkt.initialize(); + dkt.setParameter("Asym", asym); + dkt.setParameter("Delta",delta ); + dkt.setParameter("Field",field); + dkt.setParameter("Nu", nu); + + StaticKuboToyabe skt; + skt.initialize(); + skt.setParameter("A", asym); + skt.setParameter("Delta", delta); + + // define 1d domain of 10 points in interval [0,10] + Mantid::API::FunctionDomain1DVector x(0,10,10); + Mantid::API::FunctionValues y1(x); + Mantid::API::FunctionValues y2(x); + + TS_ASSERT_THROWS_NOTHING(dkt.function(x,y1)); + TS_ASSERT_THROWS_NOTHING(skt.function(x,y2)); + + for(size_t i = 0; i < x.size(); ++i) + { + TS_ASSERT_DELTA( y1[i], y2[i], 1e-6 ); + } + } + + void testZFDKTFunction() + { + // Test Dynamic Kubo Toyabe (DKT) for Zero Field (ZF) (non-zero Nu) + const double asym = 1.0; + const double delta = 0.39; + const double field = 0; + const double nu = 1.0; + + DynamicKuboToyabe dkt; + dkt.initialize(); + dkt.setParameter("Asym", asym); + dkt.setParameter("Delta",delta ); + dkt.setParameter("Field",field); + dkt.setParameter("Nu", nu); + + // define 1d domain of 5 points in interval [0,5] + Mantid::API::FunctionDomain1DVector x(0,5,5); + Mantid::API::FunctionValues y(x); + + TS_ASSERT_THROWS_NOTHING(dkt.function(x,y)); + TS_ASSERT_DELTA( y[0], 1.000000, 0.000001); + TS_ASSERT_DELTA( y[1], 0.850107, 0.000001); + TS_ASSERT_DELTA( y[2], 0.625283, 0.000001); + TS_ASSERT_DELTA( y[3], 0.449064, 0.000001); + TS_ASSERT_DELTA( y[4], 0.323394, 0.000001); + } + + void xtestZNDKTFunction() + { + // Test Dynamic Kubo Toyabe (DKT) for non-zero Field and Zero Nu (ZN) + const double asym = 1.0; + const double delta = 0.39; + const double field = 0.1; + const double nu = 0.0; + + DynamicKuboToyabe dkt; + dkt.initialize(); + dkt.setParameter("Asym", asym); + dkt.setParameter("Delta",delta ); + dkt.setParameter("Field",field); + dkt.setParameter("Nu", nu); + + // define 1d domain of 5 points in interval [0,5] + Mantid::API::FunctionDomain1DVector x(0,5,5); + Mantid::API::FunctionValues y(x); + + TS_ASSERT_THROWS_NOTHING(dkt.function(x,y)); + + TS_ASSERT_DELTA( y[0], 1.000000, 0.000001); + TS_ASSERT_DELTA( y[1], 0.784636, 0.000001); + TS_ASSERT_DELTA( y[2], 0.353978, 0.000001); + TS_ASSERT_DELTA( y[3], 0.073286, 0.000001); + TS_ASSERT_DELTA( y[4], 0.055052, 0.000001); + } + + void xtestDKTFunction() + { + // Test Dynamic Kubo Toyabe (DKT) (non-zero Field, non-zero Nu) + const double asym = 1.0; + const double delta = 0.39; + const double field = 0.1; + const double nu = 0.5; + + DynamicKuboToyabe dkt; + dkt.initialize(); + dkt.setParameter("Asym", asym); + dkt.setParameter("Delta",delta ); + dkt.setParameter("Field",field); + dkt.setParameter("Nu", nu); + + // define 1d domain of 5 points in interval [0,5] + Mantid::API::FunctionDomain1DVector x(0,5,5); + Mantid::API::FunctionValues y(x); + + TS_ASSERT_THROWS_NOTHING(dkt.function(x,y)); + + TS_ASSERT_DELTA( y[0], 1.000000, 0.000001); + TS_ASSERT_DELTA( y[1], 0.822498, 0.000001); + TS_ASSERT_DELTA( y[2], 0.518536, 0.000001); + TS_ASSERT_DELTA( y[3], 0.295988, 0.000001); + TS_ASSERT_DELTA( y[4], 0.175489, 0.000001); + } + + +}; + +#endif /*DYNAMICKUBOTOYABETEST_H_*/ diff --git a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h index 760c5712f462..ef010df67c74 100644 --- a/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/GaussianTest.h @@ -160,7 +160,7 @@ class GaussianTest : public CxxTest::TestSuite for (size_t i=0; i < 41; i++) e[i] = sqrt( y[i] ); } - void xtest_with_Levenberg_Marquardt() + void test_with_Levenberg_Marquardt() { API::FunctionDomain1D_sptr domain(new API::FunctionDomain1DVector( 79292.4, 79603.6, 41)); API::FunctionValues mockData(*domain); @@ -295,85 +295,7 @@ class GaussianTest : public CxxTest::TestSuite } - void t11estAgainstPeak2FallbackToSimplex() - { - // create peak2 mock data to test against - std::string wsName = "GaussHRP38692MockData"; - int histogramNumber = 1; - int timechannels = 41; - Workspace_sptr ws = WorkspaceFactory::Instance().create("Workspace2D",histogramNumber,timechannels,timechannels); - Workspace2D_sptr ws2D = boost::dynamic_pointer_cast(ws); - Mantid::MantidVec& x = ws2D->dataX(0); // x-values (time-of-flight) - Mantid::MantidVec& y = ws2D->dataY(0); // y-values (counts) - Mantid::MantidVec& e = ws2D->dataE(0); // error values of counts - getHRP38692Peak2Data(x, y, e); - - //put this workspace in the data service - TS_ASSERT_THROWS_NOTHING(AnalysisDataService::Instance().add(wsName, ws2D)); - - // Initialise algorithm - Fit alg; - TS_ASSERT_THROWS_NOTHING(alg.initialize()); - TS_ASSERT( alg.isInitialized() ); - - // create function you want to fit against - CompositeFunction_sptr fnWithBk( new CompositeFunction() ); - - boost::shared_ptr bk( new LinearBackground() ); - bk->initialize(); - - bk->setParameter("A0",0.0); - bk->setParameter("A1",0.0); - bk->tie("A1","0"); - - BoundaryConstraint* bc_b = new BoundaryConstraint(bk.get(),"A0",0, 20.0); - bk->addConstraint(bc_b); - - // set up Gaussian fitting function - boost::shared_ptr fn( new Gaussian() ); - fn->initialize(); - - fn->setParameter("Height",200.0); - fn->setParameter("PeakCentre",79450.0); - fn->setParameter("Sigma",300.0); - - // add constraint to function - BoundaryConstraint* bc3 = new BoundaryConstraint(fn.get(),"Sigma",20, 100.0); - fn->addConstraint(bc3); - - fnWithBk->addFunction(bk); - fnWithBk->addFunction(fn); - - alg.setProperty("Function",fnWithBk); - // Set which spectrum to fit against and initial starting values - alg.setPropertyValue("InputWorkspace", wsName); - alg.setPropertyValue("StartX","79300"); - alg.setPropertyValue("EndX","79600"); - - - // execute fit - TS_ASSERT_THROWS_NOTHING( - TS_ASSERT( alg.execute() ) - ) - TS_ASSERT( alg.isExecuted() ); - - // test the output from fit is what you expect - double dummy = alg.getProperty("OutputChi2overDoF"); - TS_ASSERT_DELTA( dummy, 0.0,0.1); - - IFunction_sptr out = alg.getProperty("Function"); - IPeakFunction *pk = dynamic_cast(dynamic_cast(out.get())->getFunction(1).get()); - TS_ASSERT_DELTA( pk->height(), 249.3187 ,0.01); - TS_ASSERT_DELTA( pk->centre(), 79430 ,0.1); - TS_ASSERT_DELTA( pk->getParameter("Sigma"), 25.3066 ,0.01); - TS_ASSERT_DELTA( out->getParameter("f0.A0"), 7.8643 ,0.001); - TS_ASSERT_DELTA( out->getParameter("f0.A1"), 0.0 ,0.01); - - AnalysisDataService::Instance().remove(wsName); - } - - - void xtestAgainstMockData() + void testAgainstMockData() { // create mock data to test against std::string wsName = "GaussMockData"; @@ -404,6 +326,7 @@ class GaussianTest : public CxxTest::TestSuite alg2.setPropertyValue("WorkspaceIndex","0"); alg2.setPropertyValue("StartX","0"); alg2.setPropertyValue("EndX","20"); + alg2.setPropertyValue("Minimizer","Levenberg-MarquardtMD"); // execute fit TS_ASSERT_THROWS_NOTHING( @@ -411,22 +334,19 @@ class GaussianTest : public CxxTest::TestSuite ) TS_ASSERT( alg2.isExecuted() ); - std::string minimizer = alg2.getProperty("Minimizer"); - TS_ASSERT( minimizer.compare("Levenberg-Marquardt") == 0 ); - // test the output from fit is what you expect double dummy = alg2.getProperty("OutputChi2overDoF"); TS_ASSERT_DELTA( dummy, 0.035,0.01); IFunction_sptr out = alg2.getProperty("Function"); IPeakFunction *pk = dynamic_cast(out.get()); - TS_ASSERT_DELTA( pk->height(), 97.9728 ,0.0001); - TS_ASSERT_DELTA( pk->centre(), 11.2194 ,0.0001); - TS_ASSERT_DELTA( pk->fwhm(), 2.6181 ,0.0001); + TS_ASSERT_DELTA( pk->height(), 97.8036 ,0.0001); + TS_ASSERT_DELTA( pk->centre(), 11.2356 ,0.0001); + TS_ASSERT_DELTA( pk->fwhm(), 2.6237 ,0.0001); } - void xtestAgainstMockDataSimplex2() + void testAgainstMockDataSimplex2() { // create mock data to test against std::string wsName = "GaussMockDataSimplex2"; @@ -492,7 +412,7 @@ class GaussianTest : public CxxTest::TestSuite // and used a starting of Sigma = 100. // Note that the no constraint simplex with Sigma = 300 also does not locate // the correct minimum but not as badly as levenberg-marquardt - void t11estAgainstHRPD_DatasetWithConstraintsSimplex() + void testAgainstHRPD_DatasetWithConstraintsSimplex() { // create peak2 mock data to test against std::string wsName = "GaussHRP38692MockData"; @@ -500,7 +420,7 @@ class GaussianTest : public CxxTest::TestSuite int timechannels = 41; Workspace_sptr ws = WorkspaceFactory::Instance().create("Workspace2D",histogramNumber,timechannels,timechannels); Workspace2D_sptr ws2D = boost::dynamic_pointer_cast(ws); - Mantid::MantidVec& x = ws2D->dataX(0); // x-values (time-of-flight) + Mantid::MantidVec& x = ws2D->dataX(0); // x-values (time-of-flight) Mantid::MantidVec& y = ws2D->dataY(0); // y-values (counts) Mantid::MantidVec& e = ws2D->dataE(0); // error values of counts getHRP38692Peak2Data(x, y, e); @@ -536,21 +456,16 @@ class GaussianTest : public CxxTest::TestSuite fn->setParameter("Sigma",10.0); // add constraint to function - //BoundaryConstraint* bc1 = new BoundaryConstraint(fn,"Height",100, 300.0); - //BoundaryConstraint* bc2 = new BoundaryConstraint(fn,"PeakCentre",79200, 79700.0); BoundaryConstraint* bc3 = new BoundaryConstraint(fn.get(),"Sigma",20, 100.0); - //fn->addConstraint(bc1); - //fn->addConstraint(bc2); fn->addConstraint(bc3); fnWithBk->addFunction(bk); fnWithBk->addFunction(fn); - //alg.setPropertyValue("Function",*fnWithBk); - alg.setProperty("Function",fnWithBk); + alg.setProperty("Function",boost::dynamic_pointer_cast(fnWithBk)); // Set which spectrum to fit against and initial starting values - alg.setPropertyValue("InputWorkspace",wsName); + alg.setProperty("InputWorkspace",ws); alg.setPropertyValue("StartX","79300"); alg.setPropertyValue("EndX","79600"); alg.setPropertyValue("Minimizer","Simplex"); @@ -566,16 +481,16 @@ class GaussianTest : public CxxTest::TestSuite // test the output from fit is what you expect double dummy = alg.getProperty("OutputChi2overDoF"); - TS_ASSERT_DELTA( dummy, 5.1604,1); + TS_ASSERT_DELTA( dummy, 2.5911,1); IFunction_sptr fun = alg.getProperty("Function"); TS_ASSERT(fun); IFunction_sptr out = alg.getProperty("Function"); - TS_ASSERT_DELTA( out->getParameter("f1.Height"), 216.419 ,1); - TS_ASSERT_DELTA( out->getParameter("f1.PeakCentre"), 79430.1 ,1); - TS_ASSERT_DELTA( out->getParameter("f1.Sigma"), 27.08 ,0.1); - TS_ASSERT_DELTA( out->getParameter("f0.A0"), 2.18 ,0.1); + TS_ASSERT_DELTA( out->getParameter("f1.Height"), 232 ,1); + TS_ASSERT_DELTA( out->getParameter("f1.PeakCentre"), 79430 ,1); + TS_ASSERT_DELTA( out->getParameter("f1.Sigma"), 26.08 ,1); + TS_ASSERT_DELTA( out->getParameter("f0.A0"), 8 ,1); TS_ASSERT_DELTA( out->getParameter("f0.A1"), 0.0 ,0.01); AnalysisDataService::Instance().remove(wsName); @@ -583,6 +498,55 @@ class GaussianTest : public CxxTest::TestSuite ConfigService::Instance().setString("curvefitting.peakRadius",priorRadius); } + void testIntensity() + { + boost::shared_ptr fn( new Gaussian() ); + fn->initialize(); + fn->setHeight(2.0); + fn->setFwhm(0.125); + fn->setCentre(-200.0); + + // Area under a gaussian is height * sigma * sqrt(2 * pi) + TS_ASSERT_DELTA(fn->intensity(), 0.26611675485780654483, 1e-10); + } + + void testSetIntensity() + { + boost::shared_ptr fn( new Gaussian() ); + fn->initialize(); + fn->setHeight(2.0); + fn->setFwhm(0.125); + fn->setCentre(-200.0); + + TS_ASSERT_THROWS_NOTHING(fn->setIntensity(0.5)); + + TS_ASSERT_DELTA(fn->intensity(), 0.5, 1e-10); + + // FWHM does not change + TS_ASSERT_EQUALS(fn->fwhm(), 0.125); + + // Height changes + TS_ASSERT_DELTA(fn->height(), 3.75774911479860533509, 1e-10); + } + + void testSetIntensityDefault() + { + boost::shared_ptr fn( new Gaussian() ); + fn->initialize(); + + TS_ASSERT_EQUALS(fn->intensity(), 0.0); + + // This does not work, because fwhm is 0 and height is 0 + TS_ASSERT_THROWS(fn->setIntensity(20.0), std::invalid_argument); + TS_ASSERT_EQUALS(fn->intensity(), 0.0); + + // Now, fwhm is not zero + fn->setFwhm(0.02); + + TS_ASSERT_THROWS_NOTHING(fn->setIntensity(20.0)); + TS_ASSERT_DELTA(fn->intensity(), 20.0, 1e-10); + } + }; diff --git a/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h b/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h new file mode 100644 index 000000000000..513f22227ae1 --- /dev/null +++ b/Code/Mantid/Framework/CurveFitting/test/IPeakFunctionIntensityTest.h @@ -0,0 +1,152 @@ +#ifndef IPEAKFUNCTIONINTENSITYTEST_H +#define IPEAKFUNCTIONINTENSITYTEST_H + +#include +#include "MantidAPI/FrameworkManager.h" +#include "MantidAPI/FunctionFactory.h" +#include "MantidAPI/IPeakFunction.h" +#include + +using namespace Mantid::API; + +#define DBL2STR(x) boost::lexical_cast(x) + +struct ParameterSet { + ParameterSet(double c, double h, double f) : center(c), height(h), fwhm(f) {} + + double center; + double height; + double fwhm; +}; + +class IPeakFunctionIntensityTest : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static IPeakFunctionIntensityTest *createSuite() { + return new IPeakFunctionIntensityTest(); + } + static void destroySuite(IPeakFunctionIntensityTest *suite) { delete suite; } + + IPeakFunctionIntensityTest() : m_blackList() { + FrameworkManager::Instance(); + + m_blackList.insert("DeltaFunction"); + m_blackList.insert("ElasticDiffRotDiscreteCircle"); + m_blackList.insert("ElasticDiffSphere"); + m_blackList.insert("Muon_ExpDecayOscTest"); + + m_peakFunctions = getAllPeakFunctions(m_blackList); + m_parameterSets = getParameterSets(); + } + + /* This test sets all peak function parameters (center, fwhm, height) + * to the values supplied in the first ParameterSet contained in + * m_parameterSets. + * + * Then it retrieves the intensities of the peak functions and stores them. + * Each time new parameters are set, the ratio of the height parameter to + * the previous step is compared to the intensity ratio - they should be + * the same. + */ + void testAllFunctions() { + initializePeakFunctions(m_peakFunctions, m_parameterSets[0]); + + std::vector initialIntensities = getIntensities(m_peakFunctions); + + for (size_t i = 1; i < m_parameterSets.size(); ++i) { + double oldHeight = m_parameterSets[i - 1].height; + double newHeight = m_parameterSets[i].height; + double heightRatio = newHeight / oldHeight; + + initializePeakFunctions(m_peakFunctions, m_parameterSets[i]); + + std::vector newIntensities = getIntensities(m_peakFunctions); + + for (size_t j = 0; j < initialIntensities.size(); ++j) { + double oldIntensity = initialIntensities[j]; + double newIntensity = newIntensities[j]; + double intensityRatio = newIntensity / oldIntensity; + + TSM_ASSERT_DELTA( + "ITERATION " + DBL2STR(i) + ", " + m_peakFunctions[j]->name() + + ": Height was increased from " + DBL2STR(oldHeight) + " to " + + DBL2STR(newHeight) + " (ratio " + DBL2STR(heightRatio) + + "), but intensity changed from " + DBL2STR(oldIntensity) + + " to " + DBL2STR(newIntensity) + " (ratio " + + DBL2STR(intensityRatio) + ").", + intensityRatio, heightRatio, 1e-10); + } + + initialIntensities = newIntensities; + } + } + +private: + std::vector + getAllPeakFunctions(const std::set &blackList) const { + std::vector peakFunctions; + + std::vector registeredFunctions = + FunctionFactory::Instance().getFunctionNames(); + + for (auto it = registeredFunctions.begin(); it != registeredFunctions.end(); + ++it) { + if (blackList.count(*it) == 0) { + IPeakFunction_sptr peakFunction = + boost::dynamic_pointer_cast( + FunctionFactory::Instance().createFunction(*it)); + + if (peakFunction) { + peakFunctions.push_back(peakFunction); + } + } + } + + return peakFunctions; + } + + void initializePeakFunctions(const std::vector &peaks, + const ParameterSet ¶meters) const { + + for (auto it = peaks.begin(); it != peaks.end(); ++it) { + (*it)->setCentre(parameters.center); + + // for Ikeda-Carpenter it's not allowed to set Fwhm + try { + (*it)->setFwhm(parameters.fwhm); + } + catch (std::invalid_argument) { + } + + (*it)->setHeight(parameters.height); + } + } + + std::vector getParameterSets() const { + std::vector parameterSets; + parameterSets.push_back(ParameterSet(0.0, 4.34, 0.25)); + parameterSets.push_back(ParameterSet(0.0, 5.34, 0.25)); + parameterSets.push_back(ParameterSet(0.0, 6.34, 0.25)); + parameterSets.push_back(ParameterSet(0.0, 7.34, 0.25)); + + return parameterSets; + } + + std::vector + getIntensities(const std::vector &peaks) const { + std::vector intensities; + + for (auto it = peaks.begin(); it != peaks.end(); ++it) { + intensities.push_back((*it)->intensity()); + } + + return intensities; + } + + std::vector m_peakFunctions; + std::vector m_parameterSets; + std::set m_blackList; +}; + +#endif // IPEAKFUNCTIONINTENSITYTEST_H diff --git a/Code/Mantid/Framework/CurveFitting/test/LorentzianTest.h b/Code/Mantid/Framework/CurveFitting/test/LorentzianTest.h index 660939553f9b..f9781ce2b345 100644 --- a/Code/Mantid/Framework/CurveFitting/test/LorentzianTest.h +++ b/Code/Mantid/Framework/CurveFitting/test/LorentzianTest.h @@ -103,6 +103,21 @@ class LorentzianTest : public CxxTest::TestSuite TS_ASSERT_EQUALS(y[0], 0.0); } + void testIntensity() + { + Mantid::CurveFitting::Lorentzian lor; + lor.initialize(); + lor.setHeight(2.0); + lor.setCentre(3.0); + lor.setFwhm(1.0); + + TS_ASSERT_DELTA(lor.intensity(), 1.873097930277787, 1e-10); + TS_ASSERT_THROWS_NOTHING(lor.setIntensity(2.0)); + + TS_ASSERT_DELTA(lor.intensity(), 2.0, 1e-10); + TS_ASSERT_EQUALS(lor.fwhm(), 1.0); + } + private: class TestableLorentzian : public Mantid::CurveFitting::Lorentzian diff --git a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h index 048970b8f801..f22452fabd9e 100644 --- a/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h +++ b/Code/Mantid/Framework/DataHandling/inc/MantidDataHandling/LoadFITS.h @@ -76,7 +76,7 @@ namespace DataHandling { class DLLExport LoadFITS : public API::IFileLoader { public: - LoadFITS() {} + LoadFITS(); virtual ~LoadFITS() {} /// Algorithm's name for identification overriding a virtual method diff --git a/Code/Mantid/Framework/DataHandling/src/DownloadInstrument.cpp b/Code/Mantid/Framework/DataHandling/src/DownloadInstrument.cpp index 8fcaf7d739ad..2d4788b2b75d 100644 --- a/Code/Mantid/Framework/DataHandling/src/DownloadInstrument.cpp +++ b/Code/Mantid/Framework/DataHandling/src/DownloadInstrument.cpp @@ -349,7 +349,8 @@ int DownloadInstrument::doDownloadFile(const std::string &urlFile, const StringToStringMap &headers) { int retStatus = 0; InternetHelper inetHelper; - retStatus = inetHelper.downloadFile(urlFile, localFilePath, headers); + inetHelper.headers() = headers; + retStatus = inetHelper.downloadFile(urlFile, localFilePath); return retStatus; } diff --git a/Code/Mantid/Framework/DataHandling/src/LoadAscii2.cpp b/Code/Mantid/Framework/DataHandling/src/LoadAscii2.cpp index 191e995b9e38..37dc4a4e6436 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadAscii2.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadAscii2.cpp @@ -25,7 +25,10 @@ using namespace Kernel; using namespace API; /// Empty constructor -LoadAscii2::LoadAscii2() : m_columnSep(), m_separatorIndex() {} +LoadAscii2::LoadAscii2() : m_columnSep(), m_separatorIndex(), m_comment(), + m_baseCols(0), m_specNo(0), m_lastBins(0), m_curBins(0), m_spectraStart(), + m_spectrumIDcount(0), m_lineNo(0), m_spectra(), m_curSpectra(NULL) { +} /** * Return the confidence with with this algorithm can load the file diff --git a/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp b/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp index b2bd92871d58..dc3afd41e776 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadEventNexus.cpp @@ -932,13 +932,19 @@ class LoadBankFromDiskTask : public Task { //---------------------------------------------------------------------------------------------- /** Empty default constructor */ -LoadEventNexus::LoadEventNexus() - : IFileLoader(), - discarded_events(0), - m_file(NULL), - m_instrument_loaded_correctly(false), - m_logs_loaded_correctly(false), - event_id_is_spec(false) {} +LoadEventNexus::LoadEventNexus() : IFileLoader(), + m_filename(), filter_tof_min(0), filter_tof_max(0), m_specList(), + m_specMin(0), m_specMax(0), filter_time_start(), filter_time_stop(), + chunk(0), totalChunks(0), firstChunkForBank(0), eventsPerChunk(0), + m_tofMutex(), longest_tof(0), shortest_tof(0), bad_tofs(0), + discarded_events(0), precount(0), compressTolerance(0), eventVectors(), + m_eventVectorMutex(), eventid_max(0), pixelID_to_wi_vector(), + pixelID_to_wi_offset(), m_bankPulseTimes(), m_allBanksPulseTimes(), + m_top_entry_name(), m_file(NULL), splitProcessing(false), + m_haveWeights(false), weightedEventVectors(), + m_instrument_loaded_correctly(false), loadlogs(false), + m_logs_loaded_correctly(false), event_id_is_spec(false) { +} //---------------------------------------------------------------------------------------------- /** Destructor */ @@ -2153,7 +2159,8 @@ void LoadEventNexus::deleteBanks(API::MatrixWorkspace_sptr workspace, for (int row = 0; row < static_cast(grandchildren.size()); row++) { Detector *d = dynamic_cast( const_cast(grandchildren[row].get())); - inst->removeDetector(d); + if (d) + inst->removeDetector(d); } } IComponent *comp = dynamic_cast(detList[i].get()); @@ -2823,7 +2830,9 @@ LoadEventNexus::runLoadNexusLogs(const std::string &nexusfilename, Kernel::TimeSeriesProperty *log = dynamic_cast *>( localWorkspace->mutableRun().getProperty("proton_charge")); - const std::vector temp = log->timesAsVector(); + std::vector temp; + if (log) + temp = log->timesAsVector(); // if (returnpulsetimes) out = new BankPulseTimes(temp); if (returnpulsetimes) out = boost::make_shared(temp); diff --git a/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus.cpp b/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus.cpp index a6d61d8b2900..d8d0ab699c66 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus.cpp @@ -78,8 +78,15 @@ static const double TOF_CONVERSION = .1; static const double CURRENT_CONVERSION = 1.e-6 / 3600.; LoadEventPreNexus::LoadEventPreNexus() - : Mantid::API::IFileLoader(), eventfile(NULL), - max_events(0) {} + : Mantid::API::IFileLoader(), + prog(NULL), spectra_list(), pulsetimes(), event_indices(), proton_charge(), + proton_charge_tot(0), pixel_to_wkspindex(), pixelmap(), detid_max(), + eventfile(NULL), num_events(0), num_pulses(0), numpixel(0), + num_good_events(0), num_error_events(0), num_ignored_events(0), + first_event(0), max_events(0), using_mapping_file(false), + loadOnlySomeSpectra(false), spectraLoadMap(), longest_tof(0), + shortest_tof(0), parallelProcessing(false) { +} LoadEventPreNexus::~LoadEventPreNexus() { delete this->eventfile; } diff --git a/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus2.cpp b/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus2.cpp index 0443bce0df6d..70aec93f7f76 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus2.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadEventPreNexus2.cpp @@ -224,8 +224,15 @@ int LoadEventPreNexus2::confidence(Kernel::FileDescriptor &descriptor) const { /** Constructor */ LoadEventPreNexus2::LoadEventPreNexus2() - : Mantid::API::IFileLoader(), eventfile(NULL), - max_events(0) {} + : Mantid::API::IFileLoader(), + prog(NULL), spectra_list(), pulsetimes(), event_indices(), proton_charge(), + proton_charge_tot(0), pixel_to_wkspindex(), pixelmap(), detid_max(), + eventfile(NULL), num_events(0), num_pulses(0), numpixel(0), + num_good_events(0), num_error_events(0), num_ignored_events(0), + first_event(0), max_events(0), using_mapping_file(false), + loadOnlySomeSpectra(false), spectraLoadMap(), longest_tof(0), + shortest_tof(0), parallelProcessing(false) { +} //---------------------------------------------------------------------------------------------- /** Desctructor diff --git a/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp b/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp index a72f3182f2c4..5d21f759abc3 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadFITS.cpp @@ -40,6 +40,16 @@ namespace DataHandling { // Register the algorithm into the AlgorithmFactory DECLARE_FILELOADER_ALGORITHM(LoadFITS); +/** + * Constructor. Just initialize everything to prevent issues. + */ +LoadFITS::LoadFITS(): m_headerScaleKey(), m_headerOffsetKey(), + m_headerBitDepthKey(), m_headerRotationKey(), + m_headerImageKeyKey(), m_mapFile(), + m_headerAxisNameKeys(), m_baseName(), + m_spectraCount(0), m_progress(NULL) { +} + /** * Return the confidence with with this algorithm can load the file * @param descriptor A descriptor for the file @@ -123,8 +133,6 @@ void LoadFITS::exec() { std::vector paths; string fName = getPropertyValue("Filename"); boost::split(paths, fName, boost::is_any_of(",")); - m_baseName = ""; - m_spectraCount = 0; // If paths contains a non fits file, assume (for now) that it contains // information about the rotations diff --git a/Code/Mantid/Framework/DataHandling/src/LoadISISNexus2.cpp b/Code/Mantid/Framework/DataHandling/src/LoadISISNexus2.cpp index 24c18a7d081a..ca7d7a0dcf2b 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadISISNexus2.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadISISNexus2.cpp @@ -51,7 +51,9 @@ LoadISISNexus2::LoadISISNexus2() m_monBlockInfo(), m_loadBlockInfo(), m_have_detector(false), m_load_selected_spectra(false), m_specInd2specNum_map(), m_spec2det_map(), m_entrynumber(0), m_tof_data(), m_proton_charge(0.), m_spec(), - m_monitors(), m_logCreator(), m_progress() {} + m_spec_end(NULL), m_monitors(), m_logCreator(), m_progress(), + m_cppFile() { +} /** * Return the confidence criteria for this algorithm can load the file diff --git a/Code/Mantid/Framework/DataHandling/src/LoadInstrument.cpp b/Code/Mantid/Framework/DataHandling/src/LoadInstrument.cpp index e6c1d39181ed..943e218a753f 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadInstrument.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadInstrument.cpp @@ -122,9 +122,14 @@ void LoadInstrument::exec() { // Initialize the parser. Avoid copying the xmltext out of the property // here. - parser.initialize( - m_filename, m_instName, - *dynamic_cast *>(InstrumentXML)); + const PropertyWithValue *xml = + dynamic_cast *>(InstrumentXML); + if (xml) { + parser.initialize(m_filename, m_instName, *xml); + } else { + throw std::invalid_argument("The instrument XML passed cannot be " + "casted to a standard string."); + } } // otherwise we need either Filename or InstrumentName to be set else { diff --git a/Code/Mantid/Framework/DataHandling/src/LoadMcStas.cpp b/Code/Mantid/Framework/DataHandling/src/LoadMcStas.cpp index 2e80fb9e8c3c..027c60f08be6 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadMcStas.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadMcStas.cpp @@ -543,24 +543,24 @@ void LoadMcStas::readHistogramData( */ int LoadMcStas::confidence(Kernel::NexusDescriptor &descriptor) const { using namespace ::NeXus; - // We will look at the first entry and check for a - // simulation class that contains a name attribute with the value=mcstas + // look at to see if entry1/simulation/name exist first and then + // if its value = mccode int confidence(0); - try { - ::NeXus::File file = ::NeXus::File(descriptor.filename()); - auto entries = file.getEntries(); - if (!entries.empty()) { - auto firstIt = entries.begin(); - file.openGroup(firstIt->first, firstIt->second); - file.openGroup("simulation", "NXnote"); - std::string nameAttrValue; - file.readData("name", nameAttrValue); - if (boost::iequals(nameAttrValue, "mccode")) - confidence = 98; - file.closeGroup(); - file.closeGroup(); + if(descriptor.pathExists("/entry1/simulation/name")) { + try { + // need to look inside file to check value of entry1/simulation/name + ::NeXus::File file = ::NeXus::File(descriptor.filename()); + file.openGroup( descriptor.firstEntryNameType().first, descriptor.firstEntryNameType().second); + file.openGroup("simulation", "NXnote"); + std::string value; + // check if entry1/simulation/name equals mccode + file.readData("name", value); + if (boost::iequals(value, "mccode")) + confidence = 98; + file.closeGroup(); + file.closeGroup(); + } catch (::NeXus::Exception &) { } - } catch (::NeXus::Exception &) { } return confidence; } diff --git a/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp b/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp index 868805dea0ac..ebbde7d28c0d 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadNexusLogs.cpp @@ -133,9 +133,6 @@ void LoadNexusLogs::exec() { // the code below will allow current SANS2D files to load if (workspace->mutableRun().hasProperty("proton_log")) { std::vector event_frame_number; - Kernel::TimeSeriesProperty *plog = - dynamic_cast *>( - workspace->mutableRun().getProperty("proton_log")); this->getLogger().notice() << "Using old ISIS proton_log and event_frame_number indirection..." << std::endl; @@ -167,6 +164,12 @@ void LoadNexusLogs::exec() { file.openPath("/" + entry_name); if (!event_frame_number.empty()) // ISIS indirection - see above comments { + Kernel::TimeSeriesProperty *plog = + dynamic_cast *>( + workspace->mutableRun().getProperty("proton_log")); + if (!plog) + throw std::runtime_error("Could not cast (interpret) proton_log as a time " + "series property. Cannot continue."); Kernel::TimeSeriesProperty *pcharge = new Kernel::TimeSeriesProperty("proton_charge"); std::vector pval; diff --git a/Code/Mantid/Framework/DataHandling/src/LoadRaw3.cpp b/Code/Mantid/Framework/DataHandling/src/LoadRaw3.cpp index 4e7b88629261..421add0dc041 100644 --- a/Code/Mantid/Framework/DataHandling/src/LoadRaw3.cpp +++ b/Code/Mantid/Framework/DataHandling/src/LoadRaw3.cpp @@ -31,8 +31,11 @@ using namespace API; /// Constructor LoadRaw3::LoadRaw3() - : m_filename(), m_noTimeRegimes(0), m_prog(0.0), m_prog_start(0.0), - m_prog_end(1.0), m_lengthIn(0), m_timeChannelsVec(), m_total_specs(0) {} + : m_filename(), m_numberOfSpectra(), m_cache_options(), + m_specTimeRegimes(), m_noTimeRegimes(0), m_prog(0.0), + m_prog_start(0.0), m_prog_end(1.0), m_lengthIn(0), + m_timeChannelsVec(), m_total_specs(0), m_periodList() { +} LoadRaw3::~LoadRaw3() {} diff --git a/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp b/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp index f3a74c85f6b8..31e715bb976c 100644 --- a/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp +++ b/Code/Mantid/Framework/DataHandling/src/ProcessDasNexusLog.cpp @@ -388,6 +388,9 @@ void ProcessDasNexusLog::convertToAbsoluteTime( Kernel::Property *log = ws->run().getProperty(logname); Kernel::TimeSeriesProperty *tslog = dynamic_cast *>(log); + if (!tslog) + throw std::runtime_error("Invalid time series log: it could not be cast " + "(interpreted) as a time series property"); std::vector times = tslog->timesAsVector(); std::vector values = tslog->valuesAsVector(); @@ -445,6 +448,9 @@ void ProcessDasNexusLog::writeLogtoFile(API::MatrixWorkspace_sptr ws, Kernel::Property *log = ws->run().getProperty(logname); Kernel::TimeSeriesProperty *tslog = dynamic_cast *>(log); + if (!tslog) + throw std::runtime_error("Invalid time series log: it could not be cast " + "(interpreted) as a time series property"); std::vector times = tslog->timesAsVector(); std::vector values = tslog->valuesAsVector(); diff --git a/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h b/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h index 598f9758378a..0ae94946fa50 100644 --- a/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h +++ b/Code/Mantid/Framework/DataHandling/test/LoadGSASInstrumentFileTest.h @@ -205,6 +205,113 @@ class LoadGSASInstrumentFileTest : public CxxTest::TestSuite return; } + void test_workspace() + { + // Generate file with two banks + string filename("TestWorskpace.irf"); + generate2BankPrmFile(filename); + + // Create workspace group to put parameters into + // This is a group of two workspaces + createWorkspaceGroup(2,"loadGSASInstrumentFileWorkspace"); + + // Set up algorithm to load into the workspace + LoadGSASInstrumentFile alg; + alg.initialize(); + alg.setProperty("Filename", filename); + alg.setPropertyValue("Banks", "1,2"); + alg.setProperty("Workspace", wsName); + + // Execute + TS_ASSERT_THROWS_NOTHING(alg.execute()); + TS_ASSERT(alg.isExecuted()); + + // Check parameters in output workspace + // The output workspace is a workspace group with each + // member corresponding to each of the one banks in the prm file + + // First, check first workspace + WorkspaceGroup_sptr gws; + gws = AnalysisDataService::Instance().retrieveWS(wsName); + auto ws = boost::dynamic_pointer_cast(gws->getItem(0)); + Mantid::Geometry::ParameterMap& paramMap = ws->instrumentParameters(); + boost::shared_ptr instr = ws->getInstrument(); + + // To check parameters in workspace + Mantid::Geometry::FitParameter fitParam; + Mantid::Geometry::Parameter_sptr param; + + // Check Alpha0 parameter + param = paramMap.get(&(*instr), "Alpha0", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 0.00); + // Check Alpha1 parameter + param = paramMap.get(&(*instr), "Alpha1", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 0.21); + // Check Beta0 parameter + param = paramMap.get(&(*instr), "Beta0", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 31.7927); + // Check Beta1 parameter + param = paramMap.get(&(*instr), "Kappa", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 51.4205); + // Check SigmsSquared parameter + // This is a formula, so values are not exact + param = paramMap.get(&(*instr), "SigmaSquared", "fitting"); + fitParam = param->value(); + TS_ASSERT_DELTA( fitParam.getValue(0.0), 0.01, 0.000001); + TS_ASSERT_DELTA( fitParam.getValue(0.5), 7814.7468, 0.000001); + // Check Gamma parameter + // Although this is a formula, all coefficients should be zero + // and so values should be exactly 0 as well + param = paramMap.get(&(*instr), "Gamma", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( fitParam.getValue( 0.0 ), 0.0); + TS_ASSERT_EQUALS( fitParam.getValue( 0.0 ), 0.0); + + + // Now check second workspace + ws = boost::dynamic_pointer_cast(gws->getItem(1)); + Mantid::Geometry::ParameterMap& paramMap2 = ws->instrumentParameters(); + instr = ws->getInstrument(); + + // Check Alpha0 parameter + param = paramMap2.get(&(*instr), "Alpha0", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 0.001); + // Check Alpha1 parameter + param = paramMap2.get(&(*instr), "Alpha1", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 0.22); + // Check Beta0 parameter + param = paramMap2.get(&(*instr), "Beta0", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 32.7927); + // Check Beta1 parameter + param = paramMap2.get(&(*instr), "Kappa", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( boost::lexical_cast(fitParam.getFormula()), 52.4205); + // Check SigmsSquared parameter + // This is a formula, so values are not exact + param = paramMap2.get(&(*instr), "SigmaSquared", "fitting"); + fitParam = param->value(); + TS_ASSERT_DELTA( fitParam.getValue(0.0), 0.04, 0.000001); + TS_ASSERT_DELTA( fitParam.getValue(0.5), 21840.741796, 0.000001); + // Check Gamma parameter + // Although this is a formula, all coefficients should be zero + // and so values should be exactly 0 as well + param = paramMap2.get(&(*instr), "Gamma", "fitting"); + fitParam = param->value(); + TS_ASSERT_EQUALS( fitParam.getValue( 0.0 ), 0.0); + TS_ASSERT_EQUALS( fitParam.getValue( 0.0 ), 0.0); + + // Clean + Poco::File("TestWorskpace.irf").remove(); + AnalysisDataService::Instance().remove("loadGSASInstrumentFileWorkspace"); + } + //---------------------------------------------------------------------------------------------- /** Parse a TableWorkspace to a map */ @@ -353,6 +460,28 @@ class LoadGSASInstrumentFileTest : public CxxTest::TestSuite return; } + //---------------------------------------------------------------------------------------------- + /** Create a workspace group with specified number of workspaces. + */ + void createWorkspaceGroup( size_t numberOfWorkspaces, std::string workspaceName) + { + // create a workspace with some sample data + WorkspaceGroup_sptr gws(new API::WorkspaceGroup); + + for (size_t i=0; i < numberOfWorkspaces; ++i) + { + Workspace_sptr ws = WorkspaceFactory::Instance().create("Workspace2D",1,1,1); + Workspace2D_sptr ws2D = boost::dynamic_pointer_cast(ws); + gws->addWorkspace( ws2D ); + } + + // put this workspace in the analysis data service + TS_ASSERT_THROWS_NOTHING(AnalysisDataService::Instance().add(workspaceName, gws)); + + // save workspace name + wsName = workspaceName; + } + /* Return the number of rows the table must have */ int getExpectedNumberOfRows() @@ -361,7 +490,7 @@ class LoadGSASInstrumentFileTest : public CxxTest::TestSuite } private: - std::string wsName; // For Workspace property + std::string wsName; // For workspace property }; diff --git a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h index 877e8adad604..c5c33fbc2a52 100644 --- a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h +++ b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/Peak.h @@ -3,12 +3,15 @@ #include "MantidAPI/IPeak.h" #include "MantidGeometry/Instrument.h" +#include "MantidKernel/Logger.h" #include "MantidKernel/Matrix.h" #include "MantidKernel/V3D.h" #include "MantidKernel/PhysicalConstants.h" #include "MantidKernel/System.h" #include "MantidGeometry/Crystal/PeakShape.h" #include +#include + namespace Mantid { namespace DataObjects { @@ -25,10 +28,10 @@ class DLLExport Peak : public API::IPeak { Peak(); Peak(Geometry::Instrument_const_sptr m_inst, Mantid::Kernel::V3D QLabFrame, - double detectorDistance = 1.0); + boost::optional detectorDistance = boost::optional()); Peak(Geometry::Instrument_const_sptr m_inst, Mantid::Kernel::V3D QSampleFrame, Mantid::Kernel::Matrix goniometer, - double detectorDistance = 1.0); + boost::optional detectorDistance = boost::optional()); Peak(Geometry::Instrument_const_sptr m_inst, int m_DetectorID, double m_Wavelength); Peak(Geometry::Instrument_const_sptr m_inst, int m_DetectorID, @@ -83,9 +86,9 @@ class DLLExport Peak : public API::IPeak { Mantid::Kernel::V3D getDetectorPositionNoCheck() const; void setQSampleFrame(Mantid::Kernel::V3D QSampleFrame, - double detectorDistance = 1.0); + boost::optional detectorDistance = boost::optional()); void setQLabFrame(Mantid::Kernel::V3D QLabFrame, - double detectorDistance = 1.0); + boost::optional detectorDistance = boost::optional()); void setWavelength(double wavelength); double getWavelength() const; @@ -134,7 +137,7 @@ class DLLExport Peak : public API::IPeak { private: - + bool findDetector(const Mantid::Kernel::V3D &beam); /// Shared pointer to the instrument (for calculating some values ) Geometry::Instrument_const_sptr m_inst; @@ -208,6 +211,9 @@ class DLLExport Peak : public API::IPeak { /// Peak shape Mantid::Geometry::PeakShape_const_sptr m_peakShape; + + /// Static logger + static Mantid::Kernel::Logger g_log; }; } // namespace Mantid diff --git a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/PeaksWorkspace.h b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/PeaksWorkspace.h index 42cc58043f1b..4c4efe464c89 100644 --- a/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/PeaksWorkspace.h +++ b/Code/Mantid/Framework/DataObjects/inc/MantidDataObjects/PeaksWorkspace.h @@ -21,6 +21,7 @@ #include #include #include +#include // IsamplePosition should be IsampleOrientation namespace Mantid { @@ -108,9 +109,13 @@ class DLLExport PeaksWorkspace : public Mantid::API::IPeaksWorkspace { const Peak &getPeak(int peakNum) const; API::IPeak *createPeak(Kernel::V3D QFrame, - double detectorDistance = 1.0) const; + boost::optional detectorDistance = boost::optional()) const; std::vector> peakInfo(Kernel::V3D qFrame, bool labCoords) const; + + + Peak *createPeakHKL(Kernel::V3D HKL) const; + int peakInfoNumber(Kernel::V3D qFrame, bool labCoords) const; std::vector &getPeaks(); diff --git a/Code/Mantid/Framework/DataObjects/src/EventWorkspace.cpp b/Code/Mantid/Framework/DataObjects/src/EventWorkspace.cpp index a99d81b44f5b..bec4ade53280 100644 --- a/Code/Mantid/Framework/DataObjects/src/EventWorkspace.cpp +++ b/Code/Mantid/Framework/DataObjects/src/EventWorkspace.cpp @@ -35,7 +35,9 @@ using namespace Mantid::Kernel; //---- Constructors //------------------------------------------------------------------- -EventWorkspace::EventWorkspace() : mru(new EventWorkspaceMRU) {} +EventWorkspace::EventWorkspace() : data(), m_noVectors(), + mru(new EventWorkspaceMRU) { +} EventWorkspace::~EventWorkspace() { delete mru; diff --git a/Code/Mantid/Framework/DataObjects/src/Peak.cpp b/Code/Mantid/Framework/DataObjects/src/Peak.cpp index 5e6101ff5e9b..71e958d83617 100644 --- a/Code/Mantid/Framework/DataObjects/src/Peak.cpp +++ b/Code/Mantid/Framework/DataObjects/src/Peak.cpp @@ -1,6 +1,7 @@ #include "MantidDataObjects/Peak.h" #include "MantidDataObjects/NoShape.h" #include "MantidGeometry/Instrument/RectangularDetector.h" +#include "MantidGeometry/Instrument/ReferenceFrame.h" #include "MantidGeometry/Objects/InstrumentRayTracer.h" #include "MantidKernel/Strings.h" #include "MantidKernel/System.h" @@ -29,11 +30,11 @@ Peak::Peak() * * @param m_inst :: Shared pointer to the instrument for this peak detection * @param QLabFrame :: Q of the center of the peak, in reciprocal space - * @param detectorDistance :: distance between the sample and the detector. + * @param detectorDistance :: Optional distance between the sample and the detector. Calculated if not explicitly provided. * Used to give a valid TOF. Default 1.0 meters. */ Peak::Peak(Geometry::Instrument_const_sptr m_inst, - Mantid::Kernel::V3D QLabFrame, double detectorDistance) + Mantid::Kernel::V3D QLabFrame, boost::optional detectorDistance) : m_H(0), m_K(0), m_L(0), m_Intensity(0), m_SigmaIntensity(0), m_BinCount(0), m_GoniometerMatrix(3, 3, true), m_InverseGoniometerMatrix(3, 3, true), m_RunNumber(0), m_MonitorCount(0), @@ -51,12 +52,12 @@ Peak::Peak(Geometry::Instrument_const_sptr m_inst, * @param QSampleFrame :: Q of the center of the peak, in reciprocal space, in *the sample frame (goniometer rotation accounted for). * @param goniometer :: a 3x3 rotation matrix - * @param detectorDistance :: distance between the sample and the detector. + * @param detectorDistance :: Optional distance between the sample and the detector. Calculated if not explicitly provided. * Used to give a valid TOF. Default 1.0 meters. */ Peak::Peak(Geometry::Instrument_const_sptr m_inst, Mantid::Kernel::V3D QSampleFrame, - Mantid::Kernel::Matrix goniometer, double detectorDistance) + Mantid::Kernel::Matrix goniometer, boost::optional detectorDistance) : m_H(0), m_K(0), m_L(0), m_Intensity(0), m_SigmaIntensity(0), m_BinCount(0), m_GoniometerMatrix(goniometer), m_InverseGoniometerMatrix(goniometer), m_RunNumber(0), m_MonitorCount(0), @@ -463,10 +464,10 @@ Mantid::Kernel::V3D Peak::getQSampleFrame() const { * This is in inelastic convention: momentum transfer of the LATTICE! * Also, q does NOT have a 2pi factor = it is equal to 1/wavelength. * @param detectorDistance :: distance between the sample and the detector. - * Used to give a valid TOF. Default 1.0 meters. + * Used to give a valid TOF. You do NOT need to explicitly set this. */ void Peak::setQSampleFrame(Mantid::Kernel::V3D QSampleFrame, - double detectorDistance) { + boost::optional detectorDistance) { V3D Qlab = m_GoniometerMatrix * QSampleFrame; this->setQLabFrame(Qlab, detectorDistance); } @@ -483,11 +484,11 @@ void Peak::setQSampleFrame(Mantid::Kernel::V3D QSampleFrame, * This is in inelastic convention: momentum transfer of the LATTICE! * Also, q does have a 2pi factor = it is equal to 2pi/wavelength (in *Angstroms). - * @param detectorDistance :: distance between the sample and the detector. - * Used to give a valid TOF. Default 1.0 meters. + * @param detectorDistance :: distance between the sample and the detector. If this is provided. Then we do not + * ray trace to find the intersecing detector. */ void Peak::setQLabFrame(Mantid::Kernel::V3D QLabFrame, - double detectorDistance) { + boost::optional detectorDistance) { // Clear out the detector = we can't know them m_DetectorID = -1; m_det = IDetector_sptr(); @@ -495,25 +496,32 @@ void Peak::setQLabFrame(Mantid::Kernel::V3D QLabFrame, m_Col = -1; m_BankName = "None"; + // The q-vector direction of the peak is = goniometer * ub * hkl_vector V3D q = QLabFrame; - /* The incident neutron wavevector is in the +Z direction, ki = 1/wl (in z - * direction). + /* The incident neutron wavevector is along the beam direction, ki = 1/wl (usually z, but referenceframe is definitive). * In the inelastic convention, q = ki - kf. - * The final neutron wavector kf = -qx in x; -qy in y; and (-qz+1/wl) in z. + * The final neutron wavector kf = -qx in x; -qy in y; and (-q.beam_dir+1/wl) in beam direction. * AND: norm(kf) = norm(ki) = 2*pi/wavelength - * THEREFORE: 1/wl = norm(q)^2 / (2*qz) + * THEREFORE: 1/wl = norm(q)^2 / (2*q.beam_dir) */ double norm_q = q.norm(); + if(!this->m_inst) + { + throw std::invalid_argument("Setting QLab without an instrument would lead to an inconsistent state for the Peak"); + } + boost::shared_ptr refFrame = this->m_inst->getReferenceFrame(); + const V3D refBeamDir = refFrame->vecPointingAlongBeam(); + const double qBeam = q.scalar_prod(refBeamDir); if (norm_q == 0.0) throw std::invalid_argument("Peak::setQLabFrame(): Q cannot be 0,0,0."); - if (q.Z() == 0.0) + if ( qBeam == 0.0) throw std::invalid_argument( - "Peak::setQLabFrame(): Q cannot be 0 in the Z (beam) direction."); + "Peak::setQLabFrame(): Q cannot be 0 in the beam direction."); - double one_over_wl = (norm_q * norm_q) / (2.0 * q.Z()); + double one_over_wl = (norm_q * norm_q) / (2.0 * qBeam); double wl = (2.0 * M_PI) / one_over_wl; if (wl < 0.0) { std::ostringstream mess; @@ -522,16 +530,30 @@ void Peak::setQLabFrame(Mantid::Kernel::V3D QLabFrame, throw std::invalid_argument(mess.str()); } - // This is the scattered direction, kf = (-qx, -qy, 1/wl-qz) - V3D beam = q * -1.0; - beam.setZ(one_over_wl - q.Z()); - beam.normalize(); // Save the wavelength this->setWavelength(wl); + V3D detectorDir = q * -1.0; + detectorDir[refFrame->pointingAlongBeam()] = one_over_wl - qBeam; + detectorDir.normalize(); + // Use the given detector distance to find the detector position. - detPos = samplePos + beam * detectorDistance; + if(detectorDistance.is_initialized()) + { + detPos = samplePos + detectorDir * detectorDistance.get(); + // We do not-update the detector as by manually setting the distance the client seems to know better. + } + else + { + // Find the detector + const bool found = findDetector(detectorDir); + if (!found) + { + // This is important, so we ought to log when this fails to happen. + g_log.debug("Could not find detector after setting qLab via setQLab with QLab : " + q.toString()); + } + } } /** After creating a peak using the Q in the lab frame, @@ -544,12 +566,22 @@ void Peak::setQLabFrame(Mantid::Kernel::V3D QLabFrame, * @return true if the detector ID was found. */ bool Peak::findDetector() { - bool found = false; + // Scattered beam direction V3D oldDetPos = detPos; V3D beam = detPos - samplePos; beam.normalize(); + return findDetector(beam); +} + +/** + * @brief Peak::findDetector : Find the detector along the beam location. sets the detector, and detector position if found + * @param beam : detector direction from the sample as V3D + * @return True if a detector has been found + */ +bool Peak::findDetector(const Mantid::Kernel::V3D &beam) { + bool found = false; // Create a ray tracer InstrumentRayTracer tracker(m_inst); tracker.traceFromSample(beam); @@ -896,5 +928,7 @@ Mantid::Kernel::V3D Peak::getDetectorPosition() const { return getDetector()->getPos(); } +Mantid::Kernel::Logger Peak::g_log("PeakLogger"); + } // namespace Mantid } // namespace DataObjects diff --git a/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp b/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp index 5258f57751e4..83aabf18e3fd 100644 --- a/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp +++ b/Code/Mantid/Framework/DataObjects/src/PeaksWorkspace.cpp @@ -199,11 +199,11 @@ const Peak &PeaksWorkspace::getPeak(const int peakNum) const { //--------------------------------------------------------------------------------------------- /** Creates an instance of a Peak BUT DOES NOT ADD IT TO THE WORKSPACE * @param QLabFrame :: Q of the center of the peak, in reciprocal space - * @param detectorDistance :: distance between the sample and the detector. + * @param detectorDistance :: optional distance between the sample and the detector. You do NOT need to explicitly provide this distance. * @return a pointer to a new Peak object. */ API::IPeak *PeaksWorkspace::createPeak(Kernel::V3D QLabFrame, - double detectorDistance) const { + boost::optional detectorDistance) const { return new Peak(this->getInstrument(), QLabFrame, detectorDistance); } @@ -299,6 +299,7 @@ PeaksWorkspace::peakInfo(Kernel::V3D qFrame, bool labCoords) const { } try { + API::IPeak *peak = createPeak(Qlab); if (sample().hasOrientedLattice()) { @@ -387,6 +388,40 @@ PeaksWorkspace::peakInfo(Kernel::V3D qFrame, bool labCoords) const { return Result; } +/** + * Create a Peak from a HKL value provided by the client. + * + * + * @param HKL : reciprocal lattice vector coefficients + * @return Fully formed peak. + */ +Peak *PeaksWorkspace::createPeakHKL(V3D HKL) const +{ + /* + The following allows us to add peaks where we have a single UB to work from. + */ + + Geometry::OrientedLattice lattice = this->sample().getOrientedLattice(); + Geometry::Goniometer goniometer = this->run().getGoniometer(); + + // Calculate qLab from q HKL. As per Busing and Levy 1967, q_lab_frame = 2pi * Goniometer * UB * HKL + V3D qLabFrame = goniometer.getR() * lattice.getUB() * HKL * 2 * M_PI; + + // create a peak using the qLab frame + auto peak = new Peak(this->getInstrument(), qLabFrame); // This should calculate the detector positions too. + + // We need to set HKL separately to keep things consistent. + peak->setHKL(HKL[0], HKL[1], HKL[2]); + + // Set the goniometer + peak->setGoniometerMatrix(goniometer.getR()); + + // Take the run number from this + peak->setRunNumber(this->getRunNumber()); + + return peak; +} + /** * Returns selected information for a "peak" at QLabFrame. * diff --git a/Code/Mantid/Framework/DataObjects/test/PeakTest.h b/Code/Mantid/Framework/DataObjects/test/PeakTest.h index e7bd1b9929f4..317d54c3e840 100644 --- a/Code/Mantid/Framework/DataObjects/test/PeakTest.h +++ b/Code/Mantid/Framework/DataObjects/test/PeakTest.h @@ -5,6 +5,11 @@ #include "MockObjects.h" #include "MantidKernel/Timer.h" #include "MantidKernel/System.h" +#include "MantidKernel/UnitFactory.h" +#include "MantidKernel/Unit.h" +#include "MantidKernel/V3D.h" +#include "MantidKernel/PhysicalConstants.h" +#include "MantidGeometry/Instrument/ReferenceFrame.h" #include #include #include @@ -18,12 +23,25 @@ using namespace Mantid::Kernel; class PeakTest : public CxxTest::TestSuite { +private: + /// Common instrument + Instrument_sptr inst; + Instrument_sptr m_minimalInstrument; public: - /// Common instrument - Instrument_sptr inst; - void setUp() + + + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static PeakTest *createSuite() { + return new PeakTest(); + } + static void destroySuite(PeakTest *suite) { delete suite; } + + + // Constructor + PeakTest() : inst(ComponentCreationHelper::createTestInstrumentRectangular(5, 100)) { - inst = ComponentCreationHelper::createTestInstrumentRectangular(5, 100); + } void test_constructor() @@ -253,14 +271,16 @@ class PeakTest : public CxxTest::TestSuite void test_setQLabFrame_ThrowsIfQIsNull() { Peak p1(inst, 10000, 2.0); - TS_ASSERT_THROWS_ANYTHING(Peak p2(inst, V3D(0,0,0), 1.0)); - TS_ASSERT_THROWS_ANYTHING(Peak p2(inst, V3D(1,2,0), 1.0)); + const boost::optional distance = 1.0; + TS_ASSERT_THROWS_ANYTHING(Peak p2(inst, V3D(0,0,0), distance)); + TS_ASSERT_THROWS_ANYTHING(Peak p2(inst, V3D(1,2,0), distance)); } /** Compare two peaks, but not the detector IDs etc. */ void comparePeaks(Peak & p1, Peak & p2) { + // TODO. Peak should implement bool operator==(const Peak&) and that should be tested, rather than having external functionality here. TS_ASSERT_EQUALS( p1.getQLabFrame(), p2.getQLabFrame() ); TS_ASSERT_EQUALS( p1.getQSampleFrame(), p2.getQSampleFrame() ); TS_ASSERT_EQUALS( p1.getDetPos(), p2.getDetPos() ); @@ -282,7 +302,7 @@ class PeakTest : public CxxTest::TestSuite V3D detPos1 = p1.getDetPos(); // Construct using just Q - Peak p2(inst, Qlab1, detPos1.norm()); + Peak p2(inst, Qlab1, boost::optional(detPos1.norm())); comparePeaks(p1, p2); TS_ASSERT_EQUALS( p2.getBankName(), "None"); TS_ASSERT_EQUALS( p2.getRow(), -1); @@ -290,6 +310,40 @@ class PeakTest : public CxxTest::TestSuite TS_ASSERT_EQUALS( p2.getDetectorID(), -1); } + void test_setQLabFrame2() + { + // Create fictional instrument + const V3D source(0,0,0); + const V3D sample(15, 0, 0); + const V3D detectorPos(20, 5, 0); + const V3D beam1 = sample - source; + const V3D beam2 = detectorPos - sample; + auto minimalInstrument = ComponentCreationHelper::createMinimalInstrument( source, sample, detectorPos ); + + // Derive distances and angles + const double l1 = beam1.norm(); + const double l2 = beam2.norm(); + const V3D qLabDir = (beam1/l1) - (beam2/l2); + + const double microSecsInSec = 1e6; + + // Derive QLab for diffraction + const double wavenumber_in_angstrom_times_tof_in_microsec = + (Mantid::PhysicalConstants::NeutronMass * (l1 + l2) * 1e-10 * microSecsInSec) / + Mantid::PhysicalConstants::h_bar; + + V3D qLab = qLabDir * wavenumber_in_angstrom_times_tof_in_microsec; + + Peak peak; // Everything will be default + peak.setInstrument(minimalInstrument); // Can't do anything without the instrument + peak.setQLabFrame(qLab); + auto detector = peak.getDetector(); + + TSM_ASSERT("No detector", detector); + TS_ASSERT_EQUALS(1, detector->getID()); + TS_ASSERT_EQUALS(detectorPos, detector->getPos()); + } + /** Create peaks using Q in sample frame + a goniometer rotation matrix*/ void test_setQSampleFrame() { @@ -323,7 +377,7 @@ class PeakTest : public CxxTest::TestSuite V3D detPos1 = p1.getDetPos(); // Construct using just Q - Peak p2(inst, Qlab1, detPos1.norm()); + Peak p2(inst, Qlab1, boost::optional(detPos1.norm())); TS_ASSERT( p2.findDetector() ); comparePeaks(p1, p2); TS_ASSERT_EQUALS( p2.getBankName(), "bank1"); @@ -350,7 +404,7 @@ class PeakTest : public CxxTest::TestSuite const double wavelength = 2; Peak p(inst, detectorId, wavelength); TSM_ASSERT_THROWS_NOTHING("Nothing wrong here, detector is valid", p.getDetectorPosition()); - p.setQLabFrame(V3D(1,1,1), 1); // This sets the detector pointer to null and detector id to -1; + p.setQLabFrame(V3D(1,1,1), 1.0); // This sets the detector pointer to null and detector id to -1; TSM_ASSERT_THROWS("Detector is not valid", p.getDetectorPosition(), Mantid::Kernel::Exception::NullPointerException&); } diff --git a/Code/Mantid/Framework/DataObjects/test/PeaksWorkspaceTest.h b/Code/Mantid/Framework/DataObjects/test/PeaksWorkspaceTest.h index 20d627c7d99e..45f37ed189d0 100644 --- a/Code/Mantid/Framework/DataObjects/test/PeaksWorkspaceTest.h +++ b/Code/Mantid/Framework/DataObjects/test/PeaksWorkspaceTest.h @@ -14,6 +14,8 @@ #include "MantidKernel/V3D.h" #include "MantidKernel/Strings.h" #include "MantidKernel/PhysicalConstants.h" +#include "MantidGeometry/Crystal/OrientedLattice.h" +#include "MantidGeometry/Instrument/Goniometer.h" #include "MantidTestHelpers/NexusTestHelper.h" #include "MantidTestHelpers/ComponentCreationHelper.h" #include "MantidAPI/AlgorithmManager.h" @@ -360,6 +362,58 @@ class PeaksWorkspaceTest : public CxxTest::TestSuite TS_ASSERT_EQUALS(coordSystem, pw->getSpecialCoordinateSystem()); } + void test_createPeakHKL() + { + // Create simple fictional instrument + const V3D source(0,0,0); + const V3D sample(15, 0, 0); + const V3D detectorPos(20, 5, 0); + const V3D beam1 = sample - source; + const V3D beam2 = detectorPos - sample; + auto minimalInstrument = ComponentCreationHelper::createMinimalInstrument( source, sample, detectorPos ); + + // Derive distances and angles + const double l1 = beam1.norm(); + const double l2 = beam2.norm(); + const V3D qLabDir = (beam1/l1) - (beam2/l2); + + const double microSecsInSec = 1e6; + + // Derive QLab for diffraction + const double wavenumber_in_angstrom_times_tof_in_microsec = + (Mantid::PhysicalConstants::NeutronMass * (l1 + l2) * 1e-10 * microSecsInSec) / + Mantid::PhysicalConstants::h_bar; + V3D qLab = qLabDir * wavenumber_in_angstrom_times_tof_in_microsec; + + Mantid::Geometry::OrientedLattice orientedLattice(1, 1, 1, 90, 90, 90); // U is identity, real and reciprocal lattice vectors are identical. + Mantid::Geometry::Goniometer goniometer; // identity + V3D hkl = qLab / (2 * M_PI); // Given our settings above, this is the simplified relationship between qLab and hkl. + + // Now create a peaks workspace around the simple fictional instrument + PeaksWorkspace ws; + ws.setInstrument(minimalInstrument); + ws.mutableSample().setOrientedLattice(&orientedLattice); + ws.mutableRun().setGoniometer(goniometer, false); + + // Create the peak + Peak* peak = ws.createPeakHKL(hkl); + + /* + Now we check we have made a self - consistent peak + */ + TSM_ASSERT_EQUALS("New peak should have HKL we demanded.", hkl, peak->getHKL()); + TSM_ASSERT_EQUALS("New peak should have QLab we expected.", qLab, peak->getQLabFrame()); + TSM_ASSERT_EQUALS("QSample and QLab should be identical given the identity goniometer settings.", peak->getQLabFrame(), peak->getQSampleFrame()); + auto detector = peak->getDetector(); + TSM_ASSERT("No detector", detector); + TSM_ASSERT_EQUALS("This detector id does not match what we expect from the instrument definition", 1, detector->getID()); + TSM_ASSERT_EQUALS("Thie detector position is wrong", detectorPos, detector->getPos()); + TSM_ASSERT_EQUALS("Goniometer has not been set properly", goniometer.getR(), peak->getGoniometerMatrix()); + + // Clean up. + delete peak; + } + private: PeaksWorkspace_sptr createSaveTestPeaksWorkspace() diff --git a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Instrument/ReferenceFrame.h b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Instrument/ReferenceFrame.h index fb4c388bfe30..338e060f4ce3 100644 --- a/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Instrument/ReferenceFrame.h +++ b/Code/Mantid/Framework/Geometry/inc/MantidGeometry/Instrument/ReferenceFrame.h @@ -8,7 +8,7 @@ namespace Mantid { namespace Geometry { /// Type to describe pointing along options -enum PointingAlong { X, Y, Z }; +enum PointingAlong { X=0, Y=1, Z=2 }; /// Type to distingusih between l and r handedness enum Handedness { Left, Right }; diff --git a/Code/Mantid/Framework/Geometry/src/Instrument/Detector.cpp b/Code/Mantid/Framework/Geometry/src/Instrument/Detector.cpp index 545d6db6433f..3cd427268ece 100644 --- a/Code/Mantid/Framework/Geometry/src/Instrument/Detector.cpp +++ b/Code/Mantid/Framework/Geometry/src/Instrument/Detector.cpp @@ -45,10 +45,14 @@ Detector::~Detector() {} * @returns the detector id */ detid_t Detector::getID() const { - if (m_map) - return dynamic_cast(m_base)->getID(); - else - return m_id; + if (m_map) { + const Detector *d = dynamic_cast(m_base); + if (d) { + return d->getID(); + } + } + + return m_id; } /// Get the distance between the detector and another component @@ -137,10 +141,14 @@ bool Detector::isMasked() const { /// Is the detector a monitor? ///@return true if it is a monitor bool Detector::isMonitor() const { - if (m_map) - return dynamic_cast(m_base)->isMonitor(); - else - return m_isMonitor; + if (m_map) { + const Detector *d = dynamic_cast(m_base); + if (d) { + return d->isMonitor(); + } + } + + return m_isMonitor; } /** Sets the flag for whether this detector object is a monitor diff --git a/Code/Mantid/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp b/Code/Mantid/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp index a83138ee4639..02c439231f9d 100644 --- a/Code/Mantid/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp +++ b/Code/Mantid/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp @@ -4,11 +4,16 @@ #include "MantidGeometry/Objects/ShapeFactory.h" #include "MantidGeometry/Objects/Object.h" #include "MantidKernel/Exception.h" +#include "MantidKernel/Logger.h" #include #include #include #include +namespace { + Mantid::Kernel::Logger g_log("ObjCompAssembly"); +} + namespace Mantid { namespace Geometry { using Kernel::V3D; @@ -352,6 +357,10 @@ boost::shared_ptr ObjCompAssembly::createOutline() { throw Kernel::Exception::InstrumentDefinitionError("Empty ObjCompAssembly"); } + if (nelements() < 2) { + g_log.warning("Creating outline with fewer than 2 elements. The outline displayed may be inaccurate."); + } + // Get information about the shape and size of a detector std::string type; int otype; diff --git a/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp b/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp index bab1459e647d..d7b2f36805bc 100644 --- a/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp +++ b/Code/Mantid/Framework/Geometry/src/Rendering/OCGeometryGenerator.cpp @@ -44,7 +44,7 @@ GCC_DIAG_OFF(cast-qual) #include #include #include -#include +#include #include #include #include @@ -121,7 +121,7 @@ void OCGeometryGenerator::AnalyzeObject() { TopoDS_Shape Result = AnalyzeRule(const_cast(top)); try { ObjSurface = new TopoDS_Shape(Result); - BRepMesh::Mesh(Result, 0.001); + BRepMesh_IncrementalMesh(Result, 0.001); } catch (StdFail_NotDone &) { g_log.error("Cannot build the geometry. Check the geometry definition"); } diff --git a/Code/Mantid/Framework/Kernel/.gitignore b/Code/Mantid/Framework/Kernel/.gitignore new file mode 100644 index 000000000000..0fee3cc6e352 --- /dev/null +++ b/Code/Mantid/Framework/Kernel/.gitignore @@ -0,0 +1,3 @@ +inc/MantidKernel/PocoVersion.h +src/MantidVersion.cpp +src/ParaViewVersion.cpp diff --git a/Code/Mantid/Framework/Kernel/CMakeLists.txt b/Code/Mantid/Framework/Kernel/CMakeLists.txt index d8193e74dae8..887bba027157 100644 --- a/Code/Mantid/Framework/Kernel/CMakeLists.txt +++ b/Code/Mantid/Framework/Kernel/CMakeLists.txt @@ -196,6 +196,7 @@ set ( INC_FILES inc/MantidKernel/NullValidator.h inc/MantidKernel/ParaViewVersion.h inc/MantidKernel/PhysicalConstants.h + inc/MantidKernel/PocoVersion.h inc/MantidKernel/ProgressBase.h inc/MantidKernel/ProgressText.h inc/MantidKernel/Property.h @@ -416,6 +417,13 @@ if ( NOT NOT_GIT_REPO OR NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/src/MantidVersio ) endif () +########################################################################### +# This section deals with creating the PocoVersion implementation +########################################################################### +configure_file ( ${CMAKE_CURRENT_SOURCE_DIR}/inc/MantidKernel/PocoVersion.h.in + ${CMAKE_CURRENT_SOURCE_DIR}/inc/MantidKernel/PocoVersion.h +) + ########################################################################### # This section deals with creating the ParaViewVersion implementation ########################################################################### diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h index d90c55c32bb9..88d2df21fa57 100644 --- a/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h +++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/InternetHelper.h @@ -5,6 +5,7 @@ #include "MantidKernel/DllConfig.h" #include "MantidKernel/ProxyInfo.h" +#include #include namespace Poco { @@ -18,6 +19,8 @@ class HTTPClientSession; class HTTPResponse; // forward declaration class HTTPRequest; +// forward declaration +class HTMLForm; } } @@ -59,21 +62,46 @@ class MANTID_KERNEL_DLL InternetHelper { // Convenience typedef typedef std::map StringToStringMap; - virtual int - downloadFile(const std::string &urlFile, - const std::string &localFilePath = "", - const StringToStringMap &headers = StringToStringMap()); - virtual int - sendRequest(const std::string &url, std::ostream &responseStream, - const StringToStringMap &headers = StringToStringMap(), - const std::string &method = std::string(), - const std::string &body = std::string()); - + //getters and setters + void setTimeout(int seconds); + int getTimeout(); + + void setMethod(const std::string& method); + const std::string& getMethod(); + + void setContentType(const std::string& contentType); + const std::string& getContentType(); + + void setContentLength(std::streamsize length); + std::streamsize getContentLength(); + + void setBody(const std::string& body); + void setBody(const std::ostringstream& body); + void setBody(Poco::Net::HTMLForm& form); + const std::string& getBody(); + + int getResponseStatus(); + const std::string& getResponseReason(); + + void addHeader(const std::string& key, const std::string& value); + void removeHeader (const std::string& key); + const std::string& getHeader (const std::string& key); + void clearHeaders(); + StringToStringMap& headers(); + void reset(); + + + //Proxy methods Kernel::ProxyInfo &getProxy(const std::string &url); void clearProxy(); void setProxy(const Kernel::ProxyInfo &proxy); - void setTimeout(int seconds); + //Execute call methods + virtual int + downloadFile(const std::string &urlFile, + const std::string &localFilePath = ""); + virtual int + sendRequest(const std::string &url, std::ostream &responseStream); protected: virtual int sendHTTPSRequest(const std::string &url, @@ -91,14 +119,17 @@ class MANTID_KERNEL_DLL InternetHelper { Poco::URI &uri, std::ostream &responseStream); int processRelocation(const Poco::Net::HTTPResponse &response, std::ostream &responseStream); + Kernel::ProxyInfo m_proxyInfo; bool m_isProxySet; int m_timeout; + std::streamsize m_contentLength; std::string m_method; std::string m_contentType; std::string m_body; StringToStringMap m_headers; Poco::Net::HTTPRequest *m_request; + Poco::Net::HTTPResponse *m_response; }; } // namespace Kernel diff --git a/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in b/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in new file mode 100644 index 000000000000..41dc2720a436 --- /dev/null +++ b/Code/Mantid/Framework/Kernel/inc/MantidKernel/PocoVersion.h.in @@ -0,0 +1,33 @@ +#ifndef MANTID_KERNEL_POCOVERSION_H_ +#define MANTID_KERNEL_POCOVERSION_H_ + +/** Macros defining Poco version used to compile Mantid. + + Copyright © 2011 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge + National Laboratory & European Spallation Source + + This file is part of Mantid. + + Mantid is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + Mantid is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + + File change history is stored at: . + Code Documentation is available at: + */ +/// Major version of Poco used to build Mantid. +#define POCO_VERSION_MAJOR @POCO_VERSION_MAJOR@ +/// Minor version of Poco used to build Mantid. +#define POCO_VERSION_MINOR @POCO_VERSION_MINOR@ +/// Patch version of Poco used to build Mantid. +#define POCO_VERSION_PATCH @POCO_VERSION_PATCH@ +#endif /* MANTID_KERNEL_POCOVERSION_H_ */ diff --git a/Code/Mantid/Framework/Kernel/src/.gitignore b/Code/Mantid/Framework/Kernel/src/.gitignore deleted file mode 100644 index a81090024ef7..000000000000 --- a/Code/Mantid/Framework/Kernel/src/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -MantidVersion.cpp -ParaViewVersion.cpp \ No newline at end of file diff --git a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp index d55e4911f9dc..f881b729f0f9 100644 --- a/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp +++ b/Code/Mantid/Framework/Kernel/src/InternetHelper.cpp @@ -7,6 +7,7 @@ // Poco #include #include +#include #include #include #include @@ -33,6 +34,7 @@ // std #include +#include namespace Mantid { namespace Kernel { @@ -72,9 +74,9 @@ bool isRelocated(const int response) { /** Constructor */ InternetHelper::InternetHelper() - : m_proxyInfo(), m_isProxySet(false), m_timeout(30), + : m_proxyInfo(), m_isProxySet(false), m_timeout(30), m_contentLength(0), m_method(HTTPRequest::HTTP_GET), m_contentType("application/json"), - m_request(NULL) {} + m_body(), m_headers(), m_request(NULL),m_response(NULL) {} //---------------------------------------------------------------------------------------------- /** Constructor @@ -82,7 +84,7 @@ InternetHelper::InternetHelper() InternetHelper::InternetHelper(const Kernel::ProxyInfo &proxy) : m_proxyInfo(proxy), m_isProxySet(true), m_timeout(30), m_method(HTTPRequest::HTTP_GET), m_contentType("application/json"), - m_request(NULL) {} + m_body(), m_headers(), m_request(NULL),m_response(NULL) {} //---------------------------------------------------------------------------------------------- /** Destructor @@ -90,6 +92,9 @@ InternetHelper::InternetHelper(const Kernel::ProxyInfo &proxy) InternetHelper::~InternetHelper() { if (m_request != NULL) { delete m_request; + } + if (m_response != NULL) { + delete m_response; } } @@ -103,15 +108,32 @@ void InternetHelper::setupProxyOnSession(HTTPClientSession &session, } void InternetHelper::createRequest(Poco::URI &uri) { + if (m_request != NULL) { + delete m_request; + } + if (m_response != NULL) { + delete m_response; + } + m_request = new HTTPRequest(m_method, uri.getPathAndQuery(), HTTPMessage::HTTP_1_1); + m_response = new HTTPResponse(); if (!m_contentType.empty()) { m_request->setContentType(m_contentType); } + m_request->set("User-Agent", "MANTID"); + if (m_contentLength > 0) { + m_request->setContentLength(m_contentLength); + } + for (auto itHeaders = m_headers.begin(); itHeaders != m_headers.end(); ++itHeaders) { m_request->set(itHeaders->first, itHeaders->second); + } + + if (m_method == "POST") { + m_request->setChunkedTransferEncoding(true); } } @@ -120,13 +142,12 @@ int InternetHelper::sendRequestAndProcess(HTTPClientSession &session, std::ostream &responseStream) { // create a request this->createRequest(uri); - m_request->setContentLength(m_body.length()); session.sendRequest(*m_request) << m_body; - HTTPResponse res; - std::istream &rs = session.receiveResponse(res); - int retStatus = res.getStatus(); - g_log.debug() << "Answer from web: " << retStatus << " " << res.getReason() + + std::istream &rs = session.receiveResponse(*m_response); + int retStatus = m_response->getStatus(); + g_log.debug() << "Answer from web: " << retStatus << " " << m_response->getReason() << std::endl; if (retStatus == HTTPResponse::HTTP_OK || @@ -135,9 +156,10 @@ int InternetHelper::sendRequestAndProcess(HTTPClientSession &session, Poco::StreamCopier::copyStream(rs, responseStream); return retStatus; } else if (isRelocated(retStatus)) { - return this->processRelocation(res, responseStream); + return this->processRelocation(*m_response, responseStream); } else { - return processErrorStates(res, rs, uri.toString()); + Poco::StreamCopier::copyStream(rs, responseStream); + return processErrorStates(*m_response, rs, uri.toString()); } } @@ -156,34 +178,19 @@ int InternetHelper::processRelocation(const HTTPResponse &response, /** Performs a request using http or https depending on the url * @param url the address to the network resource * @param responseStream The stream to fill with the reply on success -* @param headers A optional key value pair map of any additional headers to -* include in the request. -* @param method Generally GET (default) or POST. -* @param body The request body to send. **/ int InternetHelper::sendRequest(const std::string &url, - std::ostream &responseStream, - const StringToStringMap &headers, - const std::string &method, - const std::string &body) { - // set instance variables from the input as appropriate - if (!method.empty()) { - m_method = method; - } - if (!headers.empty()) { - m_headers = headers; - } - if (!body.empty()) { - m_body = body; - } - + std::ostream &responseStream) { + // send the request Poco::URI uri(url); + int retval; if ((uri.getScheme() == "https") || (uri.getPort() == 443)) { - return sendHTTPSRequest(url, responseStream); + retval = sendHTTPSRequest(url, responseStream); } else { - return sendHTTPRequest(url, responseStream); + retval = sendHTTPRequest(url, responseStream); } + return retval; } /** Performs a request using http @@ -350,6 +357,7 @@ int InternetHelper::processErrorStates(const Poco::Net::HTTPResponse &res, // show the error info << res.getReason(); info << ss.str(); + g_log.debug() << ss.str(); } throw Exception::InternetError(info.str() + ss.str(), retStatus); } @@ -372,26 +380,28 @@ The answer, will be inserted at the local_file_path. @param localFilePath : Provide the destination of the file downloaded at the url_file. -@param headers [optional] : A key value pair map of any additional headers to -include in the request. - @exception Mantid::Kernel::Exception::InternetError : For any unexpected behaviour. */ int InternetHelper::downloadFile(const std::string &urlFile, - const std::string &localFilePath, - const StringToStringMap &headers) { + const std::string &localFilePath) { int retStatus = 0; g_log.debug() << "DownloadFile : " << urlFile << " to file: " << localFilePath << std::endl; Poco::TemporaryFile tempFile; Poco::FileStream tempFileStream(tempFile.path()); - retStatus = sendRequest(urlFile, tempFileStream, headers); + retStatus = sendRequest(urlFile, tempFileStream); tempFileStream.close(); // if there have been no errors move it to the final location, and turn off // automatic deletion. + //clear the way if the target file path is already in use + Poco::File file(localFilePath); + if (file.exists()) { + file.remove(); + } + tempFile.moveTo(localFilePath); tempFile.keep(); @@ -403,5 +413,156 @@ int InternetHelper::downloadFile(const std::string &urlFile, **/ void InternetHelper::setTimeout(int seconds) { m_timeout = seconds; } + +/** Gets the timeout in seconds +* @returns The value in seconds for the timeout +**/ +int InternetHelper::getTimeout() { return m_timeout; } + +/** Sets the Method +* @param method A string of GET or POST, anything other than POST is considered GET +**/ +void InternetHelper::setMethod(const std::string& method) { + if (method == "POST") { + m_method = method; + } else { + m_method = "GET"; + } +} + +/** Gets the method +* @returns either "GET" or "POST" +**/ +const std::string& InternetHelper::getMethod() {return m_method; } + +/** Sets the Content Type +* @param contentType A string of the content type +**/ +void InternetHelper::setContentType(const std::string& contentType) { + m_contentType = contentType; +} + +/** Gets the Content Type +* @returns A string of the content type +**/ +const std::string& InternetHelper::getContentType() {return m_contentType; } + + + +/** Sets the content length +* @param length The content length in bytes +**/ +void InternetHelper::setContentLength(std::streamsize length) { m_contentLength = length; } + +/** Gets the content length +* @returns The content length in bytes +**/ +std::streamsize InternetHelper::getContentLength() { return m_contentLength; } + +/** Sets the body & content length for future requests, this will also +* set the method to POST is the body is not empty +* and GET if it is. +* @param body A string of the body +**/ +void InternetHelper::setBody(const std::string& body) { + m_body = body; + if (m_body.empty()) { + m_method="GET"; + } else { + m_method="POST"; + } + setContentLength(m_body.size()); +} + +/** Sets the body & content length for future requests, this will also +* set the method to POST is the body is not empty +* and GET if it is. +* @param body A stringstream of the body +**/ +void InternetHelper::setBody(const std::ostringstream& body) { + setBody(body.str()); +} + +/** Sets the body & content length for future requests, this will also +* set the method to POST is the body is not empty +* and GET if it is. +* @param form A HTMLform +**/ +void InternetHelper::setBody(Poco::Net::HTMLForm& form) { + + setMethod("POST"); + if (m_request == NULL) { + Poco::URI uri("http://www.mantidproject.org"); + createRequest(uri); + } + form.prepareSubmit(*m_request); + setContentType(m_request->getContentType()); + + std::ostringstream ss; + form.write(ss); + m_body = ss.str(); + setContentLength(m_body.size()); +} + +/** Gets the body set for future requests +* @returns A string of the content type +**/ +const std::string& InternetHelper::getBody() {return m_body; } + + +/** Gets the body set for future requests +* @returns A string of the content type +**/ +int InternetHelper::getResponseStatus() {return m_response->getStatus(); } + +/** Gets the body set for future requests +* @returns A string of the content type +**/ +const std::string& InternetHelper::getResponseReason() {return m_response->getReason(); } + +/** Adds a header +* @param key The key to refer to the value +* @param value The value in seconds for the timeout +**/ +void InternetHelper::addHeader(const std::string& key, const std::string& value) { + m_headers.insert(std::pair(key,value)); +} + +/** Removes a header +* @param key The key to refer to the value +**/ +void InternetHelper::removeHeader (const std::string& key) { + m_headers.erase(key); +} + +/** Gets the value of a header +* @param key The key to refer to the value +* @returns the value as a string +**/ +const std::string& InternetHelper::getHeader (const std::string& key) { + return m_headers[key]; +} + +/** Clears all headers +**/ +void InternetHelper::clearHeaders() { m_headers.clear(); } + +/** Returns a reference to the headers map +**/ +std::map& InternetHelper::headers() { + return m_headers; +} + +/** Resets properties to defaults (except the proxy) +**/ +void InternetHelper::reset() { + m_headers.clear(); + m_timeout = 30; + m_body = ""; + m_method = HTTPRequest::HTTP_GET; + m_contentType = "application/json"; + m_request = NULL ; +} + } // namespace Kernel } // namespace Mantid diff --git a/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h b/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h index 8ad8c31e512c..b82081ae5a29 100644 --- a/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h +++ b/Code/Mantid/Framework/Kernel/test/InternetHelperTest.h @@ -9,6 +9,9 @@ #include "MantidKernel/ProxyInfo.h" #include +#include +#include "Poco/Net/PartSource.h" +#include "Poco/Net/StringPartSource.h" #include #include @@ -109,6 +112,107 @@ class InternetHelperTest : public CxxTest::TestSuite { TS_ASSERT_EQUALS("HTTPS request succeeded", ss.str()); } + + void test_ContentType_GetSet() + { + MockedInternetHelper internetHelper; + TSM_ASSERT_EQUALS("Default content type is not application/json",internetHelper.getContentType(),"application/json"); + internetHelper.setContentType("test value"); + TSM_ASSERT_EQUALS("setContentType failed",internetHelper.getContentType(),"test value"); + } + + void test_Method_GetSet() + { + MockedInternetHelper internetHelper; + TSM_ASSERT_EQUALS("Default method is not GET",internetHelper.getMethod(),"GET"); + internetHelper.setMethod("POST"); + TSM_ASSERT_EQUALS("setMethod failed",internetHelper.getMethod(),"POST"); + } + + void test_Timeout_GetSet() + { + MockedInternetHelper internetHelper; + TSM_ASSERT_EQUALS("Default timeout is not 30",internetHelper.getTimeout(),30); + internetHelper.setTimeout(1); + TSM_ASSERT_EQUALS("setTimeout failed",internetHelper.getTimeout(),1); + } + + void test_Body_GetSet() + { + MockedInternetHelper internetHelper; + TSM_ASSERT_EQUALS("Default body is not empty",internetHelper.getBody(),""); + internetHelper.setBody("Test string"); + TSM_ASSERT_EQUALS("setBody failed",internetHelper.getBody(),"Test string"); + TSM_ASSERT_EQUALS("method is not POST",internetHelper.getMethod(),"POST"); + TSM_ASSERT_EQUALS("Contentlength is wrong",internetHelper.getContentLength(),11); + internetHelper.setBody(""); + TSM_ASSERT_EQUALS("setBody failed",internetHelper.getBody(),""); + TSM_ASSERT_EQUALS("method is not GET",internetHelper.getMethod(),"GET"); + TSM_ASSERT_EQUALS("Contentlength is wrong",internetHelper.getContentLength(),0); + } + + void test_BodyStream_GetSet() + { + MockedInternetHelper internetHelper; + std::ostringstream ss; + ss << "Test string"; + TSM_ASSERT_EQUALS("Default body is not empty",internetHelper.getBody(),""); + internetHelper.setBody(ss); + TSM_ASSERT_EQUALS("setBody failed",internetHelper.getBody(),ss.str()); + TSM_ASSERT_EQUALS("method is not POST",internetHelper.getMethod(),"POST"); + TSM_ASSERT_EQUALS("Contentlength is wrong",internetHelper.getContentLength(),11); + ss.str(""); + internetHelper.setBody(ss); + TSM_ASSERT_EQUALS("setBody failed",internetHelper.getBody(),""); + TSM_ASSERT_EQUALS("method is not GET",internetHelper.getMethod(),"GET"); + TSM_ASSERT_EQUALS("Contentlength is wrong",internetHelper.getContentLength(),0); + } + + void test_BodyForm_GetSet() + { + MockedInternetHelper internetHelper; + Poco::Net::HTMLForm form(Poco::Net::HTMLForm::ENCODING_MULTIPART); + form.set("field1", "value1"); + form.set("field2", "value 2"); + form.set("field3", "value=3"); + form.set("field4", "value&4"); + + form.addPart("attachment1", new Poco::Net::StringPartSource("This is an attachment")); + Poco::Net::StringPartSource* pSPS = new Poco::Net::StringPartSource("This is another attachment", "text/plain", "att2.txt"); + pSPS->headers().set("Content-ID", "1234abcd"); + form.addPart("attachment2", pSPS); + TSM_ASSERT_EQUALS("Default body is not empty",internetHelper.getBody(),""); + TSM_ASSERT_EQUALS("method is not GET",internetHelper.getMethod(),"GET"); + internetHelper.setBody(form); + std::string body = internetHelper.getBody(); + TSM_ASSERT_DIFFERS("setBody failed \"--MIME_boundary\"",body.find("--MIME_boundary"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"This is an attachment\"",body.find("This is an attachment"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"This is another attachment\"",body.find("This is another attachment"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"field1\"",body.find("field1"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"field2\"",body.find("field2"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"field3\"",body.find("field3"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"field4\"",body.find("field4"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"value1\"",body.find("value1"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"value 2\"",body.find("value 2"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"value=3\"",body.find("value=3"),std::string::npos); + TSM_ASSERT_DIFFERS("setBody failed \"value&4\"",body.find("value&4"),std::string::npos); + TSM_ASSERT_EQUALS("method is not POST",internetHelper.getMethod(),"POST"); + TSM_ASSERT_LESS_THAN("Contentlength is wrong",700,internetHelper.getContentLength()); + } + + void test_Headers_GetSet() + { + MockedInternetHelper internetHelper; + TSM_ASSERT_EQUALS("Default headers are not empty",internetHelper.headers().size(),0); + internetHelper.addHeader("Test","value"); + internetHelper.addHeader("Test2","value2"); + TSM_ASSERT_EQUALS("addHeader failed",internetHelper.getHeader("Test"),"value"); + TSM_ASSERT_EQUALS("addHeader failed",internetHelper.getHeader("Test2"),"value2"); + internetHelper.removeHeader("Test"); + TSM_ASSERT_EQUALS("Remove failed",internetHelper.headers().size(),1); + internetHelper.clearHeaders(); + TSM_ASSERT_EQUALS("Clear failed",internetHelper.headers().size(),0); + } }; #endif /* MANTID_KERNEL_INTERNETSERVICETEST_H_ */ diff --git a/Code/Mantid/Framework/LiveData/inc/MantidLiveData/StartLiveData.h b/Code/Mantid/Framework/LiveData/inc/MantidLiveData/StartLiveData.h index a7c0c4b25230..fcd7bd1db9f9 100644 --- a/Code/Mantid/Framework/LiveData/inc/MantidLiveData/StartLiveData.h +++ b/Code/Mantid/Framework/LiveData/inc/MantidLiveData/StartLiveData.h @@ -59,7 +59,6 @@ class DLLExport StartLiveData : public LiveDataAlgorithm { private: void init(); void exec(); - void afterPropertySet(const std::string &); }; } // namespace LiveData diff --git a/Code/Mantid/Framework/LiveData/src/StartLiveData.cpp b/Code/Mantid/Framework/LiveData/src/StartLiveData.cpp index 1b44d91e750f..c890cac2ab60 100644 --- a/Code/Mantid/Framework/LiveData/src/StartLiveData.cpp +++ b/Code/Mantid/Framework/LiveData/src/StartLiveData.cpp @@ -6,6 +6,8 @@ #include "MantidAPI/AlgorithmProxy.h" #include "MantidAPI/AlgorithmProperty.h" #include "MantidAPI/LiveListenerFactory.h" +#include "MantidKernel/ArrayProperty.h" +#include "MantidKernel/ArrayBoundedValidator.h" #include @@ -65,6 +67,21 @@ void StartLiveData::init() { "If you specify 0, MonitorLiveData will not launch and you will get only " "one chunk."); + // Properties used with ISISHistoDataListener + declareProperty(new ArrayProperty("SpectraList"), + "An optional list of spectra to load. If blank, all " + "available spectra will be loaded. Applied to ISIS histogram" + " data only."); + getPointerToProperty("SpectraList")->setGroup(listenerPropertyGroup); + + auto validator = boost::make_shared>(); + validator->setLower(1); + declareProperty(new ArrayProperty("PeriodList", validator), + "An optional list of periods to load. If blank, all " + "available periods will be loaded. Applied to ISIS histogram" + " data only."); + getPointerToProperty("PeriodList")->setGroup(listenerPropertyGroup); + // Initialize the properties common to LiveDataAlgorithm. initProps(); @@ -190,34 +207,5 @@ void StartLiveData::exec() { } } -/** - * After Instrument property is set copy any properties that the instrument's - * listener may have to this algorithm. - */ -void StartLiveData::afterPropertySet(const std::string &propName) { - if (propName == "Instrument") { - // remove old listener's properties - auto properties = getProperties(); - for (auto prop = properties.begin(); prop != properties.end(); ++prop) { - if ((**prop).getGroup() == listenerPropertyGroup) { - removeProperty((**prop).name()); - } - } - // add new listener's properties - auto listener = LiveListenerFactory::Instance().create( - getPropertyValue(propName), false); - auto propertyManagerListener = - boost::dynamic_pointer_cast(listener); - if (propertyManagerListener) { - auto properties = propertyManagerListener->getProperties(); - for (auto prop = properties.begin(); prop != properties.end(); ++prop) { - propertyManagerListener->removeProperty((**prop).name(), false); - declareProperty(*prop); - (**prop).setGroup(listenerPropertyGroup); - } - } - } -} - } // namespace LiveData } // namespace Mantid diff --git a/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMD2Test.h b/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMD2Test.h index 31584d4caf27..3adbed5c426d 100644 --- a/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMD2Test.h +++ b/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMD2Test.h @@ -98,9 +98,9 @@ class CentroidPeaksMD2Test : public CxxTest::TestSuite Peak pIn(inst, 1, 1.0, startPos ); if (CoordinatesToUse == "Q (lab frame)") - pIn.setQLabFrame(startPos); + pIn.setQLabFrame(startPos, 1 /*sample to detector distance*/); else if (CoordinatesToUse == "Q (sample frame)") - pIn.setQSampleFrame(startPos); + pIn.setQSampleFrame(startPos, 1 /*sample to detector distance*/); else if (CoordinatesToUse == "HKL") pIn.setHKL(startPos); peakWS->addPeak( pIn ); diff --git a/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMDTest.h b/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMDTest.h index 4e7338b07bdd..445df41cf2d4 100644 --- a/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMDTest.h +++ b/Code/Mantid/Framework/MDAlgorithms/test/CentroidPeaksMDTest.h @@ -98,9 +98,9 @@ class CentroidPeaksMDTest : public CxxTest::TestSuite Peak pIn(inst, 1, 1.0, startPos ); if (CoordinatesToUse == "Q (lab frame)") - pIn.setQLabFrame(startPos); + pIn.setQLabFrame(startPos, 1 /*sample to detector distance*/); else if (CoordinatesToUse == "Q (sample frame)") - pIn.setQSampleFrame(startPos); + pIn.setQSampleFrame(startPos, 1 /*sample to detector distance*/); else if (CoordinatesToUse == "HKL") pIn.setHKL(startPos); peakWS->addPeak( pIn ); diff --git a/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/AffineMatrixParameter.h b/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/AffineMatrixParameter.h index 12000a3620cd..5b748bfefccf 100644 --- a/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/AffineMatrixParameter.h +++ b/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/AffineMatrixParameter.h @@ -42,11 +42,13 @@ class DLLExport AffineMatrixParameter private: void copyRawMatrix(); - /// Raw matrix used for speed. - coord_t **rawMatrix; + /// Raw matrix used for speed (array of pointers to columns). + coord_t **m_rawMatrix; + /// pointer to large memory block (matrix) + coord_t *m_rawMem; /// Affine matrix. - AffineMatrixType affineMatrix; + AffineMatrixType m_affineMatrix; }; } } diff --git a/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/CoordTransformAffine.h b/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/CoordTransformAffine.h index 1115ab99dd3a..8c138de70d8f 100644 --- a/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/CoordTransformAffine.h +++ b/Code/Mantid/Framework/MDEvents/inc/MantidMDEvents/CoordTransformAffine.h @@ -55,12 +55,12 @@ class DLLExport CoordTransformAffine : public Mantid::API::CoordTransform { * can be * combined by simply multiplying the matrices. */ - Mantid::Kernel::Matrix affineMatrix; + Mantid::Kernel::Matrix m_affineMatrix; /// Raw pointer to the same underlying matrix as affineMatrix. - coord_t **rawMatrix; + coord_t **m_rawMatrix; /// raw pointer to the memory block, referred by the raw Matrix; - coord_t *rawMemory; + coord_t *m_rawMemory; void copyRawMatrix(); }; diff --git a/Code/Mantid/Framework/MDEvents/src/AffineMatrixParameter.cpp b/Code/Mantid/Framework/MDEvents/src/AffineMatrixParameter.cpp index e0f17a542ce9..643badd778cd 100644 --- a/Code/Mantid/Framework/MDEvents/src/AffineMatrixParameter.cpp +++ b/Code/Mantid/Framework/MDEvents/src/AffineMatrixParameter.cpp @@ -10,15 +10,17 @@ namespace MDEvents { * @param inD the nubmer of input dimensions */ AffineMatrixParameter::AffineMatrixParameter(size_t outD, size_t inD) - : affineMatrix(outD + 1, inD + 1) { + : m_affineMatrix(outD + 1, inD + 1) { m_isValid = false; - affineMatrix.identityMatrix(); - size_t nx = affineMatrix.numRows(); - size_t ny = affineMatrix.numCols(); - coord_t *tmpX = new coord_t[nx * ny]; - rawMatrix = new coord_t *[nx]; + m_affineMatrix.identityMatrix(); + size_t nx = m_affineMatrix.numRows(); + size_t ny = m_affineMatrix.numCols(); + // big chunk of memory holding the whole matrix + m_rawMem = new coord_t[nx * ny]; + // array of pointers (one per column) + m_rawMatrix = new coord_t *[nx]; for (size_t i = 0; i < nx; i++) - rawMatrix[i] = tmpX + (i * ny); + m_rawMatrix[i] = m_rawMem + (i * ny); // Copy into the raw matrix (for speed) copyRawMatrix(); } @@ -26,19 +28,20 @@ AffineMatrixParameter::AffineMatrixParameter(size_t outD, size_t inD) //---------------------------------------------------------------------------------------------- /// Destructor AffineMatrixParameter::~AffineMatrixParameter() { - if (rawMatrix) { - delete[] * rawMatrix; - delete[] rawMatrix; + if (m_rawMatrix) { + delete[] * m_rawMatrix; + delete[] m_rawMatrix; } - rawMatrix = NULL; + m_rawMatrix = NULL; + m_rawMem = NULL; } //---------------------------------------------------------------------------------------------- /// Copy elements from affinematrix into raw array. void AffineMatrixParameter::copyRawMatrix() { - for (size_t x = 0; x < affineMatrix.numRows(); ++x) - for (size_t y = 0; y < affineMatrix.numCols(); ++y) - rawMatrix[x][y] = affineMatrix[x][y]; + for (size_t x = 0; x < m_affineMatrix.numRows(); ++x) + for (size_t y = 0; y < m_affineMatrix.numCols(); ++y) + m_rawMatrix[x][y] = m_affineMatrix[x][y]; } //---------------------------------------------------------------------------------------------- @@ -47,7 +50,7 @@ void AffineMatrixParameter::copyRawMatrix() { * @return A copy of the underlying affine matrix. */ AffineMatrixType AffineMatrixParameter::getAffineMatrix() const { - return affineMatrix; + return m_affineMatrix; } //---------------------------------------------------------------------------------------------- @@ -55,7 +58,7 @@ AffineMatrixType AffineMatrixParameter::getAffineMatrix() const { * * @return the matrix as an array. */ -coord_t **AffineMatrixParameter::getRawMatrix() { return rawMatrix; } +coord_t **AffineMatrixParameter::getRawMatrix() { return m_rawMatrix; } //---------------------------------------------------------------------------------------------- /** Get the name of the parameter @@ -72,7 +75,7 @@ std::string AffineMatrixParameter::getName() const { * @return the object as serialized. Xml in a std::string. */ std::string AffineMatrixParameter::toXMLString() const { - std::vector elements = this->affineMatrix.getVector(); + std::vector elements = this->m_affineMatrix.getVector(); const size_t size = elements.size(); std::string parameterValue; @@ -81,7 +84,7 @@ std::string AffineMatrixParameter::toXMLString() const { sstream << elements[i - 1]; parameterValue.append(sstream.str()); sstream.clear(); - if (i % affineMatrix.numCols() == 0) { + if (i % m_affineMatrix.numCols() == 0) { if (i != size) { parameterValue.append(";"); } @@ -99,8 +102,8 @@ std::string AffineMatrixParameter::toXMLString() const { * @return Cloned parameter. */ AffineMatrixParameter *AffineMatrixParameter::clone() const { - return new AffineMatrixParameter(affineMatrix.numRows() - 1, - affineMatrix.numCols() - 1); + return new AffineMatrixParameter(m_affineMatrix.numRows() - 1, + m_affineMatrix.numCols() - 1); } //---------------------------------------------------------------------------------------------- @@ -117,14 +120,14 @@ bool AffineMatrixParameter::isValid() const { return m_isValid; } */ AffineMatrixParameter &AffineMatrixParameter:: operator=(const AffineMatrixParameter &other) { - if ((other.affineMatrix.numCols() != this->affineMatrix.numCols()) || - (other.affineMatrix.numRows() != this->affineMatrix.numRows())) { + if ((other.m_affineMatrix.numCols() != this->m_affineMatrix.numCols()) || + (other.m_affineMatrix.numRows() != this->m_affineMatrix.numRows())) { throw std::runtime_error("Cannot make assignemnts between " "AffineMatrixParameter when the matrixes are of " "different sizes."); } if (this != &other) { - this->affineMatrix = other.affineMatrix; + this->m_affineMatrix = other.m_affineMatrix; this->m_isValid = other.m_isValid; copyRawMatrix(); } @@ -136,14 +139,14 @@ operator=(const AffineMatrixParameter &other) { * @param other : another affine matrix to copy from. */ AffineMatrixParameter::AffineMatrixParameter(const AffineMatrixParameter &other) - : affineMatrix(other.affineMatrix) { + : m_affineMatrix(other.m_affineMatrix) { m_isValid = other.m_isValid; - size_t nx = affineMatrix.numRows(); - size_t ny = affineMatrix.numCols(); - coord_t *tmpX = new coord_t[nx * ny]; - rawMatrix = new coord_t *[nx]; + size_t nx = m_affineMatrix.numRows(); + size_t ny = m_affineMatrix.numCols(); + m_rawMem = new coord_t[nx * ny]; + m_rawMatrix = new coord_t *[nx]; for (size_t i = 0; i < nx; i++) - rawMatrix[i] = tmpX + (i * ny); + m_rawMatrix[i] = m_rawMem + (i * ny); copyRawMatrix(); } @@ -153,11 +156,11 @@ AffineMatrixParameter::AffineMatrixParameter(const AffineMatrixParameter &other) * @param newMatrix : new matrix to use. */ void AffineMatrixParameter::setMatrix(const AffineMatrixType newMatrix) { - if (newMatrix.numRows() != this->affineMatrix.numRows()) + if (newMatrix.numRows() != this->m_affineMatrix.numRows()) throw std::runtime_error("setMatrix(): Number of rows must match!"); - if (newMatrix.numCols() != this->affineMatrix.numCols()) + if (newMatrix.numCols() != this->m_affineMatrix.numCols()) throw std::runtime_error("setMatrix(): Number of columns must match!"); - affineMatrix = newMatrix; + m_affineMatrix = newMatrix; // Copy into the raw matrix (for speed) copyRawMatrix(); this->m_isValid = true; diff --git a/Code/Mantid/Framework/MDEvents/src/CoordTransformAffine.cpp b/Code/Mantid/Framework/MDEvents/src/CoordTransformAffine.cpp index 2860f0e58b43..4d15ad909fe7 100644 --- a/Code/Mantid/Framework/MDEvents/src/CoordTransformAffine.cpp +++ b/Code/Mantid/Framework/MDEvents/src/CoordTransformAffine.cpp @@ -25,19 +25,19 @@ namespace MDEvents { * @throw std::runtime_error if outD > inD */ CoordTransformAffine::CoordTransformAffine(const size_t inD, const size_t outD) - : CoordTransform(inD, outD), affineMatrix(outD + 1, inD + 1), - rawMatrix(NULL), rawMemory(NULL) { - affineMatrix.identityMatrix(); + : CoordTransform(inD, outD), m_affineMatrix(outD + 1, inD + 1), + m_rawMatrix(NULL), m_rawMemory(NULL) { + m_affineMatrix.identityMatrix(); // Allocate the raw matrix - size_t nx = affineMatrix.numRows(); - size_t ny = affineMatrix.numCols(); + size_t nx = m_affineMatrix.numRows(); + size_t ny = m_affineMatrix.numCols(); // vector of pointers - rawMatrix = new coord_t *[nx]; + m_rawMatrix = new coord_t *[nx]; // memory itself - rawMemory = new coord_t[nx * ny]; + m_rawMemory = new coord_t[nx * ny]; for (size_t i = 0; i < nx; i++) - rawMatrix[i] = rawMemory + (i * ny); + m_rawMatrix[i] = m_rawMemory + (i * ny); // Copy into the raw matrix (for speed) copyRawMatrix(); } @@ -46,9 +46,9 @@ CoordTransformAffine::CoordTransformAffine(const size_t inD, const size_t outD) * Call this after any change to affineMatrix */ void CoordTransformAffine::copyRawMatrix() { - for (size_t x = 0; x < affineMatrix.numRows(); ++x) - for (size_t y = 0; y < affineMatrix.numCols(); ++y) - rawMatrix[x][y] = affineMatrix[x][y]; + for (size_t x = 0; x < m_affineMatrix.numRows(); ++x) + for (size_t y = 0; y < m_affineMatrix.numCols(); ++y) + m_rawMatrix[x][y] = m_affineMatrix[x][y]; } //---------------------------------------------------------------------------------------------- @@ -64,12 +64,12 @@ CoordTransform *CoordTransformAffine::clone() const { /** Destructor */ CoordTransformAffine::~CoordTransformAffine() { - if (rawMatrix) { - delete[] rawMatrix; - delete[] rawMemory; + if (m_rawMatrix) { + delete[] * m_rawMatrix; + delete[] m_rawMatrix; } - rawMatrix = NULL; - rawMemory = NULL; + m_rawMatrix = NULL; + m_rawMemory = NULL; } //---------------------------------------------------------------------------------------------- @@ -84,7 +84,7 @@ void CoordTransformAffine::setMatrix( throw std::runtime_error("setMatrix(): Number of rows must match!"); if (newMatrix.numCols() != inD + 1) throw std::runtime_error("setMatrix(): Number of columns must match!"); - affineMatrix = newMatrix; + m_affineMatrix = newMatrix; // Copy into the raw matrix (for speed) copyRawMatrix(); } @@ -93,12 +93,12 @@ void CoordTransformAffine::setMatrix( /** Return the affine matrix in the transform. */ const Mantid::Kernel::Matrix &CoordTransformAffine::getMatrix() const { - return affineMatrix; + return m_affineMatrix; } /** @return the affine matrix */ Mantid::Kernel::Matrix CoordTransformAffine::makeAffineMatrix() const { - return affineMatrix; + return m_affineMatrix; } //---------------------------------------------------------------------------------------------- @@ -116,7 +116,7 @@ void CoordTransformAffine::addTranslation(const coord_t *translationVector) { translationMatrix[i][inD] = translationVector[i]; // Multiply the affine matrix by the translation affine matrix to combine them - affineMatrix *= translationMatrix; + m_affineMatrix *= translationMatrix; // Copy into the raw matrix (for speed) copyRawMatrix(); @@ -172,7 +172,7 @@ void CoordTransformAffine::buildOrthogonal( "workspace."); // Start with identity - affineMatrix.identityMatrix(); + m_affineMatrix.identityMatrix(); for (size_t i = 0; i < axes.size(); i++) { if (axes[i].length() == 0.0) @@ -187,7 +187,7 @@ void CoordTransformAffine::buildOrthogonal( basis.normalize(); // The row of the affine matrix = the unit vector for (size_t j = 0; j < basis.size(); j++) - affineMatrix[i][j] = static_cast(basis[j] * scaling[i]); + m_affineMatrix[i][j] = static_cast(basis[j] * scaling[i]); // Now account for the translation coord_t transl = 0; @@ -195,7 +195,7 @@ void CoordTransformAffine::buildOrthogonal( transl += static_cast( origin[j] * basis[j]); // dot product of origin * basis aka ( X0 . U ) // The last column of the matrix = the translation movement - affineMatrix[i][inD] = -transl * static_cast(scaling[i]); + m_affineMatrix[i][inD] = -transl * static_cast(scaling[i]); } // Copy into the raw matrix (for speed) @@ -213,7 +213,7 @@ void CoordTransformAffine::apply(const coord_t *inputVector, // For each output dimension for (size_t out = 0; out < outD; ++out) { // Cache the row pointer to make the matrix access a bit faster - coord_t *rawMatrixRow = rawMatrix[out]; + coord_t *rawMatrixRow = m_rawMatrix[out]; coord_t outVal = 0.0; size_t in; for (in = 0; in < inD; ++in) @@ -259,7 +259,7 @@ std::string CoordTransformAffine::toXMLString() const { // Convert the members to parameters AffineMatrixParameter affineMatrixParameter(inD, outD); - affineMatrixParameter.setMatrix(affineMatrix); + affineMatrixParameter.setMatrix(m_affineMatrix); Mantid::API::InDimParameter inD_param(inD); Mantid::API::OutDimParameter outD_param(outD); diff --git a/Code/Mantid/Framework/MDEvents/src/CoordTransformAffineParser.cpp b/Code/Mantid/Framework/MDEvents/src/CoordTransformAffineParser.cpp index 26d2419fd53c..b2f92cbb2517 100644 --- a/Code/Mantid/Framework/MDEvents/src/CoordTransformAffineParser.cpp +++ b/Code/Mantid/Framework/MDEvents/src/CoordTransformAffineParser.cpp @@ -49,20 +49,20 @@ Mantid::API::CoordTransform *CoordTransformAffineParser::createTransform( InDimParameterParser inDimParser; Poco::XML::Element *parameter = dynamic_cast(parameters->item(0)); - Mantid::API::InDimParameter *inDim = - inDimParser.createWithoutDelegation(parameter); + boost::shared_ptr + inDim(inDimParser.createWithoutDelegation(parameter)); // Add output dimension parameter. OutDimParameterParser outDimParser; parameter = dynamic_cast(parameters->item(1)); - Mantid::API::OutDimParameter *outDim = - outDimParser.createWithoutDelegation(parameter); + boost::shared_ptr + outDim(outDimParser.createWithoutDelegation(parameter)); // Add affine matrix parameter. AffineMatrixParameterParser affineMatrixDimParser; parameter = dynamic_cast(parameters->item(2)); - AffineMatrixParameter *affineMatrix = - affineMatrixDimParser.createParameter(parameter); + boost::shared_ptr + affineMatrix(affineMatrixDimParser.createParameter(parameter)); // Generate the coordinate transform with the matrix and return. CoordTransformAffine *transform = diff --git a/Code/Mantid/Framework/MDEvents/src/CoordTransformDistanceParser.cpp b/Code/Mantid/Framework/MDEvents/src/CoordTransformDistanceParser.cpp index 42de3c7b0be4..38a66a2f0c2d 100644 --- a/Code/Mantid/Framework/MDEvents/src/CoordTransformDistanceParser.cpp +++ b/Code/Mantid/Framework/MDEvents/src/CoordTransformDistanceParser.cpp @@ -51,32 +51,33 @@ Mantid::API::CoordTransform *CoordTransformDistanceParser::createTransform( InDimParameterParser inDimParamParser; Poco::XML::Element *parameter = dynamic_cast(parameters->item(0)); - Mantid::API::InDimParameter *inDimParameter = - inDimParamParser.createWithoutDelegation(parameter); + boost::shared_ptr + inDimParameter(inDimParamParser.createWithoutDelegation(parameter)); // Parse the out dimension parameter. OutDimParameterParser outDimParamParser; parameter = dynamic_cast(parameters->item(1)); - Mantid::API::OutDimParameter *outDimParameter = - outDimParamParser.createWithoutDelegation(parameter); + boost::shared_ptr + outDimParameter(outDimParamParser.createWithoutDelegation(parameter)); UNUSED_ARG(outDimParameter); // not actually used as an input. // Parse the coordinate centre parameter. CoordCenterParser coordCenterParser; parameter = dynamic_cast(parameters->item(2)); - Mantid::MDEvents::CoordCenterVectorParam *coordCenterParam = - coordCenterParser.createWithoutDelegation(parameter); + boost::shared_ptr + coordCenterParam(coordCenterParser.createWithoutDelegation(parameter)); // Parse the dimensions used parameter. DimsUsedParser dimsUsedParser; parameter = dynamic_cast(parameters->item(3)); - Mantid::MDEvents::DimensionsUsedVectorParam *dimsUsedVecParm = - dimsUsedParser.createWithoutDelegation(parameter); + boost::shared_ptr + dimsUsedVecParm(dimsUsedParser.createWithoutDelegation(parameter)); ////Generate the coordinate transform and return CoordTransformDistance *transform = new CoordTransformDistance( inDimParameter->getValue(), coordCenterParam->getPointerToStart(), dimsUsedVecParm->getPointerToStart()); + return transform; } diff --git a/Code/Mantid/Framework/MDEvents/src/Integrate3DEvents.cpp b/Code/Mantid/Framework/MDEvents/src/Integrate3DEvents.cpp index 825eef550aee..3fb6f21231da 100644 --- a/Code/Mantid/Framework/MDEvents/src/Integrate3DEvents.cpp +++ b/Code/Mantid/Framework/MDEvents/src/Integrate3DEvents.cpp @@ -188,11 +188,17 @@ int Integrate3DEvents::numInEllipsoid(std::vector const &events, /** * Given a list of events, associated with a particular peak - * and SHIFTED to be centered at (0,0,0), calculate the 3x3 + * and already SHIFTED to be centered at (0,0,0), calculate the 3x3 * covariance matrix for finding the principal axes of that * local event data. Only events within the specified radius * of (0,0,0) will be used. * + * The covariance matrix can be easily constructed. X, Y, Z of each peak position are the variables we wish to determine + * the covariance. The mean position in each dimension has already been calculated on subtracted, since this corresponds to the centre position of each + * peak, which we knew aprori. The expected values of each correlation test X,X X,Y X,Z e.t.c form the elements of this 3 by 3 matrix, but since the + * probabilities are equal, we can remove them from the sums of the expected values, and simply divide by the number of events for each matrix element. + * Note that the diagonal elements form the variance X,X, Y,Y, Z,Z + * * @param events Vector of V3D objects containing the * Q vectors for a peak, with mean at (0,0,0). * @param matrix A 3x3 matrix that will be filled out with diff --git a/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp b/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp index f13b9ca9a077..118e2caf1012 100644 --- a/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp +++ b/Code/Mantid/Framework/MDEvents/src/IntegrateEllipsoids.cpp @@ -15,6 +15,7 @@ #include "MantidMDEvents/UnitsConversionHelper.h" #include "MantidMDEvents/Integrate3DEvents.h" #include "MantidMDEvents/IntegrateEllipsoids.h" +#include "MantidDataObjects/Workspace2D.h" #include "MantidKernel/Statistics.h" @@ -268,7 +269,7 @@ void IntegrateEllipsoids::exec() { double inti; double sigi; - std::vector r1,r2,r3; + std::vector principalaxis1,principalaxis2,principalaxis3; for (size_t i = 0; i < n_peaks; i++) { V3D hkl(peaks[i].getH(), peaks[i].getK(), peaks[i].getL()); if (Geometry::IndexingUtils::ValidIndex(hkl, 1.0)) { @@ -281,79 +282,106 @@ void IntegrateEllipsoids::exec() { peaks[i].setSigmaIntensity(sigi); peaks[i].setPeakShape(shape); if (axes_radii.size() == 3) { - if (inti/sigi > cutoffIsigI && !specify_size) - { - r1.push_back(axes_radii[0]); - r2.push_back(axes_radii[1]); - r3.push_back(axes_radii[2]); + if (inti/sigi > cutoffIsigI || cutoffIsigI == EMPTY_DBL()){ + principalaxis1.push_back(axes_radii[0]); + principalaxis2.push_back(axes_radii[1]); + principalaxis3.push_back(axes_radii[2]); } - g_log.notice() - << "Radii of three axes of ellipsoid for integrating peak " << i - << " = "; - for (int i3 = 0; i3 < 3; i3++) { - g_log.notice() << axes_radii[i3] << " "; - } - g_log.notice() << std::endl; } } else { peaks[i].setIntensity(0.0); peaks[i].setSigmaIntensity(0.0); } } - if (r1.size() > 1 && !specify_size) - { - Statistics stats = getStatistics(r1); - g_log.notice() << "r1: " - << " mean " << stats.mean - << " standard_deviation " << stats.standard_deviation - << " minimum " << stats.minimum - << " maximum " << stats.maximum - << " median " << stats.median << "\n"; - stats = getStatistics(r2); - g_log.notice() << "r2: " - << " mean " << stats.mean - << " standard_deviation " << stats.standard_deviation - << " minimum " << stats.minimum - << " maximum " << stats.maximum - << " median " << stats.median << "\n"; - stats = getStatistics(r3); - g_log.notice() << "r3: " - << " mean " << stats.mean - << " standard_deviation " << stats.standard_deviation - << " minimum " << stats.minimum - << " maximum " << stats.maximum - << " median " << stats.median << "\n"; - specify_size=true; - peak_radius = stats.mean + numSigmas * stats.standard_deviation; - back_inner_radius = peak_radius; - back_outer_radius = peak_radius * 1.25992105; // A factor of 2 ^ (1/3) will make the background - // shell volume equal to the peak region volume. - for (size_t i = 0; i < n_peaks; i++) { - V3D hkl(peaks[i].getH(), peaks[i].getK(), peaks[i].getL()); - if (Geometry::IndexingUtils::ValidIndex(hkl, 1.0)) { - V3D peak_q(peaks[i].getQLabFrame()); - std::vector axes_radii; - integrator.ellipseIntegrateEvents(peak_q, specify_size, peak_radius, - back_inner_radius, back_outer_radius, - axes_radii, inti, sigi); - peaks[i].setIntensity(inti); - peaks[i].setSigmaIntensity(sigi); - if (axes_radii.size() == 3) { - g_log.notice() - << "Radii of three axes of ellipsoid for integrating peak " << i - << " = "; - for (int i3 = 0; i3 < 3; i3++) { - g_log.notice() << axes_radii[i3] << " "; + if (principalaxis1.size() > 1 ){ + size_t histogramNumber = 3; + Workspace_sptr wsProfile = WorkspaceFactory::Instance().create( + "Workspace2D", histogramNumber, principalaxis1.size(), principalaxis1.size()); + Workspace2D_sptr wsProfile2D = boost::dynamic_pointer_cast(wsProfile); + AnalysisDataService::Instance().addOrReplace("EllipsoidAxes", wsProfile2D); + for (size_t j = 0; j < principalaxis1.size(); j++) { + wsProfile2D->dataX(0)[j] = static_cast(j); + wsProfile2D->dataY(0)[j] = principalaxis1[j]; + wsProfile2D->dataE(0)[j] = std::sqrt(principalaxis1[j]); + wsProfile2D->dataX(1)[j] = static_cast(j); + wsProfile2D->dataY(1)[j] = principalaxis2[j]; + wsProfile2D->dataE(1)[j] = std::sqrt(principalaxis2[j]); + wsProfile2D->dataX(2)[j] = static_cast(j); + wsProfile2D->dataY(2)[j] = principalaxis3[j]; + wsProfile2D->dataE(2)[j] = std::sqrt(principalaxis3[j]); + } + Statistics stats1 = getStatistics(principalaxis1); + g_log.notice() << "principalaxis1: " + << " mean " << stats1.mean + << " standard_deviation " << stats1.standard_deviation + << " minimum " << stats1.minimum + << " maximum " << stats1.maximum + << " median " << stats1.median << "\n"; + Statistics stats2 = getStatistics(principalaxis2); + g_log.notice() << "principalaxis2: " + << " mean " << stats2.mean + << " standard_deviation " << stats2.standard_deviation + << " minimum " << stats2.minimum + << " maximum " << stats2.maximum + << " median " << stats2.median << "\n"; + Statistics stats3 = getStatistics(principalaxis3); + g_log.notice() << "principalaxis3: " + << " mean " << stats3.mean + << " standard_deviation " << stats3.standard_deviation + << " minimum " << stats3.minimum + << " maximum " << stats3.maximum + << " median " << stats3.median << "\n"; + if (cutoffIsigI != EMPTY_DBL()){ + principalaxis1.clear(); + principalaxis2.clear(); + principalaxis3.clear(); + specify_size=true; + peak_radius = std::max(std::max(stats1.mean,stats2.mean),stats3.mean) + numSigmas * + std::max(std::max(stats1.standard_deviation,stats2.standard_deviation),stats3.standard_deviation); + back_inner_radius = peak_radius; + back_outer_radius = peak_radius * 1.25992105; // A factor of 2 ^ (1/3) will make the background + // shell volume equal to the peak region volume. + for (size_t i = 0; i < n_peaks; i++) { + V3D hkl(peaks[i].getH(), peaks[i].getK(), peaks[i].getL()); + if (Geometry::IndexingUtils::ValidIndex(hkl, 1.0)) { + V3D peak_q(peaks[i].getQLabFrame()); + std::vector axes_radii; + integrator.ellipseIntegrateEvents(peak_q, specify_size, peak_radius, + back_inner_radius, back_outer_radius, + axes_radii, inti, sigi); + peaks[i].setIntensity(inti); + peaks[i].setSigmaIntensity(sigi); + if (axes_radii.size() == 3){ + principalaxis1.push_back(axes_radii[0]); + principalaxis2.push_back(axes_radii[1]); + principalaxis3.push_back(axes_radii[2]); } - g_log.notice() << std::endl; + } else { + peaks[i].setIntensity(0.0); + peaks[i].setSigmaIntensity(0.0); + } + } + if (principalaxis1.size() > 1 ){ + size_t histogramNumber = 3; + Workspace_sptr wsProfile2 = WorkspaceFactory::Instance().create( + "Workspace2D", histogramNumber, principalaxis1.size(), principalaxis1.size()); + Workspace2D_sptr wsProfile2D2 = boost::dynamic_pointer_cast(wsProfile2); + AnalysisDataService::Instance().addOrReplace("EllipsoidAxes_2ndPass", wsProfile2D2); + for (size_t j = 0; j < principalaxis1.size(); j++) { + wsProfile2D2->dataX(0)[j] = static_cast(j); + wsProfile2D2->dataY(0)[j] = principalaxis1[j]; + wsProfile2D2->dataE(0)[j] = std::sqrt(principalaxis1[j]); + wsProfile2D2->dataX(1)[j] = static_cast(j); + wsProfile2D2->dataY(1)[j] = principalaxis2[j]; + wsProfile2D2->dataE(1)[j] = std::sqrt(principalaxis2[j]); + wsProfile2D2->dataX(2)[j] = static_cast(j); + wsProfile2D2->dataY(2)[j] = principalaxis3[j]; + wsProfile2D2->dataE(2)[j] = std::sqrt(principalaxis3[j]); } - } else { - peaks[i].setIntensity(0.0); - peaks[i].setSigmaIntensity(0.0); } } - } + // This flag is used by the PeaksWorkspace to evaluate whether it has been // integrated. peak_ws->mutableRun().addProperty("PeaksIntegrated", 1, true); diff --git a/Code/Mantid/Framework/MDEvents/src/MDWSTransform.cpp b/Code/Mantid/Framework/MDEvents/src/MDWSTransform.cpp index 15dbab13aef5..d4c24c31db6a 100644 --- a/Code/Mantid/Framework/MDEvents/src/MDWSTransform.cpp +++ b/Code/Mantid/Framework/MDEvents/src/MDWSTransform.cpp @@ -9,9 +9,9 @@ namespace { // logger for the algorithm workspaces Kernel::Logger g_Log("MDWSTransform"); } - using namespace CnvrtToMD; + /** method to build the Q-coordinates transformation. * * @param TargWSDescription -- the class which describes target MD workspace. In diff --git a/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp b/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp index 81558d7eb491..341c06fa43df 100644 --- a/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp +++ b/Code/Mantid/Framework/Nexus/src/NexusFileIO.cpp @@ -45,11 +45,14 @@ Logger g_log("NexusFileIO"); } /// Empty default constructor -NexusFileIO::NexusFileIO() : m_nexuscompression(NX_COMP_LZW), m_progress(0) {} +NexusFileIO::NexusFileIO() : fileID(), m_filehandle(), + m_nexuscompression(NX_COMP_LZW), m_progress(0), m_filename() { +} /// Constructor that supplies a progress object -NexusFileIO::NexusFileIO(Progress *prog) - : m_nexuscompression(NX_COMP_LZW), m_progress(prog) {} +NexusFileIO::NexusFileIO(Progress *prog) : fileID(), m_filehandle(), + m_nexuscompression(NX_COMP_LZW), m_progress(prog), m_filename() { +} void NexusFileIO::resetProgress(Progress *prog) { m_progress = prog; } diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp index c5d3eec3e73f..e12912bc5a0a 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeak.cpp @@ -6,10 +6,29 @@ using Mantid::API::IPeak; using namespace boost::python; namespace { -Mantid::Geometry::PeakShape_sptr getPeakShape(IPeak& peak) { - // Use clone to make a copy of the PeakShape. - return Mantid::Geometry::PeakShape_sptr(peak.getPeakShape().clone()); +Mantid::Geometry::PeakShape_sptr getPeakShape(IPeak &peak) { + // Use clone to make a copy of the PeakShape. + return Mantid::Geometry::PeakShape_sptr(peak.getPeakShape().clone()); } +void setQLabFrame1(IPeak &peak, Mantid::Kernel::V3D qLabFrame) { + // Set the q lab frame. No explicit detector distance. + return peak.setQLabFrame(qLabFrame, boost::optional()); +} +void setQLabFrame2(IPeak &peak, Mantid::Kernel::V3D qLabFrame, double distance) { + // Set the q lab frame. Detector distance specified. + return peak.setQLabFrame(qLabFrame, distance); +} + +void setQSampleFrame1(IPeak &peak, Mantid::Kernel::V3D qSampleFrame) { + // Set the qsample frame. No explicit detector distance. + return peak.setQSampleFrame(qSampleFrame, boost::optional()); +} + +void setQSampleFrame2(IPeak &peak, Mantid::Kernel::V3D qSampleFrame, double distance) { + // Set the qsample frame. Detector distance specified. + return peak.setQSampleFrame(qSampleFrame, distance); +} + } void export_IPeak() @@ -38,8 +57,10 @@ void export_IPeak() "Using the instrument set in the peak, perform ray tracing to find the exact detector.") .def("getQSampleFrame", &IPeak::getQSampleFrame, "Return the Q change (of the lattice, k_i - k_f) for this peak." "The Q is in the Sample frame: the goniometer rotation WAS taken out. ") - .def("setQLabFrame", &IPeak::setQLabFrame, "Set the peak using the peak's position in reciprocal space, in the lab frame.") - .def("setQSampleFrame", &IPeak::setQSampleFrame, "Set the peak using the peak's position in reciprocal space, in the sample frame.") + .def("setQLabFrame", setQLabFrame1, "Set the peak using the peak's position in reciprocal space, in the lab frame.") + .def("setQLabFrame", setQLabFrame2, "Set the peak using the peak's position in reciprocal space, in the lab frame. Detector distance explicitly supplied.") // two argument overload + .def("setQSampleFrame", setQSampleFrame1, "Set the peak using the peak's position in reciprocal space, in the sample frame.") + .def("setQSampleFrame", setQSampleFrame2, "Set the peak using the peak's position in reciprocal space, in the sample frame. Detector distance explicitly supplied.") .def("setWavelength", &IPeak::setWavelength, "Set the incident wavelength of the neutron. Calculates the energy from this assuming elastic scattering.") .def("getWavelength", &IPeak::getWavelength, "Return the incident wavelength") .def("getScattering", &IPeak::getScattering, "Calculate the scattering angle of the peak") diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp index 1164cfe661d7..c8589a927a72 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeakFunction.cpp @@ -10,9 +10,13 @@ using namespace boost::python; void export_IPeakFunction() { class_, boost::shared_ptr, - boost::noncopyable>("IPeakFunction") - .def("functionLocal", (object (IPeakFunctionAdapter::*)(const object &)const)&IPeakFunction::functionLocal, - "Calculate the values of the function for the given x values. The output should be stored in the out array") - ; + boost::noncopyable>("IPeakFunction") + .def("functionLocal", (object (IPeakFunctionAdapter::*)(const object &)const)&IPeakFunction::functionLocal, + "Calculate the values of the function for the given x values. The output should be stored in the out array") + .def("intensity", &IPeakFunction::intensity, + "Returns the integral intensity of the peak function.") + .def("setIntensity", &IPeakFunction::setIntensity, + "Changes the integral intensity of the peak function by setting its " + "height.") + ; } - diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp index 80f30016b472..965bf50050c3 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/src/Exports/IPeaksWorkspace.cpp @@ -1,13 +1,38 @@ #include "MantidAPI/IPeaksWorkspace.h" #include "MantidAPI/IPeak.h" #include "MantidPythonInterface/kernel/Registry/DataItemInterface.h" +#include "MantidPythonInterface/kernel/Converters/PyObjectToV3D.h" #include #include +#include +#include using namespace Mantid::API; using Mantid::PythonInterface::Registry::DataItemInterface; using namespace boost::python; +namespace { + +/// Create a peak via it's HKL value from a list or numpy array +IPeak* createPeakHKL(IPeaksWorkspace & self, const object& data) +{ + return self.createPeakHKL(Mantid::PythonInterface::Converters::PyObjectToV3D(data)()); +} + +/// Create a peak via it's QLab value from a list or numpy array +IPeak* createPeakQLab(IPeaksWorkspace & self, const object& data) +{ + return self.createPeak(Mantid::PythonInterface::Converters::PyObjectToV3D(data)(), boost::optional()); +} + +/// Create a peak via it's QLab value from a list or numpy array +IPeak* createPeakQLabWithDistance(IPeaksWorkspace & self, const object& data, double detectorDistance) +{ + return self.createPeak(Mantid::PythonInterface::Converters::PyObjectToV3D(data)(), detectorDistance); +} + +} + void export_IPeaksWorkspace() { // IPeaksWorkspace class @@ -16,7 +41,9 @@ void export_IPeaksWorkspace() .def("addPeak", &IPeaksWorkspace::addPeak, "Add a peak to the workspace") .def("removePeak", &IPeaksWorkspace::removePeak, "Remove a peak from the workspace") .def("getPeak", &IPeaksWorkspace::getPeakPtr, return_internal_reference<>(), "Returns a peak at the given index" ) - .def("createPeak", &IPeaksWorkspace::createPeak, return_internal_reference<>(), "Create a Peak and return it") + .def("createPeak", createPeakQLab, return_value_policy(), "Create a Peak and return it from its coordinates in the QLab frame") + .def("createPeak", createPeakQLabWithDistance, return_value_policy(), "Create a Peak and return it from its coordinates in the QLab frame, detector-sample distance explicitly provided") + .def("createPeakHKL", createPeakHKL, return_value_policy(), "Create a Peak and return it from its coordinates in the HKL frame") .def("hasIntegratedPeaks", &IPeaksWorkspace::hasIntegratedPeaks, "Determine if the peaks have been integrated") .def("getRun", &IPeaksWorkspace::mutableRun, return_internal_reference<>(), "Return the Run object for this workspace") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py index da742cdd3d46..05af66bb925e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py @@ -1,8 +1,8 @@ +#pylint: disable=no-init import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * from mantid import config -import os MICROEV_TO_MILLIEV = 1000.0 DEFAULT_BINS = [0., 0., 0.] @@ -11,6 +11,29 @@ DEFAULT_MASK_FILE = "BASIS_Mask.xml" class BASISReduction(PythonAlgorithm): + + _short_inst = None + _long_inst = None + _extension = None + _doIndiv = None + _etBins = None + _qBins = None + _noMonNorm = None + _maskFile = None + _groupDetOpt = None + _overrideMask = None + _dMask = None + _doNorm = None + _normRange = None + _norm_run_list = None + _normWs = None + _normMonWs = None + _run_list = None + _samWs = None + _samMonWs = None + _samWsRun = None + _samSqwWs = None + def category(self): return "Inelastic;PythonAlgorithms" @@ -60,7 +83,7 @@ def PyExec(self): self._groupDetOpt = self.getProperty("GroupDetectors").value datasearch = config["datasearch.searcharchive"] - if (datasearch != "On"): + if datasearch != "On": config["datasearch.searcharchive"] = "On" # Handle masking file override if necessary @@ -217,7 +240,7 @@ def _calibData(self, sam_ws, mon_ws): api.MaskDetectors(Workspace=sam_ws, DetectorList=self._dMask) #MaskedWorkspace='BASIS_MASK') - api.ModeratorTzeroLinear(InputWorkspace=sam_ws, + api.ModeratorTzeroLinear(InputWorkspace=sam_ws,\ OutputWorkspace=sam_ws) api.LoadParameterFile(Workspace=sam_ws, Filename=config.getInstrumentDirectory() + 'BASIS_silicon_111_Parameters.xml') @@ -226,7 +249,7 @@ def _calibData(self, sam_ws, mon_ws): Target='Wavelength', EMode='Indirect') if not self._noMonNorm: - api.ModeratorTzeroLinear(InputWorkspace=mon_ws, + api.ModeratorTzeroLinear(InputWorkspace=mon_ws,\ OutputWorkspace=mon_ws) api.Rebin(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Params='10') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py index 9d59807f548d..0a5b4200515d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction311.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * @@ -13,6 +14,29 @@ DEFAULT_ENERGY = 7.6368 class BASISReduction311(PythonAlgorithm): + + _short_inst = None + _long_inst = None + _extension = None + _doIndiv = None + _etBins = None + _qBins = None + _noMonNorm = None + _maskFile = None + _groupDetOpt = None + _overrideMask = None + _dMask = None + _doNorm = None + _normRange = None + _norm_run_list = None + _normWs = None + _normMonWs = None + _run_list = None + _samWs = None + _samMonWs = None + _samWsRun = None + _samSqwWs = None + def category(self): return "Inelastic;PythonAlgorithms" @@ -26,31 +50,31 @@ def PyInit(self): self._short_inst = "BSS" self._long_inst = "BASIS" self._extension = "_event.nxs" - + self.declareProperty("RunNumbers", "", "Sample run numbers") self.declareProperty("DoIndividual", False, "Do each run individually") - self.declareProperty("NoMonitorNorm", False, + self.declareProperty("NoMonitorNorm", False, "Stop monitor normalization") - self.declareProperty("NormRunNumbers", "", "Normalization run numbers") - arrVal = FloatArrayLengthValidator(2) - self.declareProperty(FloatArrayProperty("NormWavelengthRange", DEFAULT_RANGE, - arrVal, direction=Direction.Input), - "Wavelength range for normalization. default:(6.24A, 6.30A)") - self.declareProperty(FloatArrayProperty("EnergyBins", DEFAULT_BINS, - direction=Direction.Input), - "Energy transfer binning scheme (in ueV)") - self.declareProperty(FloatArrayProperty("MomentumTransferBins", - DEFAULT_BINS, - direction=Direction.Input), - "Momentum transfer binning scheme") - self.declareProperty(FileProperty(name="MaskFile", defaultValue="", - action=FileAction.OptionalLoad, extensions=['.xml']), - "Directory location for standard masking and grouping files.") + self.declareProperty("NormRunNumbers", "", "Normalization run numbers") + arrVal = FloatArrayLengthValidator(2) + self.declareProperty(FloatArrayProperty("NormWavelengthRange", DEFAULT_RANGE,\ + arrVal, direction=Direction.Input),\ + "Wavelength range for normalization. default:(6.24A, 6.30A)") + self.declareProperty(FloatArrayProperty("EnergyBins", DEFAULT_BINS, + direction=Direction.Input),\ + "Energy transfer binning scheme (in ueV)") + self.declareProperty(FloatArrayProperty("MomentumTransferBins", + DEFAULT_BINS, + direction=Direction.Input),\ + "Momentum transfer binning scheme") + self.declareProperty(FileProperty(name="MaskFile", defaultValue="",\ + action=FileAction.OptionalLoad, extensions=['.xml']),\ + "Directory location for standard masking and grouping files.") grouping_type = ["None", "Low-Resolution", "By-Tube"] - self.declareProperty("GroupDetectors", "None", - StringListValidator(grouping_type), + self.declareProperty("GroupDetectors", "None", + StringListValidator(grouping_type), "Switch for grouping detectors") - + def PyExec(self): config['default.facility'] = "SNS" config['default.instrument'] = self._long_inst @@ -62,7 +86,7 @@ def PyExec(self): self._groupDetOpt = self.getProperty("GroupDetectors").value datasearch = config["datasearch.searcharchive"] - if (datasearch != "On"): + if datasearch != "On": config["datasearch.searcharchive"] = "On" # Handle masking file override if necessary @@ -71,65 +95,65 @@ def PyExec(self): config.appendDataSearchDir(DEFAULT_MASK_GROUP_DIR) self._maskFile = DEFAULT_MASK_FILE - api.LoadMask(Instrument='BASIS', OutputWorkspace='BASIS_MASK', + api.LoadMask(Instrument='BASIS', OutputWorkspace='BASIS_MASK', InputFile=self._maskFile) - + # Work around length issue _dMask = api.ExtractMask('BASIS_MASK') self._dMask = _dMask[1] api.DeleteWorkspace(_dMask[0]) - - # Do normalization if run numbers are present - norm_runs = self.getProperty("NormRunNumbers").value - self._doNorm = bool(norm_runs) - self.log().information("Do Norm: " + str(self._doNorm)) - if self._doNorm: - if ";" in norm_runs: - raise SyntaxError("Normalization does not support run groups") - # Setup the integration (rebin) parameters - normRange = self.getProperty("NormWavelengthRange").value - self._normRange = [normRange[0], normRange[1]-normRange[0], normRange[1]] - - # Process normalization runs - self._norm_run_list = self._getRuns(norm_runs) - for norm_set in self._norm_run_list: + + # Do normalization if run numbers are present + norm_runs = self.getProperty("NormRunNumbers").value + self._doNorm = bool(norm_runs) + self.log().information("Do Norm: " + str(self._doNorm)) + if self._doNorm: + if ";" in norm_runs: + raise SyntaxError("Normalization does not support run groups") + # Setup the integration (rebin) parameters + normRange = self.getProperty("NormWavelengthRange").value + self._normRange = [normRange[0], normRange[1]-normRange[0], normRange[1]] + + # Process normalization runs + self._norm_run_list = self._getRuns(norm_runs) + for norm_set in self._norm_run_list: extra_extension = "_norm" self._normWs = self._makeRunName(norm_set[0]) self._normWs += extra_extension - self._normMonWs = self._normWs + "_monitors" + self._normMonWs = self._normWs + "_monitors" self._sumRuns(norm_set, self._normWs, self._normMonWs, extra_extension) - self._calibData(self._normWs, self._normMonWs) - - api.Rebin(InputWorkspace=self._normWs, OutputWorkspace=self._normWs, - Params=self._normRange) - api.FindDetectorsOutsideLimits(InputWorkspace=self._normWs, - OutputWorkspace="BASIS_NORM_MASK") + self._calibData(self._normWs, self._normMonWs) + + api.Rebin(InputWorkspace=self._normWs, OutputWorkspace=self._normWs,\ + Params=self._normRange) + api.FindDetectorsOutsideLimits(InputWorkspace=self._normWs,\ + OutputWorkspace="BASIS_NORM_MASK") self._run_list = self._getRuns(self.getProperty("RunNumbers").value) for run_set in self._run_list: self._samWs = self._makeRunName(run_set[0]) self._samMonWs = self._samWs + "_monitors" self._samWsRun = str(run_set[0]) - - self._sumRuns(run_set, self._samWs, self._samMonWs) + + self._sumRuns(run_set, self._samWs, self._samMonWs) # After files are all added, run the reduction - self._calibData(self._samWs, self._samMonWs) - - if self._doNorm: - api.MaskDetectors(Workspace=self._samWs, - MaskedWorkspace='BASIS_NORM_MASK') - api.Divide(LHSWorkspace=self._samWs, RHSWorkspace=self._normWs, - OutputWorkspace=self._samWs) - - api.ConvertUnits(InputWorkspace=self._samWs, - OutputWorkspace=self._samWs, + self._calibData(self._samWs, self._samMonWs) + + if self._doNorm: + api.MaskDetectors(Workspace=self._samWs,\ + MaskedWorkspace='BASIS_NORM_MASK') + api.Divide(LHSWorkspace=self._samWs, RHSWorkspace=self._normWs,\ + OutputWorkspace=self._samWs) + + api.ConvertUnits(InputWorkspace=self._samWs, + OutputWorkspace=self._samWs, Target='DeltaE', EMode='Indirect') - api.CorrectKiKf(InputWorkspace=self._samWs, - OutputWorkspace=self._samWs, + api.CorrectKiKf(InputWorkspace=self._samWs, + OutputWorkspace=self._samWs, EMode='Indirect') - - api.Rebin(InputWorkspace=self._samWs, - OutputWorkspace=self._samWs, + + api.Rebin(InputWorkspace=self._samWs, + OutputWorkspace=self._samWs, Params=self._etBins) if self._groupDetOpt != "None": if self._groupDetOpt == "Low-Resolution": @@ -141,29 +165,29 @@ def PyExec(self): if self._overrideMask: config.appendDataSearchDir(DEFAULT_MASK_GROUP_DIR) - api.GroupDetectors(InputWorkspace=self._samWs, + api.GroupDetectors(InputWorkspace=self._samWs, OutputWorkspace=self._samWs, MapFile=grp_file, Behaviour="Sum") - + self._samSqwWs = self._samWs+'_sqw' - api.SofQW3(InputWorkspace=self._samWs, + api.SofQW3(InputWorkspace=self._samWs, OutputWorkspace=self._samSqwWs, - QAxisBinning=self._qBins, EMode='Indirect', + QAxisBinning=self._qBins, EMode='Indirect', EFixed=DEFAULT_ENERGY) - - dave_grp_filename = self._makeRunName(self._samWsRun, + + dave_grp_filename = self._makeRunName(self._samWsRun, False) + ".dat" - api.SaveDaveGrp(Filename=dave_grp_filename, + api.SaveDaveGrp(Filename=dave_grp_filename, InputWorkspace=self._samSqwWs, ToMicroEV=True) - processed_filename = self._makeRunName(self._samWsRun, + processed_filename = self._makeRunName(self._samWsRun, False) + "_sqw.nxs" - api.SaveNexus(Filename=processed_filename, - InputWorkspace=self._samSqwWs) + api.SaveNexus(Filename=processed_filename, + InputWorkspace=self._samSqwWs) def _getRuns(self, rlist): """ - Create sets of run numbers for analysis. A semicolon indicates a + Create sets of run numbers for analysis. A semicolon indicates a separate group of runs to be processed together. """ run_list = [] @@ -172,7 +196,7 @@ def _getRuns(self, rlist): iap = IntArrayProperty("", rlval) if self._doIndiv: run_list.extend([[x] for x in iap.value]) - else: + else: run_list.append(iap.value) return run_list @@ -184,12 +208,12 @@ def _makeRunName(self, run, useShort=True): return self._short_inst + "_" + str(run) else: return self._long_inst + "_" + str(run) - + def _makeRunFile(self, run): """ Make name like BSS24234 """ - return self._short_inst + str(run) + return self._short_inst + str(run) def _sumRuns(self, run_set, sam_ws, mon_ws, extra_ext=None): for run in run_set: @@ -198,57 +222,57 @@ def _sumRuns(self, run_set, sam_ws, mon_ws, extra_ext=None): ws_name += extra_ext mon_ws_name = ws_name + "_monitors" run_file = self._makeRunFile(run) - + api.Load(Filename=run_file, OutputWorkspace=ws_name) - + if not self._noMonNorm: - api.LoadNexusMonitors(Filename=run_file, + api.LoadNexusMonitors(Filename=run_file, OutputWorkspace=mon_ws_name) if sam_ws != ws_name: api.Plus(LHSWorkspace=sam_ws, RHSWorkspace=ws_name, OutputWorkspace=sam_ws) api.DeleteWorkspace(ws_name) if mon_ws != mon_ws_name and not self._noMonNorm: - api.Plus(LHSWorkspace=mon_ws, + api.Plus(LHSWorkspace=mon_ws, RHSWorkspace=mon_ws_name, OutputWorkspace=mon_ws) api.DeleteWorkspace(mon_ws_name) def _calibData(self, sam_ws, mon_ws): - api.LoadInstrument(Workspace=sam_ws, + api.LoadInstrument(Workspace=sam_ws, Filename=os.path.join(DEFAULT_CONFIG_DIR, 'BASIS_Definition_311.xml')) - api.MaskDetectors(Workspace=sam_ws, + api.MaskDetectors(Workspace=sam_ws, DetectorList=self._dMask) #MaskedWorkspace='BASIS_MASK') - api.ModeratorTzeroLinear(InputWorkspace=sam_ws, + api.ModeratorTzeroLinear(InputWorkspace=sam_ws,\ OutputWorkspace=sam_ws) - api.LoadParameterFile(Workspace=sam_ws, + api.LoadParameterFile(Workspace=sam_ws, Filename=os.path.join(DEFAULT_CONFIG_DIR, 'BASIS_silicon_311_Parameters.xml')) - api.ConvertUnits(InputWorkspace=sam_ws, + api.ConvertUnits(InputWorkspace=sam_ws, OutputWorkspace=sam_ws, Target='Wavelength', EMode='Indirect') - + if not self._noMonNorm: - api.ModeratorTzeroLinear(InputWorkspace=mon_ws, + api.ModeratorTzeroLinear(InputWorkspace=mon_ws,\ OutputWorkspace=mon_ws) - api.Rebin(InputWorkspace=mon_ws, + api.Rebin(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Params='10') - api.ConvertUnits(InputWorkspace=mon_ws, - OutputWorkspace=mon_ws, + api.ConvertUnits(InputWorkspace=mon_ws, + OutputWorkspace=mon_ws, Target='Wavelength') api.OneMinusExponentialCor(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, - C='0.20749999999999999', + C='0.20749999999999999', C1='0.001276') - api.Scale(InputWorkspace=mon_ws, + api.Scale(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Factor='9.9999999999999995e-07') - api.RebinToWorkspace(WorkspaceToRebin=sam_ws, + api.RebinToWorkspace(WorkspaceToRebin=sam_ws, WorkspaceToMatch=mon_ws, OutputWorkspace=sam_ws) - api.Divide(LHSWorkspace=sam_ws, - RHSWorkspace=mon_ws, + api.Divide(LHSWorkspace=sam_ws, + RHSWorkspace=mon_ws, OutputWorkspace=sam_ws) - + # Register algorithm with Mantid. AlgorithmFactory.subscribe(BASISReduction311) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py index c88d3bf4f803..7b8c955bd398 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * @@ -7,6 +8,12 @@ class CalculateSampleTransmission(PythonAlgorithm): + _bin_params = None + _chemical_formula = None + _density = None + _thickness = None + _output_ws = None + def category(self): return 'Sample' @@ -50,9 +57,11 @@ def PyExec(self): self._setup() # Create the workspace and set the sample material - CreateWorkspace(OutputWorkspace=self._output_ws, NSpec=2, DataX=[0, 0], DataY=[0, 0]) - Rebin(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws, Params=self._bin_params) - SetSampleMaterial(InputWorkspace=self._output_ws, ChemicalFormula=self._chamical_formula) + CreateWorkspace(OutputWorkspace=self._output_ws, NSpec=2, DataX=[0, 0], DataY=[0, 0], + VerticalAxisUnit='Text', VerticalAxisValues='Transmission,Scattering') + Rebin(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws, + Params=self._bin_params) + SetSampleMaterial(InputWorkspace=self._output_ws, ChemicalFormula=self._chemical_formula) ConvertToPointData(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws) ws = mtd[self._output_ws] @@ -78,7 +87,7 @@ def _setup(self): """ self._bin_params = self.getPropertyValue('WavelengthRange') - self._chamical_formula = self.getPropertyValue('ChemicalFormula') + self._chemical_formula = self.getPropertyValue('ChemicalFormula') self._density = self.getProperty('NumberDensity').value self._thickness = self.getProperty('Thickness').value self._output_ws = self.getPropertyValue('OutputWorkspace') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py index 0a9f068f51a9..fa2074ea6d4a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py @@ -1,9 +1,9 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * from mantid.simpleapi import * import os -import datetime -from time import localtime, strftime +from time import strftime from mantid import config from mantid.kernel import Direction @@ -11,6 +11,33 @@ class CalibrateRectangularDetectors(PythonAlgorithm): + _instrument = None + _filterBadPulses = None + _xpixelbin = None + _ypixelbin = None + _grouping = None + _smoothoffsets = None + _smoothGroups = None + _peakpos = None + _peakpos1 = None + _peakmin = None + _peakmax = None + _peakpos2 = None + _peakmin2 = None + _peakmax2 = None + _peakpos3 = None + _peakmin3 = None + _peakmax3 = None + _lastpixel = None + _lastpixel2 = None + _lastpixel3 = None + _ccnumber = None + _maxoffset = None + _diffractionfocus = None + _outDir = None + _outTypes = None + _binning = None + def category(self): return "Diffraction;PythonAlgorithms" @@ -25,10 +52,10 @@ def PyInit(self): instruments = [] for instr in sns.instruments(): - for tech in instr.techniques(): - if "Neutron Diffraction" == str(tech): - instruments.append(instr.shortName()) - break + for tech in instr.techniques(): + if "Neutron Diffraction" == str(tech): + instruments.append(instr.shortName()) + break self.declareProperty("Instrument", "PG3", StringListValidator(instruments)) validator = IntArrayBoundedValidator() @@ -64,15 +91,15 @@ def PyInit(self): "Comma delimited d-space positions of reference peaks. Use 1-3 for Cross Correlation. Unlimited for many peaks option.") self.declareProperty("PeakWindowMax", 0., "Maximum window around a peak to search for it. Optional.") - self.declareProperty(ITableWorkspaceProperty("FitwindowTableWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("FitwindowTableWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of input table workspace containing the fit window information for each spectrum. ") self.declareProperty("MinimumPeakHeight", 2., "Minimum value allowed for peak height") - self.declareProperty("MinimumPeakHeightObs", 0., + self.declareProperty("MinimumPeakHeightObs", 0.,\ "Minimum value of a peak's maximum observed Y value for this peak to be used to calculate offset.") - self.declareProperty(MatrixWorkspaceProperty("DetectorResolutionWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(MatrixWorkspaceProperty("DetectorResolutionWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of optional input matrix workspace for each detector's resolution (D(d)/d).") - self.declareProperty(FloatArrayProperty("AllowedResRange", [0.25, 4.0], direction=Direction.Input), + self.declareProperty(FloatArrayProperty("AllowedResRange", [0.25, 4.0], direction=Direction.Input),\ "Range of allowed individual peak's resolution factor to input detector's resolution.") self.declareProperty("PeakFunction", "Gaussian", StringListValidator(["BackToBackExponential", "Gaussian", "Lorentzian"]), @@ -148,7 +175,7 @@ def _loadPreNeXusData(self, runnumber, extension, **kwargs): wksp = LoadPreNexus(Filename=filename, OutputWorkspace=name, **mykwargs) # add the logs to it - if (str(self._instrument) == "SNAP"): + if str(self._instrument) == "SNAP": LoadInstrument(Workspace=wksp, InstrumentName=self._instrument, RewriteSpectraMap=False) return wksp @@ -232,8 +259,8 @@ def _cccalibrate(self, wksp, calib): y_s = wksp.readY(s) midBin = wksp.blocksize()/2 if y_s[midBin] > ymax: - refpixel = s - ymax = y_s[midBin] + refpixel = s + ymax = y_s[midBin] self.log().information("Reference spectra=%s" % refpixel) # Remove old calibration files cmd = "rm "+calib @@ -253,7 +280,7 @@ def _cccalibrate(self, wksp, calib): XMin=-self._ccnumber, XMax=self._ccnumber, MaxOffset=self._maxoffset, MaskWorkspace=str(wksp)+"mask") if AnalysisDataService.doesExist(str(wksp)+"cc"): - AnalysisDataService.remove(str(wksp)+"cc") + AnalysisDataService.remove(str(wksp)+"cc") if self._peakpos2 > 0.0: wksp = Rebin(InputWorkspace=wksp, OutputWorkspace=wksp.name(), Params=str(self._peakmin2)+","+str(abs(self._binning[1]))+","+str(self._peakmax2)) @@ -263,8 +290,8 @@ def _cccalibrate(self, wksp, calib): y_s = wksp.readY(s) midBin = wksp.blocksize()/2 if y_s[midBin] > ymax: - refpixel = s - ymax = y_s[midBin] + refpixel = s + ymax = y_s[midBin] msg = "Reference spectra = %s, lastpixel_3 = %s" % (refpixel, self._lastpixel3) self.log().information(msg) self._lastpixel2 = wksp.getNumberHistograms()*self._lastpixel2/self._lastpixel3-1 @@ -294,8 +321,8 @@ def _cccalibrate(self, wksp, calib): y_s = wksp.readY(s) midBin = wksp.blocksize()/2 if y_s[midBin] > ymax: - refpixel = s - ymax = y_s[midBin] + refpixel = s + ymax = y_s[midBin] self.log().information("Reference spectra=%s" % refpixel) CrossCorrelate(InputWorkspace=wksp, OutputWorkspace=str(wksp)+"cc3", ReferenceSpectra=refpixel, @@ -314,7 +341,7 @@ def _cccalibrate(self, wksp, calib): for ws in [str(wksp)+"cc3", str(wksp)+"offset3", str(wksp)+"mask3"]: if AnalysisDataService.doesExist(ws): AnalysisDataService.remove(ws) - (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping, + (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping,\ OutputWorkspace=str(wksp)+"group") if (numGroupedSpectra==0) or (numGroups==0): raise RuntimeError("%d spectra will be in %d groups" % (numGroupedSpectra, numGroups)) @@ -363,7 +390,7 @@ def _multicalibrate(self, wksp, calib): if not "histo" in self.getProperty("Extension").value: wksp = Rebin(InputWorkspace=wksp, OutputWorkspace=wksp.name(), Params=str(self._binning[0])+","+str((self._binning[1]))+","+str(self._binning[2])) - (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping, + (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping,\ OutputWorkspace=str(wksp)+"group") if (numGroupedSpectra==0) or (numGroups==0): raise RuntimeError("%d spectra will be in %d groups" % (numGroupedSpectra, numGroups)) @@ -386,7 +413,7 @@ def _multicalibrate(self, wksp, calib): reslowf = resrange[0] resupf = resrange[1] if reslowf >= resupf: - raise NotImplementedError("Allowed resolution range factor, lower boundary (%f) must be smaller than upper boundary (%f)." + raise NotImplementedError("Allowed resolution range factor, lower boundary (%f) must be smaller than upper boundary (%f)."\ % (reslowf, resupf)) else: reslowf = 0.0 @@ -436,7 +463,7 @@ def _focus(self, wksp, calib): if wksp is None: return None MaskDetectors(Workspace=wksp, MaskedWorkspace=str(wksp)+"mask") - wksp = AlignDetectors(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = AlignDetectors(InputWorkspace=wksp, OutputWorkspace=wksp.name(),\ OffsetsWorkspace=str(wksp)+"offset") # Diffraction focusing using new calibration file with offsets if self._diffractionfocus: @@ -515,7 +542,7 @@ def PyExec(self): for (samNum, backNum) in zip(samRuns, backRuns): # first round of processing the sample samRun = self._loadData(samNum, SUFFIX, filterWall) - if (backNum > 0): + if backNum > 0: backRun = self._loadData(backNum, SUFFIX, filterWall) samRun -= backRun DeleteWorkspace(backRun) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py index ff4ff2a92155..ad5329b501db 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py @@ -1,7 +1,6 @@ +#pylint: disable=invalid-name, no-init from mantid.api import PythonAlgorithm, AlgorithmFactory, WorkspaceProperty -import mantid.simpleapi from mantid.kernel import Direction, logger -from string import * class CheckForSampleLogs(PythonAlgorithm): """ Check if certain sample logs exists on a workspace @@ -24,7 +23,8 @@ def PyInit(self): """ self.declareProperty(WorkspaceProperty("Workspace", "",Direction.Input), "The workspace to check.") self.declareProperty("LogNames","","Names of the logs to look for") - self.declareProperty("Result","A string that will be empty if all the logs are found, otherwise will contain an error message",Direction.Output) + self.declareProperty("Result","A string that will be empty if all the logs are found, "\ + "otherwise will contain an error message",Direction.Output) return def PyExec(self): @@ -38,7 +38,7 @@ def PyExec(self): for value in logNames.split(','): value=value.strip() if len(value)>0: - if not w.run().hasProperty(value): + if not w.run().hasProperty(value): resultString+='Property '+value+' not found\n' #return the result diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py index 78fa1e54ff87..333e56678d68 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * from mantid.simpleapi import * @@ -27,13 +28,13 @@ def __load(self, directory, instr, run, loader, exts, wksp): return except Exception, e: logger.information(str(e)) - pass raise RuntimeError("Failed to load run %s from file %s" % (str(run), filename)) def PyInit(self): greaterThanZero = IntArrayBoundedValidator() greaterThanZero.setLower(0) - self.declareProperty(IntArrayProperty("RunNumbers",values=[0], validator=greaterThanZero), doc="Run numbers") + self.declareProperty(IntArrayProperty("RunNumbers",values=[0], + validator=greaterThanZero), doc="Run numbers") self.declareProperty(WorkspaceProperty("OutputWorkspace", "", direction=Direction.Output)) self.declareProperty(FileProperty("Directory", "", FileAction.OptionalDirectory)) @@ -64,3 +65,4 @@ def PyExec(self): self.setProperty("OutputWorkspace", mtd[wksp]) AlgorithmFactory.subscribe(ConjoinFiles) + diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py index f22e38a75532..e3fd47463893 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py @@ -1,13 +1,14 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * from mantid.simpleapi import * -import os class ConjoinSpectra(PythonAlgorithm): """ Conjoins spectra from several workspaces into a single workspace - Spectra to be conjoined must be equally binned in order for ConjoinSpectra to work. If necessary use RebinToWorkspace first. + Spectra to be conjoined must be equally binned in order for ConjoinSpectra + to work. If necessary use RebinToWorkspace first. """ def category(self): @@ -58,17 +59,20 @@ def PyExec(self): DeleteWorkspace(Workspace=wsOutput) for wsName in wsNames: #extract the spectrum - ExtractSingleSpectrum(InputWorkspace=wsName,OutputWorkspace=wsTemp,WorkspaceIndex=wsIndex) + ExtractSingleSpectrum(InputWorkspace=wsName,OutputWorkspace=wsTemp, + WorkspaceIndex=wsIndex) labelString ="" - if (labelUsing != ""): + if labelUsing != "": labelString = self.GetLogValue(mtd[wsName.strip()],labelUsing,labelValue) - if (labelString == ""): + if labelString == "": labelString =wsName+"_"+str(wsIndex) ta.setLabel(loopIndex,labelString) loopIndex += 1 if mtd.doesExist(wsOutput): - ConjoinWorkspaces(InputWorkspace1=wsOutput,InputWorkspace2=wsTemp,CheckOverlapping=False) + ConjoinWorkspaces(InputWorkspace1=wsOutput, + InputWorkspace2=wsTemp, + CheckOverlapping=False) if mtd.doesExist(wsTemp): DeleteWorkspace(Workspace=wsTemp) else: @@ -88,13 +92,13 @@ def GetLogValue(self,ws,labelUsing,labelValue): prop = run.getProperty(labelUsing) try: stats = prop.getStatistics() - if (labelValue == "Mean"): + if labelValue == "Mean": labelString = str(stats.mean) - elif (labelValue == "Median"): + elif labelValue == "Median": labelString = str(stats.median) - elif (labelValue == "Maximum"): + elif labelValue == "Maximum": labelString = str(stats.maximum) - elif (labelValue == "Minimum"): + elif labelValue == "Minimum": labelString = str(stats.minimum) else: labelString = str(prop.value[0]) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py index 93301070c0de..8ccb0c771437 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as msapi import mantid.api as api import mantid.kernel as kernel @@ -15,6 +16,12 @@ class ConvertSnsRoiFileToMask(api.PythonAlgorithm): Class to handle reading old SNS reduction ROI files and turning it into a Mantid mask workspace. """ + + _roiFile = None + _instName = None + _filePrefix = None + _outputDir = None + def category(self): """ Set the category for the algorithm. @@ -37,7 +44,7 @@ def PyInit(self): self.declareProperty(api.FileProperty(name="SnsRoiFile", defaultValue="", action=api.FileAction.Load, - extensions=EXTENSIONS), + extensions=EXTENSIONS),\ "SNS reduction ROI file to load.") allowedInstruments = kernel.StringListValidator(INSTRUMENTS) self.declareProperty("Instrument", "", @@ -48,7 +55,7 @@ def PyInit(self): +"file (Optional). Default is _Mask.") self.declareProperty(api.FileProperty(name="OutputDirectory", defaultValue=config['defaultsave.directory'], - action=api.FileAction.Directory), + action=api.FileAction.Directory),\ "Directory to save mask file."\ +" Default is current Mantid save directory.") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py index 2f2478c27b9a..e1993299e005 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py @@ -1,12 +1,14 @@ +#pylint: disable=invalid-name,no-init import mantid.simpleapi import mantid.api import mantid.kernel -import numpy class CorrectLogTimes(mantid.api.PythonAlgorithm): """ Class to shift log times to match proton charge """ + ws = None + def category(self): """ Mantid required """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py index 162f572d05da..d53125761090 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory from mantid.kernel import Direction @@ -5,11 +6,13 @@ class CreateEmptyTableWorkspace(PythonAlgorithm): def summary(self): - return "Creates an empty TableWorkspace which can be populated with various types of information." + return "Creates an empty TableWorkspace which can be populated with various "\ + "types of information." def PyInit(self): # Declare properties - self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), "The name of the table workspace that will be created.") + self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), + "The name of the table workspace that will be created.") def PyExec(self): tableWS = WorkspaceFactory.createTable() diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py index 029a0c8ada2b..780b8e1a355d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name #from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory, FileProperty, FileAction #from mantid.kernel import Direction, StringListValidator, FloatBoundedValidator @@ -30,28 +31,28 @@ def PyInit(self): #instruments=["POWGEN", "NOMAD", "VULCAN"] #self.declareProperty("Instrument", "POWGEN", StringListValidator(instruments), "Powder diffractometer's name") - self.declareProperty(FileProperty("ReflectionsFile","", FileAction.OptionalLoad, ['.hkl']), + self.declareProperty(FileProperty("ReflectionsFile","", FileAction.OptionalLoad, ['.hkl']),\ "Name of [http://www.ill.eu/sites/fullprof/ Fullprof] .hkl file that contains the peaks.") - self.declareProperty(FileProperty("FullprofParameterFile", "", FileAction.Load, ['.irf']), + self.declareProperty(FileProperty("FullprofParameterFile", "", FileAction.Load, ['.irf']),\ "Fullprof's .irf file containing the peak parameters.") - self.declareProperty("GenerateBraggReflections", False, + self.declareProperty("GenerateBraggReflections", False,\ "Generate Bragg reflections other than reading a Fullprof .irf file. ") arrvalidator = IntArrayBoundedValidator() arrvalidator.setLower(0) - self.declareProperty(IntArrayProperty("MaxHKL", values=[12, 12, 12], validator=arrvalidator, + self.declareProperty(IntArrayProperty("MaxHKL", values=[12, 12, 12], validator=arrvalidator,\ direction=Direction.Input), "Maximum reflection (HKL) to generate") self.declareProperty("Bank", 1, "Bank ID for output if there are more than one bank in .irf file.") self.declareProperty("LatticeConstant", -0.0, validator=FloatBoundedValidator(lower=1.0E-9), doc="Lattice constant for cubic crystal.") - self.declareProperty(ITableWorkspaceProperty("InstrumentParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("InstrumentParameterWorkspace", "", Direction.Output),\ "Name of Table Workspace Containing Peak Parameters From .irf File.") - self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Output),\ "Name of Table Workspace Containing Peaks' Miller Indices From .prf File.") return @@ -112,9 +113,9 @@ def importFullProfHKLFile(self, hklfilename, hklwsname): # api.DeleteWorkspace(Workspace=dummyws) # api.DeleteWorkspace(Workspace="TempXXX") - api.LoadFullprofFile( - Filename=hklfilename, - PeakParameterWorkspace = hklwsname, + api.LoadFullprofFile(\ + Filename=hklfilename,\ + PeakParameterWorkspace = hklwsname,\ OutputWorkspace = dummywsname) hklws = AnalysisDataService.retrieve(hklwsname) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py index e7720a121e5a..29a8549aeca8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py @@ -1,113 +1,122 @@ -from mantid.api import PythonAlgorithm, MatrixWorkspaceProperty, AlgorithmFactory +#pylint: disable=no-init,invalid-name +from mantid.api import PythonAlgorithm, AlgorithmFactory from mantid.simpleapi import CloneWorkspace, mtd -from mantid.kernel import StringListValidator, FloatArrayProperty, FloatArrayLengthValidator, FloatArrayMandatoryValidator, StringArrayProperty, StringArrayMandatoryValidator, Direction, FloatBoundedValidator, logger, EnabledWhenProperty, PropertyCriterion - -from pdb import set_trace as tr +from mantid.kernel import StringListValidator, FloatArrayProperty, FloatArrayMandatoryValidator,\ + StringArrayProperty, StringArrayMandatoryValidator, Direction, logger, EnabledWhenProperty, PropertyCriterion class DSFinterp(PythonAlgorithm): - def category(self): - return "Transforms\\Smoothing;Utility;PythonAlgorithms" + channelgroup = None + + def category(self): + return "Transforms\\Smoothing;Utility;PythonAlgorithms" - def name(self): - return 'DSFinterp' + def name(self): + return 'DSFinterp' - def summary(self): - return 'Given a set of parameter values {Ti} and corresponding structure factors S(Q,E,Ti), this algorithm interpolates S(Q,E,T) for any value of parameter T within the range spanned by the {Ti} set.' + def summary(self): + return 'Given a set of parameter values {Ti} and corresponding structure factors S(Q,E,Ti), this algorithm '\ + 'interpolates S(Q,E,T) for any value of parameter T within the range spanned by the {Ti} set.' - def PyInit(self): - arrvalidator = StringArrayMandatoryValidator() - lrg='Input' - self.declareProperty(StringArrayProperty('Workspaces', values=[], validator=arrvalidator, direction=Direction.Input), doc='list of input workspaces') - self.declareProperty('LoadErrors', True, direction=Direction.Input, doc='Do we load error data contained in the workspaces?') - self.declareProperty(FloatArrayProperty('ParameterValues', values=[], validator=FloatArrayMandatoryValidator(),direction=Direction.Input), doc='list of input parameter values') - self.setPropertyGroup('Workspaces', lrg) - self.setPropertyGroup('LoadErrors', lrg) - self.setPropertyGroup('ParameterValues', lrg) + def PyInit(self): + arrvalidator = StringArrayMandatoryValidator() + lrg='Input' + self.declareProperty(StringArrayProperty('Workspaces', values=[], validator=arrvalidator,\ + direction=Direction.Input), doc='list of input workspaces') + self.declareProperty('LoadErrors', True, direction=Direction.Input,\ + doc='Do we load error data contained in the workspaces?') + self.declareProperty(FloatArrayProperty('ParameterValues', values=[],\ + validator=FloatArrayMandatoryValidator(),direction=Direction.Input), doc='list of input parameter values') + self.setPropertyGroup('Workspaces', lrg) + self.setPropertyGroup('LoadErrors', lrg) + self.setPropertyGroup('ParameterValues', lrg) - self.declareProperty('LocalRegression', True, direction=Direction.Input, doc='Perform running local-regression?') - condition = EnabledWhenProperty("LocalRegression", PropertyCriterion.IsDefault) - self.declareProperty('RegressionWindow', 6, direction=Direction.Input, doc='window size for the running local-regression') - self.setPropertySettings("RegressionWindow", condition) - regtypes = [ 'linear', 'quadratic'] - self.declareProperty('RegressionType', 'quadratic', StringListValidator(regtypes), direction=Direction.Input, doc='type of local-regression; linear and quadratic are available') - self.setPropertySettings("RegressionType", condition) - lrg = 'Running Local Regression Options' - self.setPropertyGroup('LocalRegression', lrg) - self.setPropertyGroup('RegressionWindow', lrg) - self.setPropertyGroup('RegressionType', lrg) + self.declareProperty('LocalRegression', True, direction=Direction.Input, doc='Perform running local-regression?') + condition = EnabledWhenProperty("LocalRegression", PropertyCriterion.IsDefault) + self.declareProperty('RegressionWindow', 6, direction=Direction.Input, doc='window size for the running local-regression') + self.setPropertySettings("RegressionWindow", condition) + regtypes = [ 'linear', 'quadratic'] + self.declareProperty('RegressionType', 'quadratic', StringListValidator(regtypes),\ + direction=Direction.Input, doc='type of local-regression; linear and quadratic are available') + self.setPropertySettings("RegressionType", condition) + lrg = 'Running Local Regression Options' + self.setPropertyGroup('LocalRegression', lrg) + self.setPropertyGroup('RegressionWindow', lrg) + self.setPropertyGroup('RegressionType', lrg) - lrg='Output' - self.declareProperty(FloatArrayProperty('TargetParameters', values=[], ), doc="Parameters to interpolate the structure factor") - self.declareProperty(StringArrayProperty('OutputWorkspaces', values=[], validator=arrvalidator), doc='list of output workspaces to save the interpolated structure factors') - self.setPropertyGroup('TargetParameters', lrg) - self.setPropertyGroup('OutputWorkspaces', lrg) - self.channelgroup = None + lrg='Output' + self.declareProperty(FloatArrayProperty('TargetParameters', values=[], ), doc="Parameters to interpolate the structure factor") + self.declareProperty(StringArrayProperty('OutputWorkspaces', values=[], validator=arrvalidator),\ + doc='list of output workspaces to save the interpolated structure factors') + self.setPropertyGroup('TargetParameters', lrg) + self.setPropertyGroup('OutputWorkspaces', lrg) + self.channelgroup = None - def areWorkspacesCompatible(self, a, b): - sizeA = a.blocksize() * a.getNumberHistograms() - sizeB = b.blocksize() * b.getNumberHistograms() - return sizeA == sizeB + def areWorkspacesCompatible(self, a, b): + sizeA = a.blocksize() * a.getNumberHistograms() + sizeB = b.blocksize() * b.getNumberHistograms() + return sizeA == sizeB - def PyExec(self): + def PyExec(self): # Check congruence of workspaces - workspaces = self.getProperty('Workspaces').value - fvalues = self.getProperty('ParameterValues').value - if len(workspaces) != len(fvalues): - mesg = 'Number of Workspaces and ParameterValues should be the same' + workspaces = self.getProperty('Workspaces').value + fvalues = self.getProperty('ParameterValues').value + if len(workspaces) != len(fvalues): + mesg = 'Number of Workspaces and ParameterValues should be the same' #logger.error(mesg) - raise IndexError(mesg) - for workspace in workspaces[1:]: - if not self.areWorkspacesCompatible(mtd[workspaces[0]],mtd[workspace]): - mesg = 'Workspace {0} incompatible with {1}'.format(workspace, workspaces[0]) - logger.error(mesg) - raise ValueError(mesg) + raise IndexError(mesg) + for workspace in workspaces[1:]: + if not self.areWorkspacesCompatible(mtd[workspaces[0]],mtd[workspace]): + mesg = 'Workspace {0} incompatible with {1}'.format(workspace, workspaces[0]) + logger.error(mesg) + raise ValueError(mesg) # Load the workspaces into a group of dynamic structure factors - from dsfinterp.dsf import Dsf - from dsfinterp.dsfgroup import DsfGroup - from dsfinterp.channelgroup import ChannelGroup - dsfgroup = DsfGroup() - for idsf in range(len(workspaces)): - dsf = Dsf() - dsf.Load( mtd[workspaces[idsf]] ) - if not self.getProperty('LoadErrors').value: - dsf.errors = None # do not incorporate error data - dsf.SetFvalue( fvalues[idsf] ) - dsfgroup.InsertDsf(dsf) + from dsfinterp.dsf import Dsf + from dsfinterp.dsfgroup import DsfGroup + from dsfinterp.channelgroup import ChannelGroup + dsfgroup = DsfGroup() + for idsf in range(len(workspaces)): + dsf = Dsf() + dsf.Load( mtd[workspaces[idsf]] ) + if not self.getProperty('LoadErrors').value: + dsf.errors = None # do not incorporate error data + dsf.SetFvalue( fvalues[idsf] ) + dsfgroup.InsertDsf(dsf) # Create the intepolator if not instantiated before - if not self.channelgroup: - self.channelgroup = ChannelGroup() - self.channelgroup.InitFromDsfGroup(dsfgroup) - localregression = self.getProperty('LocalRegression').value - if localregression: - regressiontype = self.getProperty('RegressionType').value - windowlength = self.getProperty('RegressionWindow').value - self.channelgroup.InitializeInterpolator(running_regr_type=regressiontype, windowlength=windowlength) - else: - self.channelgroup.InitializeInterpolator(windowlength=0) + if not self.channelgroup: + self.channelgroup = ChannelGroup() + self.channelgroup.InitFromDsfGroup(dsfgroup) + localregression = self.getProperty('LocalRegression').value + if localregression: + regressiontype = self.getProperty('RegressionType').value + windowlength = self.getProperty('RegressionWindow').value + self.channelgroup.InitializeInterpolator(running_regr_type=regressiontype, windowlength=windowlength) + else: + self.channelgroup.InitializeInterpolator(windowlength=0) # Invoke the interpolator and generate the output workspaces - targetfvalues = self.getProperty('TargetParameters').value - for targetfvalue in targetfvalues: - if targetfvalue < min(fvalues) or targetfvalue > max(fvalues): - mesg = 'Target parameters should lie in [{0}, {1}]'.format(min(fvalues),max(fvalues)) - logger.error(mesg) - raise ValueError(mesg) - outworkspaces = self.getProperty('OutputWorkspaces').value - if len(targetfvalues) != len(outworkspaces): - mesg = 'Number of OutputWorkspaces and TargetParameters should be the same' - logger.error(mesg) - raise IndexError(mesg) - for i in range(len(targetfvalues)): - outworkspace = outworkspaces[i] - dsf = self.channelgroup( targetfvalues[i] ) - outws = CloneWorkspace( mtd[workspaces[0]], OutputWorkspace=outworkspaces[i]) - dsf.Save(outws) # overwrite dataY and dataE + targetfvalues = self.getProperty('TargetParameters').value + for targetfvalue in targetfvalues: + if targetfvalue < min(fvalues) or targetfvalue > max(fvalues): + mesg = 'Target parameters should lie in [{0}, {1}]'.format(min(fvalues),max(fvalues)) + logger.error(mesg) + raise ValueError(mesg) + outworkspaces = self.getProperty('OutputWorkspaces').value + if len(targetfvalues) != len(outworkspaces): + mesg = 'Number of OutputWorkspaces and TargetParameters should be the same' + logger.error(mesg) + raise IndexError(mesg) + for i in range(len(targetfvalues)): + outworkspace = outworkspaces[i] + dsf = self.channelgroup( targetfvalues[i] ) + outws = CloneWorkspace( mtd[workspaces[0]], OutputWorkspace=outworkspaces[i]) + dsf.Save(outws) # overwrite dataY and dataE ############################################################################################# - +#pylint: disable=unused-import try: - import dsfinterp - AlgorithmFactory.subscribe(DSFinterp) + import dsfinterp + AlgorithmFactory.subscribe(DSFinterp) except: - logger.debug('Failed to subscribe algorithm DSFinterp; Python package dsfinterp may be missing (https://pypi.python.org/pypi/dsfinterp)') - pass + logger.debug('Failed to subscribe algorithm DSFinterp; Python package dsfinterp'\ + 'may be missing (https://pypi.python.org/pypi/dsfinterp)') + diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py index 7a671ccb7066..f097ed09e653 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py @@ -1,9 +1,9 @@ +#pylint: disable=no-init,invalid-name from mantid.api import PythonAlgorithm, AlgorithmFactory,MatrixWorkspaceProperty,PropertyMode -from mantid.kernel import Direction,IntBoundedValidator,FloatBoundedValidator -import mantid.simpleapi +from mantid.kernel import Direction +import mantid.simpleapi import mantid import numpy -from string import * class DakotaChiSquared(PythonAlgorithm): """ Get chi squared by comparing two mantid nexus files @@ -12,7 +12,7 @@ def category(self): """ Return category """ return "PythonAlgorithms;Utility\\Workspaces" - + def name(self): """ Return name """ @@ -24,67 +24,67 @@ def summmary(self): def PyInit(self): """ Declare properties """ - f1=mantid.api.FileProperty("DataFile","",mantid.api.FileAction.Load,".nxs") - self.declareProperty(f1,"Input Nexus file containing data.") - f2=mantid.api.FileProperty("CalculatedFile","",mantid.api.FileAction.Load,".nxs") + f1=mantid.api.FileProperty("DataFile","",mantid.api.FileAction.Load,".nxs") + self.declareProperty(f1,"Input Nexus file containing data.") + f2=mantid.api.FileProperty("CalculatedFile","",mantid.api.FileAction.Load,".nxs") self.declareProperty(f2,"Input Nexus file containing calculated data.") - fout=mantid.api.FileProperty("OutputFile","",mantid.api.FileAction.Save,".xml") + fout=mantid.api.FileProperty("OutputFile","",mantid.api.FileAction.Save,".xml") self.declareProperty(fout,"Output filename containing chi^2.") - self.declareProperty("ChiSquared",0.0,Direction.Output) - self.declareProperty(MatrixWorkspaceProperty("ResidualsWorkspace", "",Direction.Output,PropertyMode.Optional), "The name of the workspace that will contain residuals.") - + self.declareProperty("ChiSquared",0.0,Direction.Output) + self.declareProperty(MatrixWorkspaceProperty("ResidualsWorkspace", "",Direction.Output,PropertyMode.Optional),\ + "The name of the workspace that will contain residuals.") return - + def PyExec(self): """ Main execution body """ - #get parameters - f1 = self.getProperty("DataFile").value - f2 = self.getProperty("CalculatedFile").value - fout = self.getProperty("OutputFile").value - - #load files + #get parameters + f1 = self.getProperty("DataFile").value + f2 = self.getProperty("CalculatedFile").value + fout = self.getProperty("OutputFile").value + + #load files __w1=mantid.simpleapi.Load(f1) - __w2=mantid.simpleapi.Load(f2) + __w2=mantid.simpleapi.Load(f2) + + #validate inputs + if type(__w1)!= mantid.api.MatrixWorkspace: + mantid.kernel.logger.error('Wrong workspace type for data file') + raise ValueError( 'Wrong workspace type for data file') + if type(__w2)!= mantid.api.MatrixWorkspace: + mantid.kernel.logger.error('Wrong workspace type for calculated file') + raise ValueError( 'Wrong workspace type for calculated file') + if __w1.blocksize()!=__w2.blocksize() or __w1.getNumberHistograms()!=__w2.getNumberHistograms(): + mantid.kernel.logger.error('The file sizes are different') + raise ValueError( 'The file sizes are different') - #validate inputs - if (type(__w1)!= mantid.api._api.MatrixWorkspace): - mantid.kernel.logger.error('Wrong workspace type for data file') - raise ValueError( 'Wrong workspace type for data file') - if (type(__w2)!= mantid.api._api.MatrixWorkspace): - mantid.kernel.logger.error('Wrong workspace type for calculated file') - raise ValueError( 'Wrong workspace type for calculated file') - if((__w1.blocksize()!=__w2.blocksize()) or (__w1.getNumberHistograms()!=__w2.getNumberHistograms())): - mantid.kernel.logger.error('The file sizes are different') - raise ValueError( 'The file sizes are different') - - #calculate chi^2 - soeName = self.getPropertyValue("ResidualsWorkspace") - if (len(soeName)>0): - mantid.simpleapi.SignalOverError(__w1-__w2,OutputWorkspace=soeName) - self.setProperty("ResidualsWorkspace",soeName) - __soe=mantid.mtd[soeName] - else: - __soe=mantid.simpleapi.SignalOverError(__w1-__w2) - __soe2=__soe*__soe - __soe2=mantid.simpleapi.ReplaceSpecialValues(__soe2,0,0,0,0) - - data=__soe2.extractY() - chisquared=numpy.sum(data) + #calculate chi^2 + soeName = self.getPropertyValue("ResidualsWorkspace") + if len(soeName)>0: + mantid.simpleapi.SignalOverError(__w1-__w2,OutputWorkspace=soeName) + self.setProperty("ResidualsWorkspace",soeName) + __soe=mantid.mtd[soeName] + else: + __soe=mantid.simpleapi.SignalOverError(__w1-__w2) + __soe2=__soe*__soe + __soe2=mantid.simpleapi.ReplaceSpecialValues(__soe2,0,0,0,0) - #write out the Dakota chi squared file - f = open(fout,'w') - f.write(str(chisquared)+' obj_fn\n') - f.close() + data=__soe2.extractY() + chisquared=numpy.sum(data) + + #write out the Dakota chi squared file + f = open(fout,'w') + f.write(str(chisquared)+' obj_fn\n') + f.close() self.setProperty("ChiSquared",chisquared) - - #cleanup - mantid.simpleapi.DeleteWorkspace(__w1.getName()) - mantid.simpleapi.DeleteWorkspace(__w2.getName()) - mantid.simpleapi.DeleteWorkspace(__soe2.getName()) - if (len(soeName)==0): - mantid.simpleapi.DeleteWorkspace(__soe.getName()) - + + #cleanup + mantid.simpleapi.DeleteWorkspace(__w1.getName()) + mantid.simpleapi.DeleteWorkspace(__w2.getName()) + mantid.simpleapi.DeleteWorkspace(__soe2.getName()) + if len(soeName)==0: + mantid.simpleapi.DeleteWorkspace(__soe.getName()) + AlgorithmFactory.subscribe(DakotaChiSquared) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py index b7dcc6e08a22..7b7cef59550e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py @@ -1,63 +1,61 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * -import csv -import numpy as np -import math class EnginXCalibrate(PythonAlgorithm): def category(self): - return "Diffraction\Engineering;PythonAlgorithms" + return "Diffraction\Engineering;PythonAlgorithms" def name(self): - return "EnginXCalibrate" + return "EnginXCalibrate" def summary(self): - return "Calibrates a detector bank by performing a single peak fitting." + return "Calibrates a detector bank by performing a single peak fitting." def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), + self.declareProperty(FileProperty("Filename", "", FileAction.Load),\ "Calibration run to use") - self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), + self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""),\ "A list of dSpacing values where peaks are expected.") - self.declareProperty("Bank", 1, "Which bank to calibrate") + self.declareProperty("Bank", 1, "Which bank to calibrate") - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional),\ "Calibrated detector positions. If not specified, default ones are used.") - self.declareProperty("Difc", 0.0, direction = Direction.Output, + self.declareProperty("Difc", 0.0, direction = Direction.Output,\ doc = "Calibrated Difc value for the bank") - self.declareProperty("Zero", 0.0, direction = Direction.Output, + self.declareProperty("Zero", 0.0, direction = Direction.Output,\ doc = "Calibrated Zero value for the bank") def PyExec(self): - ws = self._focusRun() + ws = self._focusRun() - fitPeaksAlg = self.createChildAlgorithm('EnginXFitPeaks') - fitPeaksAlg.setProperty('InputWorkspace', ws) - fitPeaksAlg.setProperty('WorkspaceIndex', 0) # There should be only one index anyway - fitPeaksAlg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) - fitPeaksAlg.execute() + fitPeaksAlg = self.createChildAlgorithm('EnginXFitPeaks') + fitPeaksAlg.setProperty('InputWorkspace', ws) + fitPeaksAlg.setProperty('WorkspaceIndex', 0) # There should be only one index anyway + fitPeaksAlg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) + fitPeaksAlg.execute() - self.setProperty('Difc', fitPeaksAlg.getProperty('Difc').value) - self.setProperty('Zero', fitPeaksAlg.getProperty('Zero').value) + self.setProperty('Difc', fitPeaksAlg.getProperty('Difc').value) + self.setProperty('Zero', fitPeaksAlg.getProperty('Zero').value) def _focusRun(self): - alg = self.createChildAlgorithm('EnginXFocus') - alg.setProperty('Filename', self.getProperty('Filename').value) - alg.setProperty('Bank', self.getProperty('Bank').value) + alg = self.createChildAlgorithm('EnginXFocus') + alg.setProperty('Filename', self.getProperty('Filename').value) + alg.setProperty('Bank', self.getProperty('Bank').value) - detPos = self.getProperty('DetectorPositions').value - if detPos: - alg.setProperty('DetectorPositions', detPos) + detPos = self.getProperty('DetectorPositions').value + if detPos: + alg.setProperty('DetectorPositions', detPos) - alg.execute() + alg.execute() - return alg.getProperty('OutputWorkspace').value + return alg.getProperty('OutputWorkspace').value -AlgorithmFactory.subscribe(EnginXCalibrate) \ No newline at end of file +AlgorithmFactory.subscribe(EnginXCalibrate) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py index 9d586a12440d..c76292257350 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py @@ -1,133 +1,134 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * import math class EnginXCalibrateFull(PythonAlgorithm): def category(self): - return "Diffraction\Engineering;PythonAlgorithms" + return "Diffraction\Engineering;PythonAlgorithms" def name(self): - return "EnginXCalibrateFull" + return "EnginXCalibrateFull" def summary(self): - return "Calibrates every pixel position by performing single peak fitting." + return "Calibrates every pixel position by performing single peak fitting." def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), + self.declareProperty(FileProperty("Filename", "", FileAction.Load),\ "Calibration run to use") - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Output),\ "A table with the detector IDs and calibrated detector positions in V3P format.") - self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), + self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""),\ "A list of dSpacing values where peaks are expected.") - self.declareProperty("Bank", 1, "Which bank to calibrate") + self.declareProperty("Bank", 1, "Which bank to calibrate") def PyExec(self): - import EnginXUtils + import EnginXUtils - ws = self._loadCalibrationRun() + ws = self._loadCalibrationRun() - ws = self._prepareWsForFitting(ws) + ws = self._prepareWsForFitting(ws) - positionTable = self._createPositionsTable() + positionTable = self._createPositionsTable() - indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) + indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) - prog = Progress(self, 0, 1, len(indices)) + prog = Progress(self, 0, 1, len(indices)) - for i in indices: + for i in indices: - _, difc = self._fitPeaks(ws, i) + _, difc = self._fitPeaks(ws, i) - det = ws.getDetector(i) + det = ws.getDetector(i) - newPos = self._getCalibratedDetPos(difc, det, ws) + newPos = self._getCalibratedDetPos(difc, det, ws) - positionTable.addRow([det.getID(), newPos]) + positionTable.addRow([det.getID(), newPos]) - prog.report() + prog.report() - self.setProperty("DetectorPositions", positionTable) + self.setProperty("DetectorPositions", positionTable) def _loadCalibrationRun(self): - """ Loads specified calibration run + """ Loads specified calibration run """ - alg = self.createChildAlgorithm('Load') - alg.setProperty('Filename', self.getProperty('Filename').value) - alg.execute() - return alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('Load') + alg.setProperty('Filename', self.getProperty('Filename').value) + alg.execute() + return alg.getProperty('OutputWorkspace').value def _prepareWsForFitting(self, ws): - """ Rebins the workspace and converts it to distribution + """ Rebins the workspace and converts it to distribution """ - rebinAlg = self.createChildAlgorithm('Rebin') - rebinAlg.setProperty('InputWorkspace', ws) - rebinAlg.setProperty('Params', '-0.0005') # The value is borrowed from OG routines - rebinAlg.execute() - result = rebinAlg.getProperty('OutputWorkspace').value + rebinAlg = self.createChildAlgorithm('Rebin') + rebinAlg.setProperty('InputWorkspace', ws) + rebinAlg.setProperty('Params', '-0.0005') # The value is borrowed from OG routines + rebinAlg.execute() + result = rebinAlg.getProperty('OutputWorkspace').value if result.isDistribution()==False: - convertAlg = self.createChildAlgorithm('ConvertToDistribution') - convertAlg.setProperty('Workspace', result) - convertAlg.execute() + convertAlg = self.createChildAlgorithm('ConvertToDistribution') + convertAlg.setProperty('Workspace', result) + convertAlg.execute() - return result + return result def _createPositionsTable(self): - """ Creates an empty table for storing detector positions + """ Creates an empty table for storing detector positions """ - alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') - alg.execute() - table = alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') + alg.execute() + table = alg.getProperty('OutputWorkspace').value - table.addColumn('int', 'Detector ID') - table.addColumn('V3D', 'Detector Position') + table.addColumn('int', 'Detector ID') + table.addColumn('V3D', 'Detector Position') - return table + return table def _fitPeaks(self, ws, wsIndex): - """ Fits expected peaks to the spectrum, and returns calibrated zero and difc values. + """ Fits expected peaks to the spectrum, and returns calibrated zero and difc values. """ - alg = self.createChildAlgorithm('EnginXFitPeaks') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('WorkspaceIndex', wsIndex) # There should be only one index anyway - alg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) - alg.execute() + alg = self.createChildAlgorithm('EnginXFitPeaks') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('WorkspaceIndex', wsIndex) # There should be only one index anyway + alg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) + alg.execute() - difc = alg.getProperty('Difc').value - zero = alg.getProperty('Zero').value + difc = alg.getProperty('Difc').value + zero = alg.getProperty('Zero').value - return (zero, difc) + return (zero, difc) def _getCalibratedDetPos(self, newDifc, det, ws): - """ Returns a detector position which corresponds to the newDifc value. + """ Returns a detector position which corresponds to the newDifc value. The two_theta and phi of the detector are preserved, L2 is changed. """ - detL2 = det.getDistance(ws.getInstrument().getSample()) - detTwoTheta = ws.detectorTwoTheta(det) - detPhi = det.getPhi() + detL2 = det.getDistance(ws.getInstrument().getSample()) + detTwoTheta = ws.detectorTwoTheta(det) + detPhi = det.getPhi() - newL2 = (newDifc / (252.816 * 2 * math.sin(detTwoTheta / 2.0))) - 50 + newL2 = (newDifc / (252.816 * 2 * math.sin(detTwoTheta / 2.0))) - 50 - newPos = self._V3DFromSpherical(newL2, detTwoTheta, detPhi) + newPos = self._V3DFromSpherical(newL2, detTwoTheta, detPhi) - return newPos + return newPos def _V3DFromSpherical(self, R, polar, azimuth): - """ Returns a cartesian 3D vector for the given spherical coordinates. + """ Returns a cartesian 3D vector for the given spherical coordinates. Borrowed from V3D::spherical (C++). """ - z = R*math.cos(polar) - ct=R*math.sin(polar) - x=ct*math.cos(azimuth) - y=ct*math.sin(azimuth) + z = R*math.cos(polar) + ct=R*math.sin(polar) + x=ct*math.cos(azimuth) + y=ct*math.sin(azimuth) - return V3D(x,y,z) + return V3D(x,y,z) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py index 5642497df446..5c75e97626e3 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py @@ -1,35 +1,35 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * import math -import numpy as np class EnginXFitPeaks(PythonAlgorithm): def category(self): - return "Diffraction\Engineering;PythonAlgorithms" + return "Diffraction\Engineering;PythonAlgorithms" def name(self): - return "EnginXFitPeaks" + return "EnginXFitPeaks" def summary(self): - return "The algorithm fits an expected diffraction pattern to a workpace spectrum by performing single peak fits." + return "The algorithm fits an expected diffraction pattern to a workpace spectrum by performing single peak fits." def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input),\ "Workspace to fit peaks in. ToF is expected X unit.") - self.declareProperty("WorkspaceIndex", 0, + self.declareProperty("WorkspaceIndex", 0,\ "Index of the spectra to fit peaks in") - self.declareProperty(FloatArrayProperty("ExpectedPeaks", (self._getDefaultPeaks())), + self.declareProperty(FloatArrayProperty("ExpectedPeaks", (self._getDefaultPeaks())),\ "A list of dSpacing values to be translated into TOF to find expected peaks.") - - self.declareProperty(FileProperty(name="ExpectedPeaksFromFile",defaultValue="",action=FileAction.OptionalLoad,extensions = [".csv"]),"Load from file a list of dSpacing values to be translated into TOF to find expected peaks.") - self.declareProperty("Difc", 0.0, direction = Direction.Output, + self.declareProperty(FileProperty(name="ExpectedPeaksFromFile",defaultValue="",action=FileAction.OptionalLoad,extensions = [".csv"]),"Load from file a list of dSpacing values to be translated into TOF to find expected peaks.") + + self.declareProperty("Difc", 0.0, direction = Direction.Output,\ doc = "Fitted Difc value") - self.declareProperty("Zero", 0.0, direction = Direction.Output, + self.declareProperty("Zero", 0.0, direction = Direction.Output,\ doc = "Fitted Zero value") def PyExec(self): @@ -39,7 +39,7 @@ def PyExec(self): # so we can match them with fitted centres later. expectedPeaksTof = sorted(expectedPeaksTof) expectedPeaksD = self._readInExpectedPeaks() - + # Find approximate peak positions, asumming Gaussian shapes findPeaksAlg = self.createChildAlgorithm('FindPeaks') findPeaksAlg.setProperty('InputWorkspace', self.getProperty("InputWorkspace").value) @@ -49,7 +49,7 @@ def PyExec(self): findPeaksAlg.execute() foundPeaks = findPeaksAlg.getProperty('PeaksList').value - if (foundPeaks.rowCount() < len(expectedPeaksTof)): + if foundPeaks.rowCount() < len(expectedPeaksTof): raise Exception("Some peaks were not found") fittedPeaks = self._createFittedPeaksTable() @@ -118,83 +118,83 @@ def _readInExpectedPeaks(self): if exPeakArray == []: print "File could not be read. Defaults being used." expectedPeaksD = sorted(self.getProperty('ExpectedPeaks').value) - else: + else: print "using file" expectedPeaksD = sorted(exPeakArray) else: expectedPeaksD = sorted(self.getProperty('ExpectedPeaks').value) - return expectedPeaksD + return expectedPeaksD def _getDefaultPeaks(self): """ Gets default peaks for EnginX algorithm. Values from CeO2 """ - defaultPeak = [3.1243, 2.7057, 1.9132, 1.6316, 1.5621, 1.3529, 1.2415, 1.2100, 1.1046, 1.0414, 0.9566, 0.9147, 0.9019, 0.8556, 0.8252, 0.8158, 0.7811] + defaultPeak = [3.1243, 2.7057, 1.9132, 1.6316, 1.5621, 1.3529, 1.2415, 1.2100, 1.1046, 1.0414, 0.9566, 0.9147, 0.9019, 0.8556, 0.8252, 0.8158, 0.7811] return defaultPeak def _fitDSpacingToTOF(self, fittedPeaksTable): - """ Fits a linear background to the dSpacing <-> TOF relationship and returns fitted difc + """ Fits a linear background to the dSpacing <-> TOF relationship and returns fitted difc and zero values. """ - convertTableAlg = self.createChildAlgorithm('ConvertTableToMatrixWorkspace') - convertTableAlg.setProperty('InputWorkspace', fittedPeaksTable) - convertTableAlg.setProperty('ColumnX', 'dSpacing') - convertTableAlg.setProperty('ColumnY', 'X0') - convertTableAlg.execute() - dSpacingVsTof = convertTableAlg.getProperty('OutputWorkspace').value + convertTableAlg = self.createChildAlgorithm('ConvertTableToMatrixWorkspace') + convertTableAlg.setProperty('InputWorkspace', fittedPeaksTable) + convertTableAlg.setProperty('ColumnX', 'dSpacing') + convertTableAlg.setProperty('ColumnY', 'X0') + convertTableAlg.execute() + dSpacingVsTof = convertTableAlg.getProperty('OutputWorkspace').value # Fit the curve to get linear coefficients of TOF <-> dSpacing relationship for the detector - fitAlg = self.createChildAlgorithm('Fit') - fitAlg.setProperty('Function', 'name=LinearBackground') - fitAlg.setProperty('InputWorkspace', dSpacingVsTof) - fitAlg.setProperty('WorkspaceIndex', 0) - fitAlg.setProperty('CreateOutput', True) - fitAlg.execute() - paramTable = fitAlg.getProperty('OutputParameters').value + fitAlg = self.createChildAlgorithm('Fit') + fitAlg.setProperty('Function', 'name=LinearBackground') + fitAlg.setProperty('InputWorkspace', dSpacingVsTof) + fitAlg.setProperty('WorkspaceIndex', 0) + fitAlg.setProperty('CreateOutput', True) + fitAlg.execute() + paramTable = fitAlg.getProperty('OutputParameters').value - zero = paramTable.cell('Value', 0) # A0 - difc = paramTable.cell('Value', 1) # A1 + zero = paramTable.cell('Value', 0) # A0 + difc = paramTable.cell('Value', 1) # A1 - return (difc, zero) + return (difc, zero) def _expectedPeaksInTOF(self): - """ Converts expected peak dSpacing values to TOF values for the detector + """ Converts expected peak dSpacing values to TOF values for the detector """ - ws = self.getProperty("InputWorkspace").value - wsIndex = self.getProperty("WorkspaceIndex").value + ws = self.getProperty("InputWorkspace").value + wsIndex = self.getProperty("WorkspaceIndex").value # Detector for specified spectrum - det = ws.getDetector(wsIndex) + det = ws.getDetector(wsIndex) # Current detector parameters - detL2 = det.getDistance(ws.getInstrument().getSample()) - detTwoTheta = ws.detectorTwoTheta(det) + detL2 = det.getDistance(ws.getInstrument().getSample()) + detTwoTheta = ws.detectorTwoTheta(det) # Function for converting dSpacing -> TOF for the detector - dSpacingToTof = lambda d: 252.816 * 2 * (50 + detL2) * math.sin(detTwoTheta / 2.0) * d - expectedPeaks = self._readInExpectedPeaks() + dSpacingToTof = lambda d: 252.816 * 2 * (50 + detL2) * math.sin(detTwoTheta / 2.0) * d + expectedPeaks = self._readInExpectedPeaks() # Expected peak positions in TOF for the detector - expectedPeaksTof = map(dSpacingToTof, expectedPeaks) + expectedPeaksTof = map(dSpacingToTof, expectedPeaks) - return expectedPeaksTof + return expectedPeaksTof def _createFittedPeaksTable(self): - """ Creates a table where to put peak fitting results to + """ Creates a table where to put peak fitting results to """ - alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') - alg.execute() - table = alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') + alg.execute() + table = alg.getProperty('OutputWorkspace').value - table.addColumn('double', 'dSpacing') + table.addColumn('double', 'dSpacing') - for name in ['A0', 'A1', 'X0', 'A', 'B', 'S', 'I']: - table.addColumn('double', name) - table.addColumn('double', name + '_Err') + for name in ['A0', 'A1', 'X0', 'A', 'B', 'S', 'I']: + table.addColumn('double', name) + table.addColumn('double', name + '_Err') - table.addColumn('double', 'Chi') + table.addColumn('double', 'Chi') - return table + return table def _addParametersToMap(self, paramMap, paramTable): """ Reads parameters from the Fit Parameter table, and add their values and errors to the map @@ -209,4 +209,4 @@ def _addParametersToMap(self, paramMap, paramTable): paramMap[name + '_Err'] = row['Error'] -AlgorithmFactory.subscribe(EnginXFitPeaks) \ No newline at end of file +AlgorithmFactory.subscribe(EnginXFitPeaks) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py index 7086f19c4b11..79a3c6e19551 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py @@ -1,125 +1,126 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * class EnginXFocus(PythonAlgorithm): def category(self): - return "Diffraction\Engineering;PythonAlgorithms" + return "Diffraction\Engineering;PythonAlgorithms" def name(self): - return "EnginXFocus" + return "EnginXFocus" def summary(self): - return "Focuses a run." + return "Focuses a run." def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), + self.declareProperty(FileProperty("Filename", "", FileAction.Load),\ "Run to focus") - self.declareProperty(WorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(WorkspaceProperty("OutputWorkspace", "", Direction.Output),\ "A workspace with focussed data") - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional),\ "Calibrated detector positions. If not specified, default ones are used.") - self.declareProperty("Bank", 1, "Which bank to focus") + self.declareProperty("Bank", 1, "Which bank to focus") def PyExec(self): # Load the run file - ws = self._loadRun() + ws = self._loadRun() # Leave the data for the bank we are interested in only - ws = self._cropData(ws) + ws = self._cropData(ws) # Apply calibration - self._applyCalibration(ws) + self._applyCalibration(ws) # Convert to dSpacing - ws = self._convertToDSpacing(ws) + ws = self._convertToDSpacing(ws) # Sum the values - ws = self._sumSpectra(ws) + ws = self._sumSpectra(ws) # Convert back to time of flight - ws = self._convertToTOF(ws) + ws = self._convertToTOF(ws) # OpenGenie displays distributions instead of pure counts (this is done implicitly when # converting units), so I guess that's what users will expect - self._convertToDistr(ws) + self._convertToDistr(ws) - self.setProperty("OutputWorkspace", ws) + self.setProperty("OutputWorkspace", ws) def _loadRun(self): - """ Loads the specified run + """ Loads the specified run """ - alg = self.createChildAlgorithm('Load') - alg.setProperty('Filename', self.getProperty("Filename").value) - alg.execute() - return alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('Load') + alg.setProperty('Filename', self.getProperty("Filename").value) + alg.execute() + return alg.getProperty('OutputWorkspace').value def _applyCalibration(self, ws): - """ Refines the detector positions using the result of calibration (if one is specified) + """ Refines the detector positions using the result of calibration (if one is specified) """ - detPos = self.getProperty("DetectorPositions").value + detPos = self.getProperty("DetectorPositions").value - if detPos: - alg = self.createChildAlgorithm('ApplyCalibration') - alg.setProperty('Workspace', ws) - alg.setProperty('PositionTable', detPos) - alg.execute() + if detPos: + alg = self.createChildAlgorithm('ApplyCalibration') + alg.setProperty('Workspace', ws) + alg.setProperty('PositionTable', detPos) + alg.execute() def _convertToDSpacing(self, ws): - """ Converts workspace to dSpacing + """ Converts workspace to dSpacing """ - alg = self.createChildAlgorithm('ConvertUnits') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('Target', 'dSpacing') - alg.setProperty('AlignBins', True) - alg.execute() - return alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('ConvertUnits') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('Target', 'dSpacing') + alg.setProperty('AlignBins', True) + alg.execute() + return alg.getProperty('OutputWorkspace').value def _convertToTOF(self, ws): - """ Converts workspace to TOF + """ Converts workspace to TOF """ - alg = self.createChildAlgorithm('ConvertUnits') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('Target', 'TOF') - alg.execute() - return alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('ConvertUnits') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('Target', 'TOF') + alg.execute() + return alg.getProperty('OutputWorkspace').value def _convertToDistr(self, ws): - """ Convert workspace to distribution + """ Convert workspace to distribution """ - alg = self.createChildAlgorithm('ConvertToDistribution') - alg.setProperty('Workspace', ws) - alg.execute() + alg = self.createChildAlgorithm('ConvertToDistribution') + alg.setProperty('Workspace', ws) + alg.execute() def _cropData(self, ws): - """ Crops the workspace so that only data for the specified bank is left. + """ Crops the workspace so that only data for the specified bank is left. NB: This assumes spectra for a bank are consequent. """ - import EnginXUtils + import EnginXUtils - indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) + indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) # Leave only spectra between min and max - alg = self.createChildAlgorithm('CropWorkspace') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('StartWorkspaceIndex', min(indices)) - alg.setProperty('EndWorkspaceIndex', max(indices)) - alg.execute() + alg = self.createChildAlgorithm('CropWorkspace') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('StartWorkspaceIndex', min(indices)) + alg.setProperty('EndWorkspaceIndex', max(indices)) + alg.execute() - return alg.getProperty('OutputWorkspace').value + return alg.getProperty('OutputWorkspace').value def _sumSpectra(self, ws): - """ Calls the SumSpectra algorithm + """ Calls the SumSpectra algorithm """ - alg = self.createChildAlgorithm('SumSpectra') - alg.setProperty('InputWorkspace', ws) - alg.execute() - return alg.getProperty('OutputWorkspace').value + alg = self.createChildAlgorithm('SumSpectra') + alg.setProperty('InputWorkspace', ws) + alg.execute() + return alg.getProperty('OutputWorkspace').value -AlgorithmFactory.subscribe(EnginXFocus) \ No newline at end of file +AlgorithmFactory.subscribe(EnginXFocus) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py index 774411536175..952a3f40991c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py @@ -1,6 +1,4 @@ -# from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory, FileProperty, FileAction, MatrixWorkspaceProperty, WorkspaceProperty, PropertyMode -# from mantid.kernel import Direction, StringListValidator - +#pylint: disable=no-init import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * @@ -10,6 +8,26 @@ class ExaminePowderDiffProfile(PythonAlgorithm): """ Create the input TableWorkspaces for LeBail Fitting """ + + loaddata = None + dataws = None + datawsname = None + datafilename = None + profiletype = None + loadinfofile = None + latticesize = None + irffilename = None + inputparamws = None + process_bkgd = None + usrbkgdpoints = None + bkgdwsname = None + bkgdtablews = None + backgroundtype = None + startx = None + endx = None + outwsname = None + inputbraggws = None + def category(self): """ """ @@ -27,9 +45,9 @@ def PyInit(self): """ Declare properties """ # Data file - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of data workspace containing the diffraction pattern in .prf file. ") - self.declareProperty(FileProperty("DataFilename","", FileAction.OptionalLoad, ['.dat']), + self.declareProperty(FileProperty("DataFilename","", FileAction.OptionalLoad, ['.dat']),\ "Name of input data file.") self.declareProperty("LoadData", False, "Option to load data other than reading from an existing data workspace.") @@ -37,34 +55,36 @@ def PyInit(self): self.declareProperty("EndX", -0.0, "Maximum x value (TOF) to do the pattern calculation.") # Peak profile type - profiletypes = ["Back-to-back exponential convoluted with PseudoVoigt", "Thermal Neutron Back-to-back exponential convoluted with PseudoVoigt"] - self.declareProperty("ProfileType", "Back-to-back exponential convoluted with PseudoVoigt", StringListValidator(profiletypes), "Type of peak profile.") + profiletypes = ["Back-to-back exponential convoluted with PseudoVoigt", \ + "Thermal Neutron Back-to-back exponential convoluted with PseudoVoigt"] + self.declareProperty("ProfileType", "Back-to-back exponential convoluted with PseudoVoigt",\ + StringListValidator(profiletypes), "Type of peak profile.") # Table workspaces - self.declareProperty(ITableWorkspaceProperty("ProfileWorkspace", "", Direction.InOut), + self.declareProperty(ITableWorkspaceProperty("ProfileWorkspace", "", Direction.InOut),\ "Name of table workspace containing peak parameters as input.") - self.declareProperty(ITableWorkspaceProperty("BraggPeakWorkspace", "", Direction.InOut), + self.declareProperty(ITableWorkspaceProperty("BraggPeakWorkspace", "", Direction.InOut),\ "Name of table workspace containing reflections (bragg peaks) in form of Miller index.") - self.declareProperty(FileProperty("ProfileFilename","", FileAction.OptionalLoad, ['.irf']), + self.declareProperty(FileProperty("ProfileFilename","", FileAction.OptionalLoad, ['.irf']),\ "Name of input data file.") self.declareProperty("Lattice", -0.0, "Lattice size of the cubic unit cell.") self.declareProperty("GenerateInformationWS", False, "Optional to genearte profile table workspace and Bragg peak table. ") # Background - self.declareProperty(ITableWorkspaceProperty("BackgroundParameterWorkspace", "", Direction.InOut), + self.declareProperty(ITableWorkspaceProperty("BackgroundParameterWorkspace", "", Direction.InOut),\ "Name of table workspace containing background parameters.") self.declareProperty("ProcessBackground", False, "Option to process background from input data file.") backgroundtypes = ["Polynomial", "Chebyshev", "FullprofPolynomial"] self.declareProperty("BackgroundType", "Polynomial", StringListValidator(backgroundtypes), "Type of background.") arrvalidator = FloatArrayBoundedValidator() arrvalidator.setLower(0.) - self.declareProperty(FloatArrayProperty("BackgroundPoints", values=[], validator=arrvalidator, direction=Direction.Input), + self.declareProperty(FloatArrayProperty("BackgroundPoints", values=[], validator=arrvalidator, direction=Direction.Input),\ "User specified X/TOF values of the data points to calculate background.") - self.declareProperty(MatrixWorkspaceProperty("BackgroundWorkspace", "", Direction.Output, PropertyMode.Optional), + self.declareProperty(MatrixWorkspaceProperty("BackgroundWorkspace", "", Direction.Output, PropertyMode.Optional),\ "Name of data workspace containing the background data. ") # Output - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output),\ "Name of data workspace containing the diffraction pattern in .prf file. ") @@ -134,71 +154,71 @@ def mainExec(self): # Load data optionally if self.loaddata is True: # Load data file - api.LoadAscii( - Filename = self.datafilename, - OutputWorkspace = self.datawsname, - Unit = 'TOF' + api.LoadAscii(\ + Filename = self.datafilename,\ + OutputWorkspace = self.datawsname,\ + Unit = 'TOF'\ ) # Load .irf file and .hkl file optionally if self.loadinfofile is True: - if dir(self).count('latticesize') == 0 or self.latticesize is None: + if dir(self).count('latticesize') == 0 or self.latticesize is None: raise NotImplementedError("Lattice size is not defined. Unable to use option 'LoadInfo'") - api.CreateLeBailFitInput( - FullprofParameterFile = self.irffilename, - MaxHKL = [13, 13, 13], - LatticeConstant = float(self.latticesize), - Bank = self.bankid, - GenerateBraggReflections = True, - InstrumentParameterWorkspace = str(self.inputparamws), - BraggPeakParameterWorkspace = str(self.inputbraggws) + api.CreateLeBailFitInput(\ + FullprofParameterFile = self.irffilename,\ + MaxHKL = [13, 13, 13],\ + LatticeConstant = float(self.latticesize),\ + Bank = self.bankid,\ + GenerateBraggReflections = True,\ + InstrumentParameterWorkspace = str(self.inputparamws),\ + BraggPeakParameterWorkspace = str(self.inputbraggws)\ ) # Process background optionally if self.process_bkgd is True: # [Background] # Remove peaks and get pure background (hopefully) - api.ProcessBackground( - Options = 'SelectBackgroundPoints', - InputWorkspace = self.dataws, - OutputWorkspace = self.bkgdwsname, - LowerBound = self.startx, - UpperBound = self.endx, - BackgroundType = self.backgroundtype, - BackgroundPoints= self.usrbkgdpoints, + api.ProcessBackground(\ + Options = 'SelectBackgroundPoints',\ + InputWorkspace = self.dataws,\ + OutputWorkspace = self.bkgdwsname,\ + LowerBound = self.startx,\ + UpperBound = self.endx,\ + BackgroundType = self.backgroundtype,\ + BackgroundPoints= self.usrbkgdpoints,\ NoiseTolerance = '0.10000000000000001') # Fit background points functionstr = "name=%s,n=%d" % (self.backgroundtype, self.backgroundorder) for iborder in xrange(self.backgroundorder+1): functionstr = "%s,A%d=%.5f" % (functionstr, iborder, 0.0) - api.Fit( - Function = functionstr, - InputWorkspace = self.bkgdwsname, - Output = self.bkgdwsname, - MaxIterations = '1000', - Minimizer = 'Levenberg-MarquardtMD', - CreateOutput = '1', - StartX = self.startx, + api.Fit(\ + Function = functionstr,\ + InputWorkspace = self.bkgdwsname,\ + Output = self.bkgdwsname,\ + MaxIterations = '1000',\ + Minimizer = 'Levenberg-MarquardtMD',\ + CreateOutput = '1',\ + StartX = self.startx,\ EndX = self.endx) # [Le Bail calculation] self.log().debug("Fit range: %f , %f, Outputworkspace = %s" % (self.startx, self.endx, self.outwsname)) - api.LeBailFit( - Function = 'Calculation', - InputWorkspace = self.dataws, - OutputWorkspace = self.outwsname, - InputParameterWorkspace = self.inputparamws, - OutputParameterWorkspace= str(self.inputparamws), - InputHKLWorkspace = self.inputbraggws, - OutputPeaksWorkspace = str(self.inputbraggws), - FitRegion = '%f, %f' % (self.startx, self.endx), - BackgroundType = self.backgroundtype, - UseInputPeakHeights = False, - PeakRadius = '7', - BackgroundParametersWorkspace = self.bkgdtablews, - PeakType = self.profiletype, + api.LeBailFit(\ + Function = 'Calculation',\ + InputWorkspace = self.dataws,\ + OutputWorkspace = self.outwsname,\ + InputParameterWorkspace = self.inputparamws,\ + OutputParameterWorkspace= str(self.inputparamws),\ + InputHKLWorkspace = self.inputbraggws,\ + OutputPeaksWorkspace = str(self.inputbraggws),\ + FitRegion = '%f, %f' % (self.startx, self.endx),\ + BackgroundType = self.backgroundtype,\ + UseInputPeakHeights = False,\ + PeakRadius = '7',\ + BackgroundParametersWorkspace = self.bkgdtablews,\ + PeakType = self.profiletype,\ ) return diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py index 76cc78dc8a9d..93c5cd44c1ff 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py index 4b7d54498f63..79d167d4e04e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py @@ -1,16 +1,32 @@ -import mantid.simpleapi as api +#pylint: disable=no-init,invalid-name import mantid from mantid.api import * from mantid.kernel import * - -import os import datetime +import time +import os class ExportExperimentLog(PythonAlgorithm): """ Algorithm to export experiment log """ + _wksp = None + _sampleLogNames = None + _sampleLogOperations = None + _fileformat = None + _valuesep = None + _logfilename = None + _reorderOld = None + _timezone = None + _titleToOrder = None + _orderRecord = None + titleToOrder = None + _removeDupRecord = None + _ovrdTitleValueDict = None + _headerTitles = None + _filemode = None + def summmary(self): return "Exports experimental log." @@ -21,11 +37,11 @@ def PyInit(self): wsprop = MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input) self.declareProperty(wsprop, "Input workspace containing the sample log information. ") - self.declareProperty(FileProperty("OutputFilename","", FileAction.Save, ['.txt, .csv']), + self.declareProperty(FileProperty("OutputFilename","", FileAction.Save, ['.txt, .csv']),\ "Output file of the experiment log.") filemodes = ["append", "fastappend", "new"] - self.declareProperty("FileMode", "append", mantid.kernel.StringListValidator(filemodes), + self.declareProperty("FileMode", "append", mantid.kernel.StringListValidator(filemodes),\ "Optional to create a new file or append to an existing file.") lognameprop = StringArrayProperty("SampleLogNames", values=[], direction=Direction.Input) @@ -42,18 +58,17 @@ def PyInit(self): "With this option, the posfix of the output file is .csv automatically. " self.declareProperty("FileFormat", "tab", mantid.kernel.StringListValidator(fileformates), des) - self.declareProperty("OrderByTitle", "", "Log file will be ordered by the value of this title from low to high.") + self.declareProperty("OrderByTitle", "", "Log file will be ordered by the value of this title from low to high.") self.declareProperty("RemoveDuplicateRecord", False, "Coupled with OrderByTitle, duplicated record will be removed.") overrideprop = StringArrayProperty("OverrideLogValue", values=[], direction=Direction.Input) self.declareProperty(overrideprop, "List of paired strings as log title and value to override values from workspace.") # Time zone - timezones = ["UTC", "America/New_York", "Asia/Shanghai", "Australia/Sydney", "Europe/London", "GMT+0", + timezones = ["UTC", "America/New_York", "Asia/Shanghai", "Australia/Sydney", "Europe/London", "GMT+0",\ "Europe/Paris", "Europe/Copenhagen"] self.declareProperty("TimeZone", "America/New_York", StringListValidator(timezones)) - return @@ -97,8 +112,6 @@ def PyExec(self): def _processInputs(self): """ Process input properties """ - import os - import os.path self._wksp = self.getProperty("InputWorkspace").value @@ -160,7 +173,7 @@ def _processInputs(self): self._orderRecord = False self._titleToOrder = None if self._filemode != "new": - ordertitle = self.getProperty("OrderByTitle").value + ordertitle = self.getProperty("OrderByTitle").value if ordertitle in self._headerTitles: self._orderRecord = True self._removeDupRecord = self.getProperty("RemoveDuplicateRecord").value @@ -237,7 +250,7 @@ def _examineLogFile(self): if len(titles) != len(self._headerTitles): if len(self._headerTitles) == 0: self._headerTitles = titles[:] - else: + else: same = False for ititle in xrange(len(titles)): title1 = titles[ititle] @@ -254,9 +267,6 @@ def _examineLogFile(self): def _startNewFile(self): """ Start a new file is user wants and save the older one to a different name """ - import datetime - import time - import os # Rename old file and reset the file mode @@ -290,10 +300,10 @@ def _appendExpLog(self, logvaluedict): skip = True else: skip = False - + headertitle = None for il in xrange(len(self._sampleLogNames)): - if skip is False: + if skip is False: headertitle = self._headerTitles[il] if headertitle is not None and headertitle in self._ovrdTitleValueDict.keys(): # overriden @@ -321,7 +331,7 @@ def _appendExpLog(self, logvaluedict): return def _orderRecordFile(self): - """ Check and order (if necessary) record file + """ Check and order (if necessary) record file by value of specified log by title """ self.log().debug("Order Record File!") @@ -347,12 +357,12 @@ def _orderRecordFile(self): titlelines.append(line) else: # value line - try: + try: keyvalue = line.split(self._valuesep)[ilog].strip() except IndexError: self.log().error("Order record failed.") return - if linedict.has_key(keyvalue) is False: + if linedict.has_key(keyvalue) is False: linedict[keyvalue] = [] linedict[keyvalue].append(line) totnumlines += 1 @@ -363,7 +373,7 @@ def _orderRecordFile(self): if linedict.keys() != sorted(linedict.keys()): # Re-write file wbuf = "" - + # title line for line in titlelines: wbuf += line @@ -385,8 +395,8 @@ def _orderRecordFile(self): numlines += 1 else: - # Consider all! - for line in linedict[ivalue]: + # Consider all! + for line in linedict[ivalue]: wbuf += line # Add extra \n in case reordered if numlines != totnumlines-1 and wbuf[-1] != '\n': diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py index 1c2aab1eeb97..7b606e5828da 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py @@ -1,13 +1,26 @@ -import mantid.simpleapi as api +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * import os -import datetime class ExportSampleLogsToCSVFile(PythonAlgorithm): """ Python algorithm to export sample logs to spread sheet file for VULCAN """ + + _wksp = None + _outputfilename = None + _sampleloglist = None + _headerconten = None + _writeheader = None + _headercontent = None + _timezone = None + _timeTolerance = None + _maxtimestamp = None + _maxtime = None + _starttime = None + _localtimediff = None + def category(self): """ Category """ @@ -42,7 +55,7 @@ def PyInit(self): self.declareProperty("Header", "", "String in the header file.") # Time zone - timezones = ["UTC", "America/New_York", "Asia/Shanghai", "Australia/Sydney", "Europe/London", "GMT+0", + timezones = ["UTC", "America/New_York", "Asia/Shanghai", "Australia/Sydney", "Europe/London", "GMT+0",\ "Europe/Paris", "Europe/Copenhagen"] self.declareProperty("TimeZone", "America/New_York", StringListValidator(timezones)) @@ -439,7 +452,7 @@ def getLocalTimeShiftInSecond(utctime, localtimezone, logger = None): if logger: logger.information("Input UTC time = %s" % (str(utctime))) - + # Return early if local time zone is UTC if localtimezone == "UTC": return 0 @@ -452,7 +465,7 @@ def getLocalTimeShiftInSecond(utctime, localtimezone, logger = None): if logger: logger.information("About to convert time string: %s" % t1str) try: - if t1str.count("T") == 1: + if t1str.count("T") == 1: utc = datetime.strptime(t1str, '%Y-%m-%dT%H:%M:%S') else: utc = datetime.strptime(t1str, '%Y-%m-%d %H:%M:%S') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py index df8108481e11..38684e50853b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py index 5e61abb53444..45f0fd876835 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * import numpy as np @@ -10,93 +11,93 @@ class FindReflectometryLines(PythonAlgorithm): # Determine if a given signal identifies a peak or not. def __is_peak(self, before, current, after): # A peak is defined to be any signal that is preceeded by a lower signal value and followed by a lower signal value. - if before < current and current > after: - return True - return False + if before < current and current > after: + return True + return False # Find a list of spectra numbers corresponding to peaks in the data. def __find_peak_spectrum_numbers(self, y_data, ws): - peak_index_list = [] - for index, current in enumerate(y_data.flat): - if (index > 0) and (index < (y_data.size - 1)): - before = y_data[index-1] - after = y_data[index+1] - if self.__is_peak(before, current, after): - spec_number = ws.getSpectrum(index).getSpectrumNo() - peak_index_list.append(spec_number) - return peak_index_list + peak_index_list = [] + for index, current in enumerate(y_data.flat): + if (index > 0) and (index < (y_data.size - 1)): + before = y_data[index-1] + after = y_data[index+1] + if self.__is_peak(before, current, after): + spec_number = ws.getSpectrum(index).getSpectrumNo() + peak_index_list.append(spec_number) + return peak_index_list # Zero-out any data considered to be background. def __remove_background(self, y_data): - y_average = np.sum(y_data) / y_data.size - y_max = np.max(y_data) + y_average = np.sum(y_data) / y_data.size + y_max = np.max(y_data) #The thresholding criteria is hard-coded to be above the average as follows. - threshold = (y_max - y_average)/10 + y_average - y_data[y_data < threshold] = 0 - return y_data + threshold = (y_max - y_average)/10 + y_average + y_data[y_data < threshold] = 0 + return y_data def category(self): - return "PythonAlgorithms;Reflectometry" + return "PythonAlgorithms;Reflectometry" def name(self): - return "FindReflectometryLines" + return "FindReflectometryLines" def summary(self): - return "Finds spectrum numbers corresponding to reflected and transmission lines in a line detector Reflectometry dataset." + return "Finds spectrum numbers corresponding to reflected and transmission lines in a line detector Reflectometry dataset." def PyInit(self): - workspace_validator = CompositeValidator() - workspace_validator.add(WorkspaceUnitValidator("Wavelength")) - workspace_validator.add(SpectraAxisValidator()) + workspace_validator = CompositeValidator() + workspace_validator.add(WorkspaceUnitValidator("Wavelength")) + workspace_validator.add(SpectraAxisValidator()) - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, workspace_validator), "Input Reflectometry Workspace") - self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Output Spectrum Numbers") - self.declareProperty(name="StartWavelength", defaultValue=0.0, validator=FloatBoundedValidator(lower=0.0), doc="Start wavelength to use for x-axis cropping") - self.declareProperty(name="KeepIntermediateWorkspaces", defaultValue=False, doc="Keeps cropped and integrated workspaces in memory after usage.") + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, workspace_validator), "Input Reflectometry Workspace") + self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Output Spectrum Numbers") + self.declareProperty(name="StartWavelength", defaultValue=0.0, validator=FloatBoundedValidator(lower=0.0), doc="Start wavelength to use for x-axis cropping") + self.declareProperty(name="KeepIntermediateWorkspaces", defaultValue=False, doc="Keeps cropped and integrated workspaces in memory after usage.") def PyExec(self): - from mantid.simpleapi import CropWorkspace, Integration, DeleteWorkspace + from mantid.simpleapi import CropWorkspace, Integration, DeleteWorkspace - in_ws = self.getPropertyValue("InputWorkspace") - min_wavelength = self.getPropertyValue("StartWavelength") - keep_workspaces = self.getPropertyValue("KeepIntermediateWorkspaces") + in_ws = self.getPropertyValue("InputWorkspace") + min_wavelength = self.getPropertyValue("StartWavelength") + keep_workspaces = self.getPropertyValue("KeepIntermediateWorkspaces") # Crop off lower wavelengths where the signal is also lower. - cropped_ws = CropWorkspace(InputWorkspace=in_ws,XMin=float(min_wavelength)) + cropped_ws = CropWorkspace(InputWorkspace=in_ws,XMin=float(min_wavelength)) # Integrate over the higher wavelengths after cropping. - summed_ws = Integration(InputWorkspace=cropped_ws) + summed_ws = Integration(InputWorkspace=cropped_ws) # Loop through each histogram, and fetch out each intensity value from the single bin to generate a list of all values. - n_histograms = summed_ws.getNumberHistograms() - y_data = np.empty([n_histograms]) - for i in range(0, n_histograms): - intensity = summed_ws.readY(i)[0] - y_data[i] = intensity + n_histograms = summed_ws.getNumberHistograms() + y_data = np.empty([n_histograms]) + for i in range(0, n_histograms): + intensity = summed_ws.readY(i)[0] + y_data[i] = intensity #Remove the background - y_data = self.__remove_background(y_data) + y_data = self.__remove_background(y_data) #Find the peaks - peak_index_list = self.__find_peak_spectrum_numbers(y_data, summed_ws) + peak_index_list = self.__find_peak_spectrum_numbers(y_data, summed_ws) #Reverse the order so that it goes from high spec number to low spec number - peak_index_list.reverse() - n_peaks_found = len(peak_index_list) - - output_ws = WorkspaceFactory.createTable("TableWorkspace") - output_ws.addColumn("int", "Reflected Spectrum Number") - - if n_peaks_found > 2: - raise PeakFindingException("Found more than two peaks.") - elif n_peaks_found == 0: - raise PeakFindingException("No peaks found") - elif n_peaks_found == 1: - output_ws.addRow(peak_index_list) - elif n_peaks_found == 2: - output_ws.addColumn("int", "Transmission Spectrum Number") - output_ws.addRow(peak_index_list) - - if int(keep_workspaces) == 0: - DeleteWorkspace(Workspace=cropped_ws) - DeleteWorkspace(Workspace=summed_ws) - - self.setProperty("OutputWorkspace", output_ws) + peak_index_list.reverse() + n_peaks_found = len(peak_index_list) + + output_ws = WorkspaceFactory.createTable("TableWorkspace") + output_ws.addColumn("int", "Reflected Spectrum Number") + + if n_peaks_found > 2: + raise PeakFindingException("Found more than two peaks.") + elif n_peaks_found == 0: + raise PeakFindingException("No peaks found") + elif n_peaks_found == 1: + output_ws.addRow(peak_index_list) + elif n_peaks_found == 2: + output_ws.addColumn("int", "Transmission Spectrum Number") + output_ws.addRow(peak_index_list) + + if int(keep_workspaces) == 0: + DeleteWorkspace(Workspace=cropped_ws) + DeleteWorkspace(Workspace=summed_ws) + + self.setProperty("OutputWorkspace", output_ws) AlgorithmFactory.subscribe(FindReflectometryLines()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py index fd44cde703f6..c01f61cbfe01 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid import mantid.api import mantid.simpleapi @@ -54,7 +55,7 @@ def PyExec(self): __w = mantid.simpleapi.LoadEmptyInstrument(Filename=IDF) i=0 - while(__w.getDetector(i).isMonitor()): + while __w.getDetector(i).isMonitor(): i += 1 #i is the index of the first true detector #now, crop the workspace of the monitors diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py index 1d8d55dab696..e2eb1fa40dab 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import PythonAlgorithm, AlgorithmFactory,WorkspaceProperty from mantid.kernel import Direction,IntBoundedValidator,FloatBoundedValidator import mantid.simpleapi diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py index 400b0fac80f6..582beaf012a8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiT0atSNS.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid import numpy diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py index f708e716043e..1b9bbcfbc9f4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py index 333e17ff3cba..0c3456f81e20 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py @@ -1,13 +1,18 @@ -from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory, FileProperty, FileAction, MatrixWorkspaceProperty, WorkspaceProperty -from mantid.kernel import Direction, StringListValidator +#pylint: disable=no-init,invalid-name +from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory,\ + FileProperty, FileAction, MatrixWorkspaceProperty +from mantid.kernel import Direction -import mantid.simpleapi as api _OUTPUTLEVEL = "NOOUTPUT" class LoadFullprofFile(PythonAlgorithm): """ Create the input TableWorkspaces for LeBail Fitting """ + + _tableWS = None + _dataWS = None + def category(self): """ """ @@ -25,20 +30,20 @@ def summary(self): def PyInit(self): """ Declare properties - """ - self.declareProperty(FileProperty("Filename","", FileAction.Load, ['.hkl', '.prf', '.dat']), + """ + self.declareProperty(FileProperty("Filename","", FileAction.Load, ['.hkl', '.prf', '.dat']),\ "Name of [http://www.ill.eu/sites/fullprof/ Fullprof] .hkl or .prf file.") #self.declareProperty("Bank", 1, "Bank ID for output if there are more than one bank in .irf file.") - self.declareProperty(ITableWorkspaceProperty("PeakParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("PeakParameterWorkspace", "", Direction.Output),\ "Name of table workspace containing peak parameters from .hkl file.") - - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), + + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output),\ "Name of data workspace containing the diffraction pattern in .prf file. ") return - + def PyExec(self): """ Main Execution Body """ @@ -46,12 +51,12 @@ def PyExec(self): fpfilename = self.getPropertyValue("Filename") # 2. Import - if fpfilename.lower().endswith(".hkl") is True: + if fpfilename.lower().endswith(".hkl") is True: # (.hkl) file self._tableWS = self._loadFPHKLFile(fpfilename) self._dataWS = self._makeEmptyDataWorkspace() elif fpfilename.lower().endswith(".prf") is True: - # (.prf) file + # (.prf) file self._tableWS, self._dataWS= self._loadFullprofPrfFile(fpfilename) elif fpfilename.lower().endswith(".dat") is True: # (.dat) file: Fullprof data file @@ -131,13 +136,13 @@ def _importFullprofHKLFile(self, hklfilename): dkey = (h, k, l) if hkldict.has_key(dkey): - if _OUTPUTLEVEL == "INFORMATION": - self.warning("Warning! Duplicate HKL %d, %d, %d" (h, k, l)) + if _OUTPUTLEVEL == "INFORMATION": + self.warning("Warning! Duplicate HKL %d, %d, %d" % (h, k, l)) continue if fwhm < 1.0E-5: # Peak width is too small/annihilated peak - if _OUTPUTLEVEL == "INFORMATION": + if _OUTPUTLEVEL == "INFORMATION": self.log.information("Peak (%d, %d, %d) has an unreasonable small FWHM. Peak does not exist. " % (h, k, l)) continue @@ -156,20 +161,20 @@ def _importFullprofHKLFile(self, hklfilename): return hkldict def _createReflectionWorkspace(self, hkldict): - """ Create TableWorkspace containing reflections and etc. + """ Create TableWorkspace containing reflections and etc. """ # 1. Set up columns tablews = WorkspaceFactory.createTable() - - tablews.addColumn("int", "H"); - tablews.addColumn("int", "K"); - tablews.addColumn("int", "L"); - tablews.addColumn("double", "Alpha"); - tablews.addColumn("double", "Beta"); - tablews.addColumn("double", "Sigma2"); - tablews.addColumn("double", "Gamma"); - tablews.addColumn("double", "FWHM"); - tablews.addColumn("double", "PeakHeight"); + + tablews.addColumn("int", "H") + tablews.addColumn("int", "K") + tablews.addColumn("int", "L") + tablews.addColumn("double", "Alpha") + tablews.addColumn("double", "Beta") + tablews.addColumn("double", "Sigma2") + tablews.addColumn("double", "Gamma") + tablews.addColumn("double", "FWHM") + tablews.addColumn("double", "PeakHeight") # 2. Add rows for hkl in sorted(hkldict.keys()): @@ -250,7 +255,7 @@ def _parseFullprofPrfFile(self, filename): # spacegroup = terms[1].strip() # infodict["SpaceGroup"] = spacegroup - # Find data line header + # Find data line header firstline = -1 for i in xrange(1, len(lines)): if lines[i].count("Yobs-Ycal") > 0: @@ -266,14 +271,14 @@ def _parseFullprofPrfFile(self, filename): headerterms = dataheader.split() dataperline = 5 # TOF., ... h k l ... - reflectionperline = len(headerterms)-5+3 + reflectionperline = len(headerterms)-5+3 # Parse data count = 0 - for i in xrange(firstline, len(lines)): - line = lines[i].strip() - if len(line) == 0: # empty line + for i in xrange(firstline, len(lines)): + line = lines[i].strip() + if len(line) == 0: # empty line continue if line.count(")") == 0 and line.count("(") == 0: @@ -312,10 +317,10 @@ def _parseFullprofPrfFile(self, filename): ycal = float(terms[2]) ydif = float(terms[3]) ybak = float(terms[4]) - + dataset.append([x, yobs, ycal, ydif, ybak]) count += 1 - + raise NotImplementedError("Need a sample line of this use case.") hklstr = line.split(")")[1].split(")")[0].strip() infodict[hklstr] = tofh @@ -357,7 +362,7 @@ def _loadFullprofDataFile(self, datafilename): # header title += line + ", " else: - # line information + # line information terms = line.split() if terms[0] != 'BANK': raise NotImplementedError("First word must be 'BANK', but not %s" % (terms[0])) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py index eaaf9bdbb5cc..0184eefad649 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import time import datetime import numbers @@ -36,7 +37,7 @@ def getGeneralLogValue(self,ws,name,begin): # get log value # average time series over run # for beamlog, etc return flag=true and value to push into previous run - if(name=="comment"): + if name=="comment": return (ws.getComment(),False,0) try: @@ -48,7 +49,7 @@ def getGeneralLogValue(self,ws,name,begin): raise ValueError(message) try: times2=[] - if (hasattr(v,"unfiltered")): + if hasattr(v,"unfiltered"): v=v.unfiltered() for tt in v.times: times2.append((datetime.datetime(*(time.strptime(str(tt),"%Y-%m-%dT%H:%M:%S")[0:6]))-begin).total_seconds()) @@ -56,11 +57,11 @@ def getGeneralLogValue(self,ws,name,begin): #print "probably not a time series" pass - if(name[0:8]=="Beamlog_" and (name.find("Counts")>0 or name.find("Frames")>0)): + if name[0:8]=="Beamlog_" and (name.find("Counts")>0 or name.find("Frames")>0): i=bisect.bisect_right(times2,2) # allowance for "slow" clearing of DAE #print "returning max beam log, list cut 0:",i,":",len(times2) return (numpy.amax(v.value[i:]),True,numpy.amax(v.value[:i])) - if(v.__class__.__name__ =="TimeSeriesProperty_dbl" or v.__class__.__name__ =="FloatTimeSeriesProperty"): + if v.__class__.__name__ =="TimeSeriesProperty_dbl" or v.__class__.__name__ =="FloatTimeSeriesProperty": i=bisect.bisect_left(times2,0) return (numpy.average(v.value[i:]),False,0) return (v.value,False,0) @@ -79,13 +80,13 @@ def PyExec(self): while file9[j9-1].isdigit(): j9=j9-1 lastnum=int(file9[j9:i9]) - if(file1[:j9] != file9[:j9]): + if file1[:j9] != file9[:j9]: raise Exception("Files from different directories or instruments") - if(file1[i1:] != file9[i9:]): + if file1[i1:] != file9[i9:]: raise Exception("Files of different types") - if(i1-j1 != i9-j9): + if i1-j1 != i9-j9: raise Exception("File numbering error") - if(lastnum < firstnum): + if lastnum < firstnum: raise Exception("Run numbers must increase") # table. Rows=runs, columns=logs (col 0 = run number) @@ -103,14 +104,14 @@ def PyExec(self): continue #check if the return type is atuple - if (type(returnTuple) == tuple): + if type(returnTuple) == tuple: loadedWs=returnTuple[0] else: loadedWs = returnTuple #check if the ws is a group ws = loadedWs - if (ws.id() == 'WorkspaceGroup'): + if ws.id() == 'WorkspaceGroup': ws=ws[0] begin=datetime.datetime(*(time.strptime(ws.getRun().getProperty("run_start").value,"%Y-%m-%dT%H:%M:%S")[0:6])) # start of day @@ -123,13 +124,13 @@ def PyExec(self): DeleteWorkspace(loadedWs) raise vallist.append(cv) - if(ff==firstnum): - if(isinstance(cv, numbers.Number)): + if ff==firstnum: + if isinstance(cv, numbers.Number): ows.addColumn("double",cc) else: ows.addColumn("str",cc) - if(leftover and ff>firstnum): - if(lval>ows.cell(cc,ff-firstnum-1)): + if leftover and ff>firstnum: + if lval>ows.cell(cc,ff-firstnum-1): ows.setCell(cc,ff-firstnum-1,lval) ows.addRow(vallist) DeleteWorkspace(loadedWs) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py index 76558b362f05..a74d3878d9eb 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py @@ -1,9 +1,14 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.simpleapi import * from mantid.kernel import * import os class LoadMultipleGSS(PythonAlgorithm): + + __exts = None + __loader = None + def category(self): return "DataHandling;PythonAlgorithms" @@ -24,7 +29,7 @@ def __load(self, directory, prefix): self.log().information("Trying to load '%s'" % filename) self.__loader(Filename=filename, OutputWorkspace=prefix, UseBankIDasSpectrumNumber=True) return - except Exception, e: + except Exception, _: pass raise RuntimeError("Failed to load run %s" % prefix) @@ -46,7 +51,6 @@ def PyExec(self): self.__loader = LoadGSS # load things and conjoin them - first = True for run in runs: wksp = "%s_%d" % (prefix,run) self.__load(directory, wksp) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQ.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQ.py index dcb74ad3bd2b..2aeedd4bc6f2 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQ.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQ.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init #-------------------------------------------------------------- # Algorithm which loads a SINQ file. # This algorithm calculates the filename from instrument @@ -7,7 +8,7 @@ # Mark Koennecke, November 2012 #-------------------------------------------------------------- from mantid.api import AlgorithmFactory -from mantid.api import PythonAlgorithm, WorkspaceFactory, FileProperty, FileAction, WorkspaceProperty +from mantid.api import PythonAlgorithm, WorkspaceProperty from mantid.kernel import Direction, StringListValidator, ConfigServiceImpl import mantid.simpleapi import datetime diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py index 734f5e6d7489..99f276747866 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name #-------------------------------------------------------------- # Algorithm which loads a SINQ file. It matches the instrument # and the right dictionary file and then goes away and calls @@ -6,8 +7,8 @@ # Mark Koennecke, November 2012 #-------------------------------------------------------------- from mantid.api import AlgorithmFactory -from mantid.api import PythonAlgorithm, WorkspaceFactory, FileProperty, FileAction, WorkspaceProperty, FrameworkManager -from mantid.kernel import Direction, StringListValidator, ConfigServiceImpl +from mantid.api import PythonAlgorithm, FileProperty, FileAction, WorkspaceProperty +from mantid.kernel import Direction, StringListValidator import mantid.simpleapi from mantid import config import os.path @@ -50,7 +51,7 @@ def PyExec(self): "RITA-2":"rita.dic", "SANS":"sans.dic", "SANS2":"sans.dic", - "TRICS":"trics.dic" + "TRICS":"trics.dic"\ } dictsearch = os.path.join(config['instrumentDefinition.directory'],"nexusdictionaries") dicname = os.path.join(dictsearch, diclookup[inst]) @@ -59,7 +60,7 @@ def PyExec(self): if inst == "POLDI": if ws.getNumberHistograms() == 800: - ws.maskDetectors(SpectraList=range(0,800)[::2]) + ws.maskDetectors(SpectraList=range(0,800)[::2]) config.appendDataSearchDir(config['groupingFiles.directory']) grp_file = "POLDI_Grouping_800to400.xml" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py index 0d23197cc062..f93c745f456a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import (CropWorkspace, LoadEmptyInstrument, LoadRaw, Plus, @@ -34,7 +35,7 @@ class LoadVesuvio(PythonAlgorithm): def summary(self): - return "Loads raw data produced by the Vesuvio instrument at ISIS." + return "Loads raw data produced by the Vesuvio instrument at ISIS." def PyInit(self): self.declareProperty(RUN_PROP, "", StringMandatoryValidator(), @@ -53,12 +54,13 @@ def PyInit(self): self.declareProperty(FileProperty(INST_PAR_PROP,"",action=FileAction.OptionalLoad, extensions=["dat"]), doc="An optional IP file. If provided the values are used to correct " - "the default instrument values and attach the t0 values to each detector") + "the default instrument values and attach the t0 values to each " + "detector") self.declareProperty(SUM_PROP, False, - doc="If true then the final output is a single spectrum containing the sum " - "of all of the requested spectra. All detector angles/parameters are " - "averaged over the individual inputs") + doc="If true then the final output is a single spectrum containing " + "the sum of all of the requested spectra. All detector angles/" + "parameters are averaged over the individual inputs") self.declareProperty(WorkspaceProperty(WKSP_PROP, "", Direction.Output), doc="The name of the output workspace.") @@ -114,13 +116,13 @@ def _exec_single_foil_state_mode(self): """ runs = self._get_runs() if len(runs) > 1: - raise RuntimeError("Single soil state mode does not currently support summing multiple files") + raise RuntimeError("Single soil state mode does not currently support summing " + "multiple files") isis = config.getFacility("ISIS") inst_prefix = isis.instrument("VESUVIO").shortName() try: - run = int(runs[0]) run_str = inst_prefix + runs[0] except ValueError: run_str = runs[0] @@ -138,7 +140,7 @@ def _exec_single_foil_state_mode(self): foil_map = SpectraToFoilPeriodMap(self._nperiods) for ws_index, spectrum_no in enumerate(all_spectra): self._set_spectra_type(spectrum_no) - foil_out_periods, foil_thin_periods, foil_thick_periods = self._get_foil_periods() + foil_out_periods, foil_thin_periods, _ = self._get_foil_periods() if self._diff_opt == "FoilOut": raw_grp_indices = foil_map.get_indices(spectrum_no, foil_out_periods) @@ -252,13 +254,15 @@ def _setup_raw(self, spectra): # Cache delta_t values raw_t = first_ws.readX(0) delay = raw_t[2] - raw_t[1] - raw_t = raw_t - delay # The original EVS loader, raw.for/rawb.for, does this. Done here to match results + # The original EVS loader, raw.for/rawb.for, does this. Done here to match results + raw_t = raw_t - delay self.pt_times = raw_t[1:] self.delta_t = (raw_t[1:] - raw_t[:-1]) mon_raw_t = self._raw_monitors[0].readX(0) delay = mon_raw_t[2] - mon_raw_t[1] - mon_raw_t = mon_raw_t - delay # The original EVS loader, raw.for/rawb.for, does this. Done here to match results + # The original EVS loader, raw.for/rawb.for, does this. Done here to match results + mon_raw_t = mon_raw_t - delay self.mon_pt_times = mon_raw_t[1:] self.delta_tmon = (mon_raw_t[1:] - mon_raw_t[:-1]) @@ -310,7 +314,8 @@ def _get_runs(self): # Load is not doing the right thing when summing. The numbers don't look correct if "-" in run_str: lower,upper = run_str.split("-") - runs = range(int(lower),int(upper)+1) #range goes lower to up-1 but we want to include the last number + # Range goes lower to up-1 but we want to include the last number + runs = range(int(lower),int(upper)+1) elif "," in run_str: runs = run_str.split(",") @@ -322,9 +327,9 @@ def _get_runs(self): def _set_spectra_type(self, spectrum_no): """ - Set whether this spectrum no is forward/backward scattering - and set the normalization range appropriately - @param spectrum_no The current spectrum no + Set whether this spectrum no is forward/backward scattering + and set the normalization range appropriately + @param spectrum_no The current spectrum no """ if spectrum_no >= self._backward_spectra_list[0] and spectrum_no <= self._backward_spectra_list[-1]: self._spectra_type=BACKWARD @@ -385,7 +390,8 @@ def _create_foil_workspaces(self): nhists = first_ws.getNumberHistograms() data_kwargs = {'NVectors':nhists,'XLength':ndata_bins,'YLength':ndata_bins} - self.foil_out = WorkspaceFactory.create(first_ws, **data_kwargs) # This will be used as the result workspace + # This will be used as the result workspace + self.foil_out = WorkspaceFactory.create(first_ws, **data_kwargs) self.foil_out.setDistribution(True) self.foil_thin = WorkspaceFactory.create(first_ws, **data_kwargs) @@ -417,20 +423,21 @@ def _sum_foil_periods(self): foil_out_periods, foil_thin_periods, foil_thick_periods = self._get_foil_periods() if self._nperiods == 6 and self._spectra_type == FORWARD: - mon_out_periods = (5,6) - mon_thin_periods = (3,4) - mon_thick_periods = foil_thick_periods + mon_out_periods = (5,6) + mon_thin_periods = (3,4) + mon_thick_periods = foil_thick_periods else: # None indicates same as standard foil mon_out_periods, mon_thin_periods, mon_thick_periods = (None,None,None) -# + # Foil out self._sum_foils(self.foil_out, self.mon_out, IOUT, foil_out_periods, mon_out_periods) # Thin foil self._sum_foils(self.foil_thin, self.mon_thin, ITHIN, foil_thin_periods, mon_thin_periods) # Thick foil if foil_thick_periods is not None: - self._sum_foils(self.foil_thick, self.mon_thick, ITHICK, foil_thick_periods, mon_thick_periods) + self._sum_foils(self.foil_thick, self.mon_thick, ITHICK, + foil_thick_periods, mon_thick_periods) #---------------------------------------------------------------------------------------- def _get_foil_periods(self): @@ -467,13 +474,14 @@ def _get_foil_periods(self): #---------------------------------------------------------------------------------------- def _sum_foils(self, foil_ws, mon_ws, sum_index, foil_periods, mon_periods=None): """ - Sums the counts from the given foil periods in the raw data group - @param foil_ws :: The workspace that will receive the summed counts - @param mon_ws :: The monitor workspace that will receive the summed monitor counts - @param sum_index :: An index into the sum3 array where the integrated counts will be accumulated - @param foil_periods :: The period numbers that contribute to this sum - @param mon_periods :: The period numbers of the monitors that contribute to this monitor sum - (if None then uses the foil_periods) + Sums the counts from the given foil periods in the raw data group + @param foil_ws :: The workspace that will receive the summed counts + @param mon_ws :: The monitor workspace that will receive the summed monitor counts + @param sum_index :: An index into the sum3 array where the integrated counts will be + accumulated + @param foil_periods :: The period numbers that contribute to this sum + @param mon_periods :: The period numbers of the monitors that contribute to this monitor sum + (if None then uses the foil_periods) """ raw_grp_indices = self.foil_map.get_indices(self._spectrum_no, foil_periods) wsindex = self._ws_index @@ -511,7 +519,9 @@ def _normalise_by_monitor(self): wsindex = self._ws_index # inner function to apply normalization def monitor_normalization(foil_ws, mon_ws): - """Applies monitor normalization to the given foil spectrum from the given monitor spectrum + """ + Applies monitor normalization to the given foil spectrum from the given + monitor spectrum. """ mon_values = mon_ws.readY(wsindex) mon_values_sum = np.sum(mon_values[indices_in_range]) @@ -542,7 +552,8 @@ def normalise_to_out(foil_ws, foil_type): values = foil_ws.dataY(wsindex) sum_values = np.sum(values[range_indices]) if sum_values == 0.0: - self.getLogger().warning("No counts in %s foil spectrum %d." % (foil_type,self._spectrum_no)) + self.getLogger().warning("No counts in %s foil spectrum %d." % ( + foil_type,self._spectrum_no)) sum_values = 1.0 norm_factor = (sum_out/sum_values) values *= norm_factor @@ -611,7 +622,8 @@ def _calculate_double_difference(self, ws_index): eout = self.foil_out.dataE(ws_index) ethin = self.foil_thin.readE(ws_index) ethick = self.foil_thick.readE(ws_index) - np.sqrt((one_min_beta*eout)**2 + ethin**2 + (self._beta**2)*ethick**2, eout) # The second argument makes it happen in place + # The second argument makes it happen in place + np.sqrt((one_min_beta*eout)**2 + ethin**2 + (self._beta**2)*ethick**2, eout) #---------------------------------------------------------------------------------------- def _calculate_thick_difference(self, ws_index): @@ -693,7 +705,8 @@ def _get_header_format(self, ip_filename): try: return IP_HEADERS[len(columns)] except KeyError: - raise ValueError("Unknown format for IP file. Currently support 5/6 column variants. ncols=%d" % (len(columns))) + raise ValueError("Unknown format for IP file. Currently support 5/6 column " + "variants. ncols=%d" % (len(columns))) #---------------------------------------------------------------------------------------- def _store_results(self): @@ -794,11 +807,13 @@ def get_foil_periods(self, spectrum_no, state): return foil_periods def get_indices(self, spectrum_no, foil_state_numbers): - """Returns a tuple of indices that can be used to access the Workspace within + """ + Returns a tuple of indices that can be used to access the Workspace within a WorkspaceGroup that corresponds to the foil state numbers given - @param spectrum_no :: A spectrum number (1->nspectra) - @param foil_state_no :: A number between 1 & 9(inclusive) that defines which foil state is required - @returns A tuple of indices in a WorkspaceGroup that gives the associated Workspace + @param spectrum_no :: A spectrum number (1->nspectra) + @param foil_state_no :: A number between 1 & 9(inclusive) that defines which foil + state is required + @returns A tuple of indices in a WorkspaceGroup that gives the associated Workspace """ indices = [] for state in foil_state_numbers: @@ -824,7 +839,7 @@ def get_index(self, spectrum_no, foil_state_no): (spectrum_no >= 167 and spectrum_no <= 174) or \ (spectrum_no >= 183 and spectrum_no <= 190): # foil_in = 1,3,5, foil out = 2,4,6 - foil_periods = self._odd_even + foil_periods = self._odd_even else: # foil_in = 2,4,6 foil out = 1,3,5 foil_periods = self._even_odd @@ -834,11 +849,13 @@ def get_index(self, spectrum_no, foil_state_no): def _validate_foil_number(self, foil_number): if foil_number < 1 or foil_number > 9: - raise ValueError("Invalid foil state given, expected a number between 1 and 9. number=%d" % foil_number) + raise ValueError("Invalid foil state given, expected a number between " + "1 and 9. number=%d" % foil_number) def _validate_spectrum_number(self, spectrum_no): if spectrum_no < 1 or spectrum_no > 198: - raise ValueError("Invalid spectrum given, expected a number between 3 and 198. spectrum=%d" % spectrum_no) + raise ValueError("Invalid spectrum given, expected a number between 3 " + "and 198. spectrum=%d" % spectrum_no) ######################################################################################### diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py index 00e12cc3fdaa..7cd1366266bd 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi import mantid.kernel import mantid.api diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py index 3e2326027143..4bd2f7b122d4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi import mantid.api import mantid.kernel @@ -7,6 +8,11 @@ class MaskBTP(mantid.api.PythonAlgorithm): """ Class to generate grouping file """ + instname = None + instrument = None + bankmin = None + bankmax = None + def category(self): """ Mantid required """ @@ -60,28 +66,28 @@ def PyExec(self): except: raise ValueError("Instrument "+self.instname+" not in the allowed list") - if (self.instrument==None): + if self.instrument==None: IDF=mantid.api.ExperimentInfo.getInstrumentFilename(self.instname) if mantid.mtd.doesExist(self.instname+"MaskBTP"): mantid.simpleapi.DeleteWorkspace(self.instname+"MaskBTP") ws=mantid.simpleapi.LoadEmptyInstrument(IDF,OutputWorkspace=self.instname+"MaskBTP") self.instrument=ws.getInstrument() - if (bankString == ""): + if bankString == "": banks=numpy.arange(self.bankmax[self.instname]-self.bankmin[self.instname]+1)+self.bankmin[self.instname] else: banks=self._parseBTPlist(bankString) - if (tubeString == ""): + if tubeString == "": tubes=numpy.arange(tubemax[self.instname]-tubemin[self.instname]+1)+tubemin[self.instname] - elif (tubeString == "edges"): + elif tubeString == "edges": tubes=[tubemin[self.instname],tubemax[self.instname]] else: tubes=self._parseBTPlist(tubeString) - if(pixelString == ""): + if pixelString == "": pixels=numpy.arange(pixmax[self.instname]-pixmin[self.instname]+1)+pixmin[self.instname] - elif (pixelString == "edges"): + elif pixelString == "edges": pixels=[pixmin[self.instname],pixmax[self.instname]] else: pixels=self._parseBTPlist(pixelString) @@ -93,11 +99,11 @@ def PyExec(self): ep=self._getEightPackHandle(b) if ep!=None: for t in tubes: - if ((ttubemax[self.instname])): + if (ttubemax[self.instname]): raise ValueError("Out of range index for tube number") else: for p in pixels: - if ((ppixmax[self.instname])): + if (ppixmax[self.instname]): raise ValueError("Out of range index for pixel number") else: try: @@ -142,47 +148,47 @@ def _getEightPackHandle(self,banknum): """ banknum=int(banknum) if self.instname=="ARCS": - if (self.bankmin[self.instname]<=banknum<= 38): + if self.bankmin[self.instname]<=banknum<= 38: return self.instrument.getComponentByName("B row")[banknum-1][0] - elif(39<=banknum<= 77): + elif 39<=banknum<= 77: return self.instrument.getComponentByName("M row")[banknum-39][0] - elif(78<=banknum<=self.bankmax[self.instname]): + elif 78<=banknum<=self.bankmax[self.instname]: return self.instrument.getComponentByName("T row")[banknum-78][0] else: raise ValueError("Out of range index for ARCS instrument bank numbers") elif self.instname=="CORELLI": - if (self.bankmin[self.instname]<=banknum<= 29): + if self.bankmin[self.instname]<=banknum<= 29: return self.instrument.getComponentByName("A row")[banknum-1][0] - elif(30<=banknum<=62): + elif 30<=banknum<=62: return self.instrument.getComponentByName("B row")[banknum-30][0] - elif(63<=banknum<=self.bankmax[self.instname]): + elif 63<=banknum<=self.bankmax[self.instname]: return self.instrument.getComponentByName("C row")[banknum-63][0] else: raise ValueError("Out of range index for CORELLI instrument bank numbers") elif self.instname=="SEQUOIA": - if (self.bankmin[self.instname]<=banknum<= 74): + if self.bankmin[self.instname]<=banknum<= 74: return self.instrument.getComponentByName("B row")[banknum-38][0] - elif(75<=banknum<= 113): + elif 75<=banknum<= 113: return self.instrument.getComponentByName("C row")[banknum-75][0] - elif(114<=banknum<=self.bankmax[self.instname]): + elif 114<=banknum<=self.bankmax[self.instname]: return self.instrument.getComponentByName("D row")[banknum-114][0] else: raise ValueError("Out of range index for SEQUOIA instrument bank numbers") elif self.instname=="CNCS" or self.instname=="HYSPEC": - if (self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]): + if self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]: return self.instrument.getComponentByName("bank"+str(banknum))[0] else: raise ValueError("Out of range index for "+str(self.instname)+" instrument bank numbers") elif self.instname=="WISH": - if (self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]): + if self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]: try: - return self.instrument.getComponentByName("panel"+"%02d" % banknum)[0] + return self.instrument.getComponentByName("panel"+"%02d" % banknum)[0] except: - return None + return None else: raise ValueError("Out of range index for "+str(self.instname)+" instrument bank numbers") else: - if (self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]): + if self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]: return self.instrument.getComponentByName("bank"+str(banknum)) else: raise ValueError("Out of range index for "+str(self.instname)+" instrument bank numbers") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py index 10848174236a..6df3c2e9af03 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py @@ -1,83 +1,85 @@ -import sys +#pylint: disable=invalid-name, no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * -class QueryFlag: - def isMasked(self, detector, yValue): - return detector.isMasked() +class QueryFlag(object): + def isMasked(self, detector, yValue): + return detector.isMasked() -class QueryValue: - def isMasked(self, detector, yValue): - return yValue == 1 +class QueryValue(object): + def isMasked(self, detector, yValue): + return yValue == 1 class MaskWorkspaceToCalFile(PythonAlgorithm): def category(self): - return "DataHandling\\Text;Diffraction;PythonAlgorithms" + return "DataHandling\\Text;Diffraction;PythonAlgorithms" def name(self): - return "MaskWorkspaceToCalFile" + return "MaskWorkspaceToCalFile" def summary(self): - return "Saves the masking information in a workspace to a Cal File." + return "Saves the masking information in a workspace to a Cal File." def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), "The workspace containing the Masking to extract.") - self.declareProperty(FileProperty(name="OutputFile",defaultValue="",action=FileAction.Save,extensions=['cal']), "The file for the results.") + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input),\ + "The workspace containing the Masking to extract.") + self.declareProperty(FileProperty(name="OutputFile",defaultValue="",\ + action=FileAction.Save,extensions=['cal']), "The file for the results.") - self.declareProperty("Invert", False, "If True, masking is inverted in the input workspace. Default: False") + self.declareProperty("Invert", False, "If True, masking is inverted in the input workspace. Default: False") def PyExec(self): #extract settings - inputWorkspace = mtd[self.getPropertyValue("InputWorkspace")] - outputFileName = self.getProperty("OutputFile").value - invert = self.getProperty("Invert").value - mask_query = QueryFlag() - if inputWorkspace.id() == "MaskWorkspace": - mask_query = QueryValue() + inputWorkspace = mtd[self.getPropertyValue("InputWorkspace")] + outputFileName = self.getProperty("OutputFile").value + invert = self.getProperty("Invert").value + mask_query = QueryFlag() + if inputWorkspace.id() == "MaskWorkspace": + mask_query = QueryValue() #check for consistency - if len(inputWorkspace.readX(0)) < 1: - raise RuntimeError('The input workspace is empty.') + if len(inputWorkspace.readX(0)) < 1: + raise RuntimeError('The input workspace is empty.') #define flags for masking and not-masking - masking_flag = 0 - not_masking_flag = 1 + masking_flag = 0 + not_masking_flag = 1 - if invert: - masking_flag, not_masking_flag = not_masking_flag, masking_flag + if invert: + masking_flag, not_masking_flag = not_masking_flag, masking_flag - calFile = open(outputFileName,"w") + calFile = open(outputFileName,"w") #write a header - instrumentName = inputWorkspace.getInstrument().getName() - calFile.write('# '+instrumentName+' detector file\n') - calFile.write('# Format: number UDET offset select group\n') + instrumentName = inputWorkspace.getInstrument().getName() + calFile.write('# '+instrumentName+' detector file\n') + calFile.write('# Format: number UDET offset select group\n') #save the grouping - for i in range(inputWorkspace.getNumberHistograms()): - try: - det = inputWorkspace.getDetector(i) - y_value = inputWorkspace.readY(i)[0] - if (mask_query.isMasked(det, y_value)): #check if masked - group = masking_flag - else: - group = not_masking_flag - detIDs = [] - try: - detIDs = det.getDetectorIDs() - except: - detIDs = [det.getID()] - for id in detIDs: - calFile.write(self.FormatLine(i,id,0.0,group,group)) - except: + for i in range(inputWorkspace.getNumberHistograms()): + try: + det = inputWorkspace.getDetector(i) + y_value = inputWorkspace.readY(i)[0] + if mask_query.isMasked(det, y_value): #check if masked + group = masking_flag + else: + group = not_masking_flag + detIDs = [] + try: + detIDs = det.getDetectorIDs() + except: + detIDs = [det.getID()] + for did in detIDs: + calFile.write(self.FormatLine(i,did,0.0,group,group)) + except: #no detector for this spectra - pass - calFile.close() + pass + calFile.close() def FormatLine(self,number,UDET,offset,select,group): - line = "{0:9d}{1:16d}{2:16.7f}{3:9d}{4:9d}\n".format(number,UDET,offset,select,group) - return line + line = "{0:9d}{1:16d}{2:16.7f}{3:9d}{4:9d}\n".format(number,UDET,offset,select,group) + return line ############################################################################################# diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py index 54b5e72b53af..22d114f4c6d9 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py @@ -1,42 +1,54 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * + class Mean(PythonAlgorithm): def category(self): return "Arithmetic" + def name(self): return "Mean" + def summary(self): return "Calculates the arithemetic mean of the workspaces provided." + def PyInit(self): mustHaveWorkspaceNames = StringMandatoryValidator() - self.declareProperty("Workspaces", "", validator=mustHaveWorkspaceNames, direction=Direction.Input, doc="Input workspaces. Comma separated workspace names") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Output mean workspace") - def areWorkspacesCompatible(self, a, b): - sizeA = a.blocksize() * a.getNumberHistograms() - sizeB = b.blocksize() * b.getNumberHistograms() + self.declareProperty("Workspaces", "", validator=mustHaveWorkspaceNames, + direction=Direction.Input, + doc="Input workspaces. Comma separated workspace names") + + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", + Direction.Output), + doc="Output mean workspace") + + + def _are_workspaces_compatible(self, ws_a, ws_b): + sizeA = ws_a.blocksize() * ws_a.getNumberHistograms() + sizeB = ws_b.blocksize() * ws_b.getNumberHistograms() return sizeA == sizeB + def PyExec(self): workspaces = self.getProperty("Workspaces").value.split(',') - out_ws = CloneWorkspace(InputWorkspace=mtd[workspaces[0]], OutputWorkspace=self.getPropertyValue("OutputWorkspace")) + out_ws = CloneWorkspace(InputWorkspace=mtd[workspaces[0]], + OutputWorkspace=self.getPropertyValue("OutputWorkspace")) for index in range(1, len(workspaces)): name = workspaces[index].strip() - ws = mtd[name] - if not self.areWorkspacesCompatible(out_ws, ws): + workspace = mtd[name] + if not self._are_workspaces_compatible(out_ws, workspace): raise RuntimeError("Input Workspaces are not the same shape.") - out_ws += ws + out_ws += workspace out_ws /= len(workspaces) self.setProperty("OutputWorkspace", out_ws) -############################################################################################# - AlgorithmFactory.subscribe(Mean()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py index ea164973bf8c..03a92e3885cf 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py @@ -1,135 +1,136 @@ +#pylint: disable=no-init from mantid.api import * from mantid.kernel import * class MergeCalFiles(PythonAlgorithm): - def category(self): - return "DataHandling\\Text;Diffraction;PythonAlgorithms" + def category(self): + return "DataHandling\\Text;Diffraction;PythonAlgorithms" - def name(self): - return "MergeCalFiles" + def name(self): + return "MergeCalFiles" - def summary(self): - return "Combines the data from two Cal Files." + def summary(self): + return "Combines the data from two Cal Files." - def PyInit(self): - self.declareProperty(FileProperty("UpdateFile","", FileAction.Load, ['cal']), doc="The cal file containing the updates to merge into another file.") - self.declareProperty(FileProperty("MasterFile","", FileAction.Load, ['cal']), doc="The master file to be altered, the file must be sorted by UDET") - self.declareProperty(FileProperty("OutputFile","", FileAction.Save, ['cal']), doc="The file to contain the results") + def PyInit(self): + self.declareProperty(FileProperty("UpdateFile","", FileAction.Load, ['cal']), doc="The cal file containing the updates to merge into another file.") + self.declareProperty(FileProperty("MasterFile","", FileAction.Load, ['cal']), doc="The master file to be altered, the file must be sorted by UDET") + self.declareProperty(FileProperty("OutputFile","", FileAction.Save, ['cal']), doc="The file to contain the results") - self.declareProperty("MergeOffsets", False, doc="If True, the offsets from file1 will be merged to the master file. Default: False") - self.declareProperty("MergeSelections", False, doc="If True, the selections from file1 will be merged to the master file. Default: False") - self.declareProperty("MergeGroups", False, doc="If True, the Groups from file1 will be merged to the master file. Default: False") + self.declareProperty("MergeOffsets", False, doc="If True, the offsets from file1 will be merged to the master file. Default: False") + self.declareProperty("MergeSelections", False, doc="If True, the selections from file1 will be merged to the master file. Default: False") + self.declareProperty("MergeGroups", False, doc="If True, the Groups from file1 will be merged to the master file. Default: False") - def PyExec(self): + def PyExec(self): #extract settings - mergeOffsets = self.getProperty("MergeOffsets").value - mergeSelections = self.getProperty("MergeSelections").value - mergeGroups = self.getProperty("MergeGroups").value - updateFileName = self.getPropertyValue("UpdateFile") - masterFileName = self.getPropertyValue("MasterFile") - outputFileName = self.getPropertyValue("OutputFile") - - - if (masterFileName == outputFileName) : - raise RuntimeError('The output file must be different to the master file.') - - self.DisplayMessage(mergeOffsets,mergeSelections,mergeGroups,updateFileName,masterFileName) - - updateFile = open(updateFileName,"r") - updateDict=dict() - lastNumber = 0 - linesUpdated = 0 - linesUntouched = 0 - linesAdded = 0 - linesInvalid=0 - for line in updateFile: - if not self.IsComment(line): + mergeOffsets = self.getProperty("MergeOffsets").value + mergeSelections = self.getProperty("MergeSelections").value + mergeGroups = self.getProperty("MergeGroups").value + updateFileName = self.getPropertyValue("UpdateFile") + masterFileName = self.getPropertyValue("MasterFile") + outputFileName = self.getPropertyValue("OutputFile") + + + if masterFileName == outputFileName : + raise RuntimeError('The output file must be different to the master file.') + + self.DisplayMessage(mergeOffsets,mergeSelections,mergeGroups,updateFileName,masterFileName) + + updateFile = open(updateFileName,"r") + updateDict=dict() + lastNumber = 0 + linesUpdated = 0 + linesUntouched = 0 + linesAdded = 0 + linesInvalid=0 + for line in updateFile: + if not self.IsComment(line): #process line - try: - (number,UDET,offset,select,group) = self.ProcessLine(line) - except ValueError: - pass + try: + (number,UDET,offset,select,group) = self.ProcessLine(line) + except ValueError: + pass #remeber all of the values - updateDict[UDET] = (offset,select,group) + updateDict[UDET] = (offset,select,group) - updateFile.close() - self.log().information(str(len(updateDict)) + " updates found in " + updateFileName) + updateFile.close() + self.log().information(str(len(updateDict)) + " updates found in " + updateFileName) - masterFile = open(masterFileName,"r") - outputFile = open(outputFileName,"w") + masterFile = open(masterFileName,"r") + outputFile = open(outputFileName,"w") - for line in masterFile: - if self.IsComment(line): + for line in masterFile: + if self.IsComment(line): #copy the comment over - outputFile.write(line) - else: + outputFile.write(line) + else: #process line - try: - (number,UDET,masterOffset,masterSelect,masterGroup) = self.ProcessLine(line) - lastNumber = number + try: + (number,UDET,masterOffset,masterSelect,masterGroup) = self.ProcessLine(line) + lastNumber = number #If line to be updated - if UDET in updateDict: - (offset,select,group)=updateDict.pop(UDET) - linesUpdated += 1 - if mergeOffsets: - masterOffset = offset - if mergeSelections: - masterSelect = select - if mergeGroups: - masterGroup = group - else: - linesUntouched += 1 - outputFile.write(self.FormatLine(number,UDET,masterOffset,masterSelect,masterGroup)) - except ValueError: + if UDET in updateDict: + (offset,select,group)=updateDict.pop(UDET) + linesUpdated += 1 + if mergeOffsets: + masterOffset = offset + if mergeSelections: + masterSelect = select + if mergeGroups: + masterGroup = group + else: + linesUntouched += 1 + outputFile.write(self.FormatLine(number,UDET,masterOffset,masterSelect,masterGroup)) + except ValueError: #invalid line - ignore it - linesInvalid += 1 + linesInvalid += 1 #add any lines at the end - for UDET in updateDict.keys(): - (offset,select,group)=updateDict.pop(UDET) - lastNumber += 1 - outputFile.write(self.FormatLine(lastNumber,UDET,offset,select,group)) - linesAdded += 1 + for UDET in updateDict.keys(): + (offset,select,group)=updateDict.pop(UDET) + lastNumber += 1 + outputFile.write(self.FormatLine(lastNumber,UDET,offset,select,group)) + linesAdded += 1 - self.log().information("{0} lines Updated, {1} lines added, {2} lines untouched".format(linesUpdated,linesAdded,linesUntouched)) + self.log().information("{0} lines Updated, {1} lines added, {2} lines untouched".format(linesUpdated,linesAdded,linesUntouched)) #close the files - masterFile.close() - outputFile.close() + masterFile.close() + outputFile.close() - def DisplayMessage(self,mergeOffsets,mergeSelections,mergeGroups,fileName1,fileName2): + def DisplayMessage(self,mergeOffsets,mergeSelections,mergeGroups,fileName1,fileName2): #Log the settings string - outputString = "Merging " - if (mergeOffsets): - outputString+= "offsets, " - if (mergeSelections): - outputString+= "selections, " - if (mergeGroups): - outputString+= "groups, " + outputString = "Merging " + if mergeOffsets: + outputString+= "offsets, " + if mergeSelections: + outputString+= "selections, " + if mergeGroups: + outputString+= "groups, " #strip the final comma - outputString = outputString [0:len(outputString)-2] - outputString += " from file " + fileName1 + " into " + fileName2 - self.log().information(outputString) - - def IsComment(self,line): - return line.startswith("#") - - def ProcessLine(self,line): - try: - elements = line.split() - number =int(elements[0]) - UDET =int(elements[1]) - offset =float(elements[2]) - select =int(elements[3]) - group =int(elements[4]) - except: - raise ValueError("invalid line: " + line) - return (number,UDET,offset,select,group) - - def FormatLine(self,number,UDET,offset,select,group): - line = "{0:9d}{1:16d}{2:16.7f}{3:9d}{4:9d}\n".format(number,UDET,offset,select,group) - return line + outputString = outputString [0:len(outputString)-2] + outputString += " from file " + fileName1 + " into " + fileName2 + self.log().information(outputString) + + def IsComment(self,line): + return line.startswith("#") + + def ProcessLine(self,line): + try: + elements = line.split() + number =int(elements[0]) + UDET =int(elements[1]) + offset =float(elements[2]) + select =int(elements[3]) + group =int(elements[4]) + except: + raise ValueError("invalid line: " + line) + return (number,UDET,offset,select,group) + + def FormatLine(self,number,UDET,offset,select,group): + line = "{0:9d}{1:16d}{2:16.7f}{3:9d}{4:9d}\n".format(number,UDET,offset,select,group) + return line ############################################################################################# AlgorithmFactory.subscribe(MergeCalFiles()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py index 9bb2ba9ed9a7..e779abe8845b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py @@ -1,4 +1,4 @@ -import mantid.simpleapi as api +#pylint: disable=no-init from mantid.api import * from mantid.kernel import * @@ -37,7 +37,7 @@ def name(self): def summary(self): return "Determines the characterizations of a workspace." - + def PyInit(self): # input parameters self.declareProperty(WorkspaceProperty("InputWorkspace", "", @@ -49,24 +49,24 @@ def PyInit(self): "Table of characterization information") self.declareProperty("ReductionProperties", - "__pd_reduction_properties", + "__pd_reduction_properties", validator=StringMandatoryValidator(), doc="Property manager name for the reduction") defaultMsg = " run to use. 0 to use value in table, -1 to not use." - self.declareProperty("BackRun", 0, + self.declareProperty("BackRun", 0, doc="The background" + defaultMsg) - self.declareProperty("NormRun", 0, + self.declareProperty("NormRun", 0, doc="The background" + defaultMsg) - self.declareProperty("NormBackRun", 0, + self.declareProperty("NormBackRun", 0, doc="The background" + defaultMsg) - self.declareProperty(StringArrayProperty("FrequencyLogNames", ["SpeedRequest1", "Speed1", "frequency"], - direction=Direction.Input), + self.declareProperty(StringArrayProperty("FrequencyLogNames", ["SpeedRequest1", "Speed1", "frequency"],\ + direction=Direction.Input),\ "Possible log names for frequency.") - self.declareProperty(StringArrayProperty("WaveLengthLogNames", ["LambdaRequest", "lambda"], - direction=Direction.Input), + self.declareProperty(StringArrayProperty("WaveLengthLogNames", ["LambdaRequest", "lambda"],\ + direction=Direction.Input),\ "Candidate log names for wave length.") return @@ -119,7 +119,7 @@ def PyExec(self): self.log().information("Determined frequency: " + str(frequency) \ + " Hz, center wavelength:" \ + str(wavelength) + " Angstrom") - + # get a row of the table info = self.getLine(char, frequency, wavelength) @@ -140,7 +140,7 @@ def PyExec(self): def processInformation(self, prop_man, info_dict): for key in COL_NAMES: val = info_dict[key] - # Convert comma-delimited list to array, else return the original + # Convert comma-delimited list to array, else return the original # value. if type("") == type(val): if (len(val)==0) and (key in DEF_INFO.keys()): @@ -177,7 +177,7 @@ def getLine(self, char, frequency, wavelength): # go through every row looking for a match result = dict(DEF_INFO) - icount = 0 + icount = 0 for i in xrange(char.rowCount()): row = char.row(i) if not self.closeEnough(frequency, row['frequency']): @@ -206,7 +206,7 @@ def getFrequency(self, logs, wkspName): self.log().information(msg) else: frequency = frequency.getStatistics().mean - if frequency == 0.: + if frequency == 0.: self.log().information("'%s' mean value is zero" % name) else: self.log().information("Found frequency in %s log" \ @@ -219,13 +219,13 @@ def getFrequency(self, logs, wkspName): def getWavelength(self, logs, wkspName): """ Get wave length Wavelength can be given by 2 sample logs, either LambdaRequest or lambda. - And its unit can be either Angstrom or A. + And its unit can be either Angstrom or A. """ wavelengthnames = self.getProperty("WaveLengthLogNames").value - for name in wavelengthnames: - # skip if not exists - if name not in logs.keys(): + for name in wavelengthnames: + # skip if not exists + if name not in logs.keys(): continue # get value @@ -233,7 +233,7 @@ def getWavelength(self, logs, wkspName): # unit if name == "LambdaRequest": - if wavelength.units != "Angstrom": + if wavelength.units != "Angstrom": msg = "Only know how to deal with LambdaRequest in Angstrom, not %s" % (wavelength.units) self.log().warning(msg) break @@ -246,17 +246,17 @@ def getWavelength(self, logs, wkspName): else: if wavelength.units != "Angstrom" and wavelength.units != "A": - msg = "Only know how to deal with %s in Angstrom (A) but not %s" % (name, + msg = "Only know how to deal with %s in Angstrom (A) but not %s" % (name,\ wavelength.units) self.log().warning(msg) break # return - wavelength = wavelength.getStatistics().mean - if wavelength == 0.: - self.log().warning("'%s' mean value is zero" % name) + wavelength = wavelength.getStatistics().mean + if wavelength == 0.: + self.log().warning("'%s' mean value is zero" % name) break - else: + else: return wavelength # ENDFOR diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py index 5120101e9c90..9432da8feb82 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import LoadAscii @@ -36,7 +37,7 @@ def PyExec(self): coeffs = self._calculateAbsorption(ascii_wkspace, float(thickness)) coeffs.setYUnitLabel("Attenuation Factor (I/I0)") - coeffs.setYUnit(""); + coeffs.setYUnit("") coeffs.setDistribution(True) self.setProperty("OutputWorkspace", coeffs) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py index 612bd8ee0d8c..c85c7c2795d4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import StringArrayProperty, Direction from mantid.simpleapi import * from mantid.api import * @@ -93,7 +94,7 @@ def makePlausibleChopperSpeed(self, chopperSpeed): # This is related to ticket #10090, where a new field in new data is used # when that ticket is finished, new data files will not need this # cleanup method anymore. - return np.floor((chopperSpeed + 250.0) / 500.0) * 500.0; + return np.floor((chopperSpeed + 250.0) / 500.0) * 500.0 def instrumentsMatch(self, leftWorkspace, rightWorkspace): leftInstrument = leftWorkspace.getInstrument() @@ -102,7 +103,7 @@ def instrumentsMatch(self, leftWorkspace, rightWorkspace): return (not self.checkInstruments) or self.instrumentParametersMatch(leftInstrument, rightInstrument) def instrumentParametersMatch(self, leftInstrument, rightInstrument): - if not (leftInstrument.getDetector(0).getPos() == rightInstrument.getDetector(0).getPos()): + if not leftInstrument.getDetector(0).getPos() == rightInstrument.getDetector(0).getPos(): raise RuntimeError("Detector positions are not equal") for parameterTuple in self.comparedInstrumentParameters: @@ -112,7 +113,7 @@ def instrumentParametersMatch(self, leftInstrument, rightInstrument): if abs(leftValue - rightValue) > 1e-12: raise RuntimeError("Instrument parameter '%s'/'%s' does not match" % parameterTuple) - return True; + return True def getParameterValue(self, instrument, parameterTuple): return instrument.getComponentByName(parameterTuple[0]).getNumberParameter(parameterTuple[1])[0] @@ -137,17 +138,17 @@ def handleError(self, error): raise RuntimeError("Workspaces can not be merged. %s. Aborting." % (str(error))) def getWorkspacesRecursive(self, workspace): - returnList = [] - if isinstance(workspace, WorkspaceGroup): - for i in range(workspace.getNumberOfEntries()): - returnList += self.getWorkspacesRecursive(workspace.getItem(i)) + returnList = [] + if isinstance(workspace, WorkspaceGroup): + for i in range(workspace.getNumberOfEntries()): + returnList += self.getWorkspacesRecursive(workspace.getItem(i)) - elif isinstance(workspace, MatrixWorkspace): - returnList.append(workspace) + elif isinstance(workspace, MatrixWorkspace): + returnList.append(workspace) - else: - raise RuntimeError("Can only merge MatrixWorkspaces, this is " + type(workspace)) + else: + raise RuntimeError("Can only merge MatrixWorkspaces, this is " + type(workspace)) - return returnList + return returnList AlgorithmFactory.subscribe(PoldiMerge) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py index 10e66a2436d7..29f48bd87486 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import (PythonAlgorithm, AlgorithmFactory) from mantid.api import (FileProperty, @@ -12,8 +13,6 @@ import re - - class PoldiProjectAddDir(PythonAlgorithm): def category(self): @@ -37,15 +36,10 @@ def PyInit(self): self.declareProperty(ITableWorkspaceProperty("PoldiAnalysis", "PoldiAnalysis", direction=Direction.Output), "Poldi analysis main worksheet") - - - - def path_leaf(path): head, tail = ntpath.split(path) return tail - def interpreteName(self, name): patern="(.*[ a-zA-Z]*/*\*)*poldi(?P[0-9]*)n(?P[0-9]*)" regex = re.match(patern, name, re.M|re.I) @@ -53,11 +47,6 @@ def interpreteName(self, name): numero = int(regex.group("numero")) return (year, numero) - - - - - def PyExec(self): """ Mantid required """ @@ -68,7 +57,7 @@ def PyExec(self): try: sample_info_ws_name = self.getProperty("PoldiAnalysis").value - if(sample_info_ws_name == ""): + if sample_info_ws_name == "": sample_info_ws_name = "PoldiAnalysis" self.log().debug('Poldi Data Analysis ---- %s'%(sample_info_ws_name)) sample_info_ws = mtd["PoldiAnalysis"] @@ -107,7 +96,7 @@ def PyExec(self): - if("hdf" in sampleExt): + if "hdf" in sampleExt: self.log().error('Poldi - samples : %s' %(sample_name)) file_path = join(directory,dataFile) sample_name_log = "%sLog" %sample_name @@ -127,7 +116,7 @@ def PyExec(self): - if(load_data_at_the_end): + if load_data_at_the_end: self.setProperty("PoldiAnalysis", sample_info_ws) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py index 6b93e1d1513e..5236eaadf166 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py @@ -1,8 +1,7 @@ +#pylint: disable=no-init from mantid.api import * from mantid.kernel import Direction - -from os import listdir -from os.path import isfile, join, split, splitext +from os.path import split, splitext import re @@ -58,7 +57,7 @@ def PyExec(self): try: sample_info_ws_name = self.getProperty("OutputWorkspace").valueAsStr - if(sample_info_ws_name == ""): + if sample_info_ws_name == "": sample_info_ws_name = "PoldiAnalysis" self.log().debug('Poldi Data Analysis ---- %s'%(sample_info_ws_name)) sample_info_ws = mtd[sample_info_ws_name] @@ -84,7 +83,7 @@ def PyExec(self): self.log().error('Poldi - : %s' %(sample_name)) self.log().error('Poldi - : %s' %(sampleExt)) - if("hdf" in sampleExt): + if "hdf" in sampleExt: self.log().error('Poldi - samples : %s' %(sample_name)) file_path = dataFile sample_name_log = "%sLog" %sample_name diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py index 3480e64a2f54..1976f889e970 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import PythonAlgorithm from mantid.api import ITableWorkspaceProperty from mantid.api import AlgorithmFactory, WorkspaceFactory @@ -12,8 +13,8 @@ PoldiLoadChopperSlits, PoldiLoadSpectra, PoldiLoadIPP, - PoldiAutoCorrelation, - PoldiPeakDetection, + #PoldiAutoCorrelation, + #PoldiPeakDetection, GroupWorkspaces, RenameWorkspace) import os.path @@ -42,7 +43,7 @@ def PyInit(self): self.declareProperty(ITableWorkspaceProperty("InputWorkspace", "PoldiAnalysis", direction=Direction.Input), "Poldi analysis main worksheet") - self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "PoldiIPPmanager", direction=Direction.Output), + self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "PoldiIPPmanager", direction=Direction.Output),\ "Poldi IPP table manager") self.declareProperty("wlenmin", 1.1, @@ -62,10 +63,6 @@ def PyInit(self): direction = Direction.Input) - - - - def PyExec(self): """ Mantid required """ @@ -76,7 +73,7 @@ def PyExec(self): load_data_at_the_end = False try: sample_ipp_ws_name = self.getProperty("OutputWorkspace").value - if(sample_ipp_ws_name == ""): + if sample_ipp_ws_name == "": sample_ipp_ws_name = "PoldiIPPmanager" self.log().debug('Poldi IPP manager ---- %s'%(sample_info_ws_name)) sample_ipp_ws = mtd["PoldiIPPmanager"] @@ -141,9 +138,9 @@ def PyExec(self): add_this_ipp = True for ipp in range(sample_ipp_ws.rowCount()): - if(sample_ipp_ws.column("ipp version")[ipp] == ipp_version): + if sample_ipp_ws.column("ipp version")[ipp] == ipp_version: add_this_ipp = False - if(add_this_ipp): + if add_this_ipp: sample_ipp_ws.addRow([sampleName, ipp_version]) @@ -194,7 +191,7 @@ def PyExec(self): RenameWorkspace(InputWorkspace=groupedResults, OutputWorkspace="%s_Metadata" % sampleName) - if(load_data_at_the_end): + if load_data_at_the_end: self.setProperty("OutputWorkspace", sample_ipp_ws) AlgorithmFactory.subscribe(PoldiProjectRun) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py index 9c173170f685..6588264e0211 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py @@ -1,7 +1,6 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.simpleapi import * -from numpy import zeros, shape, arange -import math # import sfCalculator import sys @@ -124,7 +123,7 @@ def PyExec(self): #GENERAL TOFrangeFlag = self.getProperty("TofRangeFlag") - if (TOFrangeFlag): + if TOFrangeFlag: TOFrange = self.getProperty("TOFRange").value #microS else: TOFrange = [0, 200000] @@ -137,8 +136,8 @@ def PyExec(self): qMin = self.getProperty("QMin").value qStep = self.getProperty("QStep").value - if (qStep > 0): #force logarithmic binning - qStep = -qStep; + if qStep > 0: #force logarithmic binning + qStep = -qStep # angle offset angleOffsetDeg = self.getProperty("AngleOffset").value @@ -186,8 +185,8 @@ def PyExec(self): error_0 = 1. / pc # rebin data - ws_histo_data = wks_utility.rebinNeXus(ws_event_data, - [binTOFrange[0], binTOFsteps, binTOFrange[1]], + ws_histo_data = wks_utility.rebinNeXus(ws_event_data,\ + [binTOFrange[0], binTOFsteps, binTOFrange[1]],\ 'data') # get q range @@ -197,18 +196,18 @@ def PyExec(self): [first_slit_size, last_slit_size] = wks_utility.getSlitsSize(ws_histo_data) # keep only TOF range - ws_histo_data = wks_utility.cropTOF(ws_histo_data, - TOFrange[0], - TOFrange[1], + ws_histo_data = wks_utility.cropTOF(ws_histo_data,\ + TOFrange[0],\ + TOFrange[1],\ 'data') # normalize by current proton charge ws_histo_data = wks_utility.normalizeNeXus(ws_histo_data, 'data') # integrate over low resolution range - [data_tof_axis, data_y_axis, data_y_error_axis] = wks_utility.integrateOverLowResRange(ws_histo_data, - dataLowResRange, - 'data', + [data_tof_axis, data_y_axis, data_y_error_axis] = wks_utility.integrateOverLowResRange(ws_histo_data,\ + dataLowResRange,\ + 'data',\ is_nexus_detector_rotated_flag) # #DEBUG ONLY @@ -248,36 +247,36 @@ def PyExec(self): error_0 = 1. / pc # rebin normalization - ws_histo_norm = wks_utility.rebinNeXus(ws_event_norm, - [binTOFrange[0], binTOFsteps, binTOFrange[1]], + ws_histo_norm = wks_utility.rebinNeXus(ws_event_norm,\ + [binTOFrange[0], binTOFsteps, binTOFrange[1]],\ 'normalization') # keep only TOF range - ws_histo_norm = wks_utility.cropTOF(ws_histo_norm, - TOFrange[0], - TOFrange[1], + ws_histo_norm = wks_utility.cropTOF(ws_histo_norm,\ + TOFrange[0],\ + TOFrange[1],\ 'normalization') # normalize by current proton charge ws_histo_norm = wks_utility.normalizeNeXus(ws_histo_norm, 'normalization') # integrate over low resolution range - [norm_tof_axis, norm_y_axis, norm_y_error_axis] = wks_utility.integrateOverLowResRange(ws_histo_norm, - normLowResRange, - 'normalization', + [norm_tof_axis, norm_y_axis, norm_y_error_axis] = wks_utility.integrateOverLowResRange(ws_histo_norm,\ + normLowResRange,\ + 'normalization',\ is_nexus_detector_rotated_flag) # substract background - [norm_y_axis, norm_y_error_axis] = wks_utility.substractBackground(norm_tof_axis[0:-1], - norm_y_axis, - norm_y_error_axis, - normPeakRange, - normBackFlag, - normBackRange, - error_0, + [norm_y_axis, norm_y_error_axis] = wks_utility.substractBackground(norm_tof_axis[0:-1],\ + norm_y_axis,\ + norm_y_error_axis,\ + normPeakRange,\ + normBackFlag,\ + normBackRange,\ + error_0,\ 'normalization') - [av_norm, av_norm_error] = wks_utility.fullSumWithError(norm_y_axis, + [av_norm, av_norm_error] = wks_utility.fullSumWithError(norm_y_axis,\ norm_y_error_axis) # ## DEBUGGING ONLY @@ -362,7 +361,7 @@ def PyExec(self): # cleanup data - [final_y_axis, final_y_error_axis] = wks_utility.cleanupData1D(final_y_axis, + [final_y_axis, final_y_error_axis] = wks_utility.cleanupData1D(final_y_axis,\ final_error_axis) @@ -374,7 +373,8 @@ def PyExec(self): final_workspace = wks_utility.createFinalWorkspace(final_x_axis, final_y_axis, final_y_error_axis, - name_output_ws) + name_output_ws, + ws_event_data) self.setProperty('OutputWorkspace', mtd[name_output_ws]) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py index 4db03267838d..15a3af799a12 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * import mantid.simpleapi as api from mantid.api import * @@ -11,6 +12,25 @@ class RefinePowderDiffProfileSeq(PythonAlgorithm): """ Refine powder diffractometer profile by Le Bail algorithm sequentially """ + + dataws = None + wsindex = None + startx = None + endx = None + _lastStep = None + _projectID = None + functionoption = None + peaktype = None + bkgdtype = None + bkgdparws = None + profilews = None + braggpeakws = None + paramstofit = None + numcycles = None + outprojectfilename = None + inprojectfilename = None + datawsname = None + def category(self): """ Category """ @@ -27,21 +47,21 @@ def summary(self): def PyInit(self): """ Declare properties """ - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of data workspace containing the diffraction pattern in .prf file. ") self.declareProperty("WorkspaceIndex", 0, "Spectrum (workspace index starting from 0) of the data to refine against in input workspace.") - self.declareProperty(ITableWorkspaceProperty("SeqControlInfoWorkspace", "", Direction.InOut, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("SeqControlInfoWorkspace", "", Direction.InOut, PropertyMode.Optional),\ "Name of table workspace containing sequential refinement information.") - self.declareProperty(ITableWorkspaceProperty("InputProfileWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("InputProfileWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of table workspace containing starting profile parameters.") - self.declareProperty(ITableWorkspaceProperty("InputBraggPeaksWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(ITableWorkspaceProperty("InputBraggPeaksWorkspace", "", Direction.Input, PropertyMode.Optional),\ "Name of table workspace containing a list of reflections. ") - self.declareProperty(ITableWorkspaceProperty("InputBackgroundParameterWorkspace", "", Direction.Input, + self.declareProperty(ITableWorkspaceProperty("InputBackgroundParameterWorkspace", "", Direction.Input,\ PropertyMode.Optional), "Name of table workspace containing a list of reflections. ") self.declareProperty("StartX", -0., "Start X (TOF) to refine diffraction pattern.") @@ -52,15 +72,15 @@ def PyInit(self): #refoptions = ["Levenberg-Marquardt", "Random Walk", "Single Peak Fit"] refoptions = ["Random Walk"] - self.declareProperty("RefinementOption", "Random Walk", StringListValidator(refoptions), + self.declareProperty("RefinementOption", "Random Walk", StringListValidator(refoptions),\ "Options of algorithm to refine. ") - self.declareProperty(StringArrayProperty("ParametersToRefine", values=[], direction=Direction.Input), + self.declareProperty(StringArrayProperty("ParametersToRefine", values=[], direction=Direction.Input),\ "List of parameters to refine.") self.declareProperty("NumRefineCycles", 1, "Number of refinement cycles.") - peaktypes = ["", "Neutron Back-to-back exponential convoluted with pseudo-voigt", + peaktypes = ["", "Neutron Back-to-back exponential convoluted with pseudo-voigt",\ "Thermal neutron Back-to-back exponential convoluted with pseudo-voigt"] self.declareProperty("ProfileType", "", StringListValidator(peaktypes), "Type of peak profile function.") @@ -70,11 +90,11 @@ def PyInit(self): self.declareProperty("FromStep", -1, "If non-negative, the previous code is not set from last step, but the step specified.") # Property for save project - self.declareProperty(FileProperty("OutputProjectFilename","", FileAction.OptionalSave, ['.nxs']), + self.declareProperty(FileProperty("OutputProjectFilename","", FileAction.OptionalSave, ['.nxs']),\ "Name of sequential project file.") # Property for save project - self.declareProperty(FileProperty("InputProjectFilename","", FileAction.OptionalLoad, ['.nxs']), + self.declareProperty(FileProperty("InputProjectFilename","", FileAction.OptionalLoad, ['.nxs']),\ "Name of sequential project file.") # Project ID @@ -98,7 +118,7 @@ def PyExec(self): if seqrefine.isSetup() is True: raise NotImplementedError("Impossible to have it set up already.") - seqrefine.initSetup(self.dataws, self.wsindex, self.peaktype, self.profilews, self.braggpeakws, self.bkgdtype, + seqrefine.initSetup(self.dataws, self.wsindex, self.peaktype, self.profilews, self.braggpeakws, self.bkgdtype,\ self.bkgdparws, self.startx, self.endx) elif self.functionoption == "Refine": @@ -174,7 +194,7 @@ def _processInputProperties(self): if self.functionoption != "Load": self.datawsname = str(self.dataws) if self.wsindex < 0 or self.wsindex >= self.dataws.getNumberHistograms(): - raise NotImplementedError("Input workspace index %d is out of range (0, %d)." % + raise NotImplementedError("Input workspace index %d is out of range (0, %d)." %\ (self.wsindex, self.dataws.getNumberHistograms())) return @@ -194,6 +214,23 @@ class SeqRefineProfile: 4. If no further instruction, only need to set up parameters to refine the input/starting values should be from the last """ + + _datawsname = None + _profileWS = None + _braggpeakws = None + _bkgdtype = None + _bkgdparws = None + _wsgroup = None + datawsname = None + wsindex = None + _recordws = None + _recordwsLastRowValid = None + _lastValidStep = None + _lastValidRowIndex = None + _peakType = None + _bkgdType = None + _currstep = None + def __init__(self, ID, glog): """ """ @@ -264,7 +301,7 @@ def initSetup(self, dataws, wsindex, peaktype, profilews, braggpeakws, bkgdtype, self._recordPostRefineInfo(runner) # Group the newly generated workspace and do some record - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, self._profileWS, self._braggpeakws, self._bkgdparws), + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, self._profileWS, self._braggpeakws, self._bkgdparws),\ OutputWorkspace=self._wsgroupName) self._wsgroupCreated = True @@ -355,16 +392,16 @@ def refine(self, dataws, wsindex, parametersToFit, numcycles, startx, endx, last # Group newly generated workspaces and add name to reposiotry if self._wsgroupCreated is True: - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, self._wsgroupName), + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, self._wsgroupName),\ OutputWorkspace=self._wsgroupName) else: wsgroup = AnalysisDataService.retrieve(self._wsgroupName) hasbkgd = list(wsgroup.getNames()).count(bkgdparamwsname) if hasbkgd == 1: - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname), + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname),\ OutputWorkspace=self._wsgroupName) elif hasbkgd == 0: - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, bkgdparamwsname), + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, bkgdparamwsname),\ OutputWorkspace=self._wsgroupName) else: raise NotImplementedError("Impossible to have 1 workspace appeared twice in a workspace group.") @@ -482,7 +519,7 @@ def _parseRecordTable(self, laststep): self._lastValidRowIndex = lastvalidrow if laststep > lastrecordedstep: - self.glog.warning("Last step %d is not recorded. Using step %d instead. " % + self.glog.warning("Last step %d is not recorded. Using step %d instead. " %\ (laststep, lastrecordedstep)) laststep = lastrecordedstep elif laststep < 0: @@ -500,12 +537,12 @@ def _parseRecordTable(self, laststep): bkgdtype = self._recordws.cell(lastrow, 3).strip() bkgdparamwsname = self._recordws.cell(lastrow, 4).strip() if profilewsname == "": - raise NotImplementedError("Profile workspace name is emtpy in row %d. It is not supposed to happen." % + raise NotImplementedError("Profile workspace name is emtpy in row %d. It is not supposed to happen." %\ (lastvalidrow)) break # ENDWHILE if profilewsname == "": - raise NotImplementedError("Step %d is not found in record table. It is impossible. " % + raise NotImplementedError("Step %d is not found in record table. It is impossible. " %\ (laststep)) # Current step @@ -529,7 +566,7 @@ def _recordPreRefineInfo(self, refiner, laststep): if self._recordWSLastRowInvalid is False: self._currstep = numrows - rectablews.addRow([self._currstep, "", "", "", "", "", -1.0, laststep, -1.0, "profilews", + rectablews.addRow([self._currstep, "", "", "", "", "", -1.0, laststep, -1.0, "profilews",\ "reflectionws", "Polynomial", "BkgdParm"]) else: self._currstep = numrows-1 @@ -711,6 +748,16 @@ def resetParametersGroups(tablews): class RefineProfileParameters: """ Class to refine profile parameters ONE step """ + + datawsname = None + inprofilewsname = None + inreflectionwsname = None + bkgdtype = None + bkgdtablewsname = None + outprofilewsname = None + outreflectionwsname = None + outbkgdtablewsname = None + def __init__(self, glog): """ Initialization """ @@ -774,7 +821,7 @@ def calculate(self, startx, endx): """ Do Le bail calculation """ if (self._inputIsSetup and self._outputIsSetup) is False: - raise NotImplementedError("Either input or output is not setup: inputIsStepUp = %s, outputIsSetup = %s" % + raise NotImplementedError("Either input or output is not setup: inputIsStepUp = %s, outputIsSetup = %s" %\ (str(self._inputIsSetup), str(self._outputIsSetup))) self.glog.information("**** Calculate: DataWorksapce = %s" % (str(self.datawsname))) @@ -782,20 +829,20 @@ def calculate(self, startx, endx): self.glog.information("**** Profile workspace = %s, Reflection workspace = %s" % ( self.inprofilewsname, self.inreflectionwsname)) - api.LeBailFit( - Function = 'Calculation', - InputWorkspace = self.datawsname, - OutputWorkspace = self.outwsname, - InputParameterWorkspace = self.inprofilewsname, - OutputParameterWorkspace= self.outprofilewsname, - InputHKLWorkspace = self.inreflectionwsname, - OutputPeaksWorkspace = self.outreflectionwsname, - FitRegion = '%f, %f' % (startx, endx), - PeakType = self.peaktype, - BackgroundType = self.bkgdtype, - UseInputPeakHeights = False, - PeakRadius = '8', - BackgroundParametersWorkspace = self.bkgdtablewsname + api.LeBailFit(\ + Function = 'Calculation',\ + InputWorkspace = self.datawsname,\ + OutputWorkspace = self.outwsname,\ + InputParameterWorkspace = self.inprofilewsname,\ + OutputParameterWorkspace= self.outprofilewsname,\ + InputHKLWorkspace = self.inreflectionwsname,\ + OutputPeaksWorkspace = self.outreflectionwsname,\ + FitRegion = '%f, %f' % (startx, endx),\ + PeakType = self.peaktype,\ + BackgroundType = self.bkgdtype,\ + UseInputPeakHeights = False,\ + PeakRadius = '8',\ + BackgroundParametersWorkspace = self.bkgdtablewsname\ ) return @@ -819,29 +866,29 @@ def refine(self, numsteps, parameternames, startx, endx): # UpdatePeakParameterTableValue(). It is not a real new table workspace, but a link # to the 'inprofilewsname' # There must be something wrong in AnalysisDataService. - api.UpdatePeakParameterTableValue( - InputWorkspace = self.inprofilewsname, - Column = "FitOrTie", + api.UpdatePeakParameterTableValue(\ + InputWorkspace = self.inprofilewsname,\ + Column = "FitOrTie",\ NewStringValue = "tie") - api.UpdatePeakParameterTableValue( - InputWorkspace = self.inprofilewsname, - Column = "FitOrTie", - ParameterNames = parameternames, + api.UpdatePeakParameterTableValue(\ + InputWorkspace = self.inprofilewsname,\ + Column = "FitOrTie",\ + ParameterNames = parameternames,\ NewStringValue = "fit") # Limit the range of MC if parameternames.count("Width") > 0: #self.cwl = 1.33 - UpdatePeakParameterTableValue( - InputWorkspace = self.inprofilewsname, - Column = "Min", - ParameterNames = ["Width"], + UpdatePeakParameterTableValue(\ + InputWorkspace = self.inprofilewsname,\ + Column = "Min",\ + ParameterNames = ["Width"],\ NewFloatValue = 0.50) #cwl*0.25) - UpdatePeakParameterTableValue( - InputWorkspace = self.inprofilewsname, - Column = "Max", - ParameterNames = ["Width"], + UpdatePeakParameterTableValue(\ + InputWorkspace = self.inprofilewsname,\ + Column = "Max",\ + ParameterNames = ["Width"],\ NewFloatValue = 1.25) #cwl*4.0) # Generate Monte carlo table @@ -853,26 +900,26 @@ def refine(self, numsteps, parameternames, startx, endx): else: raise NotImplementedError("Peak type %s is not supported to set up MC table." % (self.peaktype)) - api.LeBailFit( - InputWorkspace = self.datawsname, - OutputWorkspace = self.outwsname, - InputParameterWorkspace = self.inprofilewsname, - OutputParameterWorkspace = self.outprofilewsname, - InputHKLWorkspace = self.inreflectionwsname, - OutputPeaksWorkspace = self.outreflectionwsname, - FitRegion = '%f, %f' % (startx, endx), - Function = 'MonteCarlo', - NumberMinimizeSteps = numsteps, - PeakType = self.peaktype, - BackgroundType = self.bkgdtype, - BackgroundParametersWorkspace = self.bkgdtablewsname, - UseInputPeakHeights = False, - PeakRadius ='8', - Minimizer = 'Levenberg-Marquardt', - MCSetupWorkspace = str(wsname), - Damping = '5.0', - RandomSeed = 0, - AnnealingTemperature = 100.0, + api.LeBailFit(\ + InputWorkspace = self.datawsname,\ + OutputWorkspace = self.outwsname,\ + InputParameterWorkspace = self.inprofilewsname,\ + OutputParameterWorkspace = self.outprofilewsname,\ + InputHKLWorkspace = self.inreflectionwsname,\ + OutputPeaksWorkspace = self.outreflectionwsname,\ + FitRegion = '%f, %f' % (startx, endx),\ + Function = 'MonteCarlo',\ + NumberMinimizeSteps = numsteps,\ + PeakType = self.peaktype,\ + BackgroundType = self.bkgdtype,\ + BackgroundParametersWorkspace = self.bkgdtablewsname,\ + UseInputPeakHeights = False,\ + PeakRadius ='8',\ + Minimizer = 'Levenberg-Marquardt',\ + MCSetupWorkspace = str(wsname),\ + Damping = '5.0',\ + RandomSeed = 0,\ + AnnealingTemperature = 100.0,\ DrunkenWalk = True) # ENDIF (step) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py index a6c9e59a75d2..e0640213e80d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty from mantid.simpleapi import * from mantid.kernel import StringMandatoryValidator, Direction @@ -125,7 +126,7 @@ def __init__(self, filenames): # any are missing. missing_files = list(ifilterfalse(os.path.exists, filenames)) if len(missing_files) > 0: - raise ValueError("One or more files are missing: " + + raise ValueError("One or more files are missing: " +\ str(missing_files)) self._filenames = filenames @@ -188,11 +189,11 @@ def PyInit(self): '', StringMandatoryValidator(), doc='The range of runs to retrieve the run info for. E.g. "100-105".') - self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output),\ doc= """The name of the TableWorkspace that will be created. '''You must specify a name that does not already exist.''' """) def PyExec(self): - PROP_NAMES = ["inst_abrv", "run_number", "user_name", "run_title", + PROP_NAMES = ["inst_abrv", "run_number", "user_name", "run_title",\ "hd_dur"] # Not all ISIS run files have the relevant prop_names, but we may as @@ -203,7 +204,7 @@ def PyExec(self): # Ensure workspace does not already exist. output_ws_name = self.getPropertyValue("OutputWorkspace") if mtd.doesExist(output_ws_name): - raise ValueError("Workspace \"" + output_ws_name + "\" already " + raise ValueError("Workspace \"" + output_ws_name + "\" already "\ "exists. Either delete it, or choose another workspace name.") # Check that all run files are available. diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py index c79e5ce731ba..ac929f70a0d8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import Direction, FloatBoundedValidator import mantid.simpleapi diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py index 563b0b4f3fee..eb63a744ec1d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py @@ -1,6 +1,6 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * -import os import sys import numpy as np @@ -18,11 +18,11 @@ def summary(self): return "Calculate the Wide Angle correction for SANS transmissions." def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("SampleData", "", direction = Direction.Input), + self.declareProperty(MatrixWorkspaceProperty("SampleData", "", direction = Direction.Input),\ "A workspace cropped to the detector to be reduced (the SAME as the input to [[Q1D]]); used to verify the solid angle. The workspace is not modified, just inspected.") - self.declareProperty(MatrixWorkspaceProperty("TransmissionData","",direction=Direction.Input), + self.declareProperty(MatrixWorkspaceProperty("TransmissionData","",direction=Direction.Input),\ "The transmission data calculated, referred to as T_0 in equations in discussion section") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace","",direction=Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace","",direction=Direction.Output),\ "The transmission corrected SANS data, normalised (divided) by T_0, see discussion section") def PyExec(self): @@ -33,7 +33,7 @@ def PyExec(self): trans = self.getProperty("TransmissionData").value # check transmission input workspace - if (len(trans.dataX(0)) != len(wd.dataX(0))): + if len(trans.dataX(0)) != len(wd.dataX(0)): raise RuntimeError("Uncompatible sizes. Transmission must have the same bins of sample values") if min(trans.dataY(0)) < 0: raise RuntimeError("Invalid workspace for transmission, it does not accept negative values.") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py index 829f922e370c..597b6da5e367 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init import mantid import mantid.api import mantid.simpleapi as api @@ -17,6 +18,33 @@ EVENT_WORKSPACE_ID = "EventWorkspace" class SNSPowderReduction(DataProcessorAlgorithm): + + _resampleX = None + _binning = None + _bin_in_dspace = None + _instrument = None + _filterBadPulses = None + _removePromptPulseWidth = None + _LRef = None + _DIFCref = None + _wavelengthMin = None + _vanPeakFWHM = None + _vanSmoothing = None + _scaleFactor = None + _outDir = None + _outPrefix = None + _outTypes = None + _infodict = None + _chunks = None + _splitws = None + _splitinfotablews = None + _normalisebycurrent = None + _lowResTOFoffset = None + _focusPos = None + _charTable = None + iparmFile = None + _info = None + def category(self): return "Diffraction;PythonAlgorithms" @@ -34,7 +62,7 @@ def PyInit(self): self.declareProperty("Instrument", "PG3", StringListValidator(instruments), "Powder diffractometer's name") arrvalidator = IntArrayBoundedValidator() arrvalidator.setLower(0) - self.declareProperty(IntArrayProperty("RunNumber", values=[0], validator=arrvalidator, + self.declareProperty(IntArrayProperty("RunNumber", values=[0], validator=arrvalidator,\ direction=Direction.Input), "Number of sample run or 0 for only Vanadium and/or Background") extensions = [ "_histo.nxs", "_event.nxs", "_runinfo.xml"] self.declareProperty("Extension", "_event.nxs", @@ -52,9 +80,9 @@ def PyInit(self): doc="If specified overrides value in CharacterizationRunsFile. If -1 turns off correction.") self.declareProperty("VanadiumBackgroundNumber", defaultValue=0, validator=IntBoundedValidator(lower=-1), doc="If specified overrides value in CharacterizationRunsFile. If -1 turns off correction.") - self.declareProperty(FileProperty(name="CalibrationFile",defaultValue="",action=FileAction.Load, + self.declareProperty(FileProperty(name="CalibrationFile",defaultValue="",action=FileAction.Load,\ extensions = ["cal"])) - self.declareProperty(FileProperty(name="CharacterizationRunsFile",defaultValue="",action=FileAction.OptionalLoad, + self.declareProperty(FileProperty(name="CharacterizationRunsFile",defaultValue="",action=FileAction.OptionalLoad,\ extensions = ["txt"]),"File with characterization runs denoted") self.declareProperty("UnwrapRef", 0., "Reference total flight path for frame unwrapping. Zero skips the correction") @@ -67,7 +95,7 @@ def PyInit(self): self.declareProperty("MaxChunkSize", 0.0, "Specify maximum Gbytes of file to read in one chunk. Default is whole file.") self.declareProperty("FilterCharacterizations", False, "Filter the characterization runs using above parameters. This only works for event files.") - self.declareProperty(FloatArrayProperty("Binning", values=[0.,0.,0.], + self.declareProperty(FloatArrayProperty("Binning", values=[0.,0.,0.],\ direction=Direction.Input), "Positive is linear bins, negative is logorithmic") self.declareProperty("ResampleX", 0, "Number of bins in x-axis. Non-zero value overrides \"Params\" property. Negative value means logorithmic binning.") @@ -102,12 +130,12 @@ def PyInit(self): self.declareProperty("CompressTOFTolerance", 0.01, "Tolerance to compress events in TOF.") - self.declareProperty(StringArrayProperty("FrequencyLogNames", ["SpeedRequest1", "Speed1", "frequency"], - direction=Direction.Input), + self.declareProperty(StringArrayProperty("FrequencyLogNames", ["SpeedRequest1", "Speed1", "frequency"],\ + direction=Direction.Input),\ "Possible log names for frequency.") - self.declareProperty(StringArrayProperty("WaveLengthLogNames", ["LambdaRequest", "lambda"], - direction=Direction.Input), + self.declareProperty(StringArrayProperty("WaveLengthLogNames", ["LambdaRequest", "lambda"],\ + direction=Direction.Input),\ "Candidate log names for wave length.") return @@ -212,7 +240,7 @@ def PyExec(self): runnumber = temp self.log().information("[Sum] Process run number %s. " %(str(runnumber))) - temp = self._focusChunks(temp, SUFFIX, timeFilterWall, calib, + temp = self._focusChunks(temp, SUFFIX, timeFilterWall, calib,\ preserveEvents=preserveEvents) tempinfo = self._getinfo(temp) @@ -230,7 +258,7 @@ def PyExec(self): % (tempinfo["wavelength"], info["wavelength"])) samRun = api.Plus(LHSWorkspace=samRun, RHSWorkspace=temp, OutputWorkspace=samRun) if samRun.id() == EVENT_WORKSPACE_ID: - samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun, + samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun,\ Tolerance=COMPRESS_TOL_TOF) # 10ns api.DeleteWorkspace(str(temp)) # ENDIF @@ -248,7 +276,7 @@ def PyExec(self): # first round of processing the sample if not self.getProperty("Sum").value and samRun > 0: self._info = None - returned = self._focusChunks(samRun, SUFFIX, timeFilterWall, calib, self._splitws, + returned = self._focusChunks(samRun, SUFFIX, timeFilterWall, calib, self._splitws,\ preserveEvents=preserveEvents) if isinstance(returned, list): @@ -295,16 +323,16 @@ def PyExec(self): canFilterWall = timeFilterWall else: canFilterWall = (0., 0.) - if ("%s_%d" % (self._instrument, canRun)) in mtd: + if "%s_%d" % (self._instrument, canRun) in mtd: canRun = mtd["%s_%d" % (self._instrument, canRun)] else: - canRun = self._focusChunks(canRun, SUFFIX, canFilterWall, calib, + canRun = self._focusChunks(canRun, SUFFIX, canFilterWall, calib,\ preserveEvents=preserveEvents) canRun = api.ConvertUnits(InputWorkspace=canRun, OutputWorkspace=canRun, Target="TOF") smoothParams = self.getProperty("BackgroundSmoothParams").value if smoothParams != None and len(smoothParams)>0: - canRun = api.FFTSmooth(InputWorkspace=canRun, OutputWorkspace=canRun, Filter="Butterworth", + canRun = api.FFTSmooth(InputWorkspace=canRun, OutputWorkspace=canRun, Filter="Butterworth",\ Params=smoothParams,IgnoreXBins=True,AllSpectra=True) workspacelist.append(str(canRun)) @@ -318,7 +346,7 @@ def PyExec(self): vanFilterWall = timeFilterWall else: vanFilterWall = (0., 0.) - if ("%s_%d" % (self._instrument, vanRun)) in mtd: + if "%s_%d" % (self._instrument, vanRun) in mtd: vanRun = mtd["%s_%d" % (self._instrument, vanRun)] vanRun = api.ConvertUnits(InputWorkspace=vanRun, OutputWorkspace=vanRun, Target="TOF") else: @@ -375,13 +403,13 @@ def PyExec(self): # strip peaks if self.getProperty("StripVanadiumPeaks").value: vanRun = api.ConvertUnits(InputWorkspace=vanRun, OutputWorkspace=vanRun, Target="dSpacing") - vanRun = api.StripVanadiumPeaks(InputWorkspace=vanRun, OutputWorkspace=vanRun, FWHM=self._vanPeakFWHM, - PeakPositionTolerance=self.getProperty("VanadiumPeakTol").value, + vanRun = api.StripVanadiumPeaks(InputWorkspace=vanRun, OutputWorkspace=vanRun, FWHM=self._vanPeakFWHM,\ + PeakPositionTolerance=self.getProperty("VanadiumPeakTol").value,\ BackgroundType="Quadratic", HighBackground=True) else: self.log().information("Not strip vanadium peaks") vanRun = api.ConvertUnits(InputWorkspace=vanRun, OutputWorkspace=vanRun, Target="TOF") - vanRun = api.FFTSmooth(InputWorkspace=vanRun, OutputWorkspace=vanRun, Filter="Butterworth", + vanRun = api.FFTSmooth(InputWorkspace=vanRun, OutputWorkspace=vanRun, Filter="Butterworth",\ Params=self._vanSmoothing,IgnoreXBins=True,AllSpectra=True) vanRun = api.SetUncertainties(InputWorkspace=vanRun, OutputWorkspace=vanRun) vanRun = api.ConvertUnits(InputWorkspace=vanRun, OutputWorkspace=vanRun, Target="TOF") @@ -400,7 +428,7 @@ def PyExec(self): samRun = api.ConvertToMatrixWorkspace(InputWorkspace=samRun, OutputWorkspace=samRun) samRun = api.Minus(LHSWorkspace=samRun, RHSWorkspace=canRun, OutputWorkspace=samRun) if samRun.id() == EVENT_WORKSPACE_ID: - samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun, + samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun,\ Tolerance=COMPRESS_TOL_TOF) # 10ns canRun = str(canRun) if vanRun is not None: @@ -412,7 +440,7 @@ def PyExec(self): normalized = False if samRun.id() == EVENT_WORKSPACE_ID: - samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun, + samRun = api.CompressEvents(InputWorkspace=samRun, OutputWorkspace=samRun,\ Tolerance=COMPRESS_TOL_TOF) # 5ns/ # make sure there are no negative values - gsas hates them @@ -504,7 +532,7 @@ def _loadData(self, runnumber, extension, filterWall=None, outname=None, **chunk if isEventWS is True: # Event workspace - self.log().information("FilterBadPulses reduces number of events from %d to %d (under %s percent) of workspace %s." % ( + self.log().information("FilterBadPulses reduces number of events from %d to %d (under %s percent) of workspace %s." % (\ numeventsbefore, wksp.getNumberEvents(), str(self._filterBadPulses), str(wksp))) return wksp @@ -610,13 +638,13 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, # Splitting workspace basename = str(temp) if self._splitinfotablews is None: - api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename, + api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename,\ SplitterWorkspace=splitwksp, GroupWorkspaces=True) else: self.log().information("SplitterWorkspace = %s, Information Workspace = %s. " % ( str(splitwksp), str(self._splitinfotablews))) - api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename, - SplitterWorkspace=splitwksp, InformationWorkspace = str(self._splitinfotablews), + api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename,\ + SplitterWorkspace=splitwksp, InformationWorkspace = str(self._splitinfotablews),\ GroupWorkspaces=True) # ENDIF wsgroup = mtd[basename] @@ -662,19 +690,19 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, temp = tempwslist[itemp] # Align and focus focuspos = self._focusPos - temp = api.AlignAndFocusPowder(InputWorkspace=temp, OutputWorkspace=temp, CalFileName=calib, - Params=self._binning, ResampleX=self._resampleX, Dspacing=self._bin_in_dspace, - DMin=self._info["d_min"], DMax=self._info["d_max"], TMin=self._info["tof_min"], TMax=self._info["tof_max"], - PreserveEvents=preserveEvents, - RemovePromptPulseWidth=self._removePromptPulseWidth, CompressTolerance=COMPRESS_TOL_TOF, - UnwrapRef=self._LRef, LowResRef=self._DIFCref, LowResSpectrumOffset=self._lowResTOFoffset, + temp = api.AlignAndFocusPowder(InputWorkspace=temp, OutputWorkspace=temp, CalFileName=calib,\ + Params=self._binning, ResampleX=self._resampleX, Dspacing=self._bin_in_dspace,\ + DMin=self._info["d_min"], DMax=self._info["d_max"], TMin=self._info["tof_min"], TMax=self._info["tof_max"],\ + PreserveEvents=preserveEvents,\ + RemovePromptPulseWidth=self._removePromptPulseWidth, CompressTolerance=COMPRESS_TOL_TOF,\ + UnwrapRef=self._LRef, LowResRef=self._DIFCref, LowResSpectrumOffset=self._lowResTOFoffset,\ CropWavelengthMin=self._wavelengthMin, **(focuspos)) for iws in xrange(temp.getNumberHistograms()): spec = temp.getSpectrum(iws) self.log().debug("[DBx131] ws %d: spectrum ID = %d. " % (iws, spec.getSpectrumNo())) if preserveEvents is True and isinstance(temp, mantid.api._api.IEventWorkspace) is True: - self.log().information("After being aligned and focussed workspace %s; Number of events = %d of chunk %d " % (str(temp), + self.log().information("After being aligned and focussed workspace %s; Number of events = %d of chunk %d " % (str(temp),\ temp.getNumberEvents(), ichunk)) # Rename and/or add to workspace of same splitter but different chunk @@ -698,7 +726,7 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, # Sum workspaces for all mpi tasks if HAVE_MPI: for itemp in xrange(numwksp): - wksplist[itemp] = api.GatherWorkspaces(InputWorkspace=wksplist[itemp], + wksplist[itemp] = api.GatherWorkspaces(InputWorkspace=wksplist[itemp],\ PreserveEvents=preserveEvents, AccumulationMethod="Add", OutputWorkspace=wksplist[itemp]) # ENDIF MPI @@ -715,7 +743,7 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, for itemp in xrange(numwksp): if wksplist[itemp].id() == EVENT_WORKSPACE_ID: - wksplist[itemp] = api.CompressEvents(InputWorkspace=wksplist[itemp], + wksplist[itemp] = api.CompressEvents(InputWorkspace=wksplist[itemp],\ OutputWorkspace=wksplist[itemp], Tolerance=COMPRESS_TOL_TOF) # 100ns try: @@ -779,12 +807,12 @@ def _save(self, wksp, info, normalized, pdfgetn): if "pdfgetn" in self._outTypes: pdfwksp = str(wksp)+"_norm" pdfwksp = api.SetUncertainties(InputWorkspace=wksp, OutputWorkspace=pdfwksp, SetError="sqrt") - api.SaveGSS(InputWorkspace=pdfwksp, Filename=filename+".getn", SplitFiles=False, Append=False, + api.SaveGSS(InputWorkspace=pdfwksp, Filename=filename+".getn", SplitFiles=False, Append=False,\ MultiplyByBinWidth=False, Bank=info["bank"], Format="SLOG", ExtendedHeader=True) api.DeleteWorkspace(pdfwksp) return # don't do the other bits of saving if "gsas" in self._outTypes: - api.SaveGSS(InputWorkspace=wksp, Filename=filename+".gsa", SplitFiles=False, Append=False, + api.SaveGSS(InputWorkspace=wksp, Filename=filename+".gsa", SplitFiles=False, Append=False,\ MultiplyByBinWidth=normalized, Bank=info["bank"], Format="SLOG", ExtendedHeader=True) if "fullprof" in self._outTypes: api.SaveFocusedXYE(InputWorkspace=wksp, StartAtBankNumber=info["bank"], Filename=filename+".dat") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py index 4ef3adb13c09..c4ea036d7f54 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SaveVulcanGSS.py @@ -1,8 +1,7 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * -import mantid.simpleapi as api -from mantid.api import AnalysisDataService class SaveVulcanGSS(PythonAlgorithm): """ Save GSS file for VULCAN @@ -24,17 +23,17 @@ def summary(self): def PyInit(self): """ Declare properties - """ - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), + """ + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input),\ "Focussed diffraction workspace to be exported to GSAS file. ") - self.declareProperty(FileProperty("BinFilename","", FileAction.Load, ['.dat']), + self.declareProperty(FileProperty("BinFilename","", FileAction.Load, ['.dat']),\ "Name of a data file containing the bin boundaries in Log(TOF). ") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output),\ "Name of rebinned matrix workspace. ") - self.declareProperty(FileProperty("GSSFilename","", FileAction.Save, ['.gda']), + self.declareProperty(FileProperty("GSSFilename","", FileAction.Save, ['.gda']),\ "Name of the output GSAS file. ") self.declareProperty("IPTS", 0, "IPTS number") @@ -42,7 +41,7 @@ def PyInit(self): self.declareProperty("GSSParmFileName", "", "GSAS parameter file name for this GSAS data file.") return - + def PyExec(self): """ Main Execution Body """ @@ -69,7 +68,7 @@ def PyExec(self): # Generate GSAS file outputws = self._saveGSAS(gsaws, outgssfilename) - + # Convert header and bank information ipts = self.getPropertyValue("IPTS") parmfname = self.getPropertyValue("GSSParmFileName") @@ -115,14 +114,14 @@ def _loadRefLogBinFile(self, logbinfilename): return vecPow10X - + def _rebinVdrive(self, inputws, vec_refT, outputwsname): """ Rebin to match VULCAN's VDRIVE-generated GSAS file Arguments: - inputws : focussed workspace - vec_refT: list of TOF bins """ - # Create a complicated bin parameter + # Create a complicated bin parameter params = [] for ibin in xrange(len(vec_refT)-1): x0 = vec_refT[ibin] @@ -133,7 +132,7 @@ def _rebinVdrive(self, inputws, vec_refT, outputwsname): # last bin x0 = vec_refT[-1] - xf = 2*dx + x0 + xf = 2*dx + x0 params.extend([x0, 2*dx, xf]) # Rebin @@ -155,7 +154,7 @@ def _rebinVdrive(self, inputws, vec_refT, outputwsname): # ENDFOR (i) # ENDFOR (iws) api.DeleteWorkspace(Workspace=tempws) - gsaws = api.CreateWorkspace(DataX=newvecx, DataY=newvecy, DataE=newvece, NSpec=numhist, + gsaws = api.CreateWorkspace(DataX=newvecx, DataY=newvecy, DataE=newvece, NSpec=numhist,\ UnitX="TOF", ParentWorkspace=inputws, OutputWorkspace=outputwsname) return gsaws @@ -167,8 +166,8 @@ def _saveGSAS(self, gsaws, gdafilename): # Convert from PointData to Histogram gsaws = api.ConvertToHistogram(InputWorkspace=gsaws, OutputWorkspace=str(gsaws)) - # Save - api.SaveGSS(InputWorkspace=gsaws, Filename=gdafilename, SplitFiles=False, Append=False, + # Save + api.SaveGSS(InputWorkspace=gsaws, Filename=gdafilename, SplitFiles=False, Append=False,\ Format="SLOG", MultiplyByBinWidth=False, ExtendedHeader=False, UseSpectrumNumberAsBankID=True) return gsaws @@ -181,18 +180,18 @@ def _rewriteGSSFile(self, gssfilename, newheader): gfile = open(gssfilename, "r") lines = gfile.readlines() gfile.close() - + # New file filebuffer = "" filebuffer += newheader - + inbank = False banklines = [] for line in lines: cline = line.strip() if len(cline) == 0: continue - + if line.startswith("BANK"): # Indicate a new bank if len(banklines) == 0: @@ -200,41 +199,41 @@ def _rewriteGSSFile(self, gssfilename, newheader): inbank = True banklines.append(line.strip("\n")) else: - # bank line for non-first bank. + # bank line for non-first bank. tmpbuffer = self._rewriteOneBankData(banklines) filebuffer += tmpbuffer banklines = [line] # ENDIFELSE - elif (inbank is True and cline.startswith("#") is False): + elif inbank is True and cline.startswith("#") is False: # Write data line banklines.append(line.strip("\n")) - + # ENDFOR - - if len(banklines) > 0: - tmpbuffer = self._rewriteOneBankData(banklines) + + if len(banklines) > 0: + tmpbuffer = self._rewriteOneBankData(banklines) filebuffer += tmpbuffer else: raise NotImplementedError("Impossible to have this") - + # Overwrite the original file ofile = open(gssfilename, "w") ofile.write(filebuffer) ofile.close() - + return - + def _genVulcanGSSHeader(self, ws, gssfilename, ipts, parmfname): """ """ from datetime import datetime import os.path - + # Get necessary information title = ws.getTitle() - - run = ws.getRun() + + run = ws.getRun() # Get information on start/stop processtime = True @@ -249,45 +248,45 @@ def _genVulcanGSSHeader(self, ws, gssfilename, ipts, parmfname): # property run_start and duration exist runstart_sec = runstart.split(".")[0] runstart_ns = runstart.split(".")[1] - + utctime = datetime.strptime(runstart_sec, '%Y-%m-%dT%H:%M:%S') time0=datetime.strptime("1990-01-01T0:0:0",'%Y-%m-%dT%H:%M:%S') - + delta = utctime-time0 - try: + try: total_nanosecond_start = int(delta.total_seconds()*int(1.0E9)) + int(runstart_ns) - except: - total_seconds = delta.days*24*3600 + delta.seconds + except: + total_seconds = delta.days*24*3600 + delta.seconds total_nanosecond_start = total_seconds * int(1.0E9) + int(runstart_ns) total_nanosecond_stop = total_nanosecond_start + int(duration*1.0E9) else: # not both property is found total_nanosecond_start = 0 total_nanosecond_stop = 0 - + self.log().debug("Start = %d, Stop = %d" % (total_nanosecond_start, total_nanosecond_stop)) - + # Construct new header newheader = "" - + if len(title) > 80: title = title[0:80] newheader += "%-80s\n" % (title) - + newheader += "%-80s\n" % ( "Instrument parameter file: %s" %(parmfname) ) - + newheader += "%-80s\n" % ( "#IPTS: %s" % (str(ipts)) ) - + newheader += "%-80s\n" % ( "#binned by: Mantid" ) - + newheader += "%-80s\n" % ( "#GSAS file name: %s" % (os.path.basename(gssfilename)) ) - + newheader += "%-80s\n" % ( "#GSAS IPARM file: %s" % (parmfname) ) - + newheader += "%-80s\n" % ( "#Pulsestart: %d" % (total_nanosecond_start) ) - + newheader += "%-80s\n" % ( "#Pulsestop: %d" % (total_nanosecond_stop) ) - + return newheader @@ -295,33 +294,33 @@ def _rewriteOneBankData(self, banklines): """ first line is for bank information """ wbuf = "" - + # Rewrite bank lines bankline = banklines[0].strip() terms = bankline.split() tofmin = float(banklines[1].split()[0]) tofmax = float(banklines[-1].split()[0]) - + terms[5] = "%.1f" % (tofmin) terms[6] = "%.1f" % (tofmax) - + newbankline = "" - + # title for t in terms: newbankline += "%s " % (t) wbuf = "%-80s\n" % (newbankline) - + # data for i in xrange(1, len(banklines)): - cline = banklines[i] - + cline = banklines[i] + terms = cline.split() try: tof = float(terms[0]) y = float(terms[1]) e = float(terms[2]) - + x_s = "%.1f" % (tof) y_s = "%.1f" % (y) e_s = "%.2f" % (e) @@ -333,7 +332,7 @@ def _rewriteOneBankData(self, banklines): wbuf += "%-80s\n" % (temp) # ENDFOR - + return wbuf diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py index 7ed8baf4d4f2..fac88e2cbd3b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py @@ -1,5 +1,6 @@ -from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory, FileProperty, FileAction -from mantid.kernel import Direction, StringListValidator +#pylint: disable=no-init,invalid-name +from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory +from mantid.kernel import Direction import warnings _OUTPUTLEVEL = "NOOUTPUT" @@ -7,6 +8,9 @@ class SelectPowderDiffPeaks(PythonAlgorithm): """ Algorithm to select the powder diffraction peaks for Le Bail Fit """ + + mPeaks = None + def category(self): """ """ @@ -23,13 +27,13 @@ def summary(self): def PyInit(self): """ Declare properties """ - self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Input), + self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Input),\ "Name of Table Workspace containing peak parameters.") - self.declareProperty(ITableWorkspaceProperty("ZscoreWorkspace", "", Direction.Input), + self.declareProperty(ITableWorkspaceProperty("ZscoreWorkspace", "", Direction.Input),\ "Name of Table Workspace containing z-score for the peak parametrs.") - self.declareProperty(ITableWorkspaceProperty("OutputBraggPeakParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("OutputBraggPeakParameterWorkspace", "", Direction.Output),\ "Name of Table Workspace containing the filtered peaks' parameters.") self.declareProperty("MinimumPeakHeight", 0.0, "Minimum peak height allowed for the peaks to fit. ") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py index b91261511d0c..b3cbfdc1117b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py @@ -1,10 +1,9 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * from mantid.simpleapi import (DeleteWorkspace, ExtractSingleSpectrum, RenameWorkspace, ConjoinWorkspaces, Transpose) import numpy as np -import os - class SortByQVectors(PythonAlgorithm): """ Sorts spectra from a workspace diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py index 700ec5b13b40..d5a388c7d857 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py @@ -1,9 +1,9 @@ -from mantid.api import PythonAlgorithm, AlgorithmFactory,WorkspaceProperty,PropertyMode +#pylint: disable=no-init,invalid-name +from mantid.api import PythonAlgorithm, AlgorithmFactory from mantid.kernel import Direction,IntArrayProperty, FloatArrayProperty import mantid,math,numpy - class SortDetectors(PythonAlgorithm): """ Sort detectors by distance """ @@ -25,21 +25,23 @@ def summary(self): def PyInit(self): """ Declare properties """ - self.declareProperty(mantid.api.WorkspaceProperty("Workspace","",direction=mantid.kernel.Direction.Input, validator=mantid.api.InstrumentValidator()), "Input workspace") + self.declareProperty(mantid.api.WorkspaceProperty("Workspace", "", + direction=mantid.kernel.Direction.Input, + validator=mantid.api.InstrumentValidator()), + "Input workspace") - self.declareProperty(IntArrayProperty("UpstreamSpectra",Direction.Output)) - self.declareProperty(FloatArrayProperty("UpstreamDetectorDistances",Direction.Output)) - self.declareProperty(IntArrayProperty("DownstreamSpectra",Direction.Output)) - self.declareProperty(FloatArrayProperty("DownstreamDetectorDistances",Direction.Output)) - return + self.declareProperty(IntArrayProperty("UpstreamSpectra", Direction.Output)) + self.declareProperty(FloatArrayProperty("UpstreamDetectorDistances", Direction.Output)) + self.declareProperty(IntArrayProperty("DownstreamSpectra", Direction.Output)) + self.declareProperty(FloatArrayProperty("DownstreamDetectorDistances", Direction.Output)) def PyExec(self): """ Main execution body """ - w = self.getProperty("Workspace").value - samplePos=w.getInstrument().getSample().getPos() - moderatorPos=w.getInstrument().getSource().getPos() - incident=samplePos-moderatorPos + workspace = self.getProperty("Workspace").value + samplePos = workspace.getInstrument().getSample().getPos() + moderatorPos = workspace.getInstrument().getSource().getPos() + incident = samplePos - moderatorPos upstream=[] upinds=[] @@ -47,8 +49,8 @@ def PyExec(self): downstream=[] downinds=[] downdist=[] - for i in range(w.getNumberHistograms()): - detPos=w.getDetector(i).getPos() + for i in range(workspace.getNumberHistograms()): + detPos=workspace.getDetector(i).getPos() scattered=detPos-samplePos if abs(scattered.angle(incident))>0.999*math.pi: upstream.append((i,scattered.norm())) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py index 39c81a9f31a3..216a6f0a1b05 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py @@ -1,24 +1,32 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * import numpy as np -import operator class SortXAxis(PythonAlgorithm): def category(self): return "Transforms\\Axes" + def name(self): return "SortXAxis" + def summary(self): return "Clones the input MatrixWorkspace(s) and orders the x-axis in an ascending fashion." + def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", defaultValue="", direction=Direction.Input), doc="Input workspace") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", defaultValue="", direction=Direction.Output), doc="Sorted Output Workspace") + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", defaultValue="", + direction=Direction.Input), + doc="Input workspace") + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", defaultValue="", + direction=Direction.Output), + doc="Sorted Output Workspace") + def PyExec(self): input_ws = self.getProperty('InputWorkspace').value @@ -28,19 +36,19 @@ def PyExec(self): api.CloneWorkspace(InputWorkspace=input_ws, OutputWorkspace=output_ws) for i in range(0, num_specs): - x = input_ws.readX(i) - y = input_ws.readY(i) - e = input_ws.readE(i) + x_data = input_ws.readX(i) + y_data = input_ws.readY(i) + e_data = input_ws.readE(i) - indexes = x.argsort() + indexes = x_data.argsort() - x_ordered = x[indexes] + x_ordered = x_data[indexes] if input_ws.isHistogramData(): - max_index = np.argmax(indexes) - indexes = np.delete(indexes, max_index) + max_index = np.argmax(indexes) + indexes = np.delete(indexes, max_index) - y_ordered = y[indexes] - e_ordered = e[indexes] + y_ordered = y_data[indexes] + e_ordered = e_data[indexes] mtd[output_ws].setX(i, x_ordered) mtd[output_ws].setY(i, y_ordered) @@ -48,6 +56,5 @@ def PyExec(self): self.setProperty('OutputWorkspace', output_ws) -############################################################################################# AlgorithmFactory.subscribe(SortXAxis()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py index 39cfe0bbbbcc..9de958469e28 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py @@ -1,5 +1,5 @@ +#pylint: disable=no-init,invalid-name from mantid.api import PythonAlgorithm, AlgorithmFactory -import mantid.simpleapi from mantid.kernel import FloatBoundedValidator,Direction from numpy import sqrt,floor @@ -10,11 +10,11 @@ def __init__(self,minv,maxv): self.min=minv self.max=maxv def overlap(self, other): - if (other.max >self.min and other.max self.min and other.max self.min and other.minself.min and other.minself.max): + if other.minself.max: return True return False @@ -39,7 +39,7 @@ def summary(self): def PyInit(self): """ Declare properties """ - val=mantid.kernel.FloatBoundedValidator() + val=FloatBoundedValidator() val.setBounds(0.5,50) #reasonable incident nergy range for CNCS self.declareProperty("IncidentEnergy",0.,val,"Incident energy (0.5 to 50 meV)") self.declareProperty("TibMin",0.,Direction.Output) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibHYSPEC.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibHYSPEC.py index 50d32ed5451d..64aa3a82fa35 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibHYSPEC.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibHYSPEC.py @@ -1,5 +1,5 @@ +#pylint: disable=no-init from mantid.api import PythonAlgorithm, AlgorithmFactory -import mantid.simpleapi from mantid.kernel import FloatBoundedValidator,Direction,logger from numpy import sqrt,divide @@ -25,7 +25,7 @@ def summary(self): def PyInit(self): """ Declare properties """ - val=mantid.kernel.FloatBoundedValidator() + val=FloatBoundedValidator() val.setBounds(3,100) #reasonable incident nergy range for HYSPEC self.declareProperty("IncidentEnergy",0.,val,"Incident energy (3 to 100 meV)") self.declareProperty("TibMin",0.,Direction.Output) @@ -54,9 +54,9 @@ def PyExec(self): pre_lead_us = 16667 * index_under_frame pre_tail_us = pre_lead_us + tail_length_us post_lead_us = 16667 * (1+ index_under_frame) - post_tail_us = post_lead_us + tail_length_us - E_final_meV = -1 - E_transfer_meV = -1 + #post_tail_us = post_lead_us + tail_length_us + #E_final_meV = -1 + #E_transfer_meV = -1 # finding an ok TIB range MinTIB_us = 2000.0 slop_frac = 0.2 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py index 4f498695472c..3e5ecae529fc 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Symmetrise.py @@ -1,7 +1,10 @@ +#pylint: disable=no-init,invalid-name from mantid import logger, mtd -from mantid.api import PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, ITableWorkspaceProperty, PropertyMode +from mantid.api import PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, \ + ITableWorkspaceProperty, PropertyMode from mantid.kernel import Direction, IntArrayProperty -from mantid.simpleapi import CreateWorkspace, CopyLogs, CopySample, CopyInstrumentParameters, SaveNexusProcessed, CreateEmptyTableWorkspace, RenameWorkspace +from mantid.simpleapi import CreateWorkspace, CopyLogs, CopyInstrumentParameters, \ + SaveNexusProcessed, CreateEmptyTableWorkspace, RenameWorkspace import math import os.path @@ -10,6 +13,18 @@ class Symmetrise(PythonAlgorithm): + _sample = None + _x_min = None + _x_max = None + _plot = None + _save = None + _spectra_range = None + _output_workspace = None + _props_output_workspace = None + _positive_min_index = None + _positive_max_index = None + _negative_min_index = None + def category(self): return 'PythonAlgorithms' @@ -33,11 +48,12 @@ def PyInit(self): self.declareProperty('Save', defaultValue=False, doc='Switch saving result to nxs file Off/On') - self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '', + self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '',\ Direction.Output), doc='Name to call the output workspace.') self.declareProperty(ITableWorkspaceProperty('OutputPropertiesTable', '', - Direction.Output, PropertyMode.Optional), doc='Name to call the properties output table workspace.') + Direction.Output, PropertyMode.Optional), + doc='Name to call the properties output table workspace.') def PyExec(self): @@ -61,8 +77,8 @@ def PyExec(self): # Get slice bounds of array try: self._calculate_array_points(sample_x, sample_array_len) - except Exception as e: - raise RuntimeError('Failed to calculate array slice boundaries: %s' % e.message) + except Exception as exc: + raise RuntimeError('Failed to calculate array slice boundaries: %s' % exc.message) max_sample_index = sample_array_len - 1 centre_range_len = self._positive_min_index + self._negative_min_index @@ -89,8 +105,10 @@ def PyExec(self): v_axis_data = mtd[self._sample].getAxis(1).extractValues() # Take the values we need from the original vertical axis - min_spectrum_index = mtd[self._sample].getIndexFromSpectrumNumber(int(self._spectra_range[0])) - max_spectrum_index = mtd[self._sample].getIndexFromSpectrumNumber(int(self._spectra_range[1])) + min_spectrum_index = mtd[self._sample].getIndexFromSpectrumNumber( + int(self._spectra_range[0])) + max_spectrum_index = mtd[self._sample].getIndexFromSpectrumNumber( + int(self._spectra_range[1])) new_v_axis_data = v_axis_data[min_spectrum_index:max_spectrum_index + 1] # Create an empty workspace with enough storage for the new data @@ -178,7 +196,8 @@ def validateInputs(self): num_sample_spectra, _ = CheckHistZero(input_workspace_name) min_spectra_number = mtd[input_workspace_name].getSpectrum(0).getSpectrumNo() - max_spectra_number = mtd[input_workspace_name].getSpectrum(num_sample_spectra - 1).getSpectrumNo() + max_spectra_number = mtd[input_workspace_name].getSpectrum( + num_sample_spectra - 1).getSpectrumNo() if spec_min < min_spectra_number: issues['SpectraRange'] = 'Minimum spectra must be greater than or equal to %d' % min_spectra_number @@ -239,7 +258,8 @@ def _setup(self): if len(self._spectra_range) == 0: num_sample_spectra, _ = CheckHistZero(self._sample) min_spectra_number = mtd[self._sample].getSpectrum(0).getSpectrumNo() - max_spectra_number = mtd[self._sample].getSpectrum(num_sample_spectra - 1).getSpectrumNo() + max_spectra_number = mtd[self._sample].getSpectrum( + num_sample_spectra - 1).getSpectrumNo() self._spectra_range = [min_spectra_number, max_spectra_number] self._output_workspace = self.getPropertyValue('OutputWorkspace') @@ -298,7 +318,8 @@ def _generate_props_table(self): props_table.addColumn('int', 'PositiveXMinIndex') props_table.addColumn('int', 'PositiveXMaxIndex') - props_table.addRow([int(self._negative_min_index), int(self._positive_min_index), int(self._positive_max_index)]) + props_table.addRow([int(self._negative_min_index), int(self._positive_min_index), + int(self._positive_max_index)]) self.setProperty('OutputPropertiesTable', self._props_output_workspace) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/TestWorkspaceGroupProperty.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/TestWorkspaceGroupProperty.py index 8c30cd6b4d00..876e42219b17 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/TestWorkspaceGroupProperty.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/TestWorkspaceGroupProperty.py @@ -1,8 +1,6 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * -import numpy as np - -import os class TestWorkspaceGroupProperty(PythonAlgorithm): """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py index 3063fe07e683..dab3299894d9 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/USANSSimulation.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * @@ -17,7 +18,7 @@ def summary(self): def PyInit(self): self.declareProperty("TwoTheta", 0.01, "Scattering angle in degrees") - self.declareProperty(FloatArrayProperty("WavelengthPeaks", values=[0.72, 0.9, 1.2, 1.8, 3.6], + self.declareProperty(FloatArrayProperty("WavelengthPeaks", values=[0.72, 0.9, 1.2, 1.8, 3.6],\ direction=Direction.Input), "Wavelength peaks out of the monochromator") self.declareProperty("CountTime", 1000.0, "Fake count time") @@ -140,7 +141,7 @@ def _sphere_model(self, q, scale): bes = 3.0*(math.sin(qr)-qr*math.cos(qr))/(qr*qr*qr) if not qr == 0.0 else 1.0 vol = 4.0*math.pi/3.0*radius*radius*radius f2 = vol*bes*bes*1.0e-6 - return(scale*f2+bck) + return scale*f2+bck ############################################################################################# AlgorithmFactory.subscribe(USANSSimulation()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py index eb15cd0d59e6..998775666509 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py @@ -1,13 +1,16 @@ +#pylint: disable=no-init,invalid-name import mantid import mantid.api import mantid.kernel import mantid.simpleapi -from numpy import arange class UpdatePeakParameterTableValue(mantid.api.PythonAlgorithm): """ Class to generate grouping file """ + tableColNames = None + parameternames = None + def category(self): """ Mantid required """ @@ -74,7 +77,7 @@ def PyExec(self): if colnamedict.has_key(colname): icolumn = colnamedict[colname] else: - raise NotImplementedError("Column name %s does not exist in TableWorkspace %s" + raise NotImplementedError("Column name %s does not exist in TableWorkspace %s"\ % (colname, tablews.name())) # 3. Set value diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py index dd677756799f..d78656c67617 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * @@ -6,6 +7,9 @@ class VesuvioResolution(PythonAlgorithm): + _spectrum_index = None + _mass = None + def category(self): return 'Inelastic' @@ -111,8 +115,9 @@ def _calculate_resolution(self, workspace, output_ws_name): fit.initialize() fit.setChild(True) mantid.simpleapi._set_properties(fit, function, InputWorkspace=workspace, MaxIterations=0, - CreateOutput=True, Output=fit_naming_stem, WorkspaceIndex=self._spectrum_index, - OutputCompositeMembers=True) + CreateOutput=True, Output=fit_naming_stem, + WorkspaceIndex=self._spectrum_index, + OutputCompositeMembers=True) fit.execute() fit_ws = fit.getProperty('OutputWorkspace').value diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ViewBOA.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ViewBOA.py index f60ce127a51f..cb180b688301 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ViewBOA.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ViewBOA.py @@ -1,11 +1,10 @@ +#pylint: disable=no-init,invalid-name from mantid.api import AlgorithmFactory -from mantid.api import PythonAlgorithm, WorkspaceFactory, FileProperty, FileAction, WorkspaceProperty -from mantid.kernel import Direction, StringListValidator, ConfigServiceImpl +from mantid.api import PythonAlgorithm +from mantid.kernel import Direction import mantid.simpleapi from mantid.simpleapi import mtd import datetime -import math -import os.path class ViewBOA(PythonAlgorithm): def category(self): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py index e8aa6020978f..e3754e3433b8 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CreateCalibrationWorkspace.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * @@ -7,6 +8,14 @@ class CreateCalibrationWorkspace(DataProcessorAlgorithm): + _input_files = None + _out_ws = None + _peak_range = None + _back_range = None + _spec_range = None + _intensity_scale = None + _plot = None + def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' @@ -17,19 +26,19 @@ def PyInit(self): self.declareProperty(StringArrayProperty(name='InputFiles'), doc='Comma separated list of input files') - self.declareProperty(WorkspaceProperty('OutputWorkspace', '', + self.declareProperty(WorkspaceProperty('OutputWorkspace', '',\ direction=Direction.Output), doc='Output workspace for calibration data') - self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1], + self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1],\ validator=IntArrayMandatoryValidator()), doc='Range of detectors') - self.declareProperty(FloatArrayProperty(name='PeakRange', values=[0.0, 100.0], + self.declareProperty(FloatArrayProperty(name='PeakRange', values=[0.0, 100.0],\ validator=FloatArrayMandatoryValidator()), doc='') - self.declareProperty(FloatArrayProperty(name='BackgroundRange', values=[0.0, 1000.0], + self.declareProperty(FloatArrayProperty(name='BackgroundRange', values=[0.0, 1000.0],\ validator=FloatArrayMandatoryValidator()), doc='') @@ -79,8 +88,8 @@ def PyExec(self): (_, filename) = os.path.split(in_file) (root, _) = os.path.splitext(filename) try: - Load(Filename=in_file, OutputWorkspace=root, - SpectrumMin=int(self._spec_range[0]), SpectrumMax=int(self._spec_range[1]), + Load(Filename=in_file, OutputWorkspace=root,\ + SpectrumMin=int(self._spec_range[0]), SpectrumMax=int(self._spec_range[1]),\ LoadLogFiles=False) runs.append(root) except Exception as exc: @@ -94,7 +103,7 @@ def PyExec(self): else: calib_ws_name = runs[0] - CalculateFlatBackground(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name, + CalculateFlatBackground(InputWorkspace=calib_ws_name, OutputWorkspace=calib_ws_name,\ StartX=self._back_range[0], EndX=self._back_range[1], Mode='Mean') from inelastic_indirect_reduction_steps import NormaliseToUnityStep diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py index fba0c883eb6e..429609ee17cc 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CutMD.py @@ -1,23 +1,22 @@ +#pylint: disable=invalid-name,no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * import numpy as np -import os.path -import re import __builtin__ class Projection(object): u = "u" v = "v" w = "w" - + class ProjectionUnit(object): r = "r" a = "a" - - + + class CutMD(DataProcessorAlgorithm): - + def category(self): return 'MDAlgorithms' @@ -27,30 +26,30 @@ def summary(self): def PyInit(self): self.declareProperty(IMDEventWorkspaceProperty('InputWorkspace', '', direction=Direction.Input), doc='MDWorkspace to slice') - + self.declareProperty(ITableWorkspaceProperty('Projection', '', direction=Direction.Input, optional = PropertyMode.Optional), doc='Projection') - + self.declareProperty(FloatArrayProperty(name='P1Bin', values=[]), doc='Projection 1 binning') - + self.declareProperty(FloatArrayProperty(name='P2Bin', values=[]), doc='Projection 2 binning') - + self.declareProperty(FloatArrayProperty(name='P3Bin', values=[]), doc='Projection 3 binning') - + self.declareProperty(FloatArrayProperty(name='P4Bin', values=[]), doc='Projection 4 binning') - self.declareProperty(IMDWorkspaceProperty('OutputWorkspace', '', + self.declareProperty(IMDWorkspaceProperty('OutputWorkspace', '',\ direction=Direction.Output), doc='Output cut workspace') - + self.declareProperty(name="NoPix", defaultValue=False, doc="If False creates a full MDEventWorkspaces as output. True to create an MDHistoWorkspace as output. This is DND only in Horace terminology.") - + self.declareProperty(name="CheckAxes", defaultValue=True, doc="Check that the axis look to be correct, and abort if not.") - - + + def __calculate_steps(self, extents, horace_binning ): # Because the step calculations may involve moving the extents, we re-publish the extents. out_extents = extents @@ -61,13 +60,13 @@ def __calculate_steps(self, extents, horace_binning ): max_extent_index = (i*2) + 1 min_extent_index = (i*2) dim_range = extents[ max_extent_index ] - extents[ min_extent_index ] - + if n_arguments == 0: raise ValueError("binning parameter cannot be empty") elif n_arguments == 1: step_size = horace_binning[i][0] if step_size > dim_range: - step_size = dim_range + step_size = dim_range n_bins = int( dim_range / step_size) # Correct the max extent to fit n * step_size out_extents[max_extent_index] = extents[min_extent_index] + ( n_bins * step_size ) @@ -81,7 +80,7 @@ def __calculate_steps(self, extents, horace_binning ): step_size = horace_binning[i][1] dim_range = dim_max - dim_min if step_size > dim_range: - step_size = dim_range + step_size = dim_range n_bins = int( dim_range / step_size) # Correct the max extent to fit n * step_size out_extents[ max_extent_index ] = dim_min + ( n_bins * step_size ) @@ -90,40 +89,40 @@ def __calculate_steps(self, extents, horace_binning ): raise ValueError("Number of bins calculated to be < 1") out_n_bins.append( n_bins ) return out_extents, out_n_bins - + def __extents_in_current_projection(self, to_cut, dimension_index): - + dim = to_cut.getDimension(dimension_index) dim_min = dim.getMinimum() dim_max = dim.getMaximum() return (dim_min, dim_max) - + def __calculate_extents(self, v, u, w, limits): M=np.array([u,v,w]) Minv=np.linalg.inv(M) - + # unpack limits Hrange, Krange, Lrange = limits - + # Create a numpy 2D array. Makes finding minimums and maximums for each transformed coordinates over every corner easier. new_coords = np.empty([8, 3]) counter = 0 for h in Hrange: - for k in Krange: - for l in Lrange: - original_corner=np.array([h,k,l]) - new_coords[counter]=np.dot(original_corner, Minv) - counter += 1 - + for k in Krange: + for l in Lrange: + original_corner=np.array([h,k,l]) + new_coords[counter]=np.dot(original_corner, Minv) + counter += 1 + # Get the min max extents extents = list() for i in range(0,3): # Vertical slice down each corner for each dimension, then determine the max, min and use as extents extents.append(np.amin(new_coords[:,i])) extents.append(np.amax(new_coords[:,i])) - + return extents - + def __uvw_from_projection_table(self, projection_table): if not isinstance(projection_table, ITableWorkspace): I = np.identity(3) @@ -136,26 +135,26 @@ def __uvw_from_projection_table(self, projection_table): else: w = np.array(projection_table.column(Projection.w)) return (u, v, w) - + def __units_from_projection_table(self, projection_table): if not isinstance(projection_table, ITableWorkspace) or not "type" in projection_table.getColumnNames(): units = (ProjectionUnit.r, ProjectionUnit.r, ProjectionUnit.r) else: units = tuple(projection_table.column("type")) return units - - + + def __make_labels(self, projection): class Mapping: - + def __init__(self, replace): self.__replace = replace - + def replace(self, entry): if np.absolute(entry) == 1: if entry > 0: - return self.__replace + return self.__replace else: return "-" + self.__replace elif entry == 0: @@ -163,40 +162,40 @@ def replace(self, entry): else: return "%.2f%s" % ( entry, self.__replace ) return entry - - crystallographic_names = ['zeta', 'eta', 'xi' ] + + crystallographic_names = ['zeta', 'eta', 'xi' ] labels = list() for i in range(len(projection)): cmapping = Mapping(crystallographic_names[i]) labels.append( [cmapping.replace(x) for x in projection[i] ] ) - + return labels - + def __verify_projection_input(self, projection_table): if isinstance(projection_table, ITableWorkspace): column_names = set(projection_table.getColumnNames()) if not column_names == set([Projection.u, Projection.v, 'type']): - if not column_names == set([Projection.u, Projection.v, 'offsets', 'type']): - if not column_names == set([Projection.u, Projection.v, Projection.w, 'offsets', 'type']): - raise ValueError("Projection table schema is wrong! Column names received: " + str(column_names) ) + if not column_names == set([Projection.u, Projection.v, 'offsets', 'type']): + if not column_names == set([Projection.u, Projection.v, Projection.w, 'offsets', 'type']): + raise ValueError("Projection table schema is wrong! Column names received: " + str(column_names) ) if projection_table.rowCount() != 3: raise ValueError("Projection table expects 3 rows") - + def __scale_projection(self, (u, v, w), origin_units, target_units, to_cut): - + if set(origin_units) == set(target_units): return (u,v,w) # Nothing to do. - + ol = to_cut.getExperimentInfo(0).sample().getOrientedLattice() - + projection_scaled = [u, v, w] - + to_from_pairs = zip(origin_units, target_units) for i in range(len(to_from_pairs)) : - + proj = projection_scaled[i] d_star = 2 * np.pi * ol.dstar( float(proj[0]), float(proj[1]), float(proj[2]) ) - + from_unit, to_unit = to_from_pairs[i] if from_unit == to_unit: continue @@ -205,44 +204,44 @@ def __scale_projection(self, (u, v, w), origin_units, target_units, to_cut): else: # From rlu to inverse Anstroms projection_scaled[i] /= d_star return projection_scaled - - + + def PyExec(self): - + logger.warning('You are running algorithm %s that is the beta stage of development' % (self.name())) - + to_cut = self.getProperty("InputWorkspace").value - + ndims = to_cut.getNumDims() - + nopix = self.getProperty("NoPix").value - + projection_table = self.getProperty("Projection").value self.__verify_projection_input(projection_table) - + p1_bins = self.getProperty("P1Bin").value p2_bins = self.getProperty("P2Bin").value p3_bins = self.getProperty("P3Bin").value p4_bins_property = self.getProperty("P4Bin") - p4_bins = p4_bins_property.value - - x_extents = self.__extents_in_current_projection(to_cut, 0); - y_extents = self.__extents_in_current_projection(to_cut, 1); - z_extents = self.__extents_in_current_projection(to_cut, 2); - + p4_bins = p4_bins_property.value + + x_extents = self.__extents_in_current_projection(to_cut, 0) + y_extents = self.__extents_in_current_projection(to_cut, 1) + z_extents = self.__extents_in_current_projection(to_cut, 2) + projection = self.__uvw_from_projection_table(projection_table) target_units = self.__units_from_projection_table(projection_table) origin_units = (ProjectionUnit.r, ProjectionUnit.r, ProjectionUnit.r) # TODO. This is a hack! - + u,v,w = self.__scale_projection(projection, origin_units, target_units, to_cut) - + extents = self.__calculate_extents(v, u, w, ( x_extents, y_extents, z_extents ) ) extents, bins = self.__calculate_steps( extents, ( p1_bins, p2_bins, p3_bins ) ) - + if not p4_bins_property.isDefault: - if (ndims == 4): + if ndims == 4: n_args = len(p4_bins) - min, max = self.__extents_in_current_projection(to_cut, 3); + min, max = self.__extents_in_current_projection(to_cut, 3) d_range = max - min if n_args == 1: step_size = p4_bins[0] @@ -259,21 +258,21 @@ def PyExec(self): if step_size > dim_range: step_size = dim_range nbins = int( dim_range / step_size) - + extents.append(min) extents.append(max) bins.append(int(nbins)) - + e_units = to_cut.getDimension(3).getUnits() - + temp = list(target_units) temp.append(target_units) target_units = tuple(temp) else: raise ValueError("Cannot specify P4Bins unless the workspace is of sufficient dimensions") - + projection_labels = self.__make_labels(projection) - + cut_alg_name = "BinMD" if nopix else "SliceMD" ''' Actually perform the binning operation @@ -285,46 +284,46 @@ def PyExec(self): cut_alg.setProperty("NormalizeBasisVectors", False) cut_alg.setProperty("AxisAligned", False) # Now for the basis vectors. - + n_padding = __builtin__.max(0, ndims-3) - + for i in range(0, ndims): - - + + if i <= 2: - + label = projection_labels[i] unit = target_units[i] vec = list(projection[i]) + ( [0] * n_padding ) - + # These are always orthogonal to the rest. else: orthogonal_dimension = to_cut.getDimension(i) - label = orthogonal_dimension.getName() + label = orthogonal_dimension.getName() unit = orthogonal_dimension.getUnits() vec = [0] * ndims vec[i] = 1 - - value = "%s, %s, %s" % ( label, unit, ",".join(map(str, vec))) - cut_alg.setPropertyValue("BasisVector{0}".format(i) , value) - - + + value = "%s, %s, %s" % ( label, unit, ",".join(map(str, vec))) + cut_alg.setPropertyValue("BasisVector{0}".format(i) , value) + + cut_alg.setProperty("OutputExtents", extents) cut_alg.setProperty("OutputBins", bins) - + cut_alg.execute() - + slice = cut_alg.getProperty("OutputWorkspace").value - - + + # Attach the w-matrix (projection matrix) if slice.getNumExperimentInfo() > 0: u, v, w = projection w_matrix = np.array([u, v, w]).flatten().tolist() info = slice.getExperimentInfo(0) info.run().addProperty("W_MATRIX", w_matrix, True) - + self.setProperty("OutputWorkspace", slice) - - + + AlgorithmFactory.subscribe(CutMD) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py index ed313b04e543..8682789f4940 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * @@ -9,49 +10,67 @@ class DensityOfStates(PythonAlgorithm): + _float_regex = None + _temperature = None + _bin_width = None + _spec_type = None + _peak_func = None + _ws_name = None + _peak_width = None + _scale = None + _zero_threshold = None + _ions = None + _sum_contributions = None + _scale_by_cross_section = None + _calc_partial = None + _ion_dict = None + _partial_ion_numbers = None + _num_ions = None + _num_branches = None + def summary(self): return "Calculates phonon densities of states, Raman and IR spectrum." def PyInit(self): # Declare properties - self.declareProperty(FileProperty('File', '', action=FileAction.Load, - extensions = ["phonon", "castep"]), + self.declareProperty(FileProperty('File', '', action=FileAction.Load,\ + extensions = ["phonon", "castep"]),\ doc='Filename of the file.') - self.declareProperty(name='Function',defaultValue='Gaussian', - validator=StringListValidator(['Gaussian', 'Lorentzian']), + self.declareProperty(name='Function',defaultValue='Gaussian',\ + validator=StringListValidator(['Gaussian', 'Lorentzian']),\ doc="Type of function to fit to peaks.") - self.declareProperty(name='PeakWidth', defaultValue=10.0, + self.declareProperty(name='PeakWidth', defaultValue=10.0,\ doc='Set Gaussian/Lorentzian FWHM for broadening. Default is 10') - self.declareProperty(name='SpectrumType',defaultValue='DOS', - validator=StringListValidator(['IonTable', 'DOS', 'IR_Active', 'Raman_Active']), + self.declareProperty(name='SpectrumType',defaultValue='DOS',\ + validator=StringListValidator(['IonTable', 'DOS', 'IR_Active', 'Raman_Active']),\ doc="Type of intensities to extract and model (fundamentals-only) from .phonon.") - self.declareProperty(name='Scale', defaultValue=1.0, + self.declareProperty(name='Scale', defaultValue=1.0,\ doc='Scale the intesity by the given factor. Default is no scaling.') - self.declareProperty(name='BinWidth', defaultValue=1.0, + self.declareProperty(name='BinWidth', defaultValue=1.0,\ doc='Set histogram resolution for binning (eV or cm**-1). Default is 1') - self.declareProperty(name='Temperature', defaultValue=300.0, + self.declareProperty(name='Temperature', defaultValue=300.0,\ doc='Temperature to use (in raman spectrum modelling). Default is 300') - self.declareProperty(name='ZeroThreshold', defaultValue=3.0, + self.declareProperty(name='ZeroThreshold', defaultValue=3.0,\ doc='Ignore frequencies below the this threshold. Default is 3.0') - self.declareProperty(StringArrayProperty('Ions', Direction.Input), + self.declareProperty(StringArrayProperty('Ions', Direction.Input),\ doc="List of Ions to use to calculate partial density of states. If left blank, total density of states will be calculated") - self.declareProperty(name='SumContributions', defaultValue=False, + self.declareProperty(name='SumContributions', defaultValue=False,\ doc="Sum the partial density of states into a single workspace.") - self.declareProperty(name='ScaleByCrossSection', defaultValue='None', - validator=StringListValidator(['None', 'Total', 'Incoherent', 'Coherent']), + self.declareProperty(name='ScaleByCrossSection', defaultValue='None',\ + validator=StringListValidator(['None', 'Total', 'Incoherent', 'Coherent']),\ doc="Sum the partial density of states by the scattering cross section.") - self.declareProperty(WorkspaceProperty('OutputWorkspace', '', Direction.Output), + self.declareProperty(WorkspaceProperty('OutputWorkspace', '', Direction.Output),\ doc="Name to give the output workspace.") # Regex pattern for a floating point number @@ -124,7 +143,9 @@ def PyExec(self): if k in self._ions: partial_ions[k] = v - partial_workspaces, sum_workspace = self._compute_partial_ion_workflow(partial_ions, frequencies, eigenvectors, weights) + partial_workspaces, sum_workspace = self._compute_partial_ion_workflow( + partial_ions, frequencies, + eigenvectors, weights) if self._sum_contributions: # Discard the partial workspaces @@ -147,7 +168,9 @@ def PyExec(self): eigenvectors = file_data[4] - partial_workspaces, sum_workspace = self._compute_partial_ion_workflow(self._ion_dict, frequencies, eigenvectors, weights) + partial_workspaces, sum_workspace = self._compute_partial_ion_workflow( + self._ion_dict, frequencies, + eigenvectors, weights) # Discard the partial workspaces for partial_ws in partial_workspaces: @@ -288,7 +311,8 @@ def _compute_partial_ion_workflow(self, partial_ions, frequencies, eigenvectors, scattering_x_section = mtd[self._ws_name].mutableSample().getMaterial().totalScatterXSection() if self._scale_by_cross_section != 'None': - Scale(InputWorkspace=self._ws_name, OutputWorkspace=self._ws_name, Operation='Multiply', Factor=scattering_x_section) + Scale(InputWorkspace=self._ws_name, OutputWorkspace=self._ws_name, + Operation='Multiply', Factor=scattering_x_section) partial_workspaces.append(partial_ws_name) RenameWorkspace(self._ws_name, OutputWorkspace=partial_ws_name) @@ -300,9 +324,11 @@ def _compute_partial_ion_workflow(self, partial_ions, frequencies, eigenvectors, sum_workspace = '__dos_sum' # Collect spectra into a single workspace - AppendSpectra(OutputWorkspace=sum_workspace, InputWorkspace1=partial_workspaces[0], InputWorkspace2=partial_workspaces[1]) + AppendSpectra(OutputWorkspace=sum_workspace, InputWorkspace1=partial_workspaces[0], + InputWorkspace2=partial_workspaces[1]) for ws_idx in xrange(2, len(partial_workspaces)): - AppendSpectra(OutputWorkspace=sum_workspace, InputWorkspace1=sum_workspace, InputWorkspace2=partial_workspaces[ws_idx]) + AppendSpectra(OutputWorkspace=sum_workspace, InputWorkspace1=sum_workspace, + InputWorkspace2=partial_workspaces[ws_idx]) # Sum all spectra SumSpectra(InputWorkspace=sum_workspace, OutputWorkspace=total_workspace) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py index 4d22ae839387..6fe0dcb95ec4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py @@ -1,6 +1,6 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * -from mantid.simpleapi import Scale import math class EQSANSAzimuthalAverage1D(PythonAlgorithm): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py index 1f2648223ff7..31b11d3eaf20 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py @@ -1,6 +1,6 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * -import mantid.simpleapi as api import os class EQSANSDirectBeamTransmission(PythonAlgorithm): @@ -171,18 +171,18 @@ def _crop_and_compute(wl_min_prop, wl_max_prop, suffix): raise RuntimeError, "DirectBeamTransmission could not retrieve the %s property" % wl_max_prop rebin_params = "%4.1f,%4.1f,%4.1f" % (wl_min, 0.1, wl_max) - alg = TransmissionUtils.simple_algorithm("Rebin", + alg = TransmissionUtils.simple_algorithm("Rebin",\ {"InputWorkspace": sample_mon_ws, "OutputWorkspace": "__sample_mon_"+suffix, "Params": rebin_params, - "PreserveEvents": False + "PreserveEvents": False\ }) sample_ws = alg.getProperty("OutputWorkspace").value - alg = TransmissionUtils.simple_algorithm("Rebin", + alg = TransmissionUtils.simple_algorithm("Rebin",\ {"InputWorkspace": empty_mon_ws, "OutputWorkspace": "__empty_mon_"+suffix, "Params": rebin_params, - "PreserveEvents": False + "PreserveEvents": False\ }) empty_ws = alg.getProperty("OutputWorkspace").value trans_ws, raw_ws = TransmissionUtils.calculate_transmission(self, @@ -190,18 +190,18 @@ def _crop_and_compute(wl_min_prop, wl_max_prop, suffix): empty_ws, first_det, "__transmission_"+suffix) - alg = TransmissionUtils.simple_algorithm("RebinToWorkspace", + alg = TransmissionUtils.simple_algorithm("RebinToWorkspace",\ {"WorkspaceToRebin": trans_ws, "WorkspaceToMatch": workspace, "OutputWorkspace": "__transmission_"+suffix, - "PreserveEvents": False + "PreserveEvents": False\ }) trans_ws = alg.getProperty("OutputWorkspace").value - alg = TransmissionUtils.simple_algorithm("RebinToWorkspace", + alg = TransmissionUtils.simple_algorithm("RebinToWorkspace",\ {"WorkspaceToRebin": raw_ws, "WorkspaceToMatch": workspace, "OutputWorkspace": "__transmission_unfitted_"+suffix, - "PreserveEvents": False + "PreserveEvents": False\ }) raw_ws = alg.getProperty("OutputWorkspace").value @@ -213,19 +213,19 @@ def _crop_and_compute(wl_min_prop, wl_max_prop, suffix): # Second frame trans_frame_2, raw_frame_2 = _crop_and_compute("wavelength_min_frame2", "wavelength_max_frame2", "_frame2") - alg = TransmissionUtils.simple_algorithm("Plus", + alg = TransmissionUtils.simple_algorithm("Plus",\ {"LHSWorkspace": trans_frame_1, "RHSWorkspace": trans_frame_2, - "OutputWorkspace": "__transmission", + "OutputWorkspace": "__transmission",\ }) trans_ws = alg.getProperty("OutputWorkspace").value self.setPropertyValue("TransmissionWorkspace", trans_ws_name) self.setProperty("TransmissionWorkspace", trans_ws) - alg = TransmissionUtils.simple_algorithm("Plus", + alg = TransmissionUtils.simple_algorithm("Plus",\ {"LHSWorkspace": raw_frame_1, "RHSWorkspace": raw_frame_2, - "OutputWorkspace": "__transmission_unfitted", + "OutputWorkspace": "__transmission_unfitted",\ }) raw_ws = alg.getProperty("OutputWorkspace").value raw_ws_name = "__transmission_raw_%s" % input_ws_name diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py index b9f863377703..007297da7d84 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import * from mantid.kernel import * from reduction_workflow.find_data import find_file diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py index 9349f30d0d17..df2869633b8a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.kernel import * from mantid.api import * @@ -22,6 +23,18 @@ def _normalize_to_lowest_temp(elt_ws_name): class ElasticWindowMultiple(DataProcessorAlgorithm): + _plot = None + _sample_log_name = None + _input_workspaces = None + _q_workspace = None + _q2_workspace = None + _elf_workspace = None + _elt_workspace = None + _range_1_start = None + _range_1_end = None + _range_2_start = None + _range_2_end = None + def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' @@ -40,7 +53,8 @@ def PyInit(self): self.declareProperty(name='Range2Start', defaultValue='', doc='Range 2 start') self.declareProperty(name='Range2End', defaultValue='', doc='Range 2 end') - self.declareProperty(name='SampleEnvironmentLogName', defaultValue='sample', doc='Name of the sample environment log entry') + self.declareProperty(name='SampleEnvironmentLogName', defaultValue='sample', + doc='Name of the sample environment log entry') self.declareProperty(WorkspaceProperty('OutputInQ', '', Direction.Output), doc='Output workspace in Q') @@ -48,10 +62,12 @@ def PyInit(self): self.declareProperty(WorkspaceProperty('OutputInQSquared', '', Direction.Output), doc='Output workspace in Q Squared') - self.declareProperty(WorkspaceProperty('OutputELF', '', Direction.Output, PropertyMode.Optional), + self.declareProperty(WorkspaceProperty('OutputELF', '', Direction.Output, + PropertyMode.Optional), doc='Output workspace ELF') - self.declareProperty(WorkspaceProperty('OutputELT', '', Direction.Output, PropertyMode.Optional), + self.declareProperty(WorkspaceProperty('OutputELT', '', Direction.Output, + PropertyMode.Optional), doc='Output workspace ELT') self.declareProperty(name='Plot', defaultValue=False, doc='Plot result spectra') @@ -71,13 +87,13 @@ def validateInputs(self): if range_2_start != '': try: - val = float(range_2_start) + _ = float(range_2_start) except ValueError: issues['Range2Start'] = 'Range 2 start is not a double number' if range_2_end != '': try: - val = float(range_2_end) + _ = float(range_2_end) except ValueError: issues['Range2End'] = 'Range 2 end is not a double number' @@ -110,9 +126,12 @@ def PyExec(self): q2_ws = '__' + input_ws + '_q2' if self._range_2_start != '' and self._range_2_end != '': - ElasticWindow(InputWorkspace=input_ws, OutputInQ=q_ws, OutputInQSquared=q2_ws, - Range1Start=self._range_1_start, Range1End=self._range_1_end, - Range2Start=float(self._range_2_start), Range2End=float(self._range_2_end)) + ElasticWindow(InputWorkspace=input_ws, + OutputInQ=q_ws, OutputInQSquared=q2_ws, + Range1Start=self._range_1_start, + Range1End=self._range_1_end, + Range2Start=float(self._range_2_start), + Range2End=float(self._range_2_end)) else: ElasticWindow(InputWorkspace=input_ws, OutputInQ=q_ws, OutputInQSquared=q2_ws, Range1Start=self._range_1_start, Range1End=self._range_1_end) @@ -139,13 +158,19 @@ def PyExec(self): RenameWorkspace(InputWorkspace=q2_workspaces[0], OutputWorkspace=self._q2_workspace) else: # Append the spectra of the first two workspaces - AppendSpectra(InputWorkspace1=q_workspaces[0], InputWorkspace2=q_workspaces[1], OutputWorkspace=self._q_workspace) - AppendSpectra(InputWorkspace1=q2_workspaces[0], InputWorkspace2=q2_workspaces[1], OutputWorkspace=self._q2_workspace) + AppendSpectra(InputWorkspace1=q_workspaces[0], InputWorkspace2=q_workspaces[1], + OutputWorkspace=self._q_workspace) + AppendSpectra(InputWorkspace1=q2_workspaces[0], InputWorkspace2=q2_workspaces[1], + OutputWorkspace=self._q2_workspace) # Append to the spectra of each remaining workspace for idx in range(2, len(input_workspace_names)): - AppendSpectra(InputWorkspace1=self._q_workspace, InputWorkspace2=q_workspaces[idx], OutputWorkspace=self._q_workspace) - AppendSpectra(InputWorkspace1=self._q2_workspace, InputWorkspace2=q2_workspaces[idx], OutputWorkspace=self._q2_workspace) + AppendSpectra(InputWorkspace1=self._q_workspace, + InputWorkspace2=q_workspaces[idx], + OutputWorkspace=self._q_workspace) + AppendSpectra(InputWorkspace1=self._q2_workspace, + InputWorkspace2=q2_workspaces[idx], + OutputWorkspace=self._q2_workspace) # Delete the output workspaces from the ElasticWindow algorithms for q_ws in q_workspaces: @@ -193,12 +218,14 @@ def PyExec(self): if self._elt_workspace != '': logger.information('Creating ELT workspace') - # If the ELT workspace was not already created then create it here, otherwise just clone it + # If the ELT workspace was not already created then create it here, + # otherwise just clone it if self._elf_workspace == '': Transpose(InputWorkspace=self._q_workspace, OutputWorkspace=self._elt_workspace) SortXAxis(InputWorkspace=self._elt_workspace, OutputWorkspace=self._elt_workspace) else: - CloneWorkspace(InputWorkspace=self._elf_workspace, OutputWorkspace=self._elt_workspace) + CloneWorkspace(InputWorkspace=self._elf_workspace, + OutputWorkspace=self._elt_workspace) _normalize_to_lowest_temp(self._elt_workspace) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py index e478aa2674b4..eddd34cd12dd 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Fury.py @@ -1,6 +1,7 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, PropertyMode -from mantid.kernel import StringListValidator, StringMandatoryValidator, Direction, logger +from mantid.kernel import Direction, logger from mantid import config import math import os @@ -8,33 +9,50 @@ class Fury(PythonAlgorithm): + _sample = None + _resolution = None + _e_min = None + _e_max = None + _number_points_per_bin = None + _parameter_table = None + _output_workspace = None + _plot = None + _save = None + _dry_run = None + def category(self): return "Workflow\\MIDAS;PythonAlgorithms" def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty('Sample', '', + self.declareProperty(MatrixWorkspaceProperty('Sample', '',\ optional=PropertyMode.Mandatory, direction=Direction.Input), doc="Name for the Sample workspace.") - self.declareProperty(MatrixWorkspaceProperty('Resolution', '', + self.declareProperty(MatrixWorkspaceProperty('Resolution', '',\ optional=PropertyMode.Mandatory, direction=Direction.Input), doc="Name for the Resolution workspace.") - self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') - self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') - self.declareProperty(name='NumBins', defaultValue=1, doc='Decrease total number of spectrum points by this ratio through merging of intensities from neighbouring bins. Default=1') + self.declareProperty(name='EnergyMin', defaultValue=-0.5, + doc='Minimum energy for fit. Default=-0.5') + self.declareProperty(name='EnergyMax', defaultValue=0.5, + doc='Maximum energy for fit. Default=0.5') + self.declareProperty(name='NumBins', defaultValue=1, + doc='Decrease total number of spectrum points by this ratio through merging of intensities from neighbouring bins. Default=1') - self.declareProperty(MatrixWorkspaceProperty('ParameterWorkspace', '', + self.declareProperty(MatrixWorkspaceProperty('ParameterWorkspace', '',\ direction=Direction.Output, optional=PropertyMode.Optional), doc='Table workspace for saving Fury properties') - self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '', + self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '',\ direction=Direction.Output, optional=PropertyMode.Optional), doc='Output workspace') - self.declareProperty(name='Plot', defaultValue=False, doc='Switch Plot Off/On') - self.declareProperty(name='Save', defaultValue=False, doc='Switch Save result to nxs file Off/On') - self.declareProperty(name='DryRun', defaultValue=False, doc='Only calculate and output the parameters') + self.declareProperty(name='Plot', defaultValue=False, + doc='Switch Plot Off/On') + self.declareProperty(name='Save', defaultValue=False, + doc='Switch Save result to nxs file Off/On') + self.declareProperty(name='DryRun', defaultValue=False, + doc='Only calculate and output the parameters') def PyExec(self): @@ -110,7 +128,8 @@ def _calculate_parameters(self): """ Calculates the Fury parameters and saves in a table workspace. """ - CropWorkspace(InputWorkspace=self._sample, OutputWorkspace='__Fury_sample_cropped', Xmin=self._e_min, Xmax=self._e_max) + CropWorkspace(InputWorkspace=self._sample, OutputWorkspace='__Fury_sample_cropped', + Xmin=self._e_min, Xmax=self._e_max) x_data = mtd['__Fury_sample_cropped'].readX(0) number_input_points = len(x_data) - 1 num_bins = number_input_points / self._number_points_per_bin @@ -135,7 +154,8 @@ def _calculate_parameters(self): except (AttributeError, IndexError): resolution = 0.0175 - logger.warning('Could not get resolution from IPF, using default value: %f' % resolution) + logger.warning('Could not get resolution from IPF, using default value: %f' % ( + resolution)) resolution_bins = int(round((2 * resolution) / self._e_width)) @@ -178,10 +198,14 @@ def _plot_output(self): def _add_logs(self): - AddSampleLog(Workspace=self._output_workspace, LogName='fury_resolution_ws', LogType='String', LogText=self._resolution) - AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_emin', LogType='Number', LogText=str(self._e_min)) - AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_ewidth', LogType='Number', LogText=str(self._e_width)) - AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_emax', LogType='Number', LogText=str(self._e_max)) + AddSampleLog(Workspace=self._output_workspace, LogName='fury_resolution_ws', + LogType='String', LogText=self._resolution) + AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_emin', + LogType='Number', LogText=str(self._e_min)) + AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_ewidth', + LogType='Number', LogText=str(self._e_width)) + AddSampleLog(Workspace=self._output_workspace, LogName='fury_rebin_emax', + LogType='Number', LogText=str(self._e_max)) def _fury(self): @@ -197,7 +221,8 @@ def _fury(self): CheckHistSame(self._sample, 'Sample', self._resolution, 'Resolution') rebin_param = str(self._e_min) + ',' + str(self._e_width) + ',' + str(self._e_max) - Rebin(InputWorkspace=self._sample, OutputWorkspace='__sam_rebin', Params=rebin_param, FullBinsOnly=True) + Rebin(InputWorkspace=self._sample, OutputWorkspace='__sam_rebin', Params=rebin_param, + FullBinsOnly=True) Rebin(InputWorkspace=self._resolution, OutputWorkspace='__res_data', Params=rebin_param) Integration(InputWorkspace='__res_data', OutputWorkspace='__res_int') @@ -223,7 +248,8 @@ def _fury(self): # Crop nonsense values off workspace binning = int(math.ceil(mtd[self._output_workspace].blocksize() / 2.0)) bin_v = mtd[self._output_workspace].dataX(0)[binning] - CropWorkspace(InputWorkspace=self._output_workspace, OutputWorkspace=self._output_workspace, XMax=bin_v) + CropWorkspace(InputWorkspace=self._output_workspace, OutputWorkspace=self._output_workspace, + XMax=bin_v) # Clean up resolution workspaces DeleteWorkspace('__res_data') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py index 94584c4e1363..f51ed8dfce84 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py @@ -1,4 +1,5 @@ -from mantid import config, logger, mtd, AlgorithmFactory +#pylint: disable=no-init +from mantid import config, logger, AlgorithmFactory from mantid.api import * from mantid.kernel import * from mantid.simpleapi import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py index 0bac631200b2..3365684c2f7d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * @@ -60,8 +61,8 @@ def _load_data(filename, output_ws): self.default_output_dir = head else: output_str += _load_data(data_file[i], '__tmp_wksp') - api.Plus(LHSWorkspace=workspace, - RHSWorkspace='__tmp_wksp', + api.Plus(LHSWorkspace=workspace,\ + RHSWorkspace='__tmp_wksp',\ OutputWorkspace=workspace) # Get the monitor and timer values ws = AnalysisDataService.retrieve('__tmp_wksp') @@ -171,7 +172,7 @@ def PyExec(self): if "BackgroundFiles" in property_list: background = property_manager.getProperty("BackgroundFiles").value background_ws = "__background_%s" % output_ws - msg = self._multiple_load(background, background_ws, + msg = self._multiple_load(background, background_ws,\ property_manager, property_manager_name) bck_msg = "Loaded background %s\n" % background bck_msg += msg @@ -232,8 +233,8 @@ def PyExec(self): WorkspaceToMatch=output_ws, OutputWorkspace=background_ws+'_rebin', PreserveEvents=False) - api.Minus(LHSWorkspace=output_ws, - RHSWorkspace=background_ws, + api.Minus(LHSWorkspace=output_ws,\ + RHSWorkspace=background_ws,\ OutputWorkspace=output_ws) bck_msg = bck_msg.replace('\n','\n |') @@ -395,7 +396,7 @@ def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): @param property_manager: property manager object """ output_msg = "" - + def _save_ws(iq_ws): if AnalysisDataService.doesExist(iq_ws): proc_xml = "" @@ -407,14 +408,14 @@ def _save_ws(iq_ws): elif len(process_file)>0: Logger("HFIRSANSReduction").error("Could not read %s\n" % process_file) if property_manager.existsProperty("SetupAlgorithm"): - setup_info = property_manager.getProperty("SetupAlgorithm").value - proc_xml += "\n\n" + setup_info = property_manager.getProperty("SetupAlgorithm").value + proc_xml += "\n\n" # The instrument name refers to the UI, which is named BIOSANS for all HFIR SANS - proc_xml += " BIOSANS\n" - proc_xml += " %s\n" % setup_info - filename = self.getProperty("Filename").value - proc_xml += " %s\n" % filename - proc_xml += "\n" + proc_xml += " BIOSANS\n" + proc_xml += " %s\n" % setup_info + filename = self.getProperty("Filename").value + proc_xml += " %s\n" % filename + proc_xml += "\n" filename = os.path.join(output_dir, iq_ws+'.txt') @@ -448,7 +449,7 @@ def _save_ws(iq_ws): filename = _save_ws(item) if filename is not None: output_msg += "I(Q) saved in %s\n" % (filename) - + # Save I(Qx,Qy) if iqxy_output is not None: if AnalysisDataService.doesExist(iqxy_output): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py index acc78baa98ce..88f8d3073975 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py @@ -1,6 +1,8 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.kernel import StringListValidator, Direction -from mantid.api import DataProcessorAlgorithm, PropertyMode, AlgorithmFactory, FileProperty, FileAction, MatrixWorkspaceProperty +from mantid.api import DataProcessorAlgorithm, PropertyMode, AlgorithmFactory, \ + FileProperty, FileAction, MatrixWorkspaceProperty from mantid import config, logger, mtd import numpy as np @@ -9,42 +11,68 @@ class IndirectILLReduction(DataProcessorAlgorithm): + _raw_workspace = None + _red_workspace = None + _red_left_workspace = None + _red_right_workspace = None + _map_file = None + _use_mirror_mode = None + _save = None + _plot = None + _instrument_name = None + _run_number = None + _analyser = None + _reflection = None + _run_name = None + def category(self): return "Workflow\\MIDAS;Inelastic;PythonAlgorithms" + def PyInit(self): #input options self.declareProperty(FileProperty('Run', '', action=FileAction.Load, extensions=["nxs"]), doc='File path of run.') - self.declareProperty(name='Analyser', defaultValue='silicon', validator=StringListValidator(['silicon']), + self.declareProperty(name='Analyser', defaultValue='silicon', + validator=StringListValidator(['silicon']), doc='Analyser crystal') - self.declareProperty(name='Reflection', defaultValue='111', validator=StringListValidator(['111']), + self.declareProperty(name='Reflection', defaultValue='111', + validator=StringListValidator(['111']), doc='Analyser reflection') - self.declareProperty(FileProperty('MapFile', '', action=FileAction.OptionalLoad, extensions=["xml"]), + self.declareProperty(FileProperty('MapFile', '', + action=FileAction.OptionalLoad, extensions=["xml"]), doc='Filename of the map file to use. If left blank the default will be used.') - self.declareProperty(name='MirrorMode', defaultValue=False, doc='Whether to use mirror mode') + self.declareProperty(name='MirrorMode', defaultValue=False, + doc='Whether to use mirror mode') #Output workspace properties - self.declareProperty(MatrixWorkspaceProperty("RawWorkspace", "", direction=Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("RawWorkspace", "", + direction=Direction.Output), doc="Name for the output raw workspace created.") - self.declareProperty(MatrixWorkspaceProperty("ReducedWorkspace", "", direction=Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("ReducedWorkspace", "", + direction=Direction.Output), doc="Name for the output reduced workspace created. If mirror mode is used this will be the sum of both" "the left and right hand workspaces.") - self.declareProperty(MatrixWorkspaceProperty("LeftWorkspace", "", optional=PropertyMode.Optional, direction=Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("LeftWorkspace", "", + optional=PropertyMode.Optional, direction=Direction.Output), doc="Name for the left workspace if mirror mode is used.") - self.declareProperty(MatrixWorkspaceProperty("RightWorkspace", "", optional=PropertyMode.Optional, direction=Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("RightWorkspace", "", + optional=PropertyMode.Optional, direction=Direction.Output), doc="Name for the right workspace if mirror mode is used.") # output options - self.declareProperty(name='Save', defaultValue=False, doc='Switch Save result to nxs file Off/On') - self.declareProperty(name='Plot', defaultValue=False, doc='Whether to plot the output workspace.') + self.declareProperty(name='Save', defaultValue=False, + doc='Switch Save result to nxs file Off/On') + self.declareProperty(name='Plot', defaultValue=False, + doc='Whether to plot the output workspace.') + def PyExec(self): self.log().information('IndirectILLreduction') @@ -77,7 +105,8 @@ def PyExec(self): self._reflection = self.getPropertyValue('Reflection') self._run_name = self._instrument_name + '_' + str(self._run_number) - AddSampleLog(Workspace=self._raw_workspace, LogName="mirror_sense", LogType="String", LogText=str(self._use_mirror_mode)) + AddSampleLog(Workspace=self._raw_workspace, LogName="mirror_sense", + LogType="String", LogText=str(self._use_mirror_mode)) logger.information('Nxs file : %s' % run_path) @@ -92,15 +121,15 @@ def PyExec(self): if self._plot: from IndirectImport import import_mantidplot - mp = import_mantidplot() - graph = mp.newGraph() + mtd_plot = import_mantidplot() + graph = mtd_plot.newGraph() for ws in output_workspaces: - mp.plotSpectrum(ws, 0, window=graph) + mtd_plot.plotSpectrum(ws, 0, window=graph) layer = graph.activeLayer() - layer.setAxisTitle(mp.Layer.Bottom, 'Energy Transfer (meV)') - layer.setAxisTitle(mp.Layer.Left, '') + layer.setAxisTitle(mtd_plot.Layer.Bottom, 'Energy Transfer (meV)') + layer.setAxisTitle(mtd_plot.Layer.Left, '') layer.setTitle('') self.setPropertyValue('RawWorkspace', self._raw_workspace) @@ -110,14 +139,11 @@ def PyExec(self): self.setPropertyValue('LeftWorkspace', self._red_left_workspace) self.setPropertyValue('RightWorkspace', self._red_right_workspace) + def _reduction(self): """ Run energy conversion for IN16B """ - from IndirectCommon import StartTime, EndTime - - StartTime('ILLindirect') - logger.information('Input workspace : %s' % self._raw_workspace) idf_directory = config['instrumentDefinition.directory'] @@ -125,7 +151,8 @@ def _reduction(self): ipf_path = os.path.join(idf_directory, ipf_name) LoadParameterFile(Workspace=self._raw_workspace, Filename=ipf_path) - AddSampleLog(Workspace=self._raw_workspace, LogName="facility", LogType="String", LogText="ILL") + AddSampleLog(Workspace=self._raw_workspace, LogName="facility", + LogType="String", LogText="ILL") if self._map_file == '': # path name for default map file @@ -139,11 +166,12 @@ def _reduction(self): logger.information('Map file : %s' % self._map_file) grouped_ws = self._run_name + '_group' - GroupDetectors(InputWorkspace=self._raw_workspace, OutputWorkspace=grouped_ws, MapFile=self._map_file, - Behaviour='Average') + GroupDetectors(InputWorkspace=self._raw_workspace, OutputWorkspace=grouped_ws, + MapFile=self._map_file, Behaviour='Average') monitor_ws = self._run_name + '_mon' - ExtractSingleSpectrum(InputWorkspace=self._raw_workspace, OutputWorkspace=monitor_ws, WorkspaceIndex=0) + ExtractSingleSpectrum(InputWorkspace=self._raw_workspace, + OutputWorkspace=monitor_ws, WorkspaceIndex=0) if self._use_mirror_mode: output_workspaces = self._run_mirror_mode(monitor_ws, grouped_ws) @@ -153,9 +181,9 @@ def _reduction(self): self._calculate_energy(monitor_ws, grouped_ws, self._red_workspace) output_workspaces = [self._red_workspace] - EndTime('ILLindirect') return output_workspaces + def _run_mirror_mode(self, monitor_ws, grouped_ws): """ Runs energy reduction with mirror mode. @@ -199,18 +227,24 @@ def _run_mirror_mode(self, monitor_ws, grouped_ws): nrmax = np.argmax(np.array(yr)) xrmax = xr[nrmax] xshift = xlmax - xrmax - ScaleX(InputWorkspace=self._red_right_workspace, OutputWorkspace=self._red_right_workspace, Factor=xshift, Operation='Add') - RebinToWorkspace(WorkspaceToRebin=self._red_right_workspace, WorkspaceToMatch=self._red_left_workspace, OutputWorkspace=self._red_right_workspace) + ScaleX(InputWorkspace=self._red_right_workspace, OutputWorkspace=self._red_right_workspace, + Factor=xshift, Operation='Add') + RebinToWorkspace(WorkspaceToRebin=self._red_right_workspace, + WorkspaceToMatch=self._red_left_workspace, + OutputWorkspace=self._red_right_workspace) #sum both workspaces together - Plus(LHSWorkspace=self._red_left_workspace, RHSWorkspace=self._red_right_workspace, OutputWorkspace=self._red_workspace) - Scale(InputWorkspace=self._red_workspace, OutputWorkspace=self._red_workspace, Factor=0.5, Operation='Multiply') + Plus(LHSWorkspace=self._red_left_workspace, RHSWorkspace=self._red_right_workspace, + OutputWorkspace=self._red_workspace) + Scale(InputWorkspace=self._red_workspace, OutputWorkspace=self._red_workspace, + Factor=0.5, Operation='Multiply') DeleteWorkspace(monitor_ws) DeleteWorkspace(grouped_ws) return [self._red_left_workspace, self._red_right_workspace, self._red_workspace] + def _calculate_energy(self, monitor_ws, grouped_ws, red_ws): """ Convert the input run to energy transfer @@ -220,18 +254,23 @@ def _calculate_energy(self, monitor_ws, grouped_ws, red_ws): @param red_ws :: name to call the reduced workspace """ x_range = self._monitor_range(monitor_ws) - Scale(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Factor=0.001, Operation='Multiply') + Scale(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Factor=0.001, + Operation='Multiply') - CropWorkspace(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Xmin=x_range[0], XMax=x_range[1]) - ScaleX(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Factor=-x_range[0], Operation='Add') + CropWorkspace(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, + Xmin=x_range[0], XMax=x_range[1]) + ScaleX(InputWorkspace=monitor_ws, OutputWorkspace=monitor_ws, Factor=-x_range[0], + Operation='Add') - CropWorkspace(InputWorkspace=grouped_ws, OutputWorkspace=grouped_ws, Xmin=x_range[0], XMax=x_range[1]) - ScaleX(InputWorkspace=grouped_ws, OutputWorkspace=grouped_ws, Factor=-x_range[0], Operation='Add') + CropWorkspace(InputWorkspace=grouped_ws, OutputWorkspace=grouped_ws, Xmin=x_range[0], + XMax=x_range[1]) + ScaleX(InputWorkspace=grouped_ws, OutputWorkspace=grouped_ws, Factor=-x_range[0], + Operation='Add') Divide(LHSWorkspace=grouped_ws, RHSWorkspace=monitor_ws, OutputWorkspace=grouped_ws) formula = self._energy_range(grouped_ws) - ConvertAxisByFormula(InputWorkspace=grouped_ws, OutputWorkspace=red_ws, Axis='X', Formula=formula, - AxisTitle='Energy transfer', AxisUnits='meV') + ConvertAxisByFormula(InputWorkspace=grouped_ws, OutputWorkspace=red_ws, Axis='X', + Formula=formula, AxisTitle='Energy transfer', AxisUnits='meV') xnew = mtd[red_ws].readX(0) # energy array logger.information('Energy range : %f to %f' % (xnew[0], xnew[-1])) @@ -239,6 +278,7 @@ def _calculate_energy(self, monitor_ws, grouped_ws, red_ws): DeleteWorkspace(grouped_ws) DeleteWorkspace(monitor_ws) + def _monitor_range(self, monitor_ws): """ Get sensible values for the min and max cropping range @@ -257,6 +297,7 @@ def _monitor_range(self, monitor_ws): return x[imin], x[imax] + def _energy_range(self, ws): """ Calculate the energy range for the workspace @@ -282,4 +323,6 @@ def _energy_range(self, ws): return formula -AlgorithmFactory.subscribe(IndirectILLReduction) # Register algorithm with Mantid + +# Register algorithm with Mantid +AlgorithmFactory.subscribe(IndirectILLReduction) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py index 3fe3e42c49c3..868ad8f8cd9b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py @@ -1,11 +1,24 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * -from mantid import config, logger +from mantid import logger class IndirectResolution(DataProcessorAlgorithm): + _input_files = None + _out_ws = None + _instrument = None + _analyser = None + _reflection = None + _detector_range = None + _background = None + _rebin_string = None + _scale_factor = None + _plot = None + _save = None + def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' @@ -16,10 +29,11 @@ def PyInit(self): self.declareProperty(StringArrayProperty(name='InputFiles'), doc='Comma seperated list if input files') - self.declareProperty(WorkspaceProperty('OutputWorkspace', '', - optional=PropertyMode.Optional, + self.declareProperty(WorkspaceProperty('OutputWorkspace', '',\ + optional=PropertyMode.Optional,\ direction=Direction.Output), - doc='Output resolution workspace (if left blank a name will be gernerated automatically)') + doc='Output resolution workspace (if left blank a name will ' + 'be gernerated automatically)') self.declareProperty(name='Instrument', defaultValue='', validator=StringListValidator(['IRIS', 'OSIRIS', 'TOSCA']), @@ -36,17 +50,18 @@ def PyInit(self): self.declareProperty(FloatArrayProperty(name='BackgroundRange', values=[0.0, 0.0]), doc='Energy range to use as background') - self.declareProperty(name='RebinParam', defaultValue='', doc='Rebinning parameters (min,width,max)') - self.declareProperty(name='ScaleFactor', defaultValue=1.0, doc='Factor to scale resolution curve by') - self.declareProperty(name='Smooth', defaultValue=False, doc='Apply WienerSmooth to resolution') + self.declareProperty(name='RebinParam', defaultValue='', + doc='Rebinning parameters (min,width,max)') + self.declareProperty(name='ScaleFactor', defaultValue=1.0, + doc='Factor to scale resolution curve by') self.declareProperty(name='Plot', defaultValue=False, doc='Plot resolution curve') - self.declareProperty(name='Save', defaultValue=False, doc='Save resolution workspace as a Nexus file') + self.declareProperty(name='Save', defaultValue=False, + doc='Save resolution workspace as a Nexus file') def PyExec(self): from IndirectCommon import StartTime, EndTime, getWSprefix - import inelastic_indirect_reducer StartTime('IndirectResolution') self._setup() @@ -74,11 +89,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) @@ -101,7 +111,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 @@ -113,20 +122,25 @@ def _post_process(self): """ use_scale_factor = self._scale_factor == 1.0 - AddSampleLog(Workspace=self._out_ws, LogName='scale', LogType='String', LogText=str(use_scale_factor)) + AddSampleLog(Workspace=self._out_ws, LogName='scale', + LogType='String', LogText=str(use_scale_factor)) if use_scale_factor: - AddSampleLog(Workspace=self._out_ws, LogName='scale_factor', LogType='Number', LogText=str(self._scale_factor)) - - AddSampleLog(Workspace=self._out_ws, LogName='res_smoothing_applied', LogType='String', LogText=str(self._smooth)) + AddSampleLog(Workspace=self._out_ws, LogName='scale_factor', + LogType='Number', LogText=str(self._scale_factor)) - AddSampleLog(Workspace=self._out_ws, LogName='back_start', LogType='Number', LogText=str(self._background[0])) - AddSampleLog(Workspace=self._out_ws, LogName='back_end', LogType='Number', LogText=str(self._background[1])) + AddSampleLog(Workspace=self._out_ws, LogName='back_start', + LogType='Number', LogText=str(self._background[0])) + AddSampleLog(Workspace=self._out_ws, LogName='back_end', + LogType='Number', LogText=str(self._background[1])) rebin_params = self._rebin_string.split(',') if len(rebin_params) == 3: - AddSampleLog(Workspace=self._out_ws, LogName='rebin_low', LogType='Number', LogText=rebin_params[0]) - AddSampleLog(Workspace=self._out_ws, LogName='rebin_width', LogType='Number', LogText=rebin_params[1]) - AddSampleLog(Workspace=self._out_ws, LogName='rebin_high', LogType='Number', LogText=rebin_params[2]) + AddSampleLog(Workspace=self._out_ws, LogName='rebin_low', + LogType='Number', LogText=rebin_params[0]) + AddSampleLog(Workspace=self._out_ws, LogName='rebin_width', + LogType='Number', LogText=rebin_params[1]) + AddSampleLog(Workspace=self._out_ws, LogName='rebin_high', + LogType='Number', LogText=rebin_params[2]) self.setProperty('OutputWorkspace', self._out_ws) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py index 87f1d83cd956..7ae4d22ef312 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmissionMonitor.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * @@ -9,6 +10,12 @@ class IndirectTransmissionMonitor(PythonAlgorithm): + _sample_ws_in = None + _can_ws_in = None + _out_ws = None + _plot = None + _save = None + def category(self): return "Workflow\\Inelastic;PythonAlgorithms;Inelastic" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py index ccb95aedc155..aee835a87736 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/InelasticIndirectReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * @@ -5,6 +6,27 @@ class InelasticIndirectReduction(DataProcessorAlgorithm): + _out_ws_group = None + _data_files = None + _instrument = None + _analyser = None + _reflection = None + _param_file = None + _detector_range = None + _background_range = None + _calib_ws_name = None + _detailed_balance = None + _rebin_string = None + _scale_factor = None + _sum_files = None + _map_file = None + _save_formats = None + _plot_type = None + _use_calib_ws = None + _use_detailed_balance = None + _use_scale_factor = None + _plot_ws = None + def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' @@ -17,7 +39,7 @@ def PyInit(self): self.declareProperty(StringArrayProperty(name='InputFiles'), doc='Comma separated list of input files') - self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '', + self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '',\ direction=Direction.Output), doc='Workspace group for the resulting workspaces') @@ -31,10 +53,10 @@ def PyInit(self): self.declareProperty(name='Reflection', defaultValue='', doc='Reflection used during run', validator=StringListValidator(['002', '004', '006', '111'])) - self.declareProperty(WorkspaceProperty('CalibrationWorkspace', '', + self.declareProperty(WorkspaceProperty('CalibrationWorkspace', '',\ direction=Direction.Input, optional=PropertyMode.Optional), doc='Workspace contining calibration data') - self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1], + self.declareProperty(IntArrayProperty(name='DetectorRange', values=[0, 1],\ validator=IntArrayMandatoryValidator()), doc='Comma separated range of detectors to use') self.declareProperty(FloatArrayProperty(name='BackgroundRange'), diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py index 0d5e64bbfc4e..376e9820f635 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/JumpFit.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * import os @@ -5,13 +6,21 @@ class JumpFit(PythonAlgorithm): + _in_ws = None + _out_name = None + _jump_function = None + _width = None + _q_min = None + _q_max = None + _plot = None + _save = None def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' def PyInit(self): - self.declareProperty(WorkspaceProperty('InputWorkspace', '', direction=Direction.Input), + self.declareProperty(WorkspaceProperty('InputWorkspace', '', direction=Direction.Input),\ doc='Input workspace in HWHM') valid_functions = ['ChudleyElliot', 'HallRoss', 'FickDiffusion', 'TeixeiraWater'] @@ -19,25 +28,26 @@ def PyInit(self): validator=StringListValidator(valid_functions), doc='The fit function to use') - self.declareProperty(name='Width', defaultValue=0, validator=IntMandatoryValidator(), + self.declareProperty(name='Width', defaultValue=0, validator=IntMandatoryValidator(),\ doc='Spectrum in the workspace to use for fiting') - self.declareProperty(name='QMin', defaultValue=0.0, validator=FloatMandatoryValidator(), + self.declareProperty(name='QMin', defaultValue=0.0, validator=FloatMandatoryValidator(),\ doc='Lower bound of Q range to use for fitting') - self.declareProperty(name='QMax', defaultValue=0.0, validator=FloatMandatoryValidator(), + self.declareProperty(name='QMax', defaultValue=0.0, validator=FloatMandatoryValidator(),\ doc='Upper bound of Q range to use for fitting') - self.declareProperty(name='Output', defaultValue='', direction=Direction.InOut, + self.declareProperty(name='Output', defaultValue='', direction=Direction.InOut,\ doc='Output name') - self.declareProperty(name='Plot', defaultValue=False, + self.declareProperty(name='Plot', defaultValue=False,\ doc='Plot result workspace') - self.declareProperty(name='Save', defaultValue=False, + self.declareProperty(name='Save', defaultValue=False,\ doc='Save result workspace to nexus file in the default save directory') def PyExec(self): - from mantid.simpleapi import ExtractSingleSpectrum, Scale, Fit, CopyLogs, AddSampleLog, DeleteWorkspace + from mantid.simpleapi import ExtractSingleSpectrum, Fit, CopyLogs, AddSampleLog, \ + DeleteWorkspace from mantid import logger, mtd from IndirectCommon import StartTime, EndTime @@ -47,7 +57,8 @@ def PyExec(self): # Select the width we wish to fit spectrum_ws = "__" + self._in_ws - ExtractSingleSpectrum(InputWorkspace=self._in_ws, OutputWorkspace=spectrum_ws, WorkspaceIndex=self._width) + ExtractSingleSpectrum(InputWorkspace=self._in_ws, OutputWorkspace=spectrum_ws, + WorkspaceIndex=self._width) logger.information('Cropping from Q= ' + str(self._q_min) + ' to ' + str(self._q_max)) in_run = mtd[self._in_ws].getRun() diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MSGDiffractionReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MSGDiffractionReduction.py index 15438f256618..73e8140748ac 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MSGDiffractionReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MSGDiffractionReduction.py @@ -1,11 +1,9 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * from mantid import config -import os.path, math - - class MSGDiffractionReduction(PythonAlgorithm): def category(self): @@ -40,7 +38,7 @@ def PyInit(self): self.declareProperty(name='RebinParam', defaultValue='', doc='Rebin parameters.') - self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '', + self.declareProperty(WorkspaceGroupProperty('OutputWorkspace', '',\ direction=Direction.Output), doc='Group name for the result workspaces.') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py index 5e0b12ef31cc..d908602c2285 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MolDyn.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init from mantid.simpleapi import * from mantid.kernel import * from mantid.api import * @@ -61,6 +62,15 @@ def _make_list(a, l1, l2): class MolDyn(PythonAlgorithm): + _plot = None + _save = None + _sam_path = None + _symmetrise = None + _functions = None + _emax = None + _res_ws = None + _out_ws = None + def category(self): return 'Workflow\\Inelastic;PythonAlgorithms;Inelastic' @@ -70,7 +80,7 @@ def summary(self): def PyInit(self): self.declareProperty(FileProperty('Filename', '', action=FileAction.OptionalLoad, - extensions=['.cdl', '.dat']), + extensions=['.cdl', '.dat']),\ doc='File path for data') self.declareProperty(StringArrayProperty('Functions'), diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py index 5ec56cf0159c..db6ceac74b9b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py @@ -1,78 +1,79 @@ +#pylint: disable=no-init # Algorithm to start Bayes programs from mantid.api import PythonAlgorithm, AlgorithmFactory -from mantid.kernel import StringListValidator, StringMandatoryValidator, logger +from mantid.kernel import StringListValidator, StringMandatoryValidator class MuscatData(PythonAlgorithm): def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" + return "Workflow\\MIDAS;PythonAlgorithms" def summary(self): - return "Calculates multiple scattering using a sample S(Q,w)." + return "Calculates multiple scattering using a sample S(Q,w)." def PyInit(self): - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) - self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='Sample geometry') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') - self.declareProperty(name='SqwInput',defaultValue='',validator=StringMandatoryValidator(), doc='Sqw file run number') - self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') - self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') - self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') - self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') - self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') - self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') - self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') - self.declareProperty(name='Density', defaultValue=0.1, doc='Sample number density. Default=0.1') - self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') - self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') - self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') + self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) + self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='Sample geometry') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') + self.declareProperty(name='SqwInput',defaultValue='',validator=StringMandatoryValidator(), doc='Sqw file run number') + self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') + self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') + self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') + self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') + self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') + self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') + self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') + self.declareProperty(name='Density', defaultValue=0.1, doc='Sample number density. Default=0.1') + self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') + self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') + self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - if is_supported_f2py_platform(): - import IndirectMuscat as Main - run_f2py_compatibility_test() + if is_supported_f2py_platform(): + import IndirectMuscat as Main + run_f2py_compatibility_test() - self.log().information('Muscat input') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - geom = self.getPropertyValue('Geom') - sam = self.getPropertyValue('SamNumber') - sqwi = self.getPropertyValue('SqwInput') - sname = prefix+sam+'_'+ana - sqw = prefix+sqwi+'_'+ana + self.log().information('Muscat input') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + geom = self.getPropertyValue('Geom') + sam = self.getPropertyValue('SamNumber') + sqwi = self.getPropertyValue('SqwInput') + sname = prefix+sam+'_'+ana + sqw = prefix+sqwi+'_'+ana - NRUN1 = self.getPropertyValue('NR1') - NRUN2 = self.getPropertyValue('NR2') - NMST = self.getPropertyValue('Nms') - JRAND = 12345 - MRAND = 67890 - neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] + NRUN1 = self.getPropertyValue('NR1') + NRUN2 = self.getPropertyValue('NR2') + NMST = self.getPropertyValue('Nms') + JRAND = 12345 + MRAND = 67890 + neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] - HEIGHT = 3.0 - alfa = self.getPropertyValue('DetAngle') - THICK = self.getPropertyValue('Thick') - WIDTH = self.getPropertyValue('Width') - HEIGHT = self.getPropertyValue('Height') - if geom == 'Flat': - beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] - if geom == 'Cyl': - beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] - dens = self.getPropertyValue('Density') - sigb = self.getPropertyValue('SigScat') - siga = self.getPropertyValue('SigAbs') - temp = self.getPropertyValue('Temperature') - sam = [float(temp), float(dens), float(siga), float(sigb)] + HEIGHT = 3.0 + alfa = self.getPropertyValue('DetAngle') + THICK = self.getPropertyValue('Thick') + WIDTH = self.getPropertyValue('Width') + HEIGHT = self.getPropertyValue('Height') + if geom == 'Flat': + beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] + if geom == 'Cyl': + beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] + dens = self.getPropertyValue('Density') + sigb = self.getPropertyValue('SigScat') + siga = self.getPropertyValue('SigAbs') + temp = self.getPropertyValue('Temperature') + sam = [float(temp), float(dens), float(siga), float(sigb)] - kr1 = 1 - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value - Main.MuscatDataStart(sname,geom,neut,beam,sam,sqw,kr1,verbOp,plotOp,saveOp) + kr1 = 1 + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value + Main.MuscatDataStart(sname,geom,neut,beam,sam,sqw,kr1,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(MuscatData) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py index a1a21ca4818d..81b168ac4a7c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name # Algorithm to start Bayes programs from mantid.kernel import StringListValidator, StringMandatoryValidator from mantid.api import PythonAlgorithm, AlgorithmFactory @@ -5,96 +6,96 @@ class MuscatFunc(PythonAlgorithm): def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" + return "Workflow\\MIDAS;PythonAlgorithms" def summary(self): - return "Calculates multiple scattering using S(Q,w) from specified functions." + return "Calculates multiple scattering using S(Q,w) from specified functions." def PyInit(self): - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) - self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='') - self.declareProperty(name='Dispersion',defaultValue='Poly',validator=StringListValidator(['Poly','CE','SS']), doc='') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') - self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') - self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') - self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') - self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') - self.declareProperty(name='NQ', defaultValue=10, doc='Q-w grid: number of Q values. Default=10') - self.declareProperty(name='dQ', defaultValue=0.2, doc='Q-w grid: Q increment. Default=0.2') - self.declareProperty(name='NW', defaultValue=100, doc='Q-w grid: number of w values. Default=100') - self.declareProperty(name='dW', defaultValue=2.0, doc='Q-w grid: w increment (microeV). Default=2.0') - self.declareProperty(name='Coeff1', defaultValue=0., doc='Coefficient 1. Default=0.0') - self.declareProperty(name='Coeff2', defaultValue=0., doc='Coefficient 2. Default=0.0') - self.declareProperty(name='Coeff3', defaultValue=50.0, doc='Coefficient 3. Default=50.0') - self.declareProperty(name='Coeff4', defaultValue=0., doc='Coefficient 4. Default=0.0') - self.declareProperty(name='Coeff5', defaultValue=0., doc='Coefficient 5. Default=0.0') - self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') - self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') - self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') - self.declareProperty(name='Density', defaultValue=0.1, doc='Sample density. Default=0.1') - self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') - self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') - self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') + self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) + self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='') + self.declareProperty(name='Dispersion',defaultValue='Poly',validator=StringListValidator(['Poly','CE','SS']), doc='') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') + self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') + self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') + self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') + self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') + self.declareProperty(name='NQ', defaultValue=10, doc='Q-w grid: number of Q values. Default=10') + self.declareProperty(name='dQ', defaultValue=0.2, doc='Q-w grid: Q increment. Default=0.2') + self.declareProperty(name='NW', defaultValue=100, doc='Q-w grid: number of w values. Default=100') + self.declareProperty(name='dW', defaultValue=2.0, doc='Q-w grid: w increment (microeV). Default=2.0') + self.declareProperty(name='Coeff1', defaultValue=0., doc='Coefficient 1. Default=0.0') + self.declareProperty(name='Coeff2', defaultValue=0., doc='Coefficient 2. Default=0.0') + self.declareProperty(name='Coeff3', defaultValue=50.0, doc='Coefficient 3. Default=50.0') + self.declareProperty(name='Coeff4', defaultValue=0., doc='Coefficient 4. Default=0.0') + self.declareProperty(name='Coeff5', defaultValue=0., doc='Coefficient 5. Default=0.0') + self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') + self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') + self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') + self.declareProperty(name='Density', defaultValue=0.1, doc='Sample density. Default=0.1') + self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') + self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') + self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - if is_supported_f2py_platform(): - import IndirectMuscat as Main + if is_supported_f2py_platform(): + import IndirectMuscat as Main - run_f2py_compatibility_test() + run_f2py_compatibility_test() - self.log().information('Muscat input') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - geom = self.getPropertyValue('Geom') - disp = self.getPropertyValue('Dispersion') - sam = self.getPropertyValue('SamNumber') - sname = prefix+sam+'_'+ana + self.log().information('Muscat input') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + geom = self.getPropertyValue('Geom') + disp = self.getPropertyValue('Dispersion') + sam = self.getPropertyValue('SamNumber') + sname = prefix+sam+'_'+ana - NRUN1 = self.getPropertyValue('NR1') - NRUN2 = self.getPropertyValue('NR2') - NMST = self.getPropertyValue('Nms') - JRAND = 12345 - MRAND = 67890 - neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] + NRUN1 = self.getPropertyValue('NR1') + NRUN2 = self.getPropertyValue('NR2') + NMST = self.getPropertyValue('Nms') + JRAND = 12345 + MRAND = 67890 + neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] - HEIGHT = 3.0 - alfa = self.getPropertyValue('DetAngle') - THICK = self.getPropertyValue('Thick') - WIDTH = self.getPropertyValue('Width') - HEIGHT = self.getPropertyValue('Height') - if geom == 'Flat': - beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] - if geom == 'Cyl': - beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] - dens = self.getPropertyValue('Density') - sigb = self.getPropertyValue('SigScat') - siga = self.getPropertyValue('SigAbs') - sigss=sigb - temp = self.getPropertyValue('Temperature') - sam = [float(temp), float(dens), float(siga), float(sigb)] + HEIGHT = 3.0 + alfa = self.getPropertyValue('DetAngle') + THICK = self.getPropertyValue('Thick') + WIDTH = self.getPropertyValue('Width') + HEIGHT = self.getPropertyValue('Height') + if geom == 'Flat': + beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] + if geom == 'Cyl': + beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] + dens = self.getPropertyValue('Density') + sigb = self.getPropertyValue('SigScat') + siga = self.getPropertyValue('SigAbs') + sigss=sigb + temp = self.getPropertyValue('Temperature') + sam = [float(temp), float(dens), float(siga), float(sigb)] - NQ = self.getPropertyValue('NQ') - dQ = self.getPropertyValue('dQ') - Nw = self.getPropertyValue('NW') - dw = self.getPropertyValue('dW') #in microeV - grid = [int(NQ), float(dQ), int(Nw), float(dw)] - c1 = self.getPropertyValue('Coeff1') - c2 = self.getPropertyValue('Coeff2') - c3 = self.getPropertyValue('Coeff3') - c4 = self.getPropertyValue('Coeff4') - c5 = self.getPropertyValue('Coeff5') - coeff = [float(c1), float(c2), float(c3), float(c4), float(c5)] - kr1 = 1 + NQ = self.getPropertyValue('NQ') + dQ = self.getPropertyValue('dQ') + Nw = self.getPropertyValue('NW') + dw = self.getPropertyValue('dW') #in microeV + grid = [int(NQ), float(dQ), int(Nw), float(dw)] + c1 = self.getPropertyValue('Coeff1') + c2 = self.getPropertyValue('Coeff2') + c3 = self.getPropertyValue('Coeff3') + c4 = self.getPropertyValue('Coeff4') + c5 = self.getPropertyValue('Coeff5') + coeff = [float(c1), float(c2), float(c3), float(c4), float(c5)] + kr1 = 1 - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value - Main.MuscatFuncStart(sname,geom,neut,beam,sam,grid,disp,coeff,kr1,verbOp,plotOp,saveOp) + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value + Main.MuscatFuncStart(sname,geom,neut,beam,sam,grid,disp,coeff,kr1,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(MuscatFunc) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py index fb07bc838bd3..9e595dcb0c3b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * @@ -14,7 +15,7 @@ def name(self): return "NormaliseByThickness" def summary(self): - return "Normalise detector counts by the sample thickness." + return "Normalise detector counts by the sample thickness." def PyInit(self): self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py index 08b2797acd0e..af5b458c3459 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py @@ -1,22 +1,22 @@ +#pylint: disable=invalid-name,no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * import itertools -import os - -timeRegimeToDRange = { - 1.17e4: tuple([ 0.7, 2.5]), - 2.94e4: tuple([ 2.1, 3.3]), - 4.71e4: tuple([ 3.1, 4.3]), - 6.48e4: tuple([ 4.1, 5.3]), - 8.25e4: tuple([ 5.2, 6.2]), - 10.02e4: tuple([ 6.2, 7.3]), - 11.79e4: tuple([ 7.3, 8.3]), - 13.55e4: tuple([ 8.3, 9.5]), - 15.32e4: tuple([ 9.4, 10.6]), - 17.09e4: tuple([10.4, 11.6]), - 18.86e4: tuple([11.0, 12.5])} + +timeRegimeToDRange = {\ + 1.17e4: tuple([ 0.7, 2.5]),\ + 2.94e4: tuple([ 2.1, 3.3]),\ + 4.71e4: tuple([ 3.1, 4.3]),\ + 6.48e4: tuple([ 4.1, 5.3]),\ + 8.25e4: tuple([ 5.2, 6.2]),\ + 10.02e4: tuple([ 6.2, 7.3]),\ + 11.79e4: tuple([ 7.3, 8.3]),\ + 13.55e4: tuple([ 8.3, 9.5]),\ + 15.32e4: tuple([ 9.4, 10.6]),\ + 17.09e4: tuple([10.4, 11.6]),\ + 18.86e4: tuple([11.0, 12.5])}\ """ A "wrapper" class for a map, which maps workspaces from their corresponding time regimes. @@ -38,7 +38,7 @@ def addWs(self, wsname): try: dRange = timeRegimeToDRange[timeRegime] except KeyError: - raise RuntimeError("Unable to identify the DRange of " + wsname + + raise RuntimeError("Unable to identify the DRange of " + wsname +\ ", which has a time regime of " + str(timeRegime)) # Add the workspace to the map, alongside its DRange. @@ -98,17 +98,17 @@ def findIntersectionOfTwoRanges(rangeA, rangeB): assert rangeA[0] < rangeA[1], "Malformed range." assert rangeB[0] < rangeB[1], "Malformed range." - if( rangeA[0] <= rangeA[1] <= rangeB[0] <= rangeB[1]): + if rangeA[0] <= rangeA[1] <= rangeB[0] <= rangeB[1]: return - if( rangeB[0] <= rangeB[1] <= rangeA[0] <= rangeA[1]): + if rangeB[0] <= rangeB[1] <= rangeA[0] <= rangeA[1]: return - if( rangeA[0] <= rangeB[0] <= rangeB[1] <= rangeA[1] ): + if rangeA[0] <= rangeB[0] <= rangeB[1] <= rangeA[1] : return rangeB - if( rangeB[0] <= rangeA[0] <= rangeA[1] <= rangeB[1] ): + if rangeB[0] <= rangeA[0] <= rangeA[1] <= rangeB[1] : return rangeA - if( rangeA[0] <= rangeB[0] <= rangeA[1] <= rangeB[1] ): + if rangeA[0] <= rangeB[0] <= rangeA[1] <= rangeB[1] : return [rangeB[0], rangeA[1]] - if( rangeB[0] <= rangeA[0] <= rangeB[1] <= rangeA[1] ): + if rangeB[0] <= rangeA[0] <= rangeB[1] <= rangeA[1] : return [rangeA[0], rangeB[1]] assert False, "We should never reach here ..." @@ -145,11 +145,19 @@ def isInRanges(rangeList, n): class OSIRISDiffractionReduction(PythonAlgorithm): """ Handles the reduction of OSIRIS Diffraction Data. """ + + _cal = None + _outputWsName = None + _sams = None + _vans = None + _samMap = None + _vanMap = None + def category(self): return 'Diffraction;PythonAlgorithms' def summary(self): - return "This Python algorithm performs the operations necessary for the reduction of diffraction data from the Osiris instrument at ISIS \ + return "This Python algorithm performs the operations necessary for the reduction of diffraction data from the Osiris instrument at ISIS \ into dSpacing, by correcting for the monitor and linking the various d-ranges together." def PyInit(self): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py index 06c3482b634a..0d8c34b1def5 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.simpleapi import * from mantid.kernel import StringListValidator, StringMandatoryValidator from mantid.api import PythonAlgorithm, AlgorithmFactory @@ -7,35 +8,35 @@ class QLines(PythonAlgorithm): def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" + return "Workflow\\MIDAS;PythonAlgorithms" def summary(self): - return "The program estimates the quasielastic components of each of the groups of spectra and requires the resolution file (.RES file) and optionally the normalisation file created by ResNorm." + return "The program estimates the quasielastic components of each of the groups of spectra and requires the resolution file (.RES file) and optionally the normalisation file created by ResNorm." def PyInit(self): - self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) or Workspace') - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection') - self.declareProperty(name='Program',defaultValue='QL',validator=StringListValidator(['QL','QSe']), doc='Name of program to run') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') - self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') - self.declareProperty(name='ResType',defaultValue='Res',validator=StringListValidator(['Res','Data']), doc='Format of Resolution file') - self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') - self.declareProperty(name='ResNorm',defaultValue=False, doc='Use ResNorm output file') - self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') - self.declareProperty(name='ResNormNumber',defaultValue='', doc='ResNorm run number') - self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') - self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') - self.declareProperty(name='FixWidth',defaultValue=False, doc='Fix one of the widths') - self.declareProperty(name='WidthFile', defaultValue='', doc='Name of file containing fixed width values') - self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') - self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') - self.declareProperty(name='SamBinning', defaultValue=1, doc='Binning value (integer) for sample. Default=1') - self.declareProperty(name='ResBinning', defaultValue=1, doc='Binning value (integer) for resolution - QLd only. Default=1') - self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','ProbBeta','Intensity','FwHm','Fit','All']), doc='Plot options') - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') + self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) or Workspace') + self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection') + self.declareProperty(name='Program',defaultValue='QL',validator=StringListValidator(['QL','QSe']), doc='Name of program to run') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') + self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') + self.declareProperty(name='ResType',defaultValue='Res',validator=StringListValidator(['Res','Data']), doc='Format of Resolution file') + self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') + self.declareProperty(name='ResNorm',defaultValue=False, doc='Use ResNorm output file') + self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') + self.declareProperty(name='ResNormNumber',defaultValue='', doc='ResNorm run number') + self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') + self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') + self.declareProperty(name='FixWidth',defaultValue=False, doc='Fix one of the widths') + self.declareProperty(name='WidthFile', defaultValue='', doc='Name of file containing fixed width values') + self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') + self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') + self.declareProperty(name='SamBinning', defaultValue=1, doc='Binning value (integer) for sample. Default=1') + self.declareProperty(name='ResBinning', defaultValue=1, doc='Binning value (integer) for resolution - QLd only. Default=1') + self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','ProbBeta','Intensity','FwHm','Fit','All']), doc='Plot options') + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') def PyExec(self): from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform @@ -43,60 +44,60 @@ def PyExec(self): if is_supported_f2py_platform(): import IndirectBayes as Main - run_f2py_compatibility_test() - - self.log().information('QLines input') - inType = self.getPropertyValue('InputType') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - prog = self.getPropertyValue('Program') - sam = self.getPropertyValue('SamNumber') - rinType = self.getPropertyValue('ResInputType') - rtype = self.getPropertyValue('ResType') - res = self.getPropertyValue('ResNumber') - elastic = self.getProperty('ElasticOption').value - bgd = self.getPropertyValue('BackgroundOption') - width = self.getProperty('FixWidth').value - wfile = self.getPropertyValue('WidthFile') - rsnormType = self.getPropertyValue('ResNormInputType') - resnorm = self.getProperty('ResNorm').value - resn = self.getPropertyValue('ResNormNumber') - emin = self.getPropertyValue('EnergyMin') - emax = self.getPropertyValue('EnergyMax') - nbin = self.getPropertyValue('SamBinning') - nrbin = self.getPropertyValue('ResBinning') - nbins = [nbin, nrbin] - - if rtype == 'Res': + run_f2py_compatibility_test() + + self.log().information('QLines input') + inType = self.getPropertyValue('InputType') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + prog = self.getPropertyValue('Program') + sam = self.getPropertyValue('SamNumber') + rinType = self.getPropertyValue('ResInputType') + rtype = self.getPropertyValue('ResType') + res = self.getPropertyValue('ResNumber') + elastic = self.getProperty('ElasticOption').value + bgd = self.getPropertyValue('BackgroundOption') + width = self.getProperty('FixWidth').value + wfile = self.getPropertyValue('WidthFile') + rsnormType = self.getPropertyValue('ResNormInputType') + resnorm = self.getProperty('ResNorm').value + resn = self.getPropertyValue('ResNormNumber') + emin = self.getPropertyValue('EnergyMin') + emax = self.getPropertyValue('EnergyMax') + nbin = self.getPropertyValue('SamBinning') + nrbin = self.getPropertyValue('ResBinning') + nbins = [nbin, nrbin] + + if rtype == 'Res': rext = 'res' - if rtype == 'Data': + if rtype == 'Data': rext = 'red' - sname = prefix+sam+'_'+ana + '_red' - rname = prefix+res+'_'+ana + '_' + rext - rsname = prefix+resn+'_'+ana + '_ResNorm_Paras' - erange = [float(emin), float(emax)] - - fitOp = [elastic, bgd, width, resnorm] - loopOp = self.getProperty('Sequence').value - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value - - workdir = config['defaultsave.directory'] - if inType == 'File': + sname = prefix+sam+'_'+ana + '_red' + rname = prefix+res+'_'+ana + '_' + rext + rsname = prefix+resn+'_'+ana + '_ResNorm_Paras' + erange = [float(emin), float(emax)] + + fitOp = [elastic, bgd, width, resnorm] + loopOp = self.getProperty('Sequence').value + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value + + workdir = config['defaultsave.directory'] + if inType == 'File': spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) Smessage = 'Sample from File : '+spath - else: + else: Smessage = 'Sample from Workspace : '+sname - if rinType == 'File': + if rinType == 'File': rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) Rmessage = 'Resolution from File : '+rpath - else: + else: Rmessage = 'Resolution from Workspace : '+rname - if resnorm: + if resnorm: if rsnormType == 'File': rpath = os.path.join(workdir, rsname+'.nxs') # path name for res nxs file LoadNexusProcessed(Filename=rpath, OutputWorkspace=rsname) @@ -104,12 +105,12 @@ def PyExec(self): else: Rmessage = 'ResNorm from Workspace : '+rsname - if verbOp: + if verbOp: logger.notice(Smessage) logger.notice(Rmessage) - rsname = rsname[:-6] + rsname = rsname[:-6] - Main.QLRun(prog,sname,rname,rsname,erange,nbins,fitOp,wfile,loopOp,verbOp,plotOp,saveOp) + Main.QLRun(prog,sname,rname,rsname,erange,nbins,fitOp,wfile,loopOp,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(QLines) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py index b4c3a0d27b3b..fcc64819ecb9 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.api import PythonAlgorithm, AlgorithmFactory from mantid.kernel import StringListValidator, StringMandatoryValidator from mantid.simpleapi import * @@ -7,104 +8,104 @@ class Quest(PythonAlgorithm): def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" + return "Workflow\\MIDAS;PythonAlgorithms" def summary(self): - return "This is a variation of the stretched exponential option of Quasi." + return "This is a variation of the stretched exponential option of Quasi." def PyInit(self): - self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) or Workspace') - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') - self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') - self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') - self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') - self.declareProperty(name='ResNormNumber',defaultValue='',validator=StringMandatoryValidator(), doc='ResNorm run number') - self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') - self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') - self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') - self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') - self.declareProperty(name='SamBinning', defaultValue=1, doc='Binning value(integer) for sample. Default=1') - self.declareProperty(name='NumberSigma', defaultValue=50, doc='Number of sigma values. Default=50') - self.declareProperty(name='NumberBeta', defaultValue=30, doc='Number of beta values. Default=30') - self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Sigma','Beta','All']), doc='Plot options') - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') + self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) or Workspace') + self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') + self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') + self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') + self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') + self.declareProperty(name='ResNormNumber',defaultValue='',validator=StringMandatoryValidator(), doc='ResNorm run number') + self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') + self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') + self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') + self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') + self.declareProperty(name='SamBinning', defaultValue=1, doc='Binning value(integer) for sample. Default=1') + self.declareProperty(name='NumberSigma', defaultValue=50, doc='Number of sigma values. Default=50') + self.declareProperty(name='NumberBeta', defaultValue=30, doc='Number of beta values. Default=30') + self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Sigma','Beta','All']), doc='Plot options') + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - if is_supported_f2py_platform(): - import IndirectBayes as Main + if is_supported_f2py_platform(): + import IndirectBayes as Main - run_f2py_compatibility_test() + run_f2py_compatibility_test() - self.log().information('Quest input') - inType = self.getPropertyValue('InputType') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - sam = self.getPropertyValue('SamNumber') - rinType = self.getPropertyValue('ResInputType') - res = self.getPropertyValue('ResNumber') - rsnormType = self.getPropertyValue('ResNormInputType') - rsnormNum = self.getPropertyValue('ResNormNumber') - elastic = self.getProperty('ElasticOption').value - bgd = self.getPropertyValue('BackgroundOption') - emin = self.getPropertyValue('EnergyMin') - emax = self.getPropertyValue('EnergyMax') - nbin = self.getPropertyValue('SamBinning') - nbins = [nbin, 1] - nbet = self.getPropertyValue('NumberBeta') - nsig = self.getPropertyValue('NumberSigma') - nbs = [nbet, nsig] + self.log().information('Quest input') + inType = self.getPropertyValue('InputType') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + sam = self.getPropertyValue('SamNumber') + rinType = self.getPropertyValue('ResInputType') + res = self.getPropertyValue('ResNumber') + rsnormType = self.getPropertyValue('ResNormInputType') + rsnormNum = self.getPropertyValue('ResNormNumber') + elastic = self.getProperty('ElasticOption').value + bgd = self.getPropertyValue('BackgroundOption') + emin = self.getPropertyValue('EnergyMin') + emax = self.getPropertyValue('EnergyMax') + nbin = self.getPropertyValue('SamBinning') + nbins = [nbin, 1] + nbet = self.getPropertyValue('NumberBeta') + nsig = self.getPropertyValue('NumberSigma') + nbs = [nbet, nsig] - sname = prefix+sam+'_'+ana + '_red' - rname = prefix+res+'_'+ana + '_res' - rsname = prefix+rsnormNum+'_'+ana+ '_ResNorm_Paras' - erange = [float(emin), float(emax)] - if elastic: - o_el = 1 - else: - o_el = 0 - if bgd == 'Sloping': - o_bgd = 2 - if bgd == 'Flat': - o_bgd = 1 - if bgd == 'Zero': - o_bgd = 0 - fitOp = [o_el, o_bgd, 0, 0] - loopOp = self.getProperty('Sequence').value - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value + sname = prefix+sam+'_'+ana + '_red' + rname = prefix+res+'_'+ana + '_res' + rsname = prefix+rsnormNum+'_'+ana+ '_ResNorm_Paras' + erange = [float(emin), float(emax)] + if elastic: + o_el = 1 + else: + o_el = 0 + if bgd == 'Sloping': + o_bgd = 2 + if bgd == 'Flat': + o_bgd = 1 + if bgd == 'Zero': + o_bgd = 0 + fitOp = [o_el, o_bgd, 0, 0] + loopOp = self.getProperty('Sequence').value + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value - workdir = config['defaultsave.directory'] - if inType == 'File': - spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file - LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) - Smessage = 'Sample from File : '+spath - else: - Smessage = 'Sample from Workspace : '+sname + workdir = config['defaultsave.directory'] + if inType == 'File': + spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file + LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) + Smessage = 'Sample from File : '+spath + else: + Smessage = 'Sample from Workspace : '+sname - if rinType == 'File': - rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file - LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) - Rmessage = 'Resolution from File : '+rpath - else: - Rmessage = 'Resolution from Workspace : '+rname + if rinType == 'File': + rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file + LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) + Rmessage = 'Resolution from File : '+rpath + else: + Rmessage = 'Resolution from Workspace : '+rname - if rsnormType == 'File': - rpath = os.path.join(workdir, rsname+'.nxs') # path name for res nxs file - LoadNexusProcessed(Filename=rpath, OutputWorkspace=rsname) - Rmessage = 'ResNorm from File : '+rpath - else: - Rmessage = 'ResNorm from Workspace : '+rsname + if rsnormType == 'File': + rpath = os.path.join(workdir, rsname+'.nxs') # path name for res nxs file + LoadNexusProcessed(Filename=rpath, OutputWorkspace=rsname) + Rmessage = 'ResNorm from File : '+rpath + else: + Rmessage = 'ResNorm from Workspace : '+rsname - if verbOp: - logger.notice(Smessage) - logger.notice(Rmessage) - Main.QuestRun(sname,rname,rsname,nbs,erange,nbins,fitOp,loopOp,verbOp,plotOp,saveOp) + if verbOp: + logger.notice(Smessage) + logger.notice(Rmessage) + Main.QuestRun(sname,rname,rsname,nbs,erange,nbins,fitOp,loopOp,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(Quest) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py index d2aa68669a98..b9968c731e6d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * from mantid.simpleapi import * @@ -103,9 +104,9 @@ def stitch_data(self, input_file, output_dir, q_min, q_step): ws_list = AnalysisDataService.getObjectNames() for item in ws_list: if item.endswith('ts'): - (_name,_ts) = item.split('_#') - _list_name.append(item) - _list_ts.append(_ts) + (_name,_ts) = item.split('_#') + _list_name.append(item) + _list_ts.append(_ts) _name_ts = zip(_list_ts, _list_name) _name_ts.sort() @@ -147,16 +148,16 @@ def weightedMean(data_array, error_array): sz = len(data_array) # calculate the numerator of mean - dataNum = 0; + dataNum = 0 for i in range(sz): - if not (data_array[i] == 0): + if not data_array[i] == 0: tmpFactor = float(data_array[i]) / float((pow(error_array[i],2))) dataNum += tmpFactor # calculate denominator - dataDen = 0; + dataDen = 0 for i in range(sz): - if not (error_array[i] == 0): + if not error_array[i] == 0: tmpFactor = 1./float((pow(error_array[i],2))) dataDen += tmpFactor @@ -212,7 +213,7 @@ def _average_y_of_same_x_(q_min, q_step, q_max=2): data_e_i = mtd[scaled_ws_list[i]+'_histo'].dataE(0) for j in range(len(data_y_i)): if data_y[j]>0 and data_y_i[j]>0: - [data_y[j], data_e[j]] = weightedMean([data_y[j], data_y_i[j]], [data_e[j], data_e_i[j]]); + [data_y[j], data_e[j]] = weightedMean([data_y[j], data_y_i[j]], [data_e[j], data_e_i[j]]) elif (data_y[j] == 0) and (data_y_i[j]>0): data_y[j] = data_y_i[j] data_e[j] = data_e_i[j] diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py index 7f4a1e088aeb..2ba70394d509 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py @@ -1,4 +1,4 @@ -import mantid.simpleapi as api +#pylint: disable=no-init from mantid.api import * from mantid.kernel import * import math @@ -69,7 +69,7 @@ def PyExec(self): res_factor += math.pow(k*pixel_size_x/sample_detector_distance, 2)/12.0 for i in range(len(input_ws.readX(0))): - input_ws.dataDx(0)[i] = math.sqrt(res_factor+math.pow((input_ws.readX(0)[i]*d_wvl), 2)/6.0) + input_ws.dataDx(0)[i] = math.sqrt(res_factor+math.pow((input_ws.readX(0)[i]*d_wvl), 2)/6.0) else: raise RuntimeError, "ReactorSANSResolution could not find all the run parameters needed to compute the resolution." diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py index c7dd0825540e..904279c74ca7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py @@ -1,73 +1,95 @@ +#pylint: disable=no-init from mantid.api import PythonAlgorithm, AlgorithmFactory from mantid.kernel import StringListValidator, StringMandatoryValidator from mantid.simpleapi import * -from mantid import config, logger, mtd +from mantid import config, logger import os + class ResNorm(PythonAlgorithm): - def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" - - def summary(self): - return "This algorithm creates a group 'normalisation' file by taking a resolution file and fitting it to all the groups in the resolution (vanadium) data file which has the same grouping as the sample data of interest." - - def PyInit(self): - self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) or Workspace') - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection') - self.declareProperty(name='VanNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') - self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') - self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') - self.declareProperty(name='EnergyMin', defaultValue=-0.2, doc='Minimum energy for fit. Default=-0.2') - self.declareProperty(name='EnergyMax', defaultValue=0.2, doc='Maximum energy for fit. Default=0.2') - self.declareProperty(name='VanBinning', defaultValue=1, doc='Binning value (integer) for sample. Default=1') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Intensity','Stretch','Fit','All']), doc='Plot options') - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - - def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - - if is_supported_f2py_platform(): + def category(self): + return "Workflow\\MIDAS;PythonAlgorithms" + + + def summary(self): + return "This algorithm creates a group 'normalisation' file by taking a resolution file and fitting it to all the groups in the resolution (vanadium) data file which has the same grouping as the sample data of interest." + + + def PyInit(self): + self.declareProperty(name='InputType', defaultValue='File', + validator=StringListValidator(['File','Workspace']), + doc='Origin of data input - File (.nxs) or Workspace') + self.declareProperty(name='Instrument', defaultValue='iris', + validator=StringListValidator(['irs','iris','osi','osiris']), + doc='Instrument') + self.declareProperty(name='Analyser', defaultValue='graphite002', + validator=StringListValidator(['graphite002','graphite004']), + doc='Analyser & reflection') + self.declareProperty(name='VanNumber', defaultValue='', + validator=StringMandatoryValidator(), + doc='Sample run number') + self.declareProperty(name='ResInputType',defaultValue='File', + validator=StringListValidator(['File','Workspace']), + doc='Origin of res input - File (_res.nxs) or Workspace') + self.declareProperty(name='ResNumber', defaultValue='', + validator=StringMandatoryValidator(), + doc='Resolution run number') + self.declareProperty(name='EnergyMin', defaultValue=-0.2, + doc='Minimum energy for fit. Default=-0.2') + self.declareProperty(name='EnergyMax', defaultValue=0.2, + doc='Maximum energy for fit. Default=0.2') + self.declareProperty(name='VanBinning', defaultValue=1, + doc='Binning value (integer) for sample. Default=1') + self.declareProperty(name='Plot', defaultValue='None', + validator=StringListValidator(['None','Intensity','Stretch','Fit','All']), + doc='Plot options') + self.declareProperty(name='Save', defaultValue=False, + doc='Switch Save result to nxs file Off/On') + + + def PyExec(self): + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + + if is_supported_f2py_platform(): import IndirectBayes as Main - run_f2py_compatibility_test() - - self.log().information('ResNorm input') - inType = self.getPropertyValue('InputType') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - van = self.getPropertyValue('VanNumber') - rinType = self.getPropertyValue('ResInputType') - res = self.getPropertyValue('ResNumber') - emin = self.getPropertyValue('EnergyMin') - emax = self.getPropertyValue('EnergyMax') - nbin = self.getPropertyValue('VanBinning') - - vname = prefix+van+'_'+ana+ '_red' - rname = prefix+res+'_'+ana+ '_res' - erange = [float(emin), float(emax)] - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value - - workdir = config['defaultsave.directory'] - if inType == 'File': - vpath = os.path.join(workdir, vname+'.nxs') # path name for van nxs file - LoadNexusProcessed(Filename=vpath, OutputWorkspace=vname) - Vmessage = 'Vanadium from File : '+vpath - else: - Vmessage = 'Vanadium from Workspace : '+vname - if rinType == 'File': - rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file - LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) - Rmessage = 'Resolution from File : '+rpath - else: - Rmessage = 'Resolution from Workspace : '+rname - if verbOp: - logger.notice(Vmessage) - logger.notice(Rmessage) - Main.ResNormRun(vname,rname,erange,nbin,verbOp,plotOp,saveOp) - -AlgorithmFactory.subscribe(ResNorm) # Register algorithm with Mantid + run_f2py_compatibility_test() + + self.log().information('ResNorm input') + inType = self.getPropertyValue('InputType') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + van = self.getPropertyValue('VanNumber') + rinType = self.getPropertyValue('ResInputType') + res = self.getPropertyValue('ResNumber') + emin = self.getPropertyValue('EnergyMin') + emax = self.getPropertyValue('EnergyMax') + nbin = self.getPropertyValue('VanBinning') + + vname = prefix+van+'_'+ana+ '_red' + rname = prefix+res+'_'+ana+ '_res' + erange = [float(emin), float(emax)] + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value + + workdir = config['defaultsave.directory'] + if inType == 'File': + vpath = os.path.join(workdir, vname+'.nxs') # path name for van nxs file + LoadNexusProcessed(Filename=vpath, OutputWorkspace=vname) + Vmessage = 'Vanadium from File : '+vpath + else: + Vmessage = 'Vanadium from Workspace : '+vname + if rinType == 'File': + rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file + LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) + Rmessage = 'Resolution from File : '+rpath + else: + Rmessage = 'Resolution from Workspace : '+rname + logger.information(Vmessage) + logger.information(Rmessage) + Main.ResNormRun(vname,rname,erange,nbin,True,plotOp,saveOp) + + +# Register algorithm with Mantid +AlgorithmFactory.subscribe(ResNorm) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py index 6736b723ce04..101ac62f9fb5 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py @@ -1,8 +1,7 @@ +#pylint: disable=no-init,invalid-name import os -import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * -from reduction_workflow.instruments.sans import hfir_instrument from reduction_workflow.find_data import find_data class SANSAbsoluteScale(PythonAlgorithm): @@ -10,6 +9,8 @@ class SANSAbsoluteScale(PythonAlgorithm): Normalise detector counts by the sample thickness """ + instrument = None + def category(self): return "Workflow\\SANS\\UsesPropertyManager" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py index 2642c5b5dbf7..88d7baf2b75e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.api import * from mantid.kernel import * import math @@ -17,7 +18,7 @@ def PyInit(self): self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", direction=Direction.Input)) - self.declareProperty(FloatArrayProperty("Binning", values=[0.,0.,0.], + self.declareProperty(FloatArrayProperty("Binning", values=[0.,0.,0.],\ direction=Direction.InOut), "Positive is linear bins, negative is logarithmic") self.declareProperty("NumberOfBins", 100, validator=IntBoundedValidator(lower=1), @@ -35,7 +36,7 @@ def PyInit(self): self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output), "I(q) workspace") - + self.declareProperty("NumberOfWedges", 2, "Number of wedges to calculate") self.declareProperty("WedgeAngle", 30.0, "Angular opening of each wedge, in degrees") self.declareProperty("WedgeOffset", 0.0, "Angular offset for the wedges, in degrees") @@ -166,7 +167,7 @@ def PyExec(self): alg.setProperty("InfinityError", 0.0) alg.execute() wedge_i = alg.getProperty("OutputWorkspace").value - + if compute_resolution: alg = AlgorithmManager.create("ReactorSANSResolution") alg.initialize() @@ -174,7 +175,7 @@ def PyExec(self): alg.setProperty("InputWorkspace", wedge_i) alg.execute() - self.declareProperty(MatrixWorkspaceProperty("WedgeWorkspace_%s" % i, "", + self.declareProperty(MatrixWorkspaceProperty("WedgeWorkspace_%s" % i, "",\ direction = Direction.Output)) self.setPropertyValue("WedgeWorkspace_%s" % i, wedge_i_name) self.setProperty("WedgeWorkspace_%s" % i, wedge_i) @@ -238,7 +239,7 @@ def _get_binning(self, workspace, wavelength_min, wavelength_max): if f_step-n_step>10e-10: qmax = math.pow(10.0, math.log10(qmin)+qstep*n_step) return qmin, -(math.pow(10.0,qstep)-1.0), qmax - + def _get_aligned_binning(self, qmin, qmax): npts = self.getProperty("NumberOfBins").value @@ -246,18 +247,18 @@ def _get_aligned_binning(self, qmin, qmax): x_max = math.pow(10,math.ceil(npts*math.log10(qmax))/npts) b = 1.0/npts nsteps = int(1+math.ceil(npts*math.log10(x_max/x_min))) - + binning = str(x_min) x_bound = x_min - ( x_min*math.pow(10,b) - x_min )/2.0 binning2 = str(x_bound) - + x = x_min for i in range(nsteps): x_bound = 2*x-x_bound x *= math.pow(10,b) binning += ",%g,%g" % (x,x) binning2 += ",%g,%g" % (x_bound,x_bound) - + return binning2 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py index 90b04c7fbfd4..128f77083a97 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py @@ -1,8 +1,8 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * import os -import sys from reduction_workflow.find_data import find_data class SANSBeamSpreaderTransmission(PythonAlgorithm): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py index 57546fb4008b..562d77e894f0 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py @@ -1,4 +1,4 @@ -import mantid.simpleapi as api +#pylint: disable=no-init from mantid.api import * from mantid.kernel import * import os diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py index acba4b537f19..b7e48edbea1f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py index f6940f4489e9..175f8c3fbe5f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * @@ -156,7 +157,7 @@ def _py_exec(self): if "BackgroundFiles" in property_list: background = property_manager.getProperty("BackgroundFiles").value background_ws = "__background_%s" % output_ws - msg = self._multiple_load(background, background_ws, + msg = self._multiple_load(background, background_ws,\ property_manager, property_manager_name) bck_msg = "Loaded background %s\n" % background bck_msg += msg @@ -219,8 +220,8 @@ def _py_exec(self): WorkspaceToMatch=output_ws, OutputWorkspace=background_ws+'_rebin', PreserveEvents=True) - api.Minus(LHSWorkspace=output_ws, - RHSWorkspace=background_ws+'_rebin', + api.Minus(LHSWorkspace=output_ws,\ + RHSWorkspace=background_ws+'_rebin',\ OutputWorkspace=output_ws) bck_msg = bck_msg.replace('\n','\n |') @@ -402,17 +403,17 @@ def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): elif len(process_file)>0 and process_file.lower().find("none") != 0: Logger("SANSReduction").error("Could not read process info file %s\n" % process_file) if property_manager.existsProperty("SetupAlgorithm"): - if property_manager.existsProperty('InstrumentName'): - instrument_name = property_manager.getProperty('InstrumentName').value - else: - instrument_name = 'EQSANS' - setup_info = property_manager.getProperty("SetupAlgorithm").value - proc_xml += "\n\n" - proc_xml += " %s\n" % instrument_name - proc_xml += " %s\n" % setup_info - filename = self.getProperty("Filename").value - proc_xml += " %s\n" % filename - proc_xml += "\n" + if property_manager.existsProperty('InstrumentName'): + instrument_name = property_manager.getProperty('InstrumentName').value + else: + instrument_name = 'EQSANS' + setup_info = property_manager.getProperty("SetupAlgorithm").value + proc_xml += "\n\n" + proc_xml += " %s\n" % instrument_name + proc_xml += " %s\n" % setup_info + filename = self.getProperty("Filename").value + proc_xml += " %s\n" % filename + proc_xml += "\n" filename = os.path.join(output_dir, iq_output+'.txt') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py index e806b2cbcc5c..5e4beec1e3c7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name import mantid,sys class SavePlot1D(mantid.api.PythonAlgorithm): @@ -58,7 +59,7 @@ def DoPlot(self,ws): spectra=ws.getNumberHistograms() if spectra>10: mantid.kernel.logger.warning("more than 10 spectra to plot") - prog_reporter=mantid.api.Progress(self,start=0.0,end=1.0, + prog_reporter=mantid.api.Progress(self,start=0.0,end=1.0,\ nreports=spectra) for j in range(spectra): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py index 6debe06b76df..e6e8fb92e5f4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py @@ -1,6 +1,8 @@ +#pylint: disable=no-init,invalid-name # Algorithm to start Bayes programs from mantid.simpleapi import * -from mantid.api import DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, WorkspaceGroupProperty +from mantid.api import DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, \ + WorkspaceGroupProperty from mantid.kernel import Direction from mantid import logger @@ -12,21 +14,31 @@ class SofQWMoments(DataProcessorAlgorithm): def category(self): return "Workflow\\MIDAS;PythonAlgorithms" + def summary (self): return "Calculates the nth moment of y(q,w)" + def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("Sample", "", Direction.Input), doc="Sample to use.") - self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') - self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') - self.declareProperty(name='Scale', defaultValue=1.0, doc='Scale factor to multiply y(Q,w). Default=1.0') - self.declareProperty(name='Plot', defaultValue=False, doc='Switch Plot Off/On') - self.declareProperty(name='Save', defaultValue=False, doc='Switch Save result to nxs file Off/On') + self.declareProperty(MatrixWorkspaceProperty("Sample", "", Direction.Input), + doc="Sample to use.") + self.declareProperty(name='EnergyMin', defaultValue=-0.5, + doc='Minimum energy for fit. Default=-0.5') + self.declareProperty(name='EnergyMax', defaultValue=0.5, + doc='Maximum energy for fit. Default=0.5') + self.declareProperty(name='Scale', defaultValue=1.0, + doc='Scale factor to multiply y(Q,w). Default=1.0') + self.declareProperty(name='Plot', defaultValue=False, + doc='Switch Plot Off/On') + self.declareProperty(name='Save', defaultValue=False, + doc='Switch Save result to nxs file Off/On') + + self.declareProperty(WorkspaceGroupProperty("OutputWorkspace", "", Direction.Output), + doc="group_workspace workspace that includes all calculated moments.") - self.declareProperty(WorkspaceGroupProperty("OutputWorkspace", "", Direction.Output), doc="group_workspace workspace that includes all calculated moments.") def PyExec(self): - from IndirectCommon import CheckHistZero, CheckElimits, StartTime, EndTime, getDefaultWorkingDirectory + from IndirectCommon import CheckHistZero, CheckElimits, getDefaultWorkingDirectory sample_workspace = self.getPropertyValue('Sample') output_workspace = self.getPropertyValue('OutputWorkspace') @@ -38,16 +50,17 @@ def PyExec(self): Plot = self.getProperty('Plot').value Save = self.getProperty('Save').value - StartTime('SofQWMoments') num_spectra,num_w = CheckHistZero(sample_workspace) - logger.information('Sample %s has %d Q values & %d w values' % (sample_workspace, num_spectra, num_w)) + logger.information('Sample %s has %d Q values & %d w values' % ( + sample_workspace, num_spectra, num_w)) - x = np.asarray(mtd[sample_workspace].readX(0)) - CheckElimits(erange,x) + x_data = np.asarray(mtd[sample_workspace].readX(0)) + CheckElimits(erange,x_data) samWS = '__temp_sqw_moments_cropped' - CropWorkspace(InputWorkspace=sample_workspace, OutputWorkspace=samWS, XMin=erange[0], XMax=erange[1]) + CropWorkspace(InputWorkspace=sample_workspace, OutputWorkspace=samWS, + XMin=erange[0], XMax=erange[1]) logger.information('Energy range is %f to %f' % (erange[0], erange[1])) @@ -57,30 +70,31 @@ def PyExec(self): #calculate delta x ConvertToPointData(InputWorkspace=samWS, OutputWorkspace=samWS) - x = np.asarray(mtd[samWS].readX(0)) - x_workspace = CreateWorkspace(OutputWorkspace="__temp_sqw_moments_x", DataX=x, DataY=x, UnitX="DeltaE") + x_data = np.asarray(mtd[samWS].readX(0)) + x_workspace = CreateWorkspace(OutputWorkspace="__temp_sqw_moments_x", + DataX=x_data, DataY=x_data, UnitX="DeltaE") #calculate moments - m0 = output_workspace + '_M0' - m1 = output_workspace + '_M1' - m2 = output_workspace + '_M2' - m3 = output_workspace + '_M3' - m4 = output_workspace + '_M4' - - Multiply(x_workspace, samWS, OutputWorkspace=m1) - Multiply(x_workspace, m1, OutputWorkspace=m2) - Multiply(x_workspace, m2, OutputWorkspace=m3) - Multiply(x_workspace, m3, OutputWorkspace=m4) - DeleteWorkspace(m3) + moments_0 = output_workspace + '_M0' + moments_1 = output_workspace + '_M1' + moments_2 = output_workspace + '_M2' + moments_3 = output_workspace + '_M3' + moments_4 = output_workspace + '_M4' + + Multiply(x_workspace, samWS, OutputWorkspace=moments_1) + Multiply(x_workspace, moments_1, OutputWorkspace=moments_2) + Multiply(x_workspace, moments_2, OutputWorkspace=moments_3) + Multiply(x_workspace, moments_3, OutputWorkspace=moments_4) + DeleteWorkspace(moments_3) ConvertToHistogram(InputWorkspace=samWS, OutputWorkspace=samWS) - Integration(samWS, OutputWorkspace=m0) + Integration(samWS, OutputWorkspace=moments_0) - moments = [m1, m2, m4] + moments = [moments_1, moments_2, moments_4] for moment_ws in moments: ConvertToHistogram(InputWorkspace=moment_ws, OutputWorkspace=moment_ws) Integration(moment_ws, OutputWorkspace=moment_ws) - Divide(moment_ws, m0, OutputWorkspace=moment_ws) + Divide(moment_ws, moments_0, OutputWorkspace=moment_ws) DeleteWorkspace(samWS) DeleteWorkspace(x_workspace) @@ -91,12 +105,16 @@ def PyExec(self): ws_name = output_workspace+ext Transpose(InputWorkspace=ws_name, OutputWorkspace=ws_name) ConvertToHistogram(InputWorkspace=ws_name, OutputWorkspace=ws_name) - ConvertUnits(InputWorkspace=ws_name, OutputWorkspace=ws_name, Target='MomentumTransfer', EMode='Indirect') + ConvertUnits(InputWorkspace=ws_name, OutputWorkspace=ws_name, + Target='MomentumTransfer', EMode='Indirect') CopyLogs(InputWorkspace=sample_workspace, OutputWorkspace=ws_name) - AddSampleLog(Workspace=ws_name, LogName="energy_min", LogType="Number", LogText=str(emin)) - AddSampleLog(Workspace=ws_name, LogName="energy_max", LogType="Number", LogText=str(emax)) - AddSampleLog(Workspace=ws_name, LogName="scale_factor", LogType="Number", LogText=str(factor)) + AddSampleLog(Workspace=ws_name, LogName="energy_min", + LogType="Number", LogText=str(emin)) + AddSampleLog(Workspace=ws_name, LogName="energy_max", + LogType="Number", LogText=str(emax)) + AddSampleLog(Workspace=ws_name, LogName="scale_factor", + LogType="Number", LogText=str(factor)) # Group output workspace group_workspaces = ','.join([output_workspace+ext for ext in extensions]) @@ -113,14 +131,14 @@ def PyExec(self): self.setProperty("OutputWorkspace", output_workspace) - EndTime('SofQWMoments') def _plot_moments(self, inputWS): from IndirectImport import import_mantidplot - mp = import_mantidplot() + mtd_plot = import_mantidplot() + + mtd_plot.plotSpectrum(inputWS+'_M0', 0) + mtd_plot.plotSpectrum([inputWS+'_M2', inputWS+'_M4'], 0) - mp.plotSpectrum(inputWS+'_M0', 0) - mp.plotSpectrum([inputWS+'_M2', inputWS+'_M4'], 0) # Register algorithm with Mantid AlgorithmFactory.subscribe(SofQWMoments) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py index 45895d7ad55d..d318ac36ca34 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TimeSlice.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * @@ -47,6 +48,16 @@ def _count_monitors(raw_file): class TimeSlice(PythonAlgorithm): + _raw_files = None + _spectra_range = None + _peak_range = None + _output_ws_name_suffix = None + _background_range = None + _calib_ws = None + _out_ws_group = None + _plot = None + _save = None + def category(self): return 'PythonAlgorithms;Inelastic' @@ -59,7 +70,7 @@ def PyInit(self): self.declareProperty(StringArrayProperty(name='InputFiles'), doc='Comma separated list of input files') - self.declareProperty(WorkspaceProperty(name='CalibrationWorkspace', defaultValue='', + self.declareProperty(WorkspaceProperty(name='CalibrationWorkspace', defaultValue='',\ direction=Direction.Input, optional=PropertyMode.Optional), doc='Calibration workspace') @@ -81,7 +92,7 @@ def PyInit(self): self.declareProperty(name='OutputNameSuffix', defaultValue='_slice', doc='Suffix to append to raw file name for name of output workspace') - self.declareProperty(WorkspaceGroupProperty(name='OutputWorkspace', defaultValue='', + self.declareProperty(WorkspaceGroupProperty(name='OutputWorkspace', defaultValue='',\ direction=Direction.Output), doc='Name of workspace group to group result workspaces into') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py index ce4a8202ae0c..efc8c7035174 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py @@ -1,4 +1,4 @@ -import mantid.simpleapi as api +#pylint: disable=invalid-name from mantid.api import * from mantid.kernel import * import os @@ -59,7 +59,7 @@ def _load_data(filename, output_ws): alg_props = {"Filename": filename, "OutputWorkspace": output_ws, - "ReductionProperties": property_manager_name, + "ReductionProperties": property_manager_name,\ } if beam_center_x is not None and beam_center_y is not None: alg_props["BeamCenterX"] = beam_center_x @@ -111,7 +111,7 @@ def _load_data(filename, output_ws): # since the beam center may be at a different location alg = _execute("FindDetectorsInShape", {"Workspace": sample_ws, - "ShapeXML": cylXML + "ShapeXML": cylXML\ }) det_list = alg.getProperty("DetectorList").value first_det = det_list[0] @@ -131,7 +131,7 @@ def _normalise(workspace): alg = _execute(p.valueAsStr, {"InputWorkspace": workspace, "OutputWorkspace": workspace, - "ReductionProperties": property_manager_name + "ReductionProperties": property_manager_name\ }, is_name=False) msg = '' @@ -157,19 +157,19 @@ def _normalise(workspace): alg = _execute("ExtractSingleSpectrum", {"InputWorkspace": empty_ws, "OutputWorkspace": '__reference_binning', - "WorkspaceIndex": det_list[0] + "WorkspaceIndex": det_list[0]\ }) reference_ws = alg.getProperty("OutputWorkspace").value alg = _execute("RebinToWorkspace", {"WorkspaceToRebin": empty_ws, "WorkspaceToMatch": reference_ws, - "OutputWorkspace": empty_ws_name + "OutputWorkspace": empty_ws_name\ }) empty_ws = alg.getProperty("OutputWorkspace").value alg = _execute("RebinToWorkspace", {"WorkspaceToRebin": sample_ws, "WorkspaceToMatch": reference_ws, - "OutputWorkspace": sample_ws_name + "OutputWorkspace": sample_ws_name\ }) sample_ws = alg.getProperty("OutputWorkspace").value @@ -177,7 +177,7 @@ def _normalise(workspace): {"InputWorkspace": empty_ws, "OutputWorkspace": empty_mon_ws_name, "DetectorList": det_list, - "KeepUngroupedSpectra": True + "KeepUngroupedSpectra": True\ }) empty_mon_ws = alg.getProperty("OutputWorkspace").value @@ -185,26 +185,26 @@ def _normalise(workspace): {"InputWorkspace": sample_ws, "OutputWorkspace": sample_mon_ws_name, "DetectorList": det_list, - "KeepUngroupedSpectra": True + "KeepUngroupedSpectra": True\ }) sample_mon_ws = alg.getProperty("OutputWorkspace").value alg = _execute("ConvertToMatrixWorkspace", {"InputWorkspace": empty_mon_ws, - "OutputWorkspace": empty_mon_ws_name + "OutputWorkspace": empty_mon_ws_name\ }) empty_mon_ws = alg.getProperty("OutputWorkspace").value alg = _execute("ConvertToMatrixWorkspace", {"InputWorkspace": sample_mon_ws, - "OutputWorkspace": sample_mon_ws_name + "OutputWorkspace": sample_mon_ws_name\ }) sample_mon_ws = alg.getProperty("OutputWorkspace").value alg = _execute("RebinToWorkspace", {"WorkspaceToRebin": empty_mon_ws, "WorkspaceToMatch": sample_mon_ws, - "OutputWorkspace": empty_mon_ws_name + "OutputWorkspace": empty_mon_ws_name\ }) empty_mon_ws = alg.getProperty("OutputWorkspace").value @@ -267,9 +267,9 @@ def apply_transmission(self, workspace, trans_workspace): {"WorkspaceToRebin": trans_workspace, "WorkspaceToMatch": workspace, "OutputWorkspace": '__trans_rebin', - "PreserveEvents": False + "PreserveEvents": False\ }) - rebinned_ws = alg.getProperty("OutputWorkspace").value; + rebinned_ws = alg.getProperty("OutputWorkspace").value # Apply angle-dependent transmission correction using the zero-angle transmission theta_dependent = self.getProperty("ThetaDependent").value @@ -278,7 +278,7 @@ def apply_transmission(self, workspace, trans_workspace): {"InputWorkspace": workspace, "TransmissionWorkspace": rebinned_ws, "OutputWorkspace": '__corrected_output', - "ThetaDependent": theta_dependent + "ThetaDependent": theta_dependent\ }) output_ws = alg.getProperty("OutputWorkspace").value return output_ws @@ -305,7 +305,7 @@ def _dark(ws, dark_current_property, dark_current_file=None): alg_props = {"InputWorkspace": ws, "PersistentCorrection": False, - "ReductionProperties": property_manager_name + "ReductionProperties": property_manager_name\ } if dark_current_file is not None: alg_props["Filename"] = dark_current_file diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py index 5bbf242df339..f2537713ddd9 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * @@ -9,6 +10,13 @@ class USANSReduction(PythonAlgorithm): + wl_list = None + data_files = None + total_points = None + q_output = None + iq_output = None + iq_err_output = None + def category(self): return "SANS" @@ -21,7 +29,7 @@ def summary(self): def PyInit(self): arrvalidator = IntArrayBoundedValidator() arrvalidator.setLower(0) - self.declareProperty(IntArrayProperty("RunNumbers", values=[0], validator=arrvalidator, + self.declareProperty(IntArrayProperty("RunNumbers", values=[0], validator=arrvalidator,\ direction=Direction.Input), "Runs to reduce") self.declareProperty("EmptyRun", '', "Run number for the empty run") @@ -99,11 +107,11 @@ def _load_data(self): is_scan = True # Append the info for when we do the reduction - self.data_files.append(self.DataFile(workspace=ws_name, - monitor=ws_name+'_monitors', - empty='__empty', - empty_monitor='__empty_monitors', - is_scan=is_scan, + self.data_files.append(self.DataFile(workspace=ws_name,\ + monitor=ws_name+'_monitors',\ + empty='__empty',\ + empty_monitor='__empty_monitors',\ + is_scan=is_scan,\ max_index=max_index)) total_points += max_index @@ -271,9 +279,9 @@ def _get_intensity(self, sample, empty, sample_monitor, empty_monitor, tof_min, OutputWorkspace='transmission') # Scattering signal - __signal_summed = _execute('SumSpectra', InputWorkspace=sample, - StartWorkspaceIndex=0, - EndWorkspaceIndex=nspecs/2, + __signal_summed = _execute('SumSpectra', InputWorkspace=sample,\ + StartWorkspaceIndex=0,\ + EndWorkspaceIndex=nspecs/2,\ OutputWorkspace='__signal_summed') __point = _execute('CropWorkspace', InputWorkspace=__signal_summed, XMin=tof_min, XMax=tof_max, diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py index d52ec45d214f..3cc5c49da707 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name #from MantidFramework import * #from mantidsimple import * from mantid.simpleapi import * @@ -7,7 +8,7 @@ PRECISION = 0.020 -class sfCalculator(): +class sfCalculator(object): ref_date = '2014-10-01' # when the detector has been rotated @@ -66,12 +67,17 @@ class sfCalculator(): is_nexus_detector_rotated_flag = True + a = None + b = None + error_a = None + error_b = None + def __init__(self, numerator=None, denominator=None, tof_range=None): print '---> initialize calculation' - if (tof_range is None): + if tof_range is None: self.tof_min = 10000 self.tof_max = 21600 else: @@ -209,7 +215,7 @@ def isNexusTakeAfterRefDate(self, nexus_date): This function parses the output.date and returns true if this date is after the ref date ''' nexus_date_acquisition = nexus_date.split('T')[0] - + if nexus_date_acquisition > self.ref_date: return True else: @@ -238,7 +244,7 @@ def _calculateFinalYAxis(self, bNumerator=True): nexus_file_numerator = file print '----> loading nexus file: ' + nexus_file_numerator EventDataWks = LoadEventNexus(Filename=nexus_file_numerator) - + self.is_nexus_detector_rotated_flag = self.isNexusTakeAfterRefDate(EventDataWks.getRun().getProperty('run_start').value) if self.is_nexus_detector_rotated_flag: @@ -250,7 +256,7 @@ def _calculateFinalYAxis(self, bNumerator=True): proton_charge = self._getProtonCharge(EventDataWks) print '----> rebinning ' - HistoDataWks = Rebin(InputWorkspace=EventDataWks, + HistoDataWks = Rebin(InputWorkspace=EventDataWks,\ Params=self.rebin_parameters) # mt2 = mtd['HistoDataWks'] @@ -259,9 +265,9 @@ def _calculateFinalYAxis(self, bNumerator=True): x_axis = HistoDataWks.readX(0)[:] self.x_axis = x_axis - OutputWorkspace = self._createIntegratedWorkspace(InputWorkspace=HistoDataWks, - proton_charge=proton_charge, - from_pixel=self.peak_pixel_min, + OutputWorkspace = self._createIntegratedWorkspace(InputWorkspace=HistoDataWks,\ + proton_charge=proton_charge,\ + from_pixel=self.peak_pixel_min,\ to_pixel=self.peak_pixel_max) DataWks = self._removeBackground(InputWorkspace=OutputWorkspace, @@ -329,7 +335,7 @@ def _calculateFinalYAxis(self, bNumerator=True): # mt3 = mtd['DataWks'] - self._calculateFinalAxis(Workspace=DataWks, + self._calculateFinalAxis(Workspace=DataWks,\ bNumerator=bNumerator) print 'done with _calculateFinalAxis and back in calculatefinalaxis' #REMOVEME @@ -385,7 +391,7 @@ def _calculateFinalAxis(self, Workspace=None, bNumerator=None): index_tof_min = self._getIndex(self.tof_min, x_axis) index_tof_max = self._getIndex(self.tof_max, x_axis) - if (bNumerator is True): + if bNumerator is True: self.y_axis_numerator = counts_vs_tof[index_tof_min:index_tof_max].copy() self.y_axis_error_numerator = counts_vs_tof_error[index_tof_min:index_tof_max].copy() self.x_axis_ratio = self.x_axis[index_tof_min:index_tof_max].copy() @@ -429,16 +435,16 @@ def _createIntegratedWorkspace(self, index = int(y+x*304) # y_axis[y, :] += InputWorkspace.readY(index)[:] y_axis[y, :] += InputWorkspace.readY(index)[:] - y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * + y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) *\ (InputWorkspace.readE(index)[:])) - + else: for x in range(304): for y in y_range: index = int(y+x*256) # y_axis[y, :] += InputWorkspace.readY(index)[:] y_axis[y, :] += InputWorkspace.readY(index)[:] - y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * + y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) *\ (InputWorkspace.readE(index)[:])) # #DEBUG @@ -467,9 +473,9 @@ def _createIntegratedWorkspace(self, y_axis /= (proton_charge * 1e-12) y_error_axis /= (proton_charge * 1e-12) - OutputWorkspace = CreateWorkspace(DataX=x_axis, - DataY=y_axis, - DataE=y_error_axis, + OutputWorkspace = CreateWorkspace(DataX=x_axis,\ + DataY=y_axis,\ + DataE=y_error_axis,\ Nspec=self.alpha_pixel_nbr) return OutputWorkspace @@ -481,14 +487,14 @@ def weighted_mean(self, data, error): #calculate numerator dataNum = 0 for i in range(sz): - if (data[i] != 0): + if data[i] != 0: tmpFactor = float(data[i]) / (error[i]**2) dataNum += tmpFactor #calculate denominator dataDen = 0 for i in range(sz): - if (error[i] != 0): + if error[i] != 0: tmpFactor = float(1) / (error[i]**2) dataDen += tmpFactor @@ -566,15 +572,15 @@ def _removeBackground(self, peak_array = zeros(nbr_tof) peak_array_error = zeros(nbr_tof) - bMinBack = False; - bMaxBack = False; + bMinBack = False + bMaxBack = False - min_back = 0; - min_back_error = 0; - max_back = 0; - max_back_error = 0; + min_back = 0 + min_back_error = 0 + max_back = 0 + max_back_error = 0 - for t in (range(nbr_tof-1)): + for t in range(nbr_tof-1): _y_slice = data[:,t] _y_error_slice = error[:,t] @@ -616,17 +622,17 @@ def _removeBackground(self, [final_value, final_error] = self.sumWithError(new_tmp_peak, new_tmp_peak_error) - peak_array[t] = final_value; - peak_array_error[t] = final_error; + peak_array[t] = final_value + peak_array_error[t] = final_error # make new workspace y_axis = peak_array.flatten() y_error_axis = peak_array_error.flatten() - DataWks = CreateWorkspace(DataX=tof_axis[0:-1], - DataY=y_axis, - DataE=y_error_axis, + DataWks = CreateWorkspace(DataX=tof_axis[0:-1],\ + DataY=y_axis,\ + DataE=y_error_axis,\ Nspec=1) # import sys @@ -695,16 +701,16 @@ def fit(self): b coefficients (y=a+bx) """ - DataToFit = CreateWorkspace(DataX=self.x_axis_ratio, - DataY=self.y_axis_ratio, - DataE=self.y_axis_error_ratio, + DataToFit = CreateWorkspace(DataX=self.x_axis_ratio,\ + DataY=self.y_axis_ratio,\ + DataE=self.y_axis_error_ratio,\ Nspec=1) print 'replaceSpecialValues' - DataToFit = ReplaceSpecialValues(InputWorkspace=DataToFit, - NaNValue=0, - NaNError=0, - InfinityValue=0, + DataToFit = ReplaceSpecialValues(InputWorkspace=DataToFit,\ + NaNValue=0,\ + NaNError=0,\ + InfinityValue=0,\ InfinityError=0) # ResetNegatives(InputWorkspace='DataToFit', @@ -743,8 +749,8 @@ def fit(self): xmin = xaxis[0] xmax = xaxis[sz/2] - DataToFit = CropWorkspace(InputWorkspace=DataToFit, - XMin=xmin, + DataToFit = CropWorkspace(InputWorkspace=DataToFit,\ + XMin=xmin,\ XMax=xmax) Fit(InputWorkspace=DataToFit, @@ -779,7 +785,7 @@ def plotObject(instance): linestyle='', label='Exp. data') - if (instance.a is not None): + if instance.a is not None: x = linspace(10000, 22000, 100) _label = "%.3f + x*%.2e" % (instance.a, instance.b) plot(x, instance.a + instance.b * x, label=_label) @@ -857,7 +863,7 @@ def outputFittingParameters(a, b, error_a, error_b, #then if it does, parse the file and check if following infos are #already defined: # lambda_requested, S1H, S2H, S1W, S2W - if (bFileExist): + if bFileExist: f = open(output_file_name, 'r') text = f.readlines() # split_lines = text.split('\n') @@ -879,17 +885,17 @@ def outputFittingParameters(a, b, error_a, error_b, _line_split = _line.split(' ') _incident_medium = variable_value_splitter(_line_split[0]) - if (_incident_medium['value'].strip() == incident_medium.strip()): + if _incident_medium['value'].strip() == incident_medium.strip(): _lambdaRequested = variable_value_splitter(_line_split[1]) - if (isWithinRange(_lambdaRequested['value'], lambda_requested)): + if isWithinRange(_lambdaRequested['value'], lambda_requested): _s1h = variable_value_splitter(_line_split[2]) - if (isWithinRange(_s1h['value'], S1H[i])): + if isWithinRange(_s1h['value'], S1H[i]): _s2h = variable_value_splitter(_line_split[3]) - if (isWithinRange(_s2h['value'],S2H[i])): + if isWithinRange(_s2h['value'],S2H[i]): _s1w = variable_value_splitter(_line_split[4]) - if (isWithinRange(_s1w['value'],S1W[i])): + if isWithinRange(_s1w['value'],S1W[i]): _s2w = variable_value_splitter(_line_split[5]) - if (isWithinRange(_s2w['value'],S2W[i])): + if isWithinRange(_s2w['value'],S2W[i]): _match = True break @@ -994,7 +1000,7 @@ def createIndividualList(string_list_files): list_files = "1000:0, 1001:1, 1002:1, 1003:2" return {1000:0, 1001:1, 1002:2, 1003:2} """ - if (string_list_files == ''): + if string_list_files == '': return None first_split = string_list_files.split(',') @@ -1134,7 +1140,7 @@ def getSlitsValueAndLambda(full_list_runs, for i in range(_nbr_files): _full_file_name = full_list_runs[i] print '-> ' + _full_file_name - tmpWks = LoadEventNexus(Filename=_full_file_name, + tmpWks = LoadEventNexus(Filename=_full_file_name,\ MetaDataOnly='1') # mt1 = mtd['tmpWks'] _s1h_value = getS1h(tmpWks) @@ -1167,7 +1173,7 @@ def isRunsSorted(list_runs, S1H, S2H): _left_formated = "%2.1f" % _left _right_formated = "%2.1f" % _right - if (_left_formated != _right_formated): + if _left_formated != _right_formated: return False return True @@ -1198,7 +1204,7 @@ def calculateAndFit(numerator='', cal1.run() print 'Done with cal1.run()' - if (list_objects != [] and list_objects[-1] is not None): + if list_objects != [] and list_objects[-1] is not None: new_cal1 = cal1 * list_objects[-1] new_cal1.fit() return new_cal1 @@ -1218,7 +1224,7 @@ def help(): print ' list_' #if __name__ == '__main__': -def calculate(string_runs=None, +def calculate(string_runs=None,\ # list_attenuator=None, list_peak_back=None, incident_medium=None, @@ -1247,10 +1253,10 @@ def calculate(string_runs=None, """ - list_attenuator = None; + list_attenuator = None #use default string files if not provided - if (string_runs is None): + if string_runs is None: #Input from user # list_runs = ['55889', '55890', '55891', '55892', '55893', '55894', # '55895', '55896', '55897', '55898', '55899', '55900', @@ -1279,14 +1285,14 @@ def calculate(string_runs=None, list_attenuator = dico['list_attenuator'] - if (incident_medium is None): + if incident_medium is None: incident_medium = "H20" #default value - if (list_attenuator is None): + if list_attenuator is None: # list_attenuator = [0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4] - list_attenuator = [0, 1, 1, 1, 1, 1]; + list_attenuator = [0, 1, 1, 1, 1, 1] - if (list_peak_back is None): + if list_peak_back is None: list_peak_back = zeros((len(list_runs), 4)) #[peak_min, peak_max, back_min, back_max] # list_peak_back[9, ] = [128, 136, 120, 145] # list_peak_back[11, ] = [125, 140, 115, 150] @@ -1381,8 +1387,7 @@ def calculate(string_runs=None, recordSettings(a, b, error_a, error_b, name, cal) - if (i < (len(list_runs) - 1) and - list_attenuator[i + 1] == (_attenuator+1)): + if i < (len(list_runs) - 1) and list_attenuator[i + 1] == (_attenuator+1): list_objects.append(cal) #record S1H and S2H @@ -1412,10 +1417,10 @@ def calculate(string_runs=None, print 'Done !' - else: - """ - sort the files - """ - pass +# else: +# """ +# sort the files +# """ +# pass diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py index b53bc6465092..90eb73a4f8eb 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Spencer Howells, ISIS @date December 05, 2013 @@ -24,7 +25,6 @@ ''' from mantid.api import IFunction1D, FunctionFactory -from mantid import logger import math, numpy as np class ChudleyElliot(IFunction1D): @@ -53,8 +53,8 @@ def functionDeriv1D(self, xvals, jacobian): for x in xvals: s = math.sin(x*length)/(x*length) h = (1.0-s)/tau - jacobian.set(i,0,-h/tau); - jacobian.set(i,1,(math.cos(x*length)-s)/(length*tau)); + jacobian.set(i,0,-h/tau) + jacobian.set(i,1,(math.cos(x*length)-s)/(length*tau)) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py index 00b807febc9a..234ba9411913 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Jose Borreguero, NScD @date October 06, 2013 @@ -31,139 +32,153 @@ class DSFinterp1DFit(IFunction1D): - def category(self): - return 'QuasiElastic' - - def init(self): - '''Declare parameters and attributes that participate in the fitting''' + _RegressionTypes = None + _minWindow = None + _InputWorkspaces = None + _LoadErrors = None + _WorkspaceIndex = None + _ParameterValues = None + _fmin = None + _fmax = None + _LocalRegression = None + _RegressionType = None + _RegressionWindow = None + _xvalues = None + _channelgroup = None + + def category(self): + return 'QuasiElastic' + + def init(self): + '''Declare parameters and attributes that participate in the fitting''' # Active fitting parameters - self.declareParameter('Intensity', 1.0, 'Intensity') - self.declareParameter('TargetParameter', 1.0, 'Target value of the structure factor parameter') - - self.declareAttribute('InputWorkspaces','') - self.declareAttribute('LoadErrors', False) - self.declareAttribute('WorkspaceIndex', 0) - self.declareAttribute('ParameterValues', '') - self.declareAttribute('LocalRegression', True) - self.declareAttribute('RegressionType', 'quadratic') - self.declareAttribute('RegressionWindow', 6) + self.declareParameter('Intensity', 1.0, 'Intensity') + self.declareParameter('TargetParameter', 1.0, 'Target value of the structure factor parameter') + + self.declareAttribute('InputWorkspaces','') + self.declareAttribute('LoadErrors', False) + self.declareAttribute('WorkspaceIndex', 0) + self.declareAttribute('ParameterValues', '') + self.declareAttribute('LocalRegression', True) + self.declareAttribute('RegressionType', 'quadratic') + self.declareAttribute('RegressionWindow', 6) # "private" attributes associated to the declare function attributes - self._InputWorkspaces = None - self._LoadErrors = None - self._WorkspaceIndex = None - self._ParameterValues = None - self._fmin = None - self._fmax = None - self._LocalRegression = None - self._RegressionType = None - self._RegressionTypes = set(['linear','quadratic']) #valid syntaxfor python >= 2.6 - self._RegressionWindow = None - self._minWindow = { 'linear':3, 'quadratic':4 } + self._InputWorkspaces = None + self._LoadErrors = None + self._WorkspaceIndex = None + self._ParameterValues = None + self._fmin = None + self._fmax = None + self._LocalRegression = None + self._RegressionType = None + self._RegressionTypes = set(['linear','quadratic']) #valid syntaxfor python >= 2.6 + self._RegressionWindow = None + self._minWindow = { 'linear':3, 'quadratic':4 } # channelgroup to interpolate values - self._channelgroup = None - self._xvalues = None #energies of the channels - - def setAttributeValue(self, name, value): - if name == "InputWorkspaces": - self._InputWorkspaces = value.split() - if ',' in value: - self._InputWorkspaces = [x.strip() for x in value.split(',')] - elif name == 'LoadErrors': - self._LoadErrors= bool(value) - elif name == 'WorkspaceIndex': - self._WorkspaceIndex = int(value) - elif name == 'ParameterValues': - self._ParameterValues = [ float(f) for f in value.split() ] - self._fmin = min(self._ParameterValues) - self._fmax = max(self._ParameterValues) - elif name == 'LocalRegression': - self._LocalRegression = bool(value) - elif name == 'RegressionType': - self._RegressionType = value.lower() - elif name == 'RegressionWindow': - self._RegressionWindow = value - - def validateParams(self): - '''Check parameters within expected range''' - intensity = self.getParameterValue('Intensity') - if intensity <=0: - message = 'Parameter Intensity in DSFinterp1DFit must be positive. Got {0} instead'.format(intensity) - logger.error(message) - return None - f = self.getParameterValue('TargetParameter') - if f < self._fmin or f > self._fmax: - message = 'TargetParameter {0} is out of bounds [{1}, {2}]. Applying penalty...'.format(f, self._fmin, self._fmax) - logger.error(message) - return None - return {'Intensity':intensity, 'TargetParameter':f} - - - def function1D(self, xvals): - ''' Fit using the interpolated structure factor ''' - p=self.validateParams() - if not p: - return numpy.zeros(len(xvals), dtype=float) # return zeros if parameters not valid + self._channelgroup = None + self._xvalues = None #energies of the channels + + def setAttributeValue(self, name, value): + if name == "InputWorkspaces": + self._InputWorkspaces = value.split() + if ',' in value: + self._InputWorkspaces = [x.strip() for x in value.split(',')] + elif name == 'LoadErrors': + self._LoadErrors= bool(value) + elif name == 'WorkspaceIndex': + self._WorkspaceIndex = int(value) + elif name == 'ParameterValues': + self._ParameterValues = [ float(f) for f in value.split() ] + self._fmin = min(self._ParameterValues) + self._fmax = max(self._ParameterValues) + elif name == 'LocalRegression': + self._LocalRegression = bool(value) + elif name == 'RegressionType': + self._RegressionType = value.lower() + elif name == 'RegressionWindow': + self._RegressionWindow = value + + def validateParams(self): + '''Check parameters within expected range''' + intensity = self.getParameterValue('Intensity') + if intensity <=0: + message = 'Parameter Intensity in DSFinterp1DFit must be positive. Got {0} instead'.format(intensity) + logger.error(message) + return None + f = self.getParameterValue('TargetParameter') + if f < self._fmin or f > self._fmax: + message = 'TargetParameter {0} is out of bounds [{1}, {2}]. Applying penalty...'.format(f, self._fmin, self._fmax) + logger.error(message) + return None + return {'Intensity':intensity, 'TargetParameter':f} + + + def function1D(self, xvals): + ''' Fit using the interpolated structure factor ''' + p=self.validateParams() + if not p: + return numpy.zeros(len(xvals), dtype=float) # return zeros if parameters not valid # The first time the function is called requires initialization of the interpolator - if self._channelgroup == None: + if self._channelgroup == None: # Check consistency of the input # check InputWorkspaces have at least the workspace index - for w in self._InputWorkspaces: - if mtd[w].getNumberHistograms() <= self._WorkspaceIndex: - message = 'Numer of histograms in Workspace {0} does not allow for workspace index {1}'.format(w,self._WorkspaceIndex) - logger.error(message) - raise IndexError(message) + for w in self._InputWorkspaces: + if mtd[w].getNumberHistograms() <= self._WorkspaceIndex: + message = 'Numer of histograms in Workspace {0} does not allow for workspace index {1}'.format(w,self._WorkspaceIndex) + logger.error(message) + raise IndexError(message) # check number of input workspaces and parameters is the same - if len(self._ParameterValues) != len(self._InputWorkspaces): - message = 'Number of InputWorkspaces and ParameterValues should be the same. Found {0} and {1}, respectively'.format(len(self._InputWorkspaces), len(self._ParameterValues)) - logger.error(message) - raise ValueError(message) + if len(self._ParameterValues) != len(self._InputWorkspaces): + message = 'Number of InputWorkspaces and ParameterValues should be the same. Found {0} and {1}, respectively'.format(len(self._InputWorkspaces), len(self._ParameterValues)) + logger.error(message) + raise ValueError(message) # check the regression type is valid - if self._RegressionType not in self._RegressionTypes: - message = 'Regression type {0} not implemented. choose one of {1}'.format(self._RegressionType, ', '.join(self._RegressionTypes)) - logger.error(message) - raise NotImplementedError(message) + if self._RegressionType not in self._RegressionTypes: + message = 'Regression type {0} not implemented. choose one of {1}'.format(self._RegressionType, ', '.join(self._RegressionTypes)) + logger.error(message) + raise NotImplementedError(message) # check the regression window is appropriate for the regression type selected - if self._RegressionWindow < self._minWindow[self._RegressionType]: - message = 'RegressionWindow must be equal or bigger than {0} for regression type {1}'.format(self._minWindow[self._RegressionType], self._RegressionType) - logger.error(message) - raise ValueError(message) + if self._RegressionWindow < self._minWindow[self._RegressionType]: + message = 'RegressionWindow must be equal or bigger than {0} for regression type {1}'.format(self._minWindow[self._RegressionType], self._RegressionType) + logger.error(message) + raise ValueError(message) # Initialize the energies of the channels with the first of the input workspaces - self._xvalues = numpy.copy( mtd[ self._InputWorkspaces[0] ].dataX(self._WorkspaceIndex) ) - if len(self._xvalues) == 1+ len( mtd[ self._InputWorkspaces[0] ].dataY(self._WorkspaceIndex) ): - self._xvalues = (self._xvalues[1:]+self._xvalues[:-1])/2.0 # Deal with histogram data + self._xvalues = numpy.copy( mtd[ self._InputWorkspaces[0] ].dataX(self._WorkspaceIndex) ) + if len(self._xvalues) == 1+ len( mtd[ self._InputWorkspaces[0] ].dataY(self._WorkspaceIndex) ): + self._xvalues = (self._xvalues[1:]+self._xvalues[:-1])/2.0 # Deal with histogram data # Initialize the channel group - nf = len(self._ParameterValues) + nf = len(self._ParameterValues) # Load the InputWorkspaces into a group of dynamic structure factors - from dsfinterp.dsf import Dsf - from dsfinterp.dsfgroup import DsfGroup - dsfgroup = DsfGroup() - for idsf in range(nf): - dsf = Dsf() - dsf.SetIntensities( mtd[ self._InputWorkspaces[idsf] ].dataY(self._WorkspaceIndex) ) - dsf.errors = None # do not incorporate error data - if self._LoadErrors: - dsf.SetErrors(mtd[ self._InputWorkspaces[idsf] ].dataE(self._WorkspaceIndex)) - dsf.SetFvalue( self._ParameterValues[idsf] ) - dsfgroup.InsertDsf(dsf) + from dsfinterp.dsf import Dsf + from dsfinterp.dsfgroup import DsfGroup + dsfgroup = DsfGroup() + for idsf in range(nf): + dsf = Dsf() + dsf.SetIntensities( mtd[ self._InputWorkspaces[idsf] ].dataY(self._WorkspaceIndex) ) + dsf.errors = None # do not incorporate error data + if self._LoadErrors: + dsf.SetErrors(mtd[ self._InputWorkspaces[idsf] ].dataE(self._WorkspaceIndex)) + dsf.SetFvalue( self._ParameterValues[idsf] ) + dsfgroup.InsertDsf(dsf) # Create the interpolator - from dsfinterp.channelgroup import ChannelGroup - self._channelgroup = ChannelGroup() - self._channelgroup.InitFromDsfGroup(dsfgroup) - if self._LocalRegression: - self._channelgroup.InitializeInterpolator(running_regr_type=self._RegressionType, windowlength=self._RegressionWindow) - else: - self._channelgroup.InitializeInterpolator(windowlength=0) + from dsfinterp.channelgroup import ChannelGroup + self._channelgroup = ChannelGroup() + self._channelgroup.InitFromDsfGroup(dsfgroup) + if self._LocalRegression: + self._channelgroup.InitializeInterpolator(running_regr_type=self._RegressionType, windowlength=self._RegressionWindow) + else: + self._channelgroup.InitializeInterpolator(windowlength=0) # channel group has been initialized, so evaluate the interpolator - dsf = self._channelgroup(p['TargetParameter']) + dsf = self._channelgroup(p['TargetParameter']) # Linear interpolation between the energies of the channels and the xvalues we require # NOTE: interpolator evaluates to zero for any of the xvals outside of the domain defined by self._xvalues - intensities_interpolator = interp1d(self._xvalues, p['Intensity']*dsf.intensities, kind='linear') - return intensities_interpolator(xvals) # can we pass by reference? + intensities_interpolator = interp1d(self._xvalues, p['Intensity']*dsf.intensities, kind='linear') + return intensities_interpolator(xvals) # can we pass by reference? # Required to have Mantid recognize the new function +#pylint: disable=unused-import try: - import dsfinterp - FunctionFactory.subscribe(DSFinterp1DFit) + import dsfinterp + FunctionFactory.subscribe(DSFinterp1DFit) except: - logger.debug('Failed to subscribe fit function DSFinterp1DFit; Python package dsfinterp may be missing (https://pypi.python.org/pypi/dsfinterp)') - pass + logger.debug('Failed to subscribe fit function DSFinterp1DFit; Python package dsfinterp may be missing (https://pypi.python.org/pypi/dsfinterp)') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py index 314e436eaadd..e0d7949985e1 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name """ This example implements a simple Linear function that could be used as a background. @@ -9,9 +10,6 @@ derivative """ from mantid.api import IFunction1D, FunctionFactory -from mantid import logger -import math -import numpy as np class Example1DFunction(IFunction1D): @@ -53,8 +51,8 @@ def functionDeriv1D(self, xvals, jacobian): """ i = 0 for x in xvals: - jacobian.set(i,0,1); - jacobian.set(i,1,x); + jacobian.set(i,0,1) + jacobian.set(i,1,x) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py index a24fe9fc4d2c..86aaa24b0b4b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name """ This example reimplements a Gaussian fitting function. It is not meant to be used in production for fitting, it is simply provided as a relatively complete @@ -49,7 +50,7 @@ def functionLocal(self, xvals): height = self.getParameterValue("Height") # Can also be retrieve by index self.getParameterValue(0) peak_centre = self.getParameterValue("PeakCentre") sigma = self.getParameterValue("Sigma") - weight = math.pow(1./sigma,2); + weight = math.pow(1./sigma,2) # Here you can use the NTerms attr if required by # using self._nterms: see setAttributeValue below or @@ -68,10 +69,10 @@ def functionDerivLocal(self, xvals, jacobian): ip = The index of the parameter value whose partial derivative this corresponds to value = The value of the derivative """ - height = self.getParameterValue("Height"); - peak_centre = self.getParameterValue("PeakCentre"); + height = self.getParameterValue("Height") + peak_centre = self.getParameterValue("PeakCentre") sigma = self.getParameterValue("Sigma") - weight = math.pow(1./sigma,2); + weight = math.pow(1./sigma,2) # X index i = 0 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py index bc57736a6c8d..56dc7df6c1e9 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Spencer Howells, ISIS @date December 05, 2013 @@ -24,9 +25,6 @@ ''' from mantid.api import IFunction1D, FunctionFactory -from mantid import logger -import math -import numpy as np class FickDiffusion(IFunction1D): @@ -43,7 +41,7 @@ def function1D(self, xvals): def functionDeriv1D(self, xvals, jacobian): i = 0 for x in xvals: - jacobian.set(i,0,2.0*x); + jacobian.set(i,0,2.0*x) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py index 71916353ad6d..204fcec972c1 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Guinier.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Mathieu Doucet, ORNL @date Oct 10, 2014 @@ -30,7 +31,7 @@ class Guinier(IFunction1D): """ Provide a Guinier fit function for SANS - + I(q) = I(0) exp(-R^2 q^2 / 3) """ def category(self): @@ -58,7 +59,7 @@ def functionDeriv1D(self, xvals, jacobian): rg = self.getParameterValue('Rg') for x in xvals: jacobian.set(i,0, math.exp(-(rg*x)**2/3.0 ) ) - jacobian.set(i,1, -self.getParameterValue("Scale") * math.exp(-(rg*x)**2/3.0 )*2.0/3.0*rg*x*x ); + jacobian.set(i,1, -self.getParameterValue("Scale") * math.exp(-(rg*x)**2/3.0 )*2.0/3.0*rg*x*x ) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py index d567938f179e..491779e40d4a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/GuinierPorod.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Mathieu Doucet, ORNL @date Oct 13, 2014 @@ -30,7 +31,7 @@ class GuinierPorod(IFunction1D): """ Provide a Guinier-Porod model for SANS. - + See Hammouda, J. Appl. Cryst. (2010) 43, 716-719 """ def category(self): @@ -55,7 +56,7 @@ def _boundary_conditions(self, qval): m = self.getParameterValue('M') if Rg<=0: return True if m3.0: return True + if s>3.0: return True return False def _guinier_porod_core(self, qval): @@ -70,7 +71,7 @@ def _guinier_porod_core(self, qval): if self._boundary_conditions(qval): return 0.0 q1 = math.sqrt((m-s)*n/2.0)/Rg if qval < q1: - return math.pow(qval,-s)*math.exp((-qval*qval*Rg*Rg)/n) + return math.pow(qval,-s)*math.exp((-qval*qval*Rg*Rg)/n) else: return math.pow(qval,-m)*math.pow(Rg,s-m)*math.exp((s-m)/2.0)*math.pow((m-s)*n/2.0,(m-s)/2.0) @@ -93,13 +94,13 @@ def _first_derivative_dim(self, qval): result = (2.0*s-m-3.0)/(2.0*(3.0-s)) - 0.5*(math.log(m-s)+math.log(3-s)) result += math.log(Rg) + math.log(2.0) + 1.0 return result * math.pow(qval,-m) * math.pow(Rg,s-m) * math.exp((s-m)/2.0) * math.pow((m-s)*n/2.0,(m-s)/2.0) - - + + def _first_derivative_m(self, qval): """ Compute the first derivative dI/dM @param qval: q-value to evaluate at - + Derivatives can be obtained here: http://www.derivative-calculator.net/#expr=%28%28m-s%29%283-s%29%2F2%29%5E%28%28m%20-%20s%29%2F2%29q%5E-mr%5E%28s-m%29exp%28%28s-m%29%2F2%29&diffvar=m """ @@ -115,7 +116,7 @@ def _first_derivative_m(self, qval): result = -math.log(qval) - math.log(Rg) - math.log(2.0) - 1.0 result += ( (math.log(m-s)+math.log(3-s))/2.0 + 0.5 ) return result * math.pow(qval,-m) * math.pow(Rg,s-m) * math.exp((s-m)/2.0) * math.pow((m-s)*n/2.0,(m-s)/2.0) - + def _first_derivative_rg(self, qval): """ Compute the first derivative dI/d(Rg) @@ -131,9 +132,9 @@ def _first_derivative_rg(self, qval): if qval < q1: return -2.0*Rg*math.pow(qval,-s)*math.exp(-qrg/n)*qval*qval/n else: - return math.pow(qval,-m)*math.exp((s-m)/2.0)*math.pow(((m-s)*n/2.0), + return math.pow(qval,-m)*math.exp((s-m)/2.0)*math.pow(((m-s)*n/2.0),\ ((m-s)/2.0))*(s-m)*math.pow(Rg,(s-m-1)) - + def function1D(self, xvals): """ Evaluate the model @@ -143,7 +144,7 @@ def function1D(self, xvals): scale = self.getParameterValue('Scale') bgd = self.getParameterValue('Background') - output = np.zeros(len(xvals), dtype=float) + output = np.zeros(len(xvals), dtype=float) for i in range(len(xvals)): output[i] = scale * self._guinier_porod_core(xvals[i]) + bgd return output @@ -164,4 +165,4 @@ def functionDeriv1D(self, xvals, jacobian): i += 1 # Required to have Mantid recognise the new function -FunctionFactory.subscribe(GuinierPorod) \ No newline at end of file +FunctionFactory.subscribe(GuinierPorod) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py index 719057b103e6..d11191838628 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Spencer Howells, ISIS @date December 05, 2013 @@ -24,7 +25,6 @@ ''' from mantid.api import IFunction1D, FunctionFactory -from mantid import logger import math, numpy as np class HallRoss(IFunction1D): @@ -56,8 +56,8 @@ def functionDeriv1D(self, xvals, jacobian): for x in xvals: ex = math.exp(-l*x*x) h = (1.0-ex)/tau - jacobian.set(i,0,-h/tau); - jacobian.set(i,1,x*x*ex/tau); + jacobian.set(i,0,-h/tau) + jacobian.set(i,1,x*x*ex/tau) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py index c8814de43f78..6f0b8956e381 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Lorentz.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Mathieu Doucet, ORNL @date Oct 13, 2014 @@ -30,7 +31,7 @@ class Lorentz(IFunction1D): """ Provide a Lorentz model for SANS - + I(q) = scale / ( 1 + q^2 L^2 ) + background """ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py index 6f2f280682c5..69c6729bd0df 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Porod.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Mathieu Doucet, ORNL @date Oct 13, 2014 @@ -30,7 +31,7 @@ class Porod(IFunction1D): """ Provide a Porod model for SANS - + I(q) = C/q^4 + background """ def category(self): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py index fec011b8174f..9f5a53f04ac6 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ''' @author Jose Borreguero, NScD @date October 06, 2013 @@ -28,7 +29,6 @@ import numpy as np import copy -from pdb import set_trace as tr class StretchedExpFT(IFunction1D): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py index 815faac3bc8f..b49549b786eb 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init,invalid-name ''' @author Spencer Howells, ISIS @date December 05, 2013 @@ -24,8 +25,7 @@ ''' from mantid.api import IFunction1D, FunctionFactory -from mantid import logger -import math, numpy as np +import numpy as np class TeixeiraWater(IFunction1D): @@ -55,8 +55,8 @@ def functionDeriv1D(self, xvals, jacobian): i = 0 for x in xvals: h = x*x*length/(tau*(1+x*x*length)) - jacobian.set(i,0,-h/tau); - jacobian.set(i,1,h*(1.0-h*tau)/length); + jacobian.set(i,0,-h/tau) + jacobian.set(i,1,h*(1.0-h*tau)/length) i += 1 # Required to have Mantid recognise the new function diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py index 3832a39214ed..937f02a18f3d 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py @@ -13,6 +13,41 @@ def init(self): def functionLocal(self, xvals): return 5*xvals +class RectangularFunction(IPeakFunction): + def init(self): + self.declareParameter("Height") + self.declareParameter("Fwhm") + self.declareParameter("Center") + + def centre(self): + return self.getParameterValue("Center") + + def setCentre(self, newCenter): + self.setParameter("Center", newCenter) + + def height(self): + return self.getParameterValue("Height") + + def setHeight(self, newHeight): + self.setParameter("Height", newHeight) + + def fwhm(self): + return self.getParameterValue("Fwhm") + + def setFwhm(self, newFwhm): + self.setParameter("Fwhm", newFwhm) + + def functionLocal(self, xvals): + center = self.getParameterValue("Center") + fwhm = self.getParameterValue("Fwhm") + height = self.getParameterValue("Height") + + values = np.zeros(xvals.shape) + nonZero = (xvals > (center - fwhm/2.0)) & (xvals < (center + fwhm / 2.0)) + values[nonZero] = height + + return values + class IPeakFunctionTest(unittest.TestCase): def test_instance_can_be_created_standalone(self): @@ -38,5 +73,23 @@ def test_functionLocal_can_be_called_directly(self): self.assertEquals(10., out[1]) self.assertEquals(15., out[2]) + def test_get_set_intensity(self): + func = RectangularFunction() + func.initialize() + func.setCentre(1.0) + func.setHeight(2.0) + func.setFwhm(3.0) + + # This is a rectangle function with height 2 and width 3, centered + # around 1.0. The intensity should be 6.0 (height * width) + self.assertAlmostEquals(func.intensity(), 6.0, places=10) + + # Setting the intensity only changes height, not width + func.setIntensity(12.0) + + self.assertEquals(func.fwhm(), 3.0) + self.assertAlmostEquals(func.height(), 4.0, places=10) + self.assertAlmostEquals(func.intensity(), 12.0, places=10) + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py index 9726f2b928cd..be86773d8241 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py @@ -1,7 +1,8 @@ import unittest from testhelpers import run_algorithm, WorkspaceCreationHelper from mantid.kernel import V3D -from mantid.api import IPeaksWorkspace +from mantid.geometry import OrientedLattice +from mantid.api import IPeaksWorkspace, IPeak class IPeaksWorkspaceTest(unittest.TestCase): """ @@ -38,6 +39,7 @@ def test_interface(self): # Create a new peak at some Q in the lab frame qlab = V3D(1,2,3) p = pws.createPeak(qlab, 1.54) + p.getQLabFrame() self.assertAlmostEquals( p.getQLabFrame().X(), 1.0, 3) # Now try to add the peak back @@ -50,6 +52,43 @@ def test_interface(self): # Peaks workspace will not be integrated by default. self.assertTrue(not pws.hasIntegratedPeaks()) + + def test_createPeakHKL(self): + pws = WorkspaceCreationHelper.createPeaksWorkspace(0, True) + lattice = pws.mutableSample().getOrientedLattice() + + # Simple test that the creational method is exposed + p = pws.createPeakHKL([1,1,1]) + self.assertTrue(IPeak != None) + + def test_peak_setQLabFrame(self): + pws = WorkspaceCreationHelper.createPeaksWorkspace(1, True) + p = pws.getPeak(0) + try: + p.setQLabFrame(V3D(1,1,1)) + except Exception: + self.fail("Tried setQLabFrame with one V3D argument") + + try: + p.setQLabFrame(V3D(1,1,1), 1) + except Exception: + self.fail("Tried setQLabFrame with one V3D argument and a double distance") + + def test_peak_setQSampleFrame(self): + pws = WorkspaceCreationHelper.createPeaksWorkspace(1, True) + p = pws.getPeak(0) + try: + p.setQSampleFrame(V3D(1,1,1)) + except Exception: + self.fail("Tried setQSampleFrame with one V3D argument") + + try: + p.setQSampleFrame(V3D(1,1,1), 1) + except Exception: + self.fail("Tried setQSampleFrame with one V3D argument and a double distance") + + + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/testhelpers/WorkspaceCreationHelperModule.cpp b/Code/Mantid/Framework/PythonInterface/test/testhelpers/WorkspaceCreationHelperModule.cpp index 28e4e94c7e5f..032de062643f 100644 --- a/Code/Mantid/Framework/PythonInterface/test/testhelpers/WorkspaceCreationHelperModule.cpp +++ b/Code/Mantid/Framework/PythonInterface/test/testhelpers/WorkspaceCreationHelperModule.cpp @@ -69,10 +69,12 @@ BOOST_PYTHON_MODULE(WorkspaceCreationHelper) //=================================== Peak Workspaces =================================== - // Forces the returns the be IEventWorkspace_sptr + // Forces the returns the be IPeaks_sptr typedef IPeaksWorkspace_sptr (*Signature1_Peaks)(const int); + typedef IPeaksWorkspace_sptr (*Signature2_Peaks)(const int, const bool); def("createPeaksWorkspace", (Signature1_Peaks)&createPeaksWorkspace); + def("createPeaksWorkspace", (Signature2_Peaks)&createPeaksWorkspace); //=================================== MD Workspaces =================================== diff --git a/Code/Mantid/Framework/SINQ/CMakeLists.txt b/Code/Mantid/Framework/SINQ/CMakeLists.txt index c308ea296586..2cf113c7486f 100644 --- a/Code/Mantid/Framework/SINQ/CMakeLists.txt +++ b/Code/Mantid/Framework/SINQ/CMakeLists.txt @@ -20,7 +20,6 @@ set ( SRC_FILES src/PoldiTruncateData.cpp src/PoldiUtilities/IPoldiFunction1D.cpp src/PoldiUtilities/MillerIndices.cpp - src/PoldiUtilities/PeakFunctionIntegrator.cpp src/PoldiUtilities/Poldi2DFunction.cpp src/PoldiUtilities/PoldiAutoCorrelationCore.cpp src/PoldiUtilities/PoldiBasicChopper.cpp @@ -71,7 +70,6 @@ set ( INC_FILES inc/MantidSINQ/PoldiUtilities/IPoldiFunction1D.h inc/MantidSINQ/PoldiUtilities/MillerIndices.h inc/MantidSINQ/PoldiUtilities/MillerIndicesIO.h - inc/MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h inc/MantidSINQ/PoldiUtilities/Poldi2DFunction.h inc/MantidSINQ/PoldiUtilities/PoldiAbstractChopper.h inc/MantidSINQ/PoldiUtilities/PoldiAbstractDetector.h @@ -107,7 +105,6 @@ set ( TEST_FILES MDHistoToWorkspace2DTest.h MillerIndicesIOTest.h MillerIndicesTest.h - PeakFunctionIntegratorTest.h Poldi2DFunctionTest.h PoldiAnalyseResidualsTest.h PoldiAutoCorrelationCoreTest.h diff --git a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiSpectrumConstantBackground.h b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiSpectrumConstantBackground.h index 88e8a6f9b6f3..b6dbf102bd6b 100644 --- a/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiSpectrumConstantBackground.h +++ b/Code/Mantid/Framework/SINQ/inc/MantidSINQ/PoldiUtilities/PoldiSpectrumConstantBackground.h @@ -38,8 +38,8 @@ namespace Poldi { Code Documentation is available at: */ class MANTID_SINQ_DLL PoldiSpectrumConstantBackground - : public API::ParamFunction, - public API::IFunction1D, + : virtual public API::ParamFunction, + virtual public API::IFunction1D, public IPoldiFunction1D { public: PoldiSpectrumConstantBackground(); diff --git a/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp b/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp index 6653f1c3cfbc..2f5ab76ffb23 100644 --- a/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp +++ b/Code/Mantid/Framework/SINQ/src/PoldiFitPeaks2D.cpp @@ -18,7 +18,7 @@ use the Build/wiki_maker.py script to generate your full wiki page. #include "MantidSINQ/PoldiUtilities/PoldiPeakCollection.h" #include "MantidSINQ/PoldiUtilities/PoldiInstrumentAdapter.h" #include "MantidSINQ/PoldiUtilities/PoldiDeadWireDecorator.h" -#include "MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h" +#include "MantidAPI/PeakFunctionIntegrator.h" #include "MantidAPI/IPeakFunction.h" #include "MantidSINQ/PoldiUtilities/Poldi2DFunction.h" @@ -571,7 +571,7 @@ PoldiPeakCollection_sptr PoldiFitPeaks2D::getIntegratedPeakCollection( profileFunction->setCentre(0.0); IntegrationResult integration = - peakIntegrator.integrateInfinity(profileFunction); + peakIntegrator.integrateInfinity(*profileFunction); if (!integration.success) { throw std::runtime_error("Problem during peak integration. Aborting."); diff --git a/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp b/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp index 4f33df0617b0..ee0bf9f4dd06 100644 --- a/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp +++ b/Code/Mantid/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp @@ -1,5 +1,4 @@ #include "MantidSINQ/PoldiIndexKnownCompounds.h" -#include "MantidSINQ/PoldiUtilities/PeakFunctionIntegrator.h" #include "MantidKernel/ArrayProperty.h" #include "MantidKernel/MandatoryValidator.h" diff --git a/Code/Mantid/Framework/ScriptRepository/inc/MantidScriptRepository/ScriptRepositoryImpl.h b/Code/Mantid/Framework/ScriptRepository/inc/MantidScriptRepository/ScriptRepositoryImpl.h index dc9306628643..64c0750492af 100644 --- a/Code/Mantid/Framework/ScriptRepository/inc/MantidScriptRepository/ScriptRepositoryImpl.h +++ b/Code/Mantid/Framework/ScriptRepository/inc/MantidScriptRepository/ScriptRepositoryImpl.h @@ -167,7 +167,6 @@ class SCRIPT_DLL_EXPORT ScriptRepositoryImpl : public ScriptRepository { std::string ignoreregex; - bool getProxyConfig(std::string &, unsigned short &); std::string getParentFolder(const std::string &entry); }; diff --git a/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp b/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp index d7c05a2e675a..1f0f1ea81759 100644 --- a/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp +++ b/Code/Mantid/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp @@ -1,8 +1,10 @@ // from mantid #include "MantidScriptRepository/ScriptRepositoryImpl.h" #include "MantidAPI/ScriptRepositoryFactory.h" -#include "MantidKernel/Logger.h" #include "MantidKernel/ConfigService.h" +#include "MantidKernel/Exception.h" +#include "MantidKernel/InternetHelper.h" +#include "MantidKernel/Logger.h" #include "MantidKernel/NetworkProxy.h" #include "MantidKernel/ProxyInfo.h" #include @@ -18,11 +20,12 @@ using Mantid::Kernel::NetworkProxy; #include #include #include -#include -#include #include -#include #include +/*#include +#include +#include +*/ #include #include "Poco/Net/FilePartSource.h" @@ -41,7 +44,6 @@ using Mantid::Kernel::NetworkProxy; #include #endif #include -#include #include #include #include @@ -62,23 +64,6 @@ namespace { Kernel::Logger g_log("ScriptRepositoryImpl"); } -static ScriptRepoException pocoException(const std::string &info, - Poco::Exception &ex) { - std::stringstream ss; - if (dynamic_cast(&ex)) - ss << info << ", because you do not have access to write to this path :" - << ex.message() << std::ends; - else if (dynamic_cast(&ex)) - ss << info << ". The definition of the remote url is not correct. Please " - "check the Mantid settings, the ScriptRepository entry. " - "Current: " << ex.message() << std::ends; - else { - ss << info << " . Unknown:" << ex.displayText() << std::ends; - } - - return ScriptRepoException(ss.str(), ex.displayText()); -} - const char *timeformat = "%Y-%b-%d %H:%M:%S"; const char *emptyURL = @@ -781,18 +766,9 @@ void ScriptRepositoryImpl::upload(const std::string &file_path, try { g_log.notice() << "ScriptRepository uploading " << file_path << " ..." << std::endl; - Poco::URI uri(remote_upload); - std::string path(uri.getPathAndQuery()); - HTTPClientSession session(uri.getHost(), uri.getPort()); - - // configure proxy - std::string proxy_config; - unsigned short proxy_port; - if (getProxyConfig(proxy_config, proxy_port)) - session.setProxy(proxy_config, proxy_port); - // proxy end - - HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_0); + + Kernel::InternetHelper inetHelper; + HTMLForm form(HTMLForm::ENCODING_MULTIPART); // add the fields author, email and comment @@ -816,32 +792,23 @@ void ScriptRepositoryImpl::upload(const std::string &file_path, FilePartSource *m_file = new FilePartSource(absolute_path); form.addPart("file", m_file); - // get the size of everything - std::stringstream sst; - form.write(sst); - // move back to the begining of the file - m_file->stream().clear(); - m_file->stream().seekg(0, std::ios::beg); - // set the size - req.setContentLength((int)sst.str().size()); - - form.prepareSubmit(req); - std::ostream &ostr = session.sendRequest(req); - // send the request. - ostr << sst.str(); - - HTTPResponse response; - std::istream &rs = session.receiveResponse(response); + inetHelper.setBody(form); + std::stringstream server_reply; + int status; + try { + status = inetHelper.sendRequest(remote_upload,server_reply); + } catch (Kernel::Exception::InternetError &ie) { + status = ie.errorCode(); + } + g_log.information() << "ScriptRepository upload status: " - << response.getStatus() << " " << response.getReason() + << status << std::endl; std::stringstream answer; { // remove the status message from the end of the reply, in order not to // get exception from the read_json parser - std::stringstream server_reply; std::string server_reply_str; - Poco::StreamCopier::copyStream(rs, server_reply); server_reply_str = server_reply.str(); size_t pos = server_reply_str.rfind("}"); if (pos != std::string::npos) @@ -1092,20 +1059,10 @@ std::string ScriptRepositoryImpl::doDeleteRemoteFile( using namespace Poco::Net; std::stringstream answer; try { - // create the poco httprequest object - Poco::URI uri(url); - std::string path(uri.getPathAndQuery()); - HTTPClientSession session(uri.getHost(), uri.getPort()); - HTTPRequest req(HTTPRequest::HTTP_POST, path, HTTPMessage::HTTP_1_0); g_log.debug() << "Receive request to delete file " << file_path << " using " << url << std::endl; - // configure proxy - std::string proxy_config; - unsigned short proxy_port; - if (getProxyConfig(proxy_config, proxy_port)) - session.setProxy(proxy_config, proxy_port); - // proxy end + Kernel::InternetHelper inetHelper; // fill up the form required from the server to delete one file, with the // fields @@ -1117,22 +1074,23 @@ std::string ScriptRepositoryImpl::doDeleteRemoteFile( form.add("file_n", file_path); // send the request to the server - form.prepareSubmit(req); - std::ostream &ostr = session.sendRequest(req); - form.write(ostr); + inetHelper.setBody(form); + std::stringstream server_reply; + int status; + try { + status = inetHelper.sendRequest(url,server_reply); + } catch (Kernel::Exception::InternetError &ie) + { + status = ie.errorCode(); + } - // get the answer from the server - HTTPResponse response; - std::istream &rs = session.receiveResponse(response); - g_log.debug() << "ScriptRepository delete status: " << response.getStatus() - << " " << response.getReason() << std::endl; + g_log.debug() << "ScriptRepository delete status: " << status + << std::endl; { // get the answer from the server - std::stringstream server_reply; std::string server_reply_str; - Poco::StreamCopier::copyStream(rs, server_reply); server_reply_str = server_reply.str(); // remove the status message from the end of the reply, // in order not to get exception from the read_json parser @@ -1332,9 +1290,10 @@ void ScriptRepositoryImpl::doDownloadFile(const std::string &url_file, const std::string &local_file_path) { g_log.debug() << "DoDownloadFile : " << url_file << " to file: " << local_file_path << std::endl; + + // get the information from url_file - Poco::URI uri(url_file); - std::string path(uri.getPathAndQuery()); + std::string path(url_file); if (path.empty()) path = "/"; std::string given_path; @@ -1346,69 +1305,25 @@ void ScriptRepositoryImpl::doDownloadFile(const std::string &url_file, given_path = path; // Configure Poco HTTP Client Session try { - Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort()); - session.setTimeout(Poco::Timespan(3, 0)); // 3 secconds - - // configure proxy - std::string proxy_config; - unsigned short proxy_port; - if (getProxyConfig(proxy_config, proxy_port)) - session.setProxy(proxy_config, proxy_port); - // proxy end - - Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, path, - Poco::Net::HTTPMessage::HTTP_1_1); - Poco::Net::HTTPResponse response; - - session.sendRequest(request); - - std::istream &rs = session.receiveResponse(response); - g_log.debug() << "Answer from mantid web: " << response.getStatus() << " " - << response.getReason() << std::endl; - if (response.getStatus() == Poco::Net::HTTPResponse::HTTP_OK) { - if (local_file_path.empty()) { - // ignore the answer, trow it away - Poco::NullOutputStream null; - Poco::StreamCopier::copyStream(rs, null); - return; - } else { - // copy the file - Poco::FileStream _out(local_file_path); - Poco::StreamCopier::copyStream(rs, _out); - _out.close(); - } - } else { - std::stringstream info; - std::stringstream ss; - Poco::StreamCopier::copyStream(rs, ss); - if (response.getStatus() == Poco::Net::HTTPResponse::HTTP_NOT_FOUND) - info << "Failed to download " << given_path - << " because it failed to find this file at the link " - << ".\n" - << "Hint. Check that link is correct and points to the correct " - "server " - << "which you can find at " - << "Script Repository Help Page"; - else { - // show the error - // fixme, process this error - info << response.getReason(); - info << ss.str(); - } - throw ScriptRepoException(info.str(), ss.str()); - } - } catch (Poco::Net::HostNotFoundException &ex) { - // this exception occurrs when the pc is not connected to the internet + Kernel::InternetHelper inetHelper; + inetHelper.setTimeout(3); // 3 seconds + + //std::stringstream ss; + int status = inetHelper.downloadFile(url_file,local_file_path); + + g_log.debug() << "Answer from mantid web: " << status << std::endl; + } + catch (Kernel::Exception::InternetError &ie) { std::stringstream info; info << "Failed to download " << given_path - << " because there is no connection to the host " << ex.message() - << ".\nHint: Check your connection following this link: " << given_path << ""; - throw ScriptRepoException(info.str(), ex.displayText(), __FILE__, __LINE__); - - } catch (Poco::Exception &ex) { - throw pocoException("Connection and request failed", ex); + << " because it failed to find this file at the link " + << "" << url_file << ".\n" + << "Hint. Check that link is correct and points to the correct " + "server " + << "which you can find at " + << "Script Repository Help Page"; + throw ScriptRepoException(info.str(), ie.what()); } } @@ -1770,62 +1685,6 @@ std::string ScriptRepositoryImpl::convertPath(const std::string &path) { return path; } -bool ScriptRepositoryImpl::getProxyConfig(std::string &proxy_server, - unsigned short &proxy_port) { - // these variables are made static, so, to not query the system for the proxy - // configuration - // everytime this information is needed - - Mantid::Kernel::NetworkProxy proxyHelper; - ProxyInfo proxyInfo = proxyHelper.getHttpProxy(remote_url); - if (proxyInfo.emptyProxy()) { - g_log.information( - "ScriptRepository: No HTTP network proxy settings found. None used."); - } else { - g_log.information( - "ScriptRepository: HTTP System network proxy settings found."); - g_log.debug() << "ScriptRepository Host found: " << proxyInfo.host() - << " Port found: " << proxyInfo.port() << std::endl; - } - - if (!proxyInfo.emptyProxy()) { - try { - // test if the proxy is valid for connecting to remote repository - Poco::URI uri(remote_url); - Poco::Net::HTTPClientSession session(uri.getHost(), uri.getPort()); - // setup a request to read the remote url - Poco::Net::HTTPRequest request(Poco::Net::HTTPRequest::HTTP_GET, "/", - Poco::Net::HTTPMessage::HTTP_1_1); - // through the proxy - session.setProxy(proxyInfo.host(), - static_cast(proxyInfo.port())); - session.sendRequest( - request); // if it fails, it will throw exception here. - - // clear the answer. - Poco::Net::HTTPResponse response; - std::istream &rs = session.receiveResponse(response); - Poco::NullOutputStream null; - Poco::StreamCopier::copyStream(rs, null); - // report that the proxy was configured - g_log.information() << "ScriptRepository proxy found. Host: " - << proxyInfo.host() << " Port: " << proxyInfo.port() - << std::endl; - proxy_server = proxyInfo.host(); - proxy_port = static_cast(proxyInfo.port()); - } catch (Poco::Net::HostNotFoundException &ex) { - g_log.information() << "ScriptRepository found that proxy can not be " - "used for this connection.\n" << ex.displayText() - << std::endl; - } catch (...) { - g_log.warning() << "Unexpected error while looking for the proxy for " - "ScriptRepository." << std::endl; - } - } - - return !proxyInfo.emptyProxy(); - ; -} } // END API diff --git a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h index 030e53a84b3a..073fe49bd53c 100644 --- a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h +++ b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/ComponentCreationHelper.h @@ -150,6 +150,9 @@ createTestInstrumentRectangular(int num_banks, int pixels, Mantid::Geometry::Instrument_sptr createTestInstrumentRectangular2(int num_banks, int pixels, double pixelSpacing = 0.008); + +/// Creates a mimimal valid virtual instrument. +Mantid::Geometry::Instrument_sptr createMinimalInstrument(const Mantid::Kernel::V3D& sourcePos, const Mantid::Kernel::V3D& samplePos, const Mantid::Kernel::V3D& detectorPos ); } #endif // COMPONENTCREATIONHELPERS_H_ diff --git a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/WorkspaceCreationHelper.h b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/WorkspaceCreationHelper.h index ab03c4524252..82afcca56f62 100644 --- a/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/WorkspaceCreationHelper.h +++ b/Code/Mantid/Framework/TestHelpers/inc/MantidTestHelpers/WorkspaceCreationHelper.h @@ -294,7 +294,7 @@ Mantid::DataObjects::RebinnedOutput_sptr CreateRebinnedOutputWorkspace(); /// Create a simple peaks workspace containing the given number of peaks boost::shared_ptr -createPeaksWorkspace(const int numPeaks = 2); +createPeaksWorkspace(const int numPeaks = 2, const bool createOrientedLattice=false); /**Build table workspace with preprocessed detectors for existign worksapce with * instrument */ boost::shared_ptr diff --git a/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp b/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp index 110cb9803fb1..0618e788d5aa 100644 --- a/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp +++ b/Code/Mantid/Framework/TestHelpers/src/ComponentCreationHelper.cpp @@ -20,9 +20,11 @@ #include "MantidGeometry/Instrument/DetectorGroup.h" #include "MantidGeometry/Instrument/Detector.h" #include "MantidGeometry/Instrument/RectangularDetector.h" +#include "MantidGeometry/Instrument/ReferenceFrame.h" #include #include +#include #include "MantidGeometry/IDetector.h" using namespace Mantid::Geometry; @@ -559,4 +561,45 @@ Instrument_sptr createTestInstrumentRectangular2(int num_banks, int pixels, return testInst; } + +/** + * createOneDetectorInstrument, creates the most simple possible definition of an instrument in which we can extract a valid L1 and L2 distance for unit calculations. + * + * Beam direction is along X, + * Up direction is Y + * + * @param sourcePos : V3D position + * @param samplePos : V3D sample position + * @param detectorPos : V3D detector position + * @return Instrument generated. + */ +Instrument_sptr createMinimalInstrument(const Mantid::Kernel::V3D& sourcePos, const Mantid::Kernel::V3D& samplePos, const Mantid::Kernel::V3D& detectorPos ) +{ + Instrument_sptr instrument = boost::make_shared(); + instrument->setReferenceFrame( + boost::make_shared(Mantid::Geometry::Y /*up*/, Mantid::Geometry::X /*along*/, Left, "0,0,0")); + + // A source + ObjComponent *source = new ObjComponent("source"); + source->setPos(sourcePos); + source->setShape(createSphere(0.01 /*1cm*/, V3D(0,0,0), "1")); + instrument->add(source); + instrument->markAsSource(source); + + // A sample + ObjComponent *sample = new ObjComponent("some-surface-holder"); + sample->setPos(samplePos); + sample->setShape(createSphere(0.01 /*1cm*/, V3D(0,0,0), "1")); + instrument->add(sample); + instrument->markAsSamplePos(sample); + + // A detector + Detector *det = new Detector("point-detector", 1 /*detector id*/, NULL); + det->setPos(detectorPos); + det->setShape(createSphere(0.01 /*1cm*/, V3D(0,0,0), "1")); + instrument->add(det); + instrument->markAsDetector(det); + + return instrument; +} } diff --git a/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp b/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp index 9e2b671e577f..11df5295a6c6 100644 --- a/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp +++ b/Code/Mantid/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp @@ -318,7 +318,7 @@ create2DWorkspaceWithFullInstrument(int nhist, int nbins, bool includeMonitors, boost::shared_ptr testInst(new Instrument(instrumentName)); testInst->setReferenceFrame( - boost::shared_ptr(new ReferenceFrame(Y, X, Left, ""))); + boost::shared_ptr(new ReferenceFrame(Y, Z, Left, ""))); space->setInstrument(testInst); const double pixelRadius(0.05); @@ -366,14 +366,14 @@ create2DWorkspaceWithFullInstrument(int nhist, int nbins, bool includeMonitors, // Define a source and sample position // Define a source component ObjComponent *source = - new ObjComponent("moderator", Object_sptr(), testInst.get()); + new ObjComponent("moderator", ComponentCreationHelper::createSphere(0.1, V3D(0,0,0), "1"), testInst.get()); source->setPos(V3D(-20, 0.0, 0.0)); testInst->add(source); testInst->markAsSource(source); // Define a sample as a simple sphere ObjComponent *sample = - new ObjComponent("samplePos", Object_sptr(), testInst.get()); + new ObjComponent("samplePos", ComponentCreationHelper::createSphere(0.1, V3D(0,0,0), "1"), testInst.get()); testInst->setPos(0.0, 0.0, 0.0); testInst->add(sample); testInst->markAsSamplePos(sample); @@ -1182,7 +1182,7 @@ RebinnedOutput_sptr CreateRebinnedOutputWorkspace() { } Mantid::DataObjects::PeaksWorkspace_sptr -createPeaksWorkspace(const int numPeaks) { +createPeaksWorkspace(const int numPeaks, const bool createOrientedLattice) { PeaksWorkspace_sptr peaksWS(new PeaksWorkspace()); Instrument_sptr inst = ComponentCreationHelper::createTestInstrumentRectangular2(1, 10); @@ -1193,6 +1193,10 @@ createPeaksWorkspace(const int numPeaks) { peaksWS->addPeak(peak); } + if(createOrientedLattice) { + Mantid::Geometry::OrientedLattice lattice; + peaksWS->mutableSample().setOrientedLattice(&lattice); + } return peaksWS; } diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp b/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp index b5ee9826cf2d..ae6efa60dc60 100644 --- a/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp +++ b/Code/Mantid/Framework/WorkflowAlgorithms/src/SendUsage.cpp @@ -6,7 +6,6 @@ #include "MantidKernel/InternetHelper.h" #include "MantidKernel/MantidVersion.h" #include "MantidKernel/ParaViewVersion.h" -#include #include namespace Mantid { @@ -35,9 +34,6 @@ const int STATUS_DEFAULT = -1; const std::string URL("http://reports.mantidproject.org/api/usage"); // const std::string URL("http://127.0.0.1:8000/api/usage"); // dev location -/// The string for post method -const std::string POST(Poco::Net::HTTPRequest::HTTP_POST); - /// @returns true if Kernel::ConfigService says the option is on. bool doSend() { // create a variable to pass in @@ -121,10 +117,10 @@ void SendUsage::sendReport(const std::string &json) { int status = STATUS_DEFAULT; try { - std::map htmlHeaders; Kernel::InternetHelper helper; std::stringstream responseStream; - status = helper.sendRequest(URL, responseStream, htmlHeaders, POST, json); + helper.setBody(json); + status = helper.sendRequest(URL, responseStream); g_log.debug() << "Call to \"" << URL << "\" responded with " << status << "\n" << responseStream.str() << "\n"; } diff --git a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp index a13343453c9d..1101ccb3f69f 100644 --- a/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp +++ b/Code/Mantid/MantidPlot/src/ApplicationWindow.cpp @@ -2203,15 +2203,17 @@ void ApplicationWindow::updateTableNames(const QString& oldName, const QString& { QList windows = windowsList(); foreach (MdiSubWindow *w, windows) { - if (w->isA("MultiLayer")) { - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + auto g3d = dynamic_cast(w); + if (ml) { + QList layers = ml->layersList(); foreach(Graph *g, layers) - g->updateCurveNames(oldName, newName); - } else if (w->isA("Graph3D")) { - QString name = dynamic_cast(w)->formula(); + g->updateCurveNames(oldName, newName); + } else if (g3d) { + QString name = g3d->formula(); if (name.contains(oldName, true)) { name.replace(oldName,newName); - dynamic_cast(w)->setPlotAssociation(name); + g3d->setPlotAssociation(name); } } } @@ -2221,13 +2223,18 @@ void ApplicationWindow::updateColNames(const QString& oldName, const QString& ne { QList windows = windowsList(); foreach (MdiSubWindow *w, windows){ - if (w->isA("MultiLayer")){ - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + auto g3d = dynamic_cast(w); + + if(ml) + { + QList layers = ml->layersList(); foreach(Graph *g, layers) - g->updateCurveNames(oldName, newName, false); + g->updateCurveNames(oldName, newName, false); } - else if (w->isA("Graph3D")){ - QString name = dynamic_cast(w)->formula(); + else if(g3d) + { + QString name = g3d->formula(); if (name.contains(oldName)){ name.replace(oldName,newName); dynamic_cast(w)->setPlotAssociation(name); @@ -2242,16 +2249,22 @@ void ApplicationWindow::changeMatrixName(const QString& oldName, const QString& foreach(MdiSubWindow *w, windows){ if (w->isA("Graph3D")) { - QString s = dynamic_cast(w)->formula(); + auto g3d = dynamic_cast(w); + if(!g3d) + return; + QString s = g3d->formula(); if (s.contains(oldName)) { s.replace(oldName, newName); - dynamic_cast(w)->setPlotAssociation(s); + g3d->setPlotAssociation(s); } } else if (w->isA("MultiLayer")) { - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + if(!ml) + return; + QList layers = ml->layersList(); foreach(Graph *g, layers){ for (int i=0; icurves(); i++){ QwtPlotItem *sp = dynamic_cast(g->plotItem(i)); @@ -2272,10 +2285,13 @@ void ApplicationWindow::remove3DMatrixPlots(Matrix *m) QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ - if (w->isA("Graph3D") && dynamic_cast(w)->matrix() == m) - dynamic_cast(w)->clearData(); - else if (w->isA("MultiLayer")){ - QList layers = dynamic_cast(w)->layersList(); + auto g3d = dynamic_cast(w); + if(g3d && g3d->matrix() == m) + g3d->clearData(); + auto ml = dynamic_cast(w); + + if(ml) { + QList layers = ml->layersList(); foreach(Graph *g, layers){ for (int i=0; icurves(); i++){ if (g->curveType(i) == Graph::Histogram){ @@ -2304,10 +2320,17 @@ void ApplicationWindow::updateMatrixPlots(MdiSubWindow *window) QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ - if (w->isA("Graph3D") && dynamic_cast(w)->matrix() == m) - dynamic_cast(w)->updateMatrixData(m); + if (w->isA("Graph3D")) { + auto g3d = dynamic_cast(w); + if(g3d && g3d->matrix() == m) + g3d->updateMatrixData(m); + } else if (w->isA("MultiLayer")){ - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + if(!ml) + continue; + + QList layers = ml->layersList(); foreach(Graph *g, layers){ for (int i=0; icurves(); i++){ if (g->curveType(i) == Graph::Histogram){ @@ -2418,7 +2441,10 @@ void ApplicationWindow::insert3DMatrixPlot(const QString& matrix_name) if (!w) return; - dynamic_cast(w)->addMatrixData(matrix(matrix_name)); + auto g3d = dynamic_cast(w); + if(g3d) + g3d->addMatrixData(matrix(matrix_name)); + emit modified(); } @@ -2428,7 +2454,9 @@ void ApplicationWindow::insertNew3DData(const QString& colName) if (!w) return; - dynamic_cast(w)->insertNewData(table(colName),colName); + auto g3d = dynamic_cast(w); + if(g3d) + g3d->insertNewData(table(colName),colName); emit modified(); } @@ -2452,6 +2480,9 @@ void ApplicationWindow::editSurfacePlot() return; Graph3D* g = dynamic_cast(w); + if(!g) + return; + SurfaceDialog* sd = new SurfaceDialog(this); sd->setAttribute(Qt::WA_DeleteOnClose); @@ -3015,7 +3046,11 @@ void ApplicationWindow::customizeTables(const QColor& bgColor,const QColor& text QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ if (w->inherits("Table")) - customTable(dynamic_cast(w)); + { + auto table = dynamic_cast(w); + if(table) + customTable(table); + } } } @@ -3837,6 +3872,9 @@ void ApplicationWindow::removeErrorBars() return; MultiLayer* plot = dynamic_cast(w); + if(!plot) + return; + if (plot->isEmpty()){ QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid tr("

There are no plot layers available in this window.

" @@ -3871,7 +3909,11 @@ void ApplicationWindow::removeErrorBars(const QString& name) if (!w) return; - Graph* g = dynamic_cast(w)->activeGraph(); + auto ml = dynamic_cast(w); + if(!ml) + return; + + Graph* g = ml->activeGraph(); if (!g) return; @@ -3885,7 +3927,11 @@ void ApplicationWindow::defineErrorBars(const QString& name, int type, const QSt if (!w) return; - Graph* g = dynamic_cast(w)->activeGraph(); + auto ml = dynamic_cast(w); + if(!ml) + return; + + Graph* g = ml->activeGraph(); if (!g) return; @@ -3903,6 +3949,9 @@ void ApplicationWindow::defineErrorBars(const QString& name, int type, const QSt } DataCurve *master_curve = dynamic_cast(g->curve(name)); + if(!master_curve) + return; + QString xColName = master_curve->xColumnName(); if (xColName.isEmpty()) return; @@ -4004,14 +4053,18 @@ void ApplicationWindow::removeCurves(const QString& name) foreach(MdiSubWindow *w, windows){ if (w->isA("MultiLayer")) { - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + if(!ml) + return; + QList layers = ml->layersList(); foreach(Graph *g, layers) - g->removeCurves(name); + g->removeCurves(name); } else if (w->isA("Graph3D")) { - if ( (dynamic_cast(w)->formula()).contains(name) ) - dynamic_cast(w)->clearData(); + auto g3d = dynamic_cast(w); + if(g3d && g3d->formula().contains(name)) + g3d->clearData(); } } QApplication::restoreOverrideCursor(); @@ -4022,12 +4075,16 @@ void ApplicationWindow::updateCurves(Table *t, const QString& name) QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ if (w->isA("MultiLayer")){ - QList layers = dynamic_cast(w)->layersList(); - foreach(Graph *g, layers) - g->updateCurvesData(t, name); + MultiLayer* ml = dynamic_cast(w); + if(ml) + { + QList layers = ml->layersList(); + foreach(Graph *g, layers) + g->updateCurvesData(t, name); + } } else if (w->isA("Graph3D")){ Graph3D* g = dynamic_cast(w); - if ((g->formula()).contains(name)) + if (g && (g->formula()).contains(name)) g->updateData(t); } } @@ -4169,7 +4226,10 @@ void ApplicationWindow::setGraphDefaultSettings(bool autoscale, bool scaleFonts, foreach(MdiSubWindow *w, windows){ if (w->isA("MultiLayer")) { - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + if(!ml) + continue; + QList layers = ml->layersList(); foreach(Graph *g, layers) { g->enableAutoscaling(autoscale2DPlots); @@ -4509,7 +4569,11 @@ ApplicationWindow* ApplicationWindow::open(const QString& fn, bool factorySettin QFile f(fname); QTextStream t( &f ); - f.open(QIODevice::ReadOnly); + if(!f.open(QIODevice::ReadOnly)) + { + QMessageBox::critical(this, tr("MantidPlot - File opening error"), tr("The file: %1 could not be opened!").arg(fn)); + return 0; + } QString s = t.readLine(); QStringList list = s.split(QRegExp("\\s"), QString::SkipEmptyParts); if (list.count() < 2 || list[0] != "MantidPlot"){ @@ -5894,6 +5958,8 @@ void ApplicationWindow::exportAllGraphs() if (w->isA("MultiLayer")) { plot3D = 0; plot2D = dynamic_cast(w); + if(!plot2D) + continue; if (plot2D->isEmpty()) { QApplication::restoreOverrideCursor(); QMessageBox::warning(this, tr("MantidPlot - Warning"),//Mantid @@ -5905,6 +5971,8 @@ void ApplicationWindow::exportAllGraphs() } else if (w->isA("Graph3D")) { plot2D = 0; plot3D = dynamic_cast(w); + if(!plot3D) + continue; } else continue; @@ -5915,8 +5983,7 @@ void ApplicationWindow::exportAllGraphs() QString msg = tr("A file called:

%1

already exists. ""Do you want to overwrite it?").arg(file_name); QMessageBox msgBox(QMessageBox::Question, tr("MantidPlot - Overwrite file?"), msg,//Mantid - QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::Cancel, - dynamic_cast(this)); + QMessageBox::Yes | QMessageBox::YesToAll | QMessageBox::No | QMessageBox::Cancel, this); msgBox.exec(); switch(msgBox.standardButton(msgBox.clickedButton())){ case QMessageBox::Yes: @@ -6057,7 +6124,11 @@ void ApplicationWindow::restoreWindowGeometry(ApplicationWindow *app, MdiSubWind Folder* ApplicationWindow::projectFolder() const { - return dynamic_cast(folders->firstChild())->folder(); + auto fli = dynamic_cast(folders->firstChild()); + if(fli) + return fli->folder(); + else + throw std::runtime_error("Couldn't retrieve project folder"); } bool ApplicationWindow::saveProject(bool compress) @@ -6212,8 +6283,11 @@ void ApplicationWindow::saveProjectAs(const QString& fileName, bool compress) QFileInfo fi(fn); QString baseName = fi.baseName(); FolderListItem *item = dynamic_cast(folders->firstChild()); - item->setText(0, baseName); - item->folder()->setObjectName(baseName); + if(item) + { + item->setText(0, baseName); + item->folder()->setObjectName(baseName); + } } } } @@ -6241,6 +6315,9 @@ void ApplicationWindow::rename() void ApplicationWindow::renameWindow() { WindowListItem *it = dynamic_cast(lv->currentItem()); + if (!it) + return; + MdiSubWindow *w = it->window(); if (!w) return; @@ -6256,8 +6333,15 @@ void ApplicationWindow::renameWindow(Q3ListViewItem *item, int, const QString &t if (!item) return; - MdiSubWindow *w = dynamic_cast(item)->window(); - if (!w || text == w->objectName()) + WindowListItem *wli = dynamic_cast(item); + if (!wli) + return; + + MdiSubWindow *w = wli->window(); + if (!w) + return; + + if(text == w->objectName()) return; if(!setWindowName(w, text)) @@ -6330,14 +6414,18 @@ void ApplicationWindow::showCurvesDialog() if (!w) return; - if (dynamic_cast(w)->isEmpty()){ + auto ml = dynamic_cast(w); + if(!ml) + return; + + if (ml->isEmpty()){ QMessageBox::warning(this,tr("MantidPlot - Error"),//Mantid tr("

There are no plot layers available in this window.

" "

Please add a layer and try again!

")); return; } - Graph* g = dynamic_cast(w)->activeGraph(); + Graph* g = ml->activeGraph(); if (!g) return; @@ -6403,7 +6491,11 @@ AssociationsDialog* ApplicationWindow::showPlotAssociations(int curve) if (!w) return 0; - Graph *g = dynamic_cast(w)->activeGraph(); + auto ml = dynamic_cast(w); + if(!ml) + return 0; + + Graph *g = ml->activeGraph(); if (!g) return 0; @@ -6421,8 +6513,12 @@ void ApplicationWindow::showTitleDialog() return; if (w->isA("MultiLayer")){ - Graph* g = dynamic_cast(w)->activeGraph(); - if (g){ + auto ml = dynamic_cast(w); + if(!ml) + return; + + Graph* g = ml->activeGraph(); + if (g) { TextDialog* td= new TextDialog(TextDialog::LayerTitle, this,0); td->setGraph(g); td->exec(); @@ -6440,7 +6536,11 @@ void ApplicationWindow::showAxisTitleDialog() if (!w) return; - Graph* g = dynamic_cast(w)->activeGraph(); + auto ml = dynamic_cast(w); + if(!ml) + return; + + Graph* g = ml->activeGraph(); if (!g) return; @@ -6478,35 +6578,28 @@ void ApplicationWindow::exportAllTables(const QString& sep, bool colNames, bool if (w->inherits("Table") || w->isA("Matrix")){ QString fileName = dir + "/" + w->objectName() + ".txt"; QFile f(fileName); - if (f.exists(fileName) && confirmOverwrite){ + if (f.exists(fileName) && confirmOverwrite) + { QApplication::restoreOverrideCursor(); - switch(QMessageBox::question(this, tr("MantidPlot - Overwrite file?"),//Mantid + auto result = QMessageBox::question(this, tr("MantidPlot - Overwrite file?"), tr("A file called:

%1

already exists. " - "Do you want to overwrite it?").arg(fileName), tr("&Yes"), tr("&All"), tr("&Cancel"), 0, 1)) - { - case 0: - if (w->inherits("Table")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, colNames, colComments, expSelection); - else if (w->isA("Matrix")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, expSelection); - break; + "Do you want to overwrite it?").arg(fileName), + tr("&Yes"), tr("&All"), tr("&Cancel"), 0, 1); - case 1: + if(result == 1) confirmOverwrite = false; - if (w->inherits("Table")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, colNames, colComments, expSelection); - else if (w->isA("Matrix")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, expSelection); - break; - - case 2: + else if(result == 2) return; - break; - } - } else if (w->inherits("Table")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, colNames, colComments, expSelection); - else if (w->isA("Matrix")) - success = (dynamic_cast(w))->exportASCII(fileName, sep, expSelection); + + } + + auto table = dynamic_cast(w); + auto matrix = dynamic_cast(w); + + if(table) + success = table->exportASCII(fileName, sep, colNames, colComments, expSelection); + else if(matrix) + success = matrix->exportASCII(fileName, sep, expSelection); if (!success) break; @@ -6623,10 +6716,13 @@ void ApplicationWindow::recalculateTable() if (!w) return; - if (w->inherits("Table")) - (dynamic_cast(w))->calculate(); - else if (w->isA("Matrix")) - (dynamic_cast(w))->calculate(); + auto table = dynamic_cast(w); + auto matrix = dynamic_cast(w); + + if(table) + table->calculate(); + else if(matrix) + matrix->calculate(); } void ApplicationWindow::sortActiveTable() @@ -7147,32 +7243,18 @@ void ApplicationWindow::showAxisDialog() QDialog* gd = showScaleDialog(); if (gd && plot->isA("MultiLayer")) { - MultiLayer* ml; - try - { - ml = dynamic_cast(plot); - } - catch(std::runtime_error& ) - { - g_log.error() << "Failed to open axis dialog for multi layer plot"; + MultiLayer* ml = dynamic_cast(plot); + if (!ml || (ml && !ml->layers())) return; - } - if (ml && ml->layers()) - dynamic_cast(gd)->showAxesPage(); + + auto ad = dynamic_cast(gd); + if(ad) + ad->showAxesPage(); } else if (gd && plot->isA("Graph3D")) { - Plot3DDialog* p3d; - try - { - p3d = dynamic_cast(gd); - } - catch(std::runtime_error& ) - { - g_log.error() << "Failed to open axis dialog for multi layer plot"; - return; - } - if (p3d) + Plot3DDialog* p3d = dynamic_cast(gd); + if(p3d) p3d->showAxisTab(); } } @@ -7191,20 +7273,14 @@ QDialog* ApplicationWindow::showScaleDialog() return 0; if (w->isA("MultiLayer")){ - MultiLayer* ml; - try - { - ml = dynamic_cast(w); - } - catch(std::runtime_error& ) - { - g_log.error() << "Failed to open scale dialog for multi layer plot"; - return 0; - } + auto ml = dynamic_cast(w); if (!ml || ml->isEmpty()) return 0; - Graph* g = dynamic_cast(w)->activeGraph(); + Graph* g = ml->activeGraph(); + if(!g) + return 0; + if (g->isPiePlot()){ QMessageBox::warning(this, tr("MantidPlot - Warning"), tr("This functionality is not available for pie plots!"));//Mantid return 0; @@ -7437,20 +7513,17 @@ void ApplicationWindow::showCurveWorksheet(Graph *g, int curveIndex) if (!it) return; - if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) - { - Spectrogram *sp = dynamic_cast(it); - if (sp->matrix()) - sp->matrix()->showMaximized(); - } - else if (dynamic_cast(it)->type() == Graph::Function) - { - g->createTable(dynamic_cast(it)); - } - else - { + + auto sp = dynamic_cast(it); + auto pc = dynamic_cast(it); + + if(sp && sp->matrix()) + sp->matrix()->showMaximized(); + if(pc && pc->type() == Graph::Function) + g->createTable(pc); + + if(!pc && !sp) showTable(it->title().text()); - } } void ApplicationWindow::showCurveWorksheet() @@ -7623,7 +7696,9 @@ void ApplicationWindow::exportPDF() if (!w) return; - if (w->isA("MultiLayer") && (dynamic_cast(w))->isEmpty()){ + auto ml = dynamic_cast(w); + + if (w->isA("MultiLayer") && ml && ml->isEmpty()) { QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid tr("

There are no plot layers available in this window.

")); return; @@ -7658,7 +7733,8 @@ void ApplicationWindow::print() if (!w) return; - if (w->isA("MultiLayer") && (dynamic_cast(w))->isEmpty()){ + auto ml = dynamic_cast(w); + if (w->isA("MultiLayer") && ml && ml->isEmpty()){ QMessageBox::warning(this,tr("MantidPlot - Warning"),//Mantid tr("

There are no plot layers available in this window.

")); return; @@ -7689,7 +7765,11 @@ void ApplicationWindow::printAllPlots() foreach(MdiSubWindow *w, windows){ if (w->isA("MultiLayer") && printer.newPage()) - dynamic_cast(w)->printAllLayers(paint); + { + MultiLayer* ml = dynamic_cast(w); + if (ml) + ml->printAllLayers(paint); + } } paint->end(); delete paint; @@ -7744,7 +7824,11 @@ void ApplicationWindow::showFitDialog() if(w->isA("MultiLayer")) plot = dynamic_cast(w); else if(w->inherits("Table")) - plot = multilayerPlot(dynamic_cast(w), dynamic_cast(w)->drawableColumnSelection(), Graph::LineSymbols); + { + Table* t = dynamic_cast(w); + if(t) + plot = multilayerPlot(t, t->drawableColumnSelection(), Graph::LineSymbols); + } if (!plot) return; @@ -7806,20 +7890,33 @@ void ApplicationWindow::showFFTDialog() FFTDialog *sd = 0; if (w->isA("MultiLayer")) { - Graph* g = dynamic_cast(w)->activeGraph(); - if ( g && g->validCurvesDataSize() ){ + MultiLayer* ml = dynamic_cast(w); + if(!ml) + return; + + Graph* g = ml->activeGraph(); + if(!g) + return; + + if (g->validCurvesDataSize() ){ sd = new FFTDialog(FFTDialog::onGraph, this); sd->setAttribute(Qt::WA_DeleteOnClose); sd->setGraph(g); } } else if (w->inherits("Table")) { + Table* t = dynamic_cast(w); + if(!t) + return; sd = new FFTDialog(FFTDialog::onTable, this); sd->setAttribute(Qt::WA_DeleteOnClose); - sd->setTable(dynamic_cast(w)); + sd->setTable(t); } else if (w->inherits("Matrix")) { + Matrix* m = dynamic_cast(w); + if(!m) + return; sd = new FFTDialog(FFTDialog::onMatrix, this); sd->setAttribute(Qt::WA_DeleteOnClose); - sd->setMatrix(dynamic_cast(w)); + sd->setMatrix(m); } if (sd) @@ -8338,22 +8435,36 @@ void ApplicationWindow::clearSelection() return; if (m->inherits("Table")) - dynamic_cast(m)->clearSelection(); + { + auto t = dynamic_cast(m); + if(t) + t->clearSelection(); + } else if (m->isA("Matrix")) - dynamic_cast(m)->clearSelection(); + { + auto matrix = dynamic_cast(m); + if(matrix) + matrix->clearSelection(); + } else if (m->isA("MultiLayer")) { - Graph* g = dynamic_cast(m)->activeGraph(); + auto ml = dynamic_cast(m); + if(!ml) + return; + + Graph* g = ml->activeGraph(); if (!g) return; if (g->activeTool()) { - if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector) - dynamic_cast(g->activeTool())->clearSelection(); + auto rst = dynamic_cast(g->activeTool()); + auto lbt = dynamic_cast(g->activeTool()); - if (g->activeTool()->rtti() == PlotToolInterface::Rtti_LabelTool) - dynamic_cast(g->activeTool())->removeTextBox(); + if(rst) + rst->clearSelection(); + else if(lbt) + lbt->removeTextBox(); } else if (g->titleSelected()) @@ -8362,7 +8473,11 @@ void ApplicationWindow::clearSelection() g->removeMarker(); } else if (m->isA("Note")) - dynamic_cast(m)->editor()->clear(); + { + auto note = dynamic_cast(m); + if(note) + note->editor()->clear(); + } emit modified(); } @@ -8376,11 +8491,20 @@ void ApplicationWindow::copySelection() if (!m) return; - if (m->inherits("Table")) - dynamic_cast(m)->copySelection(); + if (m->inherits("Table")) + { + Table* table = dynamic_cast(m); + if(table) + table->copySelection(); + } else if (m->isA("Matrix")) - dynamic_cast(m)->copySelection(); - else if (m->isA("MultiLayer")){ + { + Matrix* matrix = dynamic_cast(m); + if(matrix) + matrix->copySelection(); + } + else if (m->isA("MultiLayer")) + { MultiLayer* plot = dynamic_cast(m); if (!plot || plot->layers() == 0) return; @@ -8392,7 +8516,9 @@ void ApplicationWindow::copySelection() if (g->activeTool()){ if (g->activeTool()->rtti() == PlotToolInterface::Rtti_RangeSelector) { - dynamic_cast(g->activeTool())->copySelection(); + RangeSelectorTool* rst = dynamic_cast(g->activeTool()); + if(rst) + rst->copySelection(); } } else if (g->markerSelected()){ copyMarker(); @@ -8404,7 +8530,11 @@ void ApplicationWindow::copySelection() plot->copyAllLayers(); } else if (m->isA("Note")) - dynamic_cast(m)->editor()->copy(); + { + Note* note = dynamic_cast(m); + if(note) + note->editor()->copy(); + } else mantidUI->copyValues();//Mantid } @@ -8479,11 +8609,23 @@ void ApplicationWindow::pasteSelection() return; if (m->inherits("Table")) - dynamic_cast(m)->pasteSelection(); + { + auto table = dynamic_cast(m); + if(table) + table->pasteSelection(); + } else if (m->isA("Matrix")) - dynamic_cast(m)->pasteSelection(); + { + auto matrix = dynamic_cast(m); + if(matrix) + matrix->pasteSelection(); + } else if (m->isA("Note")) - dynamic_cast(m)->editor()->paste(); + { + auto note = dynamic_cast(m); + if(note) + note->editor()->paste(); + } else if (m->isA("MultiLayer")){ MultiLayer* plot = dynamic_cast(m); if (!plot) @@ -8558,18 +8700,26 @@ MdiSubWindow* ApplicationWindow::clone(MdiSubWindow* w) if (w->isA("MultiLayer")){ MultiLayer *g = dynamic_cast(w); + if(!g) + return NULL; nw = multilayerPlot(generateUniqueName(tr("Graph")), 0, g->getRows(), g->getCols()); - dynamic_cast(nw)->copy(g); + auto nwg = dynamic_cast(nw); + if(nwg) + nwg->copy(g); } else if (w->inherits("Table")){ Table *t = dynamic_cast(w); + if(!t) + return NULL; QString caption = generateUniqueName(tr("Table")); nw = newTable(caption, t->numRows(), t->numCols()); } else if (w->isA("Graph3D")){ Graph3D *g = dynamic_cast(w); + if(!g) + return NULL; if (!g->hasData()){ QApplication::restoreOverrideCursor(); QMessageBox::warning(this, tr("MantidPlot - Duplicate error"), tr("Empty 3D surface plots cannot be duplicated!"));//Mantid - return 0; + return NULL; } QString caption = generateUniqueName(tr("Graph")); @@ -8602,15 +8752,32 @@ MdiSubWindow* ApplicationWindow::clone(MdiSubWindow* w) if (status == MdiSubWindow::Maximized) nw->hide(); - dynamic_cast(nw)->copy(g); + auto g3d = dynamic_cast(nw); + if(g3d) + g3d->copy(g); customToolBars(nw); } else if (w->isA("Matrix")){ - nw = newMatrix((dynamic_cast(w))->numRows(), (dynamic_cast(w))->numCols()); - dynamic_cast(nw)->copy(dynamic_cast(w)); + auto matrix = dynamic_cast(w); + if(!matrix) + return NULL; + nw = newMatrix(matrix->numRows(), matrix->numCols()); + auto nwmatrix = dynamic_cast(nw); + if(nwmatrix) + nwmatrix->copy(matrix); } else if (w->isA("Note")){ + auto note = dynamic_cast(w); + if(!note) + return NULL; + nw = newNote(); - if (nw) - dynamic_cast(nw)->setText(dynamic_cast(w)->text()); + if(!nw) + return NULL; + + auto nwnote = dynamic_cast(nw); + if(!nwnote) + return NULL; + + nwnote->setText(note->text()); } if (nw){ @@ -8618,13 +8785,16 @@ MdiSubWindow* ApplicationWindow::clone(MdiSubWindow* w) if (status == MdiSubWindow::Maximized) nw->showMaximized(); } else if (w->isA("Graph3D")){ - dynamic_cast(nw)->setIgnoreFonts(true); + auto g3d = dynamic_cast(nw); + if(!g3d) + return NULL; + g3d->setIgnoreFonts(true); if (status != MdiSubWindow::Maximized){ nw->resize(w->size()); nw->showNormal(); } else nw->showMaximized(); - dynamic_cast(nw)->setIgnoreFonts(false); + g3d->setIgnoreFonts(false); } else { nw->resize(w->size()); nw->showNormal(); @@ -8647,10 +8817,14 @@ void ApplicationWindow::undo() QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - if (qobject_cast(w)) - dynamic_cast(w)->editor()->undo(); - else if (qobject_cast(w)){ - QUndoStack *stack = (dynamic_cast(w))->undoStack(); + auto note = dynamic_cast(w); + auto matrix = dynamic_cast(w); + + if(note) + note->editor()->undo(); + else if(matrix) + { + QUndoStack *stack = matrix->undoStack(); if (stack && stack->canUndo()) stack->undo(); } @@ -8665,10 +8839,14 @@ void ApplicationWindow::redo() QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - if (qobject_cast(w)) - dynamic_cast(w)->editor()->redo(); - else if (qobject_cast(w)){ - QUndoStack *stack = (dynamic_cast(w))->undoStack(); + auto note = dynamic_cast(w); + auto matrix = dynamic_cast(w); + + if(note) + note->editor()->redo(); + else if(matrix) + { + QUndoStack *stack = matrix->undoStack(); if (stack && stack->canRedo()) stack->redo(); } @@ -8746,6 +8924,9 @@ void ApplicationWindow::resizeActiveWindow() void ApplicationWindow::resizeWindow() { WindowListItem *it = dynamic_cast(lv->currentItem()); + if (!it) + return; + MdiSubWindow *w = it->window(); if (!w) return; @@ -8824,7 +9005,8 @@ void ApplicationWindow::setActiveWindow(MdiSubWindow* w) void ApplicationWindow::activateWindow() { WindowListItem *it = dynamic_cast(lv->currentItem()); - activateWindow(it->window()); + if(it) + activateWindow(it->window()); } /** @@ -8906,7 +9088,9 @@ void ApplicationWindow::activateWindow(Q3ListViewItem * lbi) if (!lbi || lbi->rtti() == FolderListItem::RTTI) return; - activateWindow(dynamic_cast(lbi)->window()); + auto wli = dynamic_cast(lbi); + if(wli) + activateWindow(wli->window()); } void ApplicationWindow::maximizeWindow(Q3ListViewItem * lbi) @@ -8917,7 +9101,9 @@ void ApplicationWindow::maximizeWindow(Q3ListViewItem * lbi) if (!lbi || lbi->rtti() == FolderListItem::RTTI) return; - maximizeWindow(dynamic_cast(lbi)->window()); + auto wli = dynamic_cast(lbi); + if(wli) + maximizeWindow(wli->window()); } void ApplicationWindow::maximizeWindow(MdiSubWindow *w) @@ -8940,8 +9126,10 @@ void ApplicationWindow::maximizeWindow(MdiSubWindow *w) void ApplicationWindow::minimizeWindow(MdiSubWindow *w) { + auto wli = dynamic_cast(lv->currentItem()); + if (!w) - w = (dynamic_cast(lv->currentItem()))->window(); + w = wli->window(); if (!w) return; @@ -8974,23 +9162,28 @@ void ApplicationWindow::removeWindowFromLists(MdiSubWindow* w) QString caption = w->objectName(); if (w->inherits("Table")){ - Table* m=dynamic_cast(w); + Table* m = dynamic_cast(w); + if(!m) + return; for (int i=0; inumCols(); i++){ QString name=m->colName(i); removeCurves(name); } } else if (w->isA("MultiLayer")){ - MultiLayer *ml = dynamic_cast(w); + MultiLayer *ml = dynamic_cast(w); + if(!ml) + return; Graph *g = ml->activeGraph(); - if (g) - btnPointer->setChecked(true); + if(!g) + return; + btnPointer->setChecked(true); } else if (w->isA("Matrix")) { - remove3DMatrixPlots(dynamic_cast(w)); + auto matrix = dynamic_cast(w); + if(matrix) + remove3DMatrixPlots(matrix); } - else { } - if (hiddenWindows->contains(w)) { hiddenWindows->takeAt(hiddenWindows->indexOf(w)); @@ -9565,7 +9758,11 @@ void ApplicationWindow::savedProject() foreach(MdiSubWindow *w, folderWindows) { if (w->isA("Matrix")) - (dynamic_cast(w))->undoStack()->setClean(); + { + Matrix* m = dynamic_cast(w); + if (m) + m->undoStack()->setClean(); + } } f = f->folderBelow(); } @@ -9724,11 +9921,17 @@ void ApplicationWindow::deleteSelectedItems() folders->blockSignals(true); foreach(item, lst){ if (item->rtti() == FolderListItem::RTTI){ - Folder *f = dynamic_cast(item)->folder(); + auto fli = dynamic_cast(item); + if(!fli) + continue; + Folder *f = fli->folder(); if (deleteFolder(f)) delete item; - } else - dynamic_cast(item)->window()->close(); + } else { + auto wli = dynamic_cast(item); + if(wli) + wli->window()->close(); + } } folders->blockSignals(false); } @@ -9786,12 +9989,20 @@ void ApplicationWindow::showWindowPopupMenu(Q3ListViewItem *it, const QPoint &p, } if (it->rtti() == FolderListItem::RTTI){ - d_current_folder = dynamic_cast(it)->folder(); - showFolderPopupMenu(it, p, false); + auto fli = dynamic_cast(it); + if(fli) + { + d_current_folder = fli->folder(); + showFolderPopupMenu(it, p, false); + } return; } - MdiSubWindow *w= dynamic_cast(it)->window(); + auto wli = dynamic_cast(it); + if(!wli) + return; + + MdiSubWindow *w = wli->window(); if (w){ QMenu cm(this); QMenu plots(this); @@ -9842,6 +10053,8 @@ void ApplicationWindow::showWindowPopupMenu(Q3ListViewItem *it, const QPoint &p, } } else if (w->isA("Graph3D")) { Graph3D *sp=dynamic_cast(w); + if(!sp) + return; Matrix *m = sp->matrix(); QString formula = sp->formula(); if (!formula.isEmpty()){ @@ -9903,8 +10116,12 @@ QStringList ApplicationWindow::depending3DPlots(Matrix *m) QStringList plots; QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ - if (w->isA("Graph3D") && dynamic_cast(w)->matrix() == m) - plots << w->objectName(); + if (w->isA("Graph3D")) + { + auto g3d = dynamic_cast(w); + if(g3d && g3d->matrix() == m) + plots << w->objectName(); + } } return plots; } @@ -9916,7 +10133,10 @@ QStringList ApplicationWindow::dependingPlots(const QString& name) QList windows = windowsList(); foreach(MdiSubWindow *w, windows){ if (w->isA("MultiLayer")){ - QList layers = dynamic_cast(w)->layersList(); + auto ml = dynamic_cast(w); + if(!ml) + return plots; + QList layers = ml->layersList(); foreach(Graph *g, layers){ onPlot = g->curvesList(); onPlot = onPlot.grep (name,TRUE); @@ -9924,7 +10144,8 @@ QStringList ApplicationWindow::dependingPlots(const QString& name) plots << w->objectName(); } }else if (w->isA("Graph3D")){ - if ((dynamic_cast(w)->formula()).contains(name,TRUE) && plots.contains(w->objectName())<=0) + auto g3d = dynamic_cast(w); + if (g3d && (g3d->formula()).contains(name,TRUE) && !plots.contains(w->objectName())) plots << w->objectName(); } } @@ -9934,14 +10155,17 @@ QStringList ApplicationWindow::dependingPlots(const QString& name) QStringList ApplicationWindow::multilayerDependencies(QWidget *w) { QStringList tables; - MultiLayer *g=dynamic_cast(w); + MultiLayer* g = dynamic_cast(w); + if(!g) + return tables; + QList layers = g->layersList(); foreach(Graph *ag, layers){ QStringList onPlot=ag->curvesList(); for (int j=0; j(plot->activeGraph()); + if(!ag) + return; PlotToolInterface* tool = ag->activeTool(); if (dynamic_cast(tool)) { - dynamic_cast(tool)->prepareContextMenu(cm); + auto ppt = dynamic_cast(tool); + if(!ppt) + return; + ppt->prepareContextMenu(cm); cm.exec(QCursor::pos()); return; } @@ -10062,6 +10291,8 @@ void ApplicationWindow::showWindowContextMenu() QMenu plot3D(this); if (w->isA("MultiLayer")){ MultiLayer *g = dynamic_cast(w); + if(!g) + return; if (lastCopiedLayer){ cm.insertItem(getQPixmap("paste_xpm"), tr("&Paste Layer"), this, SLOT(pasteSelection())); cm.insertSeparator(); @@ -10083,6 +10314,8 @@ void ApplicationWindow::showWindowContextMenu() cm.addAction(actionCloseWindow); } else if (w->isA("Graph3D")){ Graph3D *g=dynamic_cast(w); + if(!g) + return; if (!g->hasData()){ cm.insertItem(tr("3D &Plot"), &plot3D); plot3D.addAction(actionAdd3DData); @@ -10109,6 +10342,8 @@ void ApplicationWindow::showWindowContextMenu() cm.addAction(actionCloseWindow); } else if (w->isA("Matrix")) { Matrix *t = dynamic_cast(w); + if(!t) + return; if (t->viewType() == Matrix::TableView){ cm.insertItem(getQPixmap("cut_xpm"),tr("Cu&t"), t, SLOT(cutSelection())); cm.insertItem(getQPixmap("copy_xpm"),tr("&Copy"), t, SLOT(copySelection())); @@ -10740,6 +10975,8 @@ void ApplicationWindow::custom3DActions(MdiSubWindow *w) if (w && w->isA("Graph3D")) { Graph3D* plot = dynamic_cast(w); + if(!plot) + return; actionAnimate->setOn(plot->isAnimated()); actionPerspective->setOn(!plot->isOrthogonal()); switch(plot->plotStyle()) @@ -11667,11 +11904,16 @@ void ApplicationWindow::integrate() if (w->isA("MultiLayer")) analysis(Integrate); - else if (w->isA("Matrix")){ + else if (w->isA("Matrix")) + { + auto matrix = dynamic_cast(w); + if(!matrix) + return; + QDateTime dt = QDateTime::currentDateTime (); QString info = dt.toString(Qt::LocalDate); info += "\n" + tr("Integration of %1 from zero is").arg(QString(w->objectName())) + ":\t"; - info += QString::number((dynamic_cast(w))->integrate()) + "\n"; + info += QString::number(matrix->integrate()) + "\n"; info += "-------------------------------------------------------------\n"; currentFolder()->appendLogInfo(info); showResults(true); @@ -11839,6 +12081,8 @@ void ApplicationWindow::setPlot3DOptions() foreach(MdiSubWindow *w, windows){ if (w->isA("Graph3D")){ Graph3D *g = dynamic_cast(w); + if(!g) + continue; g->setOrthogonal(orthogonal3DPlots); g->setAutoscale(autoscale3DPlots); g->setAntialiasing(smooth3DMesh); @@ -13495,12 +13739,24 @@ void ApplicationWindow::deleteFitTables() foreach(QWidget *ml, *mLst){ if (ml->isA("MultiLayer")){ - QList layers = dynamic_cast(ml)->layersList(); + auto cml = dynamic_cast(ml); + if(!cml) + continue; + + QList layers = cml->layersList(); foreach(Graph *g, layers){ QList curves = g->fitCurvesList(); foreach(QwtPlotCurve *c, curves){ - if (dynamic_cast(c)->type() != Graph::Function){ - Table *t = dynamic_cast(c)->table(); + auto curve = dynamic_cast(c); + if(!curve) + continue; + + if(curve->type() != Graph::Function) + { + auto dc = dynamic_cast(c); + if(!dc) + continue; + Table *t = dc->table(); if (!t) continue; @@ -14127,7 +14383,12 @@ Folder* ApplicationWindow::appendProject(const QString& fn, Folder* parentFolder QFile file(fn); QFileInfo fileInfo(fn); - file.open(QIODevice::ReadOnly); + if(!file.open(QIODevice::ReadOnly)) + { + QMessageBox::critical(this, tr("MantidPlot - File opening error"), tr("The file: %1 could not be opened!").arg(fn)); + return 0; + } + QTextStream fileTS(&file); fileTS.setEncoding(QTextStream::UnicodeUTF8); @@ -14274,7 +14535,12 @@ void ApplicationWindow::showFolderPopupMenu(Q3ListViewItem *it, const QPoint &p, cm.insertItem(tr("&Find..."), this, SLOT(showFindDialogue())); cm.insertSeparator(); cm.insertItem(tr("App&end Project..."), this, SLOT(appendProject())); - if (dynamic_cast(it)->folder()->parent()) + + auto fli = dynamic_cast(it); + if(!fli) + return; + + if (fli->folder()->parent()) cm.insertItem(tr("Save &As Project..."), this, SLOT(saveAsProject())); else cm.insertItem(tr("Save Project &As..."), this, SLOT(saveProjectAs())); @@ -14287,7 +14553,7 @@ void ApplicationWindow::showFolderPopupMenu(Q3ListViewItem *it, const QPoint &p, cm.insertSeparator(); } - if (dynamic_cast(it)->folder()->parent()) + if (fli->folder()->parent()) { cm.insertItem(getQPixmap("close_xpm"), tr("&Delete Folder"), this, SLOT(deleteFolder()), Qt::Key_F8); cm.insertItem(tr("&Rename"), this, SLOT(startRenameFolder()), Qt::Key_F2); @@ -14364,8 +14630,12 @@ void ApplicationWindow::startRenameFolder(Q3ListViewItem *item) return; if (item->listView() == lv && item->rtti() == FolderListItem::RTTI) { + auto fli = dynamic_cast(item); + if(!fli) + return; + disconnect(folders, SIGNAL(currentChanged(Q3ListViewItem *)), this, SLOT(folderItemChanged(Q3ListViewItem *))); - d_current_folder = dynamic_cast(item)->folder(); + d_current_folder = fli->folder(); FolderListItem *it = d_current_folder->folderListItem(); it->setRenameEnabled (0, true); it->startRename (0); @@ -14379,8 +14649,8 @@ void ApplicationWindow::renameFolder(Q3ListViewItem *it, int col, const QString { Q_UNUSED(col) - if (!it) - return; + if (!it) + return; Folder *parent = dynamic_cast(currentFolder()->parent()); if (!parent)//the parent folder is the project folder (it always exists) @@ -14446,10 +14716,15 @@ void ApplicationWindow::showAllFolderWindows() FolderListItem *fi = currentFolder()->folderListItem(); FolderListItem *item = dynamic_cast(fi->firstChild()); + if(!item) + return; int initial_depth = item->depth(); while (item && item->depth() >= initial_depth) {// show/hide windows in all subfolders - lst = dynamic_cast(item->folder())->windowsList(); + auto fld = dynamic_cast(item->folder()); + if(!fld) + break; + lst = fld->windowsList(); foreach(MdiSubWindow *w, lst){ if (w && show_windows_policy == SubFolders){ updateWindowLists(w); @@ -14693,7 +14968,11 @@ void ApplicationWindow::folderItemDoubleClicked(Q3ListViewItem *it) if (!it || it->rtti() != FolderListItem::RTTI) return; - FolderListItem *item = dynamic_cast(it)->folder()->folderListItem(); + auto fli = dynamic_cast(it); + if(!fli) + return; + + FolderListItem *item = fli->folder()->folderListItem(); folders->setCurrentItem(item); } @@ -14703,7 +14982,13 @@ void ApplicationWindow::folderItemChanged(Q3ListViewItem *it) return; it->setOpen(true); - changeFolder (dynamic_cast(it)->folder()); + + auto fli = dynamic_cast(it); + + if(!fli) + return; + + changeFolder(fli->folder()); folders->setFocus(); } @@ -14885,6 +15170,9 @@ void ApplicationWindow::addListViewItem(MdiSubWindow *w) void ApplicationWindow::windowProperties() { WindowListItem *it = dynamic_cast(lv->currentItem()); + if(!it) + return; + MdiSubWindow *w = it->window(); if (!w) return; @@ -14989,21 +15277,27 @@ void ApplicationWindow::dropFolderItems(Q3ListViewItem *dest) if (!dest || draggedItems.isEmpty ()) return; - Folder *dest_f = dynamic_cast(dest)->folder(); + auto dfli = dynamic_cast(dest); + if(!dfli) + return; + Folder *dest_f = dfli->folder(); Q3ListViewItem *it; QStringList subfolders = dest_f->subfolders(); foreach(it, draggedItems){ if (it->rtti() == FolderListItem::RTTI){ - Folder *f = dynamic_cast(it)->folder(); + auto itfli = dynamic_cast(it); + if(!itfli) + continue; + Folder *f = itfli->folder(); FolderListItem *src = f->folderListItem(); if (dest_f == f){ QMessageBox::critical(this, "MantidPlot - Error", tr("Cannot move an object to itself!"));//Mantid return; } - if (dynamic_cast(dest)->isChildOf(src)){ + if (dfli->isChildOf(src)){ QMessageBox::critical(this,"MantidPlot - Error",tr("Cannot move a parent folder into a child folder!"));//Mantid draggedItems.clear(); folders->setCurrentItem(currentFolder()->folderListItem()); @@ -15020,17 +15314,22 @@ void ApplicationWindow::dropFolderItems(Q3ListViewItem *dest) QMessageBox::critical(this, tr("MantidPlot") +" - " + tr("Skipped moving folder"),//Mantid tr("The destination folder already contains a folder called '%1'! Folder skipped!").arg(f->objectName())); } else - moveFolder(src, dynamic_cast(dest)); + moveFolder(src, dfli); } else { if (dest_f == currentFolder()) return; - MdiSubWindow *w = dynamic_cast(it)->window(); - if (w){ - currentFolder()->removeWindow(w); - w->hide(); - dest_f->addWindow(w); - delete it; + auto wli = dynamic_cast(it); + if(wli) + { + MdiSubWindow *w = wli->window(); + if (w) + { + currentFolder()->removeWindow(w); + w->hide(); + dest_f->addWindow(w); + delete it; + } } } } @@ -15174,10 +15473,13 @@ void ApplicationWindow::goToRow() if ( !ok ) return; - if (w->inherits("Table")) - dynamic_cast(w)->goToRow(row); - else if (w->isA("Matrix")) - (dynamic_cast(w))->goToRow(row); + auto table = dynamic_cast(w); + auto matrix = dynamic_cast(w); + + if(table) + table->goToRow(row); + else if(matrix) + matrix->goToRow(row); } } @@ -15598,7 +15900,11 @@ void ApplicationWindow::hideSelectedWindows() folders->blockSignals(true); foreach(item, lst){ if (item->rtti() != FolderListItem::RTTI) - hideWindow(dynamic_cast(item)->window()); + { + auto wli = dynamic_cast(item); + if(wli) + hideWindow(wli->window()); + } } folders->blockSignals(false); } @@ -15615,7 +15921,11 @@ void ApplicationWindow::showSelectedWindows() folders->blockSignals(true); foreach(item, lst){ if (item->rtti() != FolderListItem::RTTI) - activateWindow(dynamic_cast(item)->window()); + { + auto wli = dynamic_cast(item); + if(wli) + activateWindow(wli->window()); + } } folders->blockSignals(false); } @@ -16291,7 +16601,10 @@ void ApplicationWindow::setMatrixUndoStackSize(int size) QList folderWindows = f->windowsList(); foreach(MdiSubWindow *w, folderWindows){ if (w->isA("Matrix")){ - QUndoStack *stack = (dynamic_cast(w))->undoStack(); + auto matrix = dynamic_cast(w); + if(!matrix) + continue; + QUndoStack *stack = matrix->undoStack(); if (!stack->count())// undo limit can only be changed for empty stacks stack->setUndoLimit(size); } diff --git a/Code/Mantid/MantidPlot/src/ConfigDialog.cpp b/Code/Mantid/MantidPlot/src/ConfigDialog.cpp index be208dd139f8..cafb5a066b9b 100644 --- a/Code/Mantid/MantidPlot/src/ConfigDialog.cpp +++ b/Code/Mantid/MantidPlot/src/ConfigDialog.cpp @@ -662,13 +662,12 @@ void ConfigDialog::initMantidPage() grid->addWidget(new QLabel("Facility"), 0, 0); grid->addWidget(facility, 0, 1); - defInstr = new MantidQt::MantidWidgets::InstrumentSelector(); + // Here we only want the default instrument updated if the user clicks Ok/Apply + defInstr->updateInstrumentOnSelection(false); grid->addWidget(new QLabel("Default Instrument"), 2, 0); grid->addWidget(defInstr, 2, 1); grid->setRowStretch(3,1); - //Here we only want the default instrument updated if the user clicks Ok/Apply - disconnect(defInstr, SIGNAL(currentIndexChanged(const QString&)), defInstr, SLOT(updateDefaultInstrument(const QString &))); //Ignore paraview. ckIgnoreParaView = new QCheckBox("Ignore ParaView"); diff --git a/Code/Mantid/MantidPlot/src/Graph.cpp b/Code/Mantid/MantidPlot/src/Graph.cpp index c791973a8530..a3fcaf85c6d6 100644 --- a/Code/Mantid/MantidPlot/src/Graph.cpp +++ b/Code/Mantid/MantidPlot/src/Graph.cpp @@ -238,9 +238,12 @@ void Graph::deselectMarker() cp->disableEditing(); QObjectList lst = d_plot->children(); - foreach(QObject *o, lst){ - if (o->inherits("LegendWidget")) - dynamic_cast(o)->setSelected(false); + foreach(QObject *o, lst) { + if (o->inherits("LegendWidget")) { + LegendWidget *lw = dynamic_cast(o); + if (lw) + lw->setSelected(false); + } } } @@ -302,19 +305,33 @@ void Graph::setSelectedMarker(int _mrk, bool add) selectedMarker = mrk; if (add) { if (d_markers_selector) { - if (d_lines.contains(mrk)) - d_markers_selector->add(dynamic_cast(d_plot->marker(mrk))); - else if (d_images.contains(mrk)) - d_markers_selector->add(dynamic_cast(d_plot->marker(mrk))); - else + if (d_lines.contains(mrk)) { + ArrowMarker *am = dynamic_cast(d_plot->marker(mrk)); + if (!am) + return; + d_markers_selector->add(am); + } else if (d_images.contains(mrk)) { + ImageMarker *im = dynamic_cast(d_plot->marker(mrk)); + if (!im) + return; + d_markers_selector->add(im); + } else { return; + } } else { - if (d_lines.contains(mrk)) - d_markers_selector = new SelectionMoveResizer(dynamic_cast(d_plot->marker(mrk))); - else if (d_images.contains(mrk)) - d_markers_selector = new SelectionMoveResizer(dynamic_cast(d_plot->marker(mrk))); - else + if (d_lines.contains(mrk)) { + ArrowMarker *am = dynamic_cast(d_plot->marker(mrk)); + if (!am) + return; + d_markers_selector = new SelectionMoveResizer(am); + } else if (d_images.contains(mrk)) { + ImageMarker *im = dynamic_cast(d_plot->marker(mrk)); + if (!im) + return; + d_markers_selector = new SelectionMoveResizer(im); + } else { return; + } connect(d_markers_selector, SIGNAL(targetsChanged()), this, SIGNAL(modifiedGraph())); } @@ -325,14 +342,20 @@ void Graph::setSelectedMarker(int _mrk, bool add) return; delete d_markers_selector; } - d_markers_selector = new SelectionMoveResizer(dynamic_cast(d_plot->marker(mrk))); + ArrowMarker *am = dynamic_cast(d_plot->marker(mrk)); + if (!am) + return; + d_markers_selector = new SelectionMoveResizer(am); } else if (d_images.contains(mrk)) { if (d_markers_selector) { if (d_markers_selector->contains(dynamic_cast(d_plot->marker(mrk)))) return; delete d_markers_selector; } - d_markers_selector = new SelectionMoveResizer(dynamic_cast(d_plot->marker(mrk))); + ImageMarker *im = dynamic_cast(d_plot->marker(mrk)); + if (!im) + return; + d_markers_selector = new SelectionMoveResizer(im); } else return; @@ -404,7 +427,11 @@ ScaleDraw::ScaleType Graph::axisType(int axis) if (!d_plot->axisEnabled(axis)) return ScaleDraw::Numeric; - return dynamic_cast(d_plot->axisScaleDraw(axis))->scaleType(); + ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw(axis)); + if (sd) + return sd->scaleType(); + else // assuming this is a good default + return ScaleDraw::Numeric; } void Graph::setLabelsNumericFormat(int axis, int format, int prec, const QString& formula) @@ -445,14 +472,17 @@ void Graph::setMajorTicksType(const QList& lst) for (int i=0;i<(int)lst.count();i++) { ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw (i)); + if (!sd) + continue; + if (lst[i]==ScaleDraw::None || lst[i]==ScaleDraw::In) sd->enableComponent (QwtAbstractScaleDraw::Ticks, false); else { - sd->enableComponent (QwtAbstractScaleDraw::Ticks); - sd->setTickLength (QwtScaleDiv::MinorTick, d_plot->minorTickLength()); - sd->setTickLength (QwtScaleDiv::MediumTick, d_plot->minorTickLength()); - sd->setTickLength (QwtScaleDiv::MajorTick, d_plot->majorTickLength()); + sd->enableComponent(QwtAbstractScaleDraw::Ticks); + sd->setTickLength(QwtScaleDiv::MinorTick, d_plot->minorTickLength()); + sd->setTickLength(QwtScaleDiv::MediumTick, d_plot->minorTickLength()); + sd->setTickLength(QwtScaleDiv::MajorTick, d_plot->majorTickLength()); } sd->setMajorTicksStyle((ScaleDraw::TicksStyle)lst[i]); } @@ -499,6 +529,9 @@ void Graph::setAxisTicksLength(int axis, int majTicksType, int minTicksType, d_plot->setTickLength(minLength, majLength); ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw(axis)); + if (!sd) + return; + sd->setMajorTicksStyle((ScaleDraw::TicksStyle)majTicksType); sd->setMinorTicksStyle((ScaleDraw::TicksStyle)minTicksType); @@ -558,11 +591,16 @@ void Graph::showAxis(int axis, int type, const QString& formatInfo, Table *table if (!axisOn) return; - QList majTicksTypeList = d_plot->getMajorTicksType(); - QList minTicksTypeList = d_plot->getMinorTicksType(); - QwtScaleWidget *scale = dynamic_cast(d_plot->axisWidget(axis)); + if (!scale) + return; + ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw(axis)); + if (!sd) + return; + + QList majTicksTypeList = d_plot->getMajorTicksType(); + QList minTicksTypeList = d_plot->getMinorTicksType(); if (d_plot->axisEnabled (axis) == axisOn && majTicksTypeList[axis] == majTicksType && @@ -928,7 +966,7 @@ void Graph::updateSecondaryAxis(int axis) if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram){ Spectrogram *sp = dynamic_cast(it); - if (sp->colorScaleAxis() == axis) + if (!sp || sp->colorScaleAxis() == axis) return; } @@ -945,7 +983,10 @@ void Graph::updateSecondaryAxis(int axis) return; ScaleEngine *sc_engine = dynamic_cast(d_plot->axisScaleEngine(axis)); - sc_engine->clone(dynamic_cast(d_plot->axisScaleEngine(a))); + if (sc_engine) { + ScaleEngine *a_engine = dynamic_cast(d_plot->axisScaleEngine(a)); + sc_engine->clone(a_engine); + } /*QwtScaleEngine *qwtsc_engine = d_plot->axisScaleEngine(axis); ScaleEngine *sc_engine=dynamic_cast(qwtsc_engine); @@ -1074,17 +1115,23 @@ void Graph::niceLogScales(QwtPlot::Axis axis) double start = QMIN(scDiv->lBound(), scDiv->hBound()); double end = QMAX(scDiv->lBound(), scDiv->hBound()); - // log scales can't represent zero or negative values, 1e-10 as a low range is enough to display all data but still be plottable on a log scale + // log scales can't represent zero or negative values, 1e-10 as a + // low range is enough to display all data but still be plottable on + // a log scale start = start < 1e-90 ? 1e-10 : start; - // improve the scale labelling by ensuring that the graph starts and ends on numbers that can have major ticks e.g. 0.1 or 1 or 100 + // improve the scale labelling by ensuring that the graph starts and + // ends on numbers that can have major ticks e.g. 0.1 or 1 or 100 const double exponent = floor(log10(start)); start = pow(10.0, exponent); end = ceil(log10(end)); end = pow(10.0, end); ScaleEngine *scaleEng = dynamic_cast(d_plot->axisScaleEngine(axis)); + if (!scaleEng) + return; - // call the QTiPlot function set scale which takes many arguments, fill the arguments with the same settings the plot already has + // call the QTiPlot function set scale which takes many arguments, + // fill the arguments with the same settings the plot already has setScale(axis, start, end, axisStep(axis), scDiv->ticks(QwtScaleDiv::MajorTick).count(), d_plot->axisMaxMinor(axis), @@ -1140,6 +1187,9 @@ void Graph::setScale(QwtPlot::Axis axis, QwtScaleTransformation::Type scaleType) { //check if the scale is already of the desired type, ScaleEngine *sc_engine = dynamic_cast(d_plot->axisScaleEngine(axis)); + if (!sc_engine) + return; + QwtScaleTransformation::Type type = sc_engine->type(); if ( scaleType == QwtScaleTransformation::Log10 ) { @@ -1158,8 +1208,11 @@ void Graph::setScale(QwtPlot::Axis axis, QwtScaleTransformation::Type scaleType) double end = QMAX(scDiv->lBound(), scDiv->hBound()); ScaleEngine *scaleEng = dynamic_cast(d_plot->axisScaleEngine(axis)); + if (!scaleEng) + return; - // call the QTiPlot function set scale which takes many arguments, fill the arguments with the same settings the plot already has + // call the QTiPlot function set scale which takes many arguments, + // fill the arguments with the same settings the plot already has setScale(axis, start, end, axisStep(axis), scDiv->ticks(QwtScaleDiv::MajorTick).count(), d_plot->axisMaxMinor(axis), scaleType, @@ -1669,11 +1722,13 @@ void Graph::deselectCurves() foreach(QwtPlotItem *i, curves){ PlotCurve *c = dynamic_cast(i); DataCurve *dc = dynamic_cast(i); - if(dc && i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && - c->type() != Graph::Function && dc->hasSelectedLabels() ){ - dc->setLabelsSelected(false); - return; - } + if(c && dc && + i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && + c->type() != Graph::Function && dc->hasSelectedLabels() ) + { + dc->setLabelsSelected(false); + return; + } } } @@ -1683,8 +1738,9 @@ DataCurve* Graph::selectedCurveLabels() foreach(QwtPlotItem *i, curves){ PlotCurve *c = dynamic_cast(i); DataCurve *dc = dynamic_cast(i); - if(dc && i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && - c->type() != Graph::Function && dc->hasSelectedLabels()) + if(dc && c && + i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && + c->type() != Graph::Function && dc->hasSelectedLabels()) return dc; } return NULL; @@ -1752,6 +1808,9 @@ void Graph::removeLegend() void Graph::updateImageMarker(int x, int y, int w, int h) { ImageMarker* mrk = dynamic_cast(d_plot->marker(selectedMarker)); + if (!mrk) + return; + mrk->setRect(x, y, w, h); d_plot->replot(); emit modifiedGraph(); @@ -1932,6 +1991,9 @@ QString Graph::savePieCurveLayout() QString s="PieCurve\t"; QwtPieCurve *pie = dynamic_cast(curve(0)); + if (!pie) + return s; + s+= pie->title().text()+"\t"; QPen pen = pie->pen(); s+=QString::number(pen.widthF())+"\t"; @@ -1995,30 +2057,36 @@ QString Graph::saveCurveLayout(int index) if(style == VerticalBars || style == HorizontalBars || style == Histogram){ QwtBarCurve *b = dynamic_cast(c); - s+=QString::number(b->gap())+"\t"; - s+=QString::number(b->offset())+"\t"; + if (b) { + s+=QString::number(b->gap())+"\t"; + s+=QString::number(b->offset())+"\t"; + } } if (style == Histogram){ QwtHistogram *h = dynamic_cast(c); - s+=QString::number(h->autoBinning())+"\t"; - s+=QString::number(h->binSize())+"\t"; - s+=QString::number(h->begin())+"\t"; - s+=QString::number(h->end())+"\t"; + if (h) { + s+=QString::number(h->autoBinning())+"\t"; + s+=QString::number(h->binSize())+"\t"; + s+=QString::number(h->begin())+"\t"; + s+=QString::number(h->end())+"\t"; + } } else if(style == VectXYXY || style == VectXYAM){ VectorCurve *v = dynamic_cast(c); - s+=v->color().name()+"\t"; - s+=QString::number(v->width())+"\t"; - s+=QString::number(v->headLength())+"\t"; - s+=QString::number(v->headAngle())+"\t"; - s+=QString::number(v->filledArrowHead())+"\t"; - - QStringList colsList = v->plotAssociation().split(",", QString::SkipEmptyParts); - s+=colsList[2].remove("(X)").remove("(A)")+"\t"; - s+=colsList[3].remove("(Y)").remove("(M)"); - if (style == VectXYAM) - s+="\t"+QString::number(v->position()); - s+="\t"; + if (v) { + s+=v->color().name()+"\t"; + s+=QString::number(v->width())+"\t"; + s+=QString::number(v->headLength())+"\t"; + s+=QString::number(v->headAngle())+"\t"; + s+=QString::number(v->filledArrowHead())+"\t"; + + QStringList colsList = v->plotAssociation().split(",", QString::SkipEmptyParts); + s+=colsList[2].remove("(X)").remove("(A)")+"\t"; + s+=colsList[3].remove("(Y)").remove("(M)"); + if (style == VectXYAM) + s+="\t"+QString::number(v->position()); + s+="\t"; + } } else if(style == Box){ BoxCurve *b = static_cast(c); s+=QString::number(SymbolBox::symbolIndex(b->maxStyle()))+"\t"; @@ -2780,7 +2848,9 @@ PlotCurve* Graph::insertCurve(Table* w, const QString& xColName, const QString& c = new QwtBarCurve(QwtBarCurve::Horizontal, w, xColName, yColName, startRow, endRow); } else if (style == Histogram){ c = new QwtHistogram(w, xColName, yColName, startRow, endRow); - dynamic_cast(c)->initData(Y.data(), size); + QwtHistogram *histo = dynamic_cast(c); + if (histo) + histo->initData(Y.data(), size); } else c = new DataCurve(w, xColName, yColName, startRow, endRow); @@ -3024,9 +3094,13 @@ void Graph::removePie() if (d_legend) d_legend->setText(QString::null); - QList labels = dynamic_cast(curve(0))->labelsList(); + QwtPieCurve *pieCurve = dynamic_cast(curve(0)); + if (!pieCurve) + return; + + QList labels = pieCurve->labelsList(); foreach(PieLabel *l, labels) - l->setPieCurve(0); + l->setPieCurve(0); d_plot->removeCurve(c_keys[0]); d_plot->replot(); @@ -3054,7 +3128,9 @@ void Graph::removeCurves(const QString& s) if (it->rtti() != QwtPlotItem::Rtti_PlotCurve) continue; - if (dynamic_cast(it)->type() == Function) + + PlotCurve *pc = dynamic_cast(it); + if (!pc || pc->type() == Function) continue; DataCurve * dc = dynamic_cast(it); @@ -3091,9 +3167,10 @@ void Graph::removeCurve(int index) if (it->rtti() != QwtPlotItem::Rtti_PlotSpectrogram) { - if (dynamic_cast(it)->type() == ErrorBars) - dynamic_cast(it)->detachFromMasterCurve(); - else if (c->type() != Function && dc){ + if (c->type() == ErrorBars) { + QwtErrorPlotCurve *epc = dynamic_cast(it); + epc->detachFromMasterCurve(); + } else if (c->type() != Function && dc) { dc->clearErrorBars(); dc->clearLabels(); } @@ -3685,9 +3762,13 @@ void Graph::scaleFonts(double factor) QObjectList lst = d_plot->children(); foreach(QObject *o, lst){ if (o->inherits("LegendWidget")){ - QFont font = dynamic_cast(o)->font(); + LegendWidget *lw = dynamic_cast(o); + if (!lw) + continue; + + QFont font = lw->font(); font.setPointSizeFloat(factor*font.pointSizeFloat()); - dynamic_cast(o)->setFont(font); + lw->setFont(font); } } @@ -4033,9 +4114,14 @@ void Graph::copy(Graph* g) QwtPlotItem *it = (QwtPlotItem *)g->plotItem(i); if (it->rtti() == QwtPlotItem::Rtti_PlotCurve){ DataCurve *cv = dynamic_cast(it); - if (!cv) continue; + if (!cv) + continue; + + PlotCurve *pc = dynamic_cast(it); + if (!pc) + continue; + int n = cv->dataSize(); - int style = dynamic_cast(it)->type(); QVector x(n); QVector y(n); for (int j=0; jy(j); } + int style = pc->type(); + PlotCurve *c = 0; c_keys.resize(++n_curves); c_type.resize(n_curves); @@ -4054,43 +4142,73 @@ void Graph::copy(Graph* g) } else if (style == Function) { c = new FunctionCurve(cv->title().text()); c_keys[i] = d_plot->insertCurve(c); - dynamic_cast(c)->copy(dynamic_cast(cv)); + FunctionCurve *fc = dynamic_cast(c); + if (fc) { + FunctionCurve *fcCV = dynamic_cast(cv); + if (fcCV) + fc->copy(fcCV); + } } else if (style == VerticalBars || style == HorizontalBars) { - c = new QwtBarCurve(dynamic_cast(cv)->orientation(), cv->table(), cv->xColumnName(), - cv->title().text(), cv->startRow(), cv->endRow()); - c_keys[i] = d_plot->insertCurve(c); - (dynamic_cast(c))->copy(dynamic_cast(cv)); + QwtBarCurve *bc = dynamic_cast(c); + if (bc) { + c = new QwtBarCurve(bc->orientation(), cv->table(), cv->xColumnName(), + cv->title().text(), cv->startRow(), cv->endRow()); + c_keys[i] = d_plot->insertCurve(c); + + const QwtBarCurve *cvBC = dynamic_cast(cv); + if (cvBC) + bc->copy(cvBC); + } } else if (style == ErrorBars) { QwtErrorPlotCurve *er = dynamic_cast(cv); - DataCurve *master_curve = masterCurve(er); - if (master_curve) { - c = new QwtErrorPlotCurve(cv->table(), cv->title().text()); - c_keys[i] = d_plot->insertCurve(c); - dynamic_cast(c)->copy(er); - dynamic_cast(c)->setMasterCurve(master_curve); + if (er) { + DataCurve *master_curve = masterCurve(er); + if (master_curve) { + c = new QwtErrorPlotCurve(cv->table(), cv->title().text()); + c_keys[i] = d_plot->insertCurve(c); + QwtErrorPlotCurve *epc = dynamic_cast(c); + if (epc) { + epc->copy(er); + epc->setMasterCurve(master_curve); + } + } } } else if (style == Histogram) { QwtHistogram *h = dynamic_cast(cv); - if (h->matrix()) + if (h && h->matrix()) c = new QwtHistogram(h->matrix()); else c = new QwtHistogram(cv->table(), cv->xColumnName(), cv->title().text(), cv->startRow(), cv->endRow()); c_keys[i] = d_plot->insertCurve(c); - dynamic_cast(c)->copy(h); + + QwtHistogram *cQH = dynamic_cast(c); + if (cQH) + cQH->copy(h); } else if (style == VectXYXY || style == VectXYAM) { VectorCurve::VectorStyle vs = VectorCurve::XYXY; if (style == VectXYAM) vs = VectorCurve::XYAM; - c = new VectorCurve(vs, cv->table(), cv->xColumnName(), cv->title().text(), - dynamic_cast(cv)->vectorEndXAColName(), - dynamic_cast(cv)->vectorEndYMColName(), - cv->startRow(), cv->endRow()); - c_keys[i] = d_plot->insertCurve(c); - dynamic_cast(c)->copy(dynamic_cast(cv)); + VectorCurve *cvVC = dynamic_cast(cv); + if (cvVC) { + c = new VectorCurve(vs, cv->table(), cv->xColumnName(), cv->title().text(), + cvVC->vectorEndXAColName(), + cvVC->vectorEndYMColName(), + cv->startRow(), cv->endRow()); + c_keys[i] = d_plot->insertCurve(c); + + VectorCurve *cVC = dynamic_cast(c); + if (cVC) // it really should be, just did 'c = new VectorCurve(...' + cVC->copy(cvVC); + } } else if (style == Box) { c = new BoxCurve(cv->table(), cv->title().text(), cv->startRow(), cv->endRow()); c_keys[i] = d_plot->insertCurve(c); - dynamic_cast(c)->copy(dynamic_cast(cv)); + BoxCurve *bc = dynamic_cast(c); + if (bc) { + const BoxCurve *cvBC = dynamic_cast(cv); + if (cvBC) + bc->copy(cvBC); + } QwtSingleArrayData dat(x[0], y, n); c->setData(dat); } else { @@ -4100,12 +4218,23 @@ void Graph::copy(Graph* g) if (c_type[i] != Box && c_type[i] != ErrorBars){ c->setData(x.data(), y.data(), n); - if (c->type() != Function && c->type() != Pie) - dynamic_cast(c)->clone(cv); - else if (c->type() == Pie) - dynamic_cast(c)->clone(dynamic_cast(cv)); + if (c->type() != Function && c->type() != Pie) { + DataCurve *dc = dynamic_cast(c); + if (dc) + dc->clone(cv); + } else if (c->type() == Pie) { + QwtPieCurve *cPie = dynamic_cast(c); + if (cPie) { + QwtPieCurve *cvPie = dynamic_cast(cv); + if (cvPie) + cPie->clone(cvPie); + } + } } + if (!c) + continue; + c->setPen(cv->pen()); c->setBrush(cv->brush()); c->setStyle(cv->style()); @@ -4122,8 +4251,11 @@ void Graph::copy(Graph* g) QListlst = g->fitCurvesList(); if (lst.contains(dynamic_cast(it))) d_fit_curves << c; - }else if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram){ - Spectrogram *sp = (dynamic_cast(it))->copy(); + } else if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram){ + Spectrogram *spc = (dynamic_cast(it)); + if (!spc) + continue; + Spectrogram *sp = spc->copy(); c_keys.resize(++n_curves); c_keys[i] = d_plot->insertCurve(sp); @@ -4157,7 +4289,7 @@ void Graph::copy(Graph* g) continue; ScaleDraw *sdg = dynamic_cast(g->plotWidget()->axisScaleDraw (i)); - if (sdg->hasComponent(QwtAbstractScaleDraw::Labels)) + if (sdg && sdg->hasComponent(QwtAbstractScaleDraw::Labels)) { ScaleDraw::ScaleType type = sdg->scaleType(); if (type == ScaleDraw::Numeric) @@ -4168,9 +4300,10 @@ void Graph::copy(Graph* g) setLabelsMonthFormat(i, sdg->nameFormat()); else if (type == ScaleDraw::Time || type == ScaleDraw::Date) setLabelsDateTimeFormat(i, type, sdg->formatString()); - else{ + else { ScaleDraw *sd = dynamic_cast(plot->axisScaleDraw(i)); - d_plot->setAxisScaleDraw(i, new ScaleDraw(d_plot, sd->labelsList(), sd->formatString(), sd->scaleType())); + if (sd) + d_plot->setAxisScaleDraw(i, new ScaleDraw(d_plot, sd->labelsList(), sd->formatString(), sd->scaleType())); } } else { ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw (i)); @@ -4182,9 +4315,6 @@ void Graph::copy(Graph* g) if (!se) continue; - ScaleEngine *sc_engine = dynamic_cast(d_plot->axisScaleEngine(i)); - sc_engine->clone(se); - int majorTicks = plot->axisMaxMajor(i); int minorTicks = plot->axisMaxMinor(i); d_plot->setAxisMaxMajor (i, majorTicks); @@ -4192,6 +4322,12 @@ void Graph::copy(Graph* g) double step = g->axisStep(i); d_user_step[i] = step; + + ScaleEngine *sc_engine = dynamic_cast(d_plot->axisScaleEngine(i)); + if (!sc_engine) + continue; + + sc_engine->clone(se); const QwtScaleDiv *sd = plot->axisScaleDiv(i); QwtScaleDiv div = sc_engine->divideScale (QMIN(sd->lBound(), sd->hBound()), QMAX(sd->lBound(), sd->hBound()), majorTicks, minorTicks, step); @@ -4434,6 +4570,9 @@ void Graph::guessUniqueCurveLayout(int& colorIndex, int& symbolIndex) if (curve_index >= 0 && c_type[curve_index] == ErrorBars) {// find out the pen color of the master curve QwtErrorPlotCurve *er = dynamic_cast(d_plot->curve(c_keys[curve_index])); + if (!er) + return; + DataCurve *master_curve = er->masterCurve(); if (master_curve){ colorIndex = ColorBox::colorIndex(master_curve->pen().color()); @@ -4739,7 +4878,11 @@ QString Graph::axisFormatInfo(int axis) if (axis < 0 || axis > QwtPlot::axisCnt) return QString(); - return dynamic_cast(d_plot->axisScaleDraw(axis))->formatString(); + ScaleDraw *sd = dynamic_cast(d_plot->axisScaleDraw(axis)); + if (sd) + return sd->formatString(); + else + return "Not available!"; } void Graph::updateCurveNames(const QString& oldName, const QString& newName, bool updateTableName) @@ -4834,12 +4977,14 @@ void Graph::setGrayScale() QwtPlotItem * it = plotItem(i); if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) { - dynamic_cast(it)->setGrayScale(); + Spectrogram *spec = dynamic_cast(it); + if (spec) + spec->setGrayScale(); continue; } PlotCurve *c = dynamic_cast(it); - if (c->type() == ErrorBars) + if (!c || c->type() == ErrorBars) continue; QPen pen = c->pen(); @@ -4877,9 +5022,12 @@ void Graph::setGrayScale() continue; PlotCurve *c = dynamic_cast(it); - if (c->type() == ErrorBars) + if (c && c->type() == ErrorBars) { - QwtErrorPlotCurve *er = dynamic_cast(it); // QtiPlot: ErrorBarsCurve *er = (ErrorBarsCurve *) it; + // QtiPlot: ErrorBarsCurve *er = (ErrorBarsCurve *) it; + QwtErrorPlotCurve *er = dynamic_cast(it); + if (!er) + continue; DataCurve* mc = er->masterCurve(); if (mc) er->setColor(mc->pen().color()); @@ -4909,7 +5057,7 @@ void Graph::setIndexedColors() continue; PlotCurve *c = dynamic_cast(it); - if (c->type() == ErrorBars) + if (!c || c->type() == ErrorBars) continue; QPen pen = c->pen(); @@ -4943,7 +5091,11 @@ void Graph::setIndexedColors() PlotCurve *c = dynamic_cast(it); if (c->type() == ErrorBars) { - QwtErrorPlotCurve *er = dynamic_cast(it); // QtiPlot: ErrorBarsCurve *er = (ErrorBarsCurve *) it; + // QtiPlot: ErrorBarsCurve *er = (ErrorBarsCurve *) it; + QwtErrorPlotCurve *er = dynamic_cast(it); + if (!er) + continue; + DataCurve* mc = er->masterCurve(); if (mc) er->setColor(mc->pen().color()); @@ -4964,7 +5116,8 @@ DataCurve* Graph::masterCurve(QwtErrorPlotCurve *er) continue; if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) continue; - if (dynamic_cast(it)->type() == Function) + PlotCurve *pc = dynamic_cast(it); + if (!pc || pc->type() == Function) continue; DataCurve* dc = dynamic_cast(it); @@ -4986,7 +5139,8 @@ DataCurve* Graph::masterCurve(const QString& xColName, const QString& yColName) continue; if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) continue; - if (dynamic_cast(it)->type() == Function) + PlotCurve *pc = dynamic_cast(it); + if (!pc || pc->type() == Function) continue; DataCurve* dc = dynamic_cast(it); @@ -5139,8 +5293,10 @@ void Graph::setCurrentFont(const QFont& f) QList curves = d_plot->curvesList(); foreach(QwtPlotItem *i, curves){ DataCurve* dc = dynamic_cast(i); - if(dc && i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && - dynamic_cast(i)->type() != Graph::Function){ + PlotCurve* pc = dynamic_cast(i); + if(pc && dc + && i->rtti() != QwtPlotItem::Rtti_PlotSpectrogram && + pc->type() != Graph::Function){ if(dc->hasSelectedLabels()){ dc->setLabelsFont(f); d_plot->replot(); @@ -5921,8 +6077,13 @@ void Graph::loadFromProject(const std::string& lines, ApplicationWindow* app, co if(plotType == Graph::Histogram) { QwtHistogram* h = dynamic_cast(curve(curveID)); - h->setBinning(curveValues[17].toInt(),curveValues[18].toDouble(),curveValues[19].toDouble(),curveValues[20].toDouble()); - h->loadData(); + if (h) { + h->setBinning(curveValues[17].toInt(), + curveValues[18].toDouble(), + curveValues[19].toDouble(), + curveValues[20].toDouble()); + h->loadData(); + } } if(plotType == Graph::VerticalBars diff --git a/Code/Mantid/MantidPlot/src/Interpolation.cpp b/Code/Mantid/MantidPlot/src/Interpolation.cpp index 3a6bf0b26826..db4dfc68dfbd 100644 --- a/Code/Mantid/MantidPlot/src/Interpolation.cpp +++ b/Code/Mantid/MantidPlot/src/Interpolation.cpp @@ -177,8 +177,8 @@ int Interpolation::sortedCurveData(QwtPlotCurve *c, double start, double end, do for (int i = i_start; i <= i_end; i++){ xtemp[j] = c->x(i); if (i > i_start && xtemp[j] == pr_x){ - delete (*x); - delete (*y); + delete[] (*x); + delete[] (*y); delete[] xtemp; delete[] ytemp; return -1;//this kind of data causes division by zero in GSL interpolation routines diff --git a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjCompAssemblyActor.cpp b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjCompAssemblyActor.cpp index 12ca86abf272..c812be286cb0 100644 --- a/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjCompAssemblyActor.cpp +++ b/Code/Mantid/MantidPlot/src/Mantid/InstrumentWidget/ObjCompAssemblyActor.cpp @@ -117,6 +117,19 @@ void ObjCompAssemblyActor::generateTexture(unsigned char* data, unsigned int& id GLint texParam = GL_NEAREST; glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); OpenGLError::check("TexObject::generateTexture()[set data] "); + /* If the above call to glTexImage2D has generated an error, it is likely as a result + * of outline="yes" being set in the IDF. If this is enabled then the texture above + * is generated with a width being equal to the number of points that make up the + * outline. However, some OpenGL implementations only support textures with a 2^n size. + * On the machines tested (Ubuntu 14.04, Windows 7, and RHEL6), this was not an issue, + * but we can't guarantee that a user wont try this on a system that doesn't support + * non power of 2 textures. In that case, the best thing to do would be to create a + * texture with a width of the next 2^n up, and adjust the texture coordinates + * accordingly. However, this is not a trivial change to make, and as far as we can tell + * no one has ever run into this issue, so it's being left for now. If this does prove + * problematic in the future, hopefully this note will save you some time figuring out + * the problem. + */ glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,texParam); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,texParam); OpenGLError::check("TexObject::generateTexture()[parameters] "); diff --git a/Code/Mantid/MantidPlot/src/Plot.cpp b/Code/Mantid/MantidPlot/src/Plot.cpp index 8ab3ae206a62..e44b275dd3b8 100644 --- a/Code/Mantid/MantidPlot/src/Plot.cpp +++ b/Code/Mantid/MantidPlot/src/Plot.cpp @@ -756,12 +756,17 @@ void Plot::showEvent (QShowEvent * event) \brief Paint the plot into a given rectangle. Paint the contents of a QwtPlot instance into a given rectangle (Qwt modified code). + Note that this method is const so that it properly overrides + QwtPlot::print (coverity issue 1076125). This however requires + several const_casts in the code, as constness either is not + specified in some methods called or it is actually arguable. + @param painter :: Painter @param plotRect :: Bounding rectangle @param pfilter :: Print filter */ void Plot::print(QPainter *painter, const QRect &plotRect, - const QwtPlotPrintFilter &pfilter) + const QwtPlotPrintFilter &pfilter) const { int axisId; @@ -787,7 +792,7 @@ void Plot::print(QPainter *painter, const QRect &plotRect, // reset the widget attributes again. This way we produce a lot of // useless layout events ... - pfilter.apply((QwtPlot *)this); + pfilter.apply((QwtPlot *)const_cast(this)); int baseLineDists[QwtPlot::axisCnt]; if ( !(pfilter.options() & 16) ){ @@ -795,7 +800,7 @@ void Plot::print(QPainter *painter, const QRect &plotRect, // the scale on the frame of the canvas. for (axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){ - QwtScaleWidget *scaleWidget = (QwtScaleWidget *)axisWidget(axisId); + QwtScaleWidget *scaleWidget = const_cast(axisWidget(axisId)); if ( scaleWidget ){ baseLineDists[axisId] = scaleWidget->margin(); scaleWidget->setMargin(0); @@ -811,7 +816,7 @@ void Plot::print(QPainter *painter, const QRect &plotRect, if ( !(pfilter.options() & QwtPlotPrintFilter::PrintLegend) ) layoutOptions |= QwtPlotLayout::IgnoreLegend; - ((QwtPlot *)this)->plotLayout()->activate(this, + ((QwtPlot *)const_cast(this))->plotLayout()->activate(this, QwtPainter::metricsMap().deviceToLayout(plotRect), layoutOptions); @@ -875,7 +880,7 @@ void Plot::print(QPainter *painter, const QRect &plotRect, for ( axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){ - QwtScaleWidget *scaleWidget = (QwtScaleWidget *)axisWidget(axisId); + QwtScaleWidget *scaleWidget = const_cast(axisWidget(axisId)); if (scaleWidget){ int baseDist = scaleWidget->margin(); @@ -919,21 +924,22 @@ void Plot::print(QPainter *painter, const QRect &plotRect, - ((QwtPlot *)this)->plotLayout()->invalidate(); + ((QwtPlot *)const_cast(this))->plotLayout()->invalidate(); // reset all widgets with their original attributes. if ( !(pfilter.options() & 16) ){ // restore the previous base line dists for (axisId = 0; axisId < QwtPlot::axisCnt; axisId++ ){ - QwtScaleWidget *scaleWidget = (QwtScaleWidget *)axisWidget(axisId); + QwtScaleWidget *scaleWidget = + const_cast(axisWidget(axisId)); if ( scaleWidget ) scaleWidget->setMargin(baseLineDists[axisId]); } } - pfilter.reset((QwtPlot *)this); + pfilter.reset((QwtPlot *)const_cast(this)); painter->restore(); - setTitle(t);//hack used to avoid bug in Qwt::printTitle(): the title attributes are overwritten + const_cast(this)->setTitle(t);//hack used to avoid bug in Qwt::printTitle(): the title attributes are overwritten } diff --git a/Code/Mantid/MantidPlot/src/Plot.h b/Code/Mantid/MantidPlot/src/Plot.h index 7d4e57bfa9dd..9aecdb0bf689 100644 --- a/Code/Mantid/MantidPlot/src/Plot.h +++ b/Code/Mantid/MantidPlot/src/Plot.h @@ -90,21 +90,21 @@ class Plot: public QwtPlot void axisLabelFormat(int axis, char &f, int &prec) const; - int axisLabelFormat(int axis); - int axisLabelPrecision(int axis); + int axisLabelFormat(int axis); + int axisLabelPrecision(int axis); - QColor frameColor(); - const QColor & paletteBackgroundColor() const; + QColor frameColor(); + const QColor & paletteBackgroundColor() const; using QwtPlot::print; // Avoid Intel compiler warning - void print(QPainter *, const QRect &rect, const QwtPlotPrintFilter & = QwtPlotPrintFilter()); - void updateLayout(); + void print(QPainter *, const QRect &rect, const QwtPlotPrintFilter & = QwtPlotPrintFilter()) const; + void updateLayout(); void updateCurveLabels(); - // pass through method that is public on the base class in later qwt versions - void updateAxes() { QwtPlot::updateAxes(); } + // pass through method that is public on the base class in later qwt versions + void updateAxes() { QwtPlot::updateAxes(); } - void reverseCurveOrder(); // Created in connection with waterfall plots. Called from Graph method of same name. + void reverseCurveOrder(); // Created in connection with waterfall plots. Called from Graph method of same name. signals: void dragMousePress(QPoint); diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.cpp b/Code/Mantid/MantidPlot/src/PlotDialog.cpp index eae4be1e6635..839fd3f965ba 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.cpp +++ b/Code/Mantid/MantidPlot/src/PlotDialog.cpp @@ -283,6 +283,9 @@ void PlotDialog::setEquidistantLevels() return; CurveTreeItem *item = dynamic_cast(it); + if (!item) + return; + QwtPlotItem *plotItem = dynamic_cast(item->plotItem()); if (!plotItem) return; @@ -317,30 +320,37 @@ void PlotDialog::showPlotAssociations(QTreeWidgetItem *item, int) if (item->type() != CurveTreeItem::PlotCurveTreeItem) return; - QwtPlotItem *it = dynamic_cast(dynamic_cast(item)->plotItem()); // crazy + CurveTreeItem *ctit = dynamic_cast(item); + if (!ctit) + return; + QwtPlotItem *it = dynamic_cast(ctit->plotItem()); if (!it) return; if (it->rtti() == QwtPlotItem::Rtti_PlotSpectrogram) { Spectrogram *sp = dynamic_cast(it); - if (sp->matrix()) + if (sp && sp->matrix()) sp->matrix()->showMaximized(); return; } hide(); - if (dynamic_cast(it)->type() == Graph::Function) + PlotCurve *pc = dynamic_cast(it); + if (!pc) + return; + if (pc->type() == Graph::Function) { - FunctionDialog *fd = d_app->showFunctionDialog((dynamic_cast(item))->graph(), - dynamic_cast(item)->plotItemIndex()); + FunctionDialog *fd = d_app->showFunctionDialog(ctit->graph(), + ctit->plotItemIndex()); + if (fd) connect((QObject *) fd, SIGNAL(destroyed()), this, SLOT(show())); } else { - AssociationsDialog* ad = d_app->showPlotAssociations( - dynamic_cast(item)->plotItemIndex()); + AssociationsDialog* ad = d_app->showPlotAssociations(ctit->plotItemIndex()); + if (ad) connect((QObject *) ad, SIGNAL(destroyed()), this, SLOT(show())); } @@ -356,7 +366,10 @@ void PlotDialog::editCurve() return; int index = item->plotItemIndex(); - int curveType = dynamic_cast(item->plotItem())->type(); + PlotCurve* pc = dynamic_cast(item->plotItem()); + if (!pc) + return; + int curveType = pc->type(); hide(); @@ -403,6 +416,9 @@ void PlotDialog::changePlotType(int plotType) insertTabs(curveType); VectorCurve *v = dynamic_cast(item->plotItem()); + if (!v) + return; + if (plotType) { graph->setCurveType(item->plotItemIndex(), Graph::VectXYAM); @@ -1415,7 +1431,10 @@ void PlotDialog::selectCurve(int index) QTreeWidgetItem *item = layerItem->child(index); if (item) { - (dynamic_cast(item))->setActive(true); + CurveTreeItem *ctit = dynamic_cast(item); + if (!ctit) + return; + ctit->setActive(true); listBox->setCurrentItem(item); } } @@ -1431,7 +1450,11 @@ void PlotDialog::showStatistics() if (it->type() != CurveTreeItem::PlotCurveTreeItem) return; - QwtPlotItem *plotItem = dynamic_cast(dynamic_cast(it)->plotItem()); + CurveTreeItem *ctit = dynamic_cast(it); + if (!ctit) + return; + + QwtPlotItem *plotItem = dynamic_cast(ctit->plotItem()); if (!plotItem) return; @@ -1486,7 +1509,12 @@ void PlotDialog::contextMenuEvent(QContextMenuEvent *e) return; if (item->type() != CurveTreeItem::PlotCurveTreeItem) return; - QwtPlotItem *it = dynamic_cast(dynamic_cast(item)->plotItem()); + + CurveTreeItem *ctit = dynamic_cast(item); + if (!ctit) + return; + + QwtPlotItem *it = dynamic_cast(ctit->plotItem()); if (!it) return; @@ -1499,7 +1527,10 @@ void PlotDialog::contextMenuEvent(QContextMenuEvent *e) if (it->rtti() == QwtPlotItem::Rtti_PlotCurve) { - if (dynamic_cast(it)->type() == Graph::Function) + PlotCurve *pc = dynamic_cast(it); + if (!pc) + return; + if (pc->type() == Graph::Function) contextMenu.insertItem(tr("&Edit..."), this, SLOT(editCurve())); else contextMenu.insertItem(tr("&Plot Associations..."), this, SLOT(editCurve())); @@ -1548,18 +1579,32 @@ void PlotDialog::updateTabWindow(QTreeWidgetItem *currentItem, QTreeWidgetItem * forceClearTabs = true; } - if (previousItem->type() == CurveTreeItem::PlotCurveTreeItem) - dynamic_cast(previousItem)->setActive(false); - else if (previousItem->type() == LayerItem::LayerTreeItem) - dynamic_cast(previousItem)->setActive(false); + if (previousItem->type() == CurveTreeItem::PlotCurveTreeItem) { + CurveTreeItem *prev = dynamic_cast(previousItem); + if (!prev) + return; + prev->setActive(false); + } else if (previousItem->type() == LayerItem::LayerTreeItem) { + LayerItem *prev = dynamic_cast(previousItem); + if (!prev) + return; + prev->setActive(false); + } boxPlotType->blockSignals(true); if (currentItem->type() == CurveTreeItem::PlotCurveTreeItem) { CurveTreeItem *curveItem = dynamic_cast(currentItem); + if (!curveItem) + return; + + CurveTreeItem *pi = dynamic_cast(previousItem); + if (!pi) + return; + if (previousItem->type() != CurveTreeItem::PlotCurveTreeItem - || dynamic_cast(previousItem)->plotItemType() != curveItem->plotItemType() + || pi->plotItemType() != curveItem->plotItemType() || forceClearTabs) { clearTabWidget(); @@ -1682,7 +1727,11 @@ void PlotDialog::insertTabs(int plot_type) if (!item || item->type() != CurveTreeItem::PlotCurveTreeItem) return; - const DataCurve *c = dynamic_cast((dynamic_cast(item))->plotItem()); + CurveTreeItem *ctit = dynamic_cast(item); + if (!ctit) + return; + + const DataCurve *c = dynamic_cast(ctit->plotItem()); if (!c) return; if (c && c->type() != Graph::Function) @@ -1885,6 +1934,8 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item) btnEditCurve->hide(); Spectrogram *sp = dynamic_cast(i); + if (!sp) + return; imageGroupBox->setChecked(sp->testDisplayMode(QwtPlotSpectrogram::ImageMode)); grayScaleBox->setChecked(sp->colorMapPolicy() == Spectrogram::GrayScale); @@ -1942,7 +1993,11 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item) privateTabWidget->showPage(labelsPage); return; } + PlotCurve *c = dynamic_cast(i); + if (!c) + return; + if (c->type() == Graph::Function) btnEditCurve->setText(tr("&Edit...")); else @@ -1952,6 +2007,8 @@ void PlotDialog::setActiveCurve(CurveTreeItem *item) if (curveType == Graph::Pie) { QwtPieCurve *pie = dynamic_cast(i); + if (!pie) + return; boxPiePattern->setPattern(pie->pattern()); boxPieLineWidth->setValue(pie->pen().widthF()); boxPieLineColor->setColor(pie->pen().color()); @@ -2298,6 +2355,9 @@ bool PlotDialog::acceptParams() return false; CurveTreeItem *item = dynamic_cast(it); + if (!item) + return false; + QwtPlotItem *plotItem = dynamic_cast(item->plotItem()); if (!plotItem) return false; @@ -2479,6 +2539,9 @@ bool PlotDialog::acceptParams() else if (privateTabWidget->currentPage() == piePage) { QwtPieCurve *pie = dynamic_cast(plotItem); + if (!pie) + return false; + pie->setPen( QPen(boxPieLineColor->color(), boxPieLineWidth->value(), Graph::getPenStyle(boxPieLineStyle->currentIndex()))); @@ -2488,6 +2551,9 @@ bool PlotDialog::acceptParams() else if (privateTabWidget->currentPage() == pieGeometryPage) { QwtPieCurve *pie = dynamic_cast(plotItem); + if (!pie) + return false; + pie->setViewAngle(boxPieViewAngle->value()); pie->setThickness(boxPieThickness->value()); pie->setRadius(boxRadius->value()); @@ -2498,6 +2564,9 @@ bool PlotDialog::acceptParams() else if (privateTabWidget->currentPage() == pieLabelsPage) { QwtPieCurve *pie = dynamic_cast(plotItem); + if (!pie) + return false; + pie->setLabelsAutoFormat(pieAutoLabelsBox->isChecked()); pie->setLabelValuesFormat(boxPieValues->isChecked()); pie->setLabelPercentagesFormat(boxPiePercentages->isChecked()); @@ -3002,8 +3071,12 @@ void PlotDialog::chooseLabelsFont() if (!item || item->type() != CurveTreeItem::PlotCurveTreeItem) return; - QwtPlotItem *i = dynamic_cast(item)->plotItem(); - Graph *graph = dynamic_cast(item)->graph(); + CurveTreeItem* ctit = dynamic_cast(item); + if (!ctit) + return; + + QwtPlotItem *i = ctit->plotItem(); + Graph *graph = ctit->graph(); if (!i || !graph) return; @@ -3075,6 +3148,9 @@ void LayerItem::insertCurvesList() { PlotCurve *c = dynamic_cast(it); DataCurve* dc = dynamic_cast(it); + if (!c || !dc) + continue; + if (dc && c->type() != Graph::Function && dc->table()) { QString s = dc->plotAssociation(); @@ -3110,6 +3186,16 @@ CurveTreeItem::CurveTreeItem(QwtPlotItem *curve, LayerItem *parent, const QStrin setIcon(0, getQPixmap("graph_disabled_xpm")); } +Graph* CurveTreeItem::graph() +{ + LayerItem *l = dynamic_cast(parent()); + if (l) { + return l->graph(); + } else { + return NULL; + } +} + void CurveTreeItem::setActive(bool on) { if (on) diff --git a/Code/Mantid/MantidPlot/src/PlotDialog.h b/Code/Mantid/MantidPlot/src/PlotDialog.h index cebfeacc1dce..f5e1d9017a55 100644 --- a/Code/Mantid/MantidPlot/src/PlotDialog.h +++ b/Code/Mantid/MantidPlot/src/PlotDialog.h @@ -298,7 +298,7 @@ class CurveTreeItem : public QTreeWidgetItem enum {PlotCurveTreeItem = 1002}; CurveTreeItem(QwtPlotItem *curve, LayerItem *parent, const QString& s); - Graph* graph(){return dynamic_cast(parent())->graph();}; + Graph* graph(); void setActive(bool on); QwtPlotItem *plotItem() const{ return d_curve; }; diff --git a/Code/Mantid/MantidPlot/src/main.cpp b/Code/Mantid/MantidPlot/src/main.cpp index 8e8f9a066eac..646f3102b24e 100644 --- a/Code/Mantid/MantidPlot/src/main.cpp +++ b/Code/Mantid/MantidPlot/src/main.cpp @@ -187,7 +187,7 @@ int main( int argc, char ** argv ) // Splash QPixmap pixmap; if (!pixmap.load(":/MantidSplashScreen.png")) std::cerr << "Couldn't load splashscreen\n"; - QSplashScreen splash(pixmap, Qt::WindowStaysOnTopHint); + QSplashScreen splash(pixmap); const QString releaseDateTime(Mantid::Kernel::MantidVersion::releaseDate()); const QString versionInfo(Mantid::Kernel::MantidVersion::version()); splash.showMessage("Release: " + releaseDateTime + " (Version " + versionInfo + ")", Qt::AlignLeft | Qt::AlignBottom); diff --git a/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py b/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py index 829047a78158..9f30dff27a0b 100644 --- a/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py +++ b/Code/Mantid/MantidPlot/test/MantidPlot1DPlotTest.py @@ -41,7 +41,6 @@ def tearDown(self): def test_plotSpectrum_errorBars(self): g = plotSpectrum("fake", 0, error_bars=True) - screenshot(g, "plotSpectrum_errorBars", "Call to plotSpectrum() of 1 spectrum, with error bars.") self.g = g def test_plotSpectrum_fromWorkspaceProxy(self): @@ -51,7 +50,6 @@ def test_plotSpectrum_fromWorkspaceProxy(self): def test_plotSpectrum_severalSpectra(self): g = plotSpectrum("fake", [0, 1]) - screenshot(g, "plotSpectrum_severalSpectra", "Call to plotSpectrum() of 2 spectra, no error bars.") self.g = g def test_Customized1DPlot(self): @@ -65,7 +63,6 @@ def test_Customized1DPlot(self): l.setTitleAlignment(QtCore.Qt.AlignLeft) l.setScale(2, 0.0, 3.0) l.setAntialiasing(True) - screenshot(g, "Customized1DPlot", "1D plot of a spectrum, with error bars, an orange line of width 2, a custom title in red Arial font, with X from 0 to 3") self.g = g def test_standard_plot_command(self): diff --git a/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py b/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py index 9c08fd1bcc6e..b1c355684955 100644 --- a/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py +++ b/Code/Mantid/MantidPlot/test/MantidPlotProxiesTest.py @@ -121,7 +121,6 @@ def test_closing_MantidMatrix_plotGraph2D(self): mm = importMatrixWorkspace("fake", visible=True) g = mm.plotGraph2D() spec = g.activeLayer().spectrogram() - screenshot(g, "MantidMatrix.plotGraph2D", "Call to MantidMatrix.plotGraph2D() on a workspace.") self.try_closing(mm, "importMatrixWorkspace()") self.assertTrue(g._getHeldObject() is None, "Deleted graph safely when the parent MantidMatrix was deleted") self.assertTrue(spec._getHeldObject() is None, "Deleted spectrogram safely") @@ -135,13 +134,11 @@ def test_closing_MantidMatrix_plotGraph3D(self): def test_closing_getInstrumentView(self): iv = getInstrumentView("IRS26173") - screenshot(iv, "getInstrumentView", "Call to getInstrumentView() on a workspace.") self.try_closing(iv, "getInstrumentView()") def test_convertToWaterfall(self): g = plot(workspace("IRS26173"),(0,1,2,3,4)) convertToWaterfall(g) - screenshot(g, "convertToWaterfall", "Call to convertToWaterfall() on a workspace.") self.try_closing(g, "convertToWaterfall()") def test_dock_method_produces_docked_window_on_matrix(self): diff --git a/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py b/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py index 734da230cc4f..27961933c3f1 100644 --- a/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py +++ b/Code/Mantid/MantidPlot/test/MantidPlotSliceViewerTest.py @@ -41,7 +41,6 @@ def test_mouseMove(self): svw = plotSlice('uniform') svw.setSlicePoint(2, 2.5) moveMouseToCentre(svw._getHeldObject()) - screenshot(svw, "SliceViewer", "SliceViewer with mouse at center, showing coordinates.") def test_plotSlice_empty(self): """ Plot slice on an empty workspace """ @@ -68,7 +67,6 @@ def test_plot4D_workspace(self): svw.setSlicePoint(3, 7.5) self.assertAlmostEqual(svw.getSlicePoint(2), 2.5, 3) self.assertAlmostEqual(svw.getSlicePoint(3), 7.5, 3) - screenshot(svw, "SliceViewer_4D", "SliceViewer open to a 4D workspace; z=2.5, e=7.5.") svw.setXYDim("z", "e") self.assertEqual(svw.getDimX(), 2) self.assertEqual(svw.getDimY(), 3) @@ -114,10 +112,16 @@ def test_saveImage(self): dest = get_screenshot_dir() if not dest is None: filename = "SliceViewerSaveImage" - svw.saveImage(os.path.join(dest, filename+".png") ) - # Add to the HTML report - screenshot(None, filename, "SliceViewer: result of saveImage(). Should be only the 2D plot with a color bar (no GUI elements)", - png_exists=True) + filepath = os.path.join(dest, filename+".png") + # Remove any old file + if os.path.isfile(filepath): + os.remove(filepath) + # Save + svw.saveImage(filepath) + self.assertEquals(os.path.isfile(filepath), True, + "Screenshot was not written out as expected.") + if os.path.isfile(filepath): + os.remove(filepath) def test_showLine(self): svw = plotSlice('uniform') @@ -133,7 +137,6 @@ def test_showLine(self): self.assertAlmostEqual(liner.getBinWidth(), 0.05, 3) # Width was set self.assertAlmostEqual(liner.getPlanarWidth(), 0.88, 3) - screenshot(svw, "SliceViewer_and_LineViewer", "SliceViewer with LineViewer open, showing line overlay and integrated line.") # Now turn it off svw.toggleLineMode(False) self.assertFalse( liner.isVisible(), "LineViewer was hidden") diff --git a/Code/Mantid/MantidPlot/test/mantidplottests.py b/Code/Mantid/MantidPlot/test/mantidplottests.py index 39d59919da8f..f5b14b0c5dba 100644 --- a/Code/Mantid/MantidPlot/test/mantidplottests.py +++ b/Code/Mantid/MantidPlot/test/mantidplottests.py @@ -46,7 +46,7 @@ def runTests(classname): if src is None: runner = unittest.TextTestRunner() else: - sys.path.append( os.path.join(src, "TestingTools/unittest-xml-reporting/src") ) + sys.path.append( os.path.join(src, "Testing", "Tools", "unittest-xml-reporting", "src") ) import xmlrunner runner = xmlrunner.XMLTestRunner(output='Testing') diff --git a/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.ui b/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.ui index 5d891ba75661..57ba9eee696c 100644 --- a/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.ui +++ b/Code/Mantid/MantidQt/CustomDialogs/inc/MantidQtCustomDialogs/PlotAsymmetryByLogValueDialog.ui @@ -1,351 +1,373 @@ - PlotAsymmetryByLogValueDialog - - - - 0 - 0 - 479 - 544 - - - - PlotAsymmetryByLogValue - - - - - - - - + PlotAsymmetryByLogValueDialog + + + + 0 + 0 + 479 + 544 + + + + PlotAsymmetryByLogValue + + - - - - - First run + + + - - - - - - - - - Browse - - - - + + + + + + + First run + + + + + + + + + + Browse + + + + + + + + + + + Last run + + + + + + + + + + Browse + + + + + + + + + + + Log value + + + + + + + + 0 + 0 + + + + true + + + + + + + + + + Function + + + + + + + + 0 + 0 + + + + + + + + + + + + + + Output workspace + + + + + + + + + + + + Type + + + + + + + + 0 + 0 + + + + + + + + + + - - - - - Last run - - - - - - - - - - Browse + + + Periods - - - + + + + + + + Red + + + + + + + + + + Green + + + + + + + + + + - - - - - Log value - - - - - - - - 0 - 0 - - - - true + + + Grouping - - - + + + + + + + Forward spectra + + + + + + + false + + + + + + + Backward spectra + + + + + + + + + + - - - - - Output workspace + + + Time - - - - - - - - - - - Type - - - - - - - - 0 - 0 - - - - - - - + + + + + + + Min + + + + + + + + + + Max + + + + + + + + + + - - - - - - - Periods - - - - - - - Red + + + Dead Time Correction - - - - - - - - - Green - - - - - - - + + + + + QLayout::SetDefaultConstraint + + + + + Type + + + + + + + + 0 + 0 + + + + + + + + + + + 0 + + + + + File + + + + + + + + + + Browse + + + + + + + + - - - - - - - Grouping - - - - - - - Forward spectra - - - - - - - false - - - - - - - Backward spectra - - - - - - - - - - - - - - - Time - - - - - - - - Min - - - - - - - - - - Max + + + 6 - - - - - - - - - - - - - - Dead Time Correction - - - - - - QLayout::SetDefaultConstraint - - - - - Type - - - - - - - - 0 - 0 - - - - - - - - - - - 0 - - - - - File - - - - - - - - - - Browse - - - + + + + + 31 + 26 + + + + ? + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + OK + + + + + + + Cancel + + + - - - - - - - - 6 - - - - - - 31 - 26 - - - - ? - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - - - OK - - - - - - - Cancel - - - - - - - - firstRunBox - browseFirstButton - lastRunBox - browseLastButton - logBox - outWSBox - redBox - forwardBox - timeMinBox - - - + + + firstRunBox + browseFirstButton + lastRunBox + browseLastButton + logBox + outWSBox + redBox + forwardBox + timeMinBox + + + diff --git a/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp b/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp index 4e14e4a4bca5..9d9acccbb437 100644 --- a/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp +++ b/Code/Mantid/MantidQt/CustomDialogs/src/PlotAsymmetryByLogValueDialog.cpp @@ -66,6 +66,7 @@ void PlotAsymmetryByLogValueDialog::initLayout() tie(m_uiForm.firstRunBox, "FirstRun", m_uiForm.FirstRunLayout); tie(m_uiForm.lastRunBox, "LastRun", m_uiForm.LastRunLayout); tie(m_uiForm.logBox, "LogValue"); + tie(m_uiForm.typeBoxLog, "Function"); tie(m_uiForm.outWSBox, "OutputWorkspace", m_uiForm.OutputWSLayout); tie(m_uiForm.typeBox, "Type"); tie(m_uiForm.redBox, "Red"); @@ -96,6 +97,7 @@ void PlotAsymmetryByLogValueDialog::initLayout() // Fill ComboBoxes with allowed values fillAndSetComboBox("Type", m_uiForm.typeBox); + fillAndSetComboBox("Function", m_uiForm.typeBoxLog); fillAndSetComboBox("DeadTimeCorrType", m_uiForm.dtcType); // Fill log values from the file @@ -215,5 +217,5 @@ void PlotAsymmetryByLogValueDialog::fillLogBox(const QString&) void PlotAsymmetryByLogValueDialog::showHideDeadTimeFileWidget(int deadTimeTypeIndex) { // Show only if "Using specified file" selected - m_uiForm.dtcFileContainer->setVisible(deadTimeTypeIndex == 1); + m_uiForm.dtcFileContainer->setVisible(deadTimeTypeIndex == 2); } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt b/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt index dd7c0b528b97..ea898a3f890a 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt +++ b/Code/Mantid/MantidQt/CustomInterfaces/CMakeLists.txt @@ -63,6 +63,7 @@ set ( SRC_FILES src/ReflLegacyTransferStrategy.cpp src/ReflMainViewPresenter.cpp src/ReflSearchModel.cpp + src/SampleTransmission.cpp src/SANSAddFiles.cpp src/SANSDiagnostics.cpp src/SANSEventSlicing.cpp @@ -151,6 +152,7 @@ set ( INC_FILES inc/MantidQtCustomInterfaces/QReflTableModel.h inc/MantidQtCustomInterfaces/QtReflMainView.h inc/MantidQtCustomInterfaces/QtReflOptionsDialog.h + inc/MantidQtCustomInterfaces/SampleTransmission.h inc/MantidQtCustomInterfaces/SANSAddFiles.h inc/MantidQtCustomInterfaces/SANSDiagnostics.h inc/MantidQtCustomInterfaces/SANSEventSlicing.h @@ -223,6 +225,7 @@ set ( MOC_FILES inc/MantidQtCustomInterfaces/Background.h inc/MantidQtCustomInterfaces/QReflTableModel.h inc/MantidQtCustomInterfaces/QtReflMainView.h inc/MantidQtCustomInterfaces/QtReflOptionsDialog.h + inc/MantidQtCustomInterfaces/SampleTransmission.h inc/MantidQtCustomInterfaces/SANSAddFiles.h inc/MantidQtCustomInterfaces/SANSPlotSpecial.h inc/MantidQtCustomInterfaces/SANSRunWindow.h @@ -273,6 +276,7 @@ set ( UI_FILES inc/MantidQtCustomInterfaces/AddWorkspace.ui inc/MantidQtCustomInterfaces/ReflMainWidget.ui inc/MantidQtCustomInterfaces/ReflOptionsDialog.ui inc/MantidQtCustomInterfaces/ReflWindow.ui + inc/MantidQtCustomInterfaces/SampleTransmission.ui inc/MantidQtCustomInterfaces/SANSPlotSpecial.ui inc/MantidQtCustomInterfaces/SANSRunWindow.ui inc/MantidQtCustomInterfaces/SANSEventSlicing.ui diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/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..4c9363a65e14 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/ApplyCorr.ui @@ -97,7 +97,7 @@ - false + true @@ -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/IndirectTransmissionCalc.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.ui index 32c2578b8209..44809830545b 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.ui +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.ui @@ -169,11 +169,6 @@ - - MantidQt::MantidWidgets::InstrumentSelector - QComboBox -
MantidQtMantidWidgets/InstrumentSelector.h
-
MantidQt::MantidWidgets::IndirectInstrumentConfig QComboBox diff --git a/Code/Mantid/MantidQt/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/inc/MantidQtCustomInterfaces/SampleTransmission.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h new file mode 100644 index 000000000000..c40016894a5b --- /dev/null +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.h @@ -0,0 +1,57 @@ +#ifndef MANTIDQTCUSTOMINTERFACES_SAMPLETRANSMISSION_H_ +#define MANTIDQTCUSTOMINTERFACES_SAMPLETRANSMISSION_H_ + +//---------------------- +// Includes +//---------------------- +#include "ui_SampleTransmission.h" +#include "MantidQtAPI/AlgorithmRunner.h" +#include "MantidQtAPI/UserSubWindow.h" +#include "MantidQtAPI/WorkspaceObserver.h" +#include "MantidAPI/MatrixWorkspace.h" + + +namespace MantidQt +{ +namespace CustomInterfaces +{ + class SampleTransmission : public MantidQt::API::UserSubWindow + { + Q_OBJECT + + public: + /// The name of the interface as registered into the factory + static std::string name() { return "Sample Transmission Calculator"; } + // This interface's categories. + static QString categoryInfo() { return "General"; } + + public: + /// Default Constructor + SampleTransmission(QWidget *parent = 0); + + private slots: + /// Opens the Qt help page for the interface + void showHelp(); + /// Runs the calculation + void calculate(); + /// Handle completion of the calculation algorithm + void algorithmComplete(bool error); + + private: + /// Initialize the layout + virtual void initLayout(); + /// Validates UI input + bool validate(bool silent = false); + + private: + /// The form generated by Qt Designer + Ui::SampleTransmission m_uiForm; + /// Algorithm runner + API::AlgorithmRunner * m_algRunner; + + }; + +} +} + +#endif //MANTIDQTCUSTOMINTERFACES_SAMPLETRANSMISSION_H_ diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui new file mode 100644 index 000000000000..cb9b0b849dbb --- /dev/null +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui @@ -0,0 +1,368 @@ + + + SampleTransmission + + + + 0 + 0 + 550 + 570 + + + + + 0 + 0 + + + + Sample Transmission Calculator + + + + + 0 + 0 + + + + + + + Input Wavelength Range (Å) + + + + 0 + + + 0 + + + + + + Single + + + + + Multiple + + + + + + + + Type: + + + + + + + + 0 + 0 + + + + 0 + + + + + + + Low: + + + + + + + -99.989999999999995 + + + 0.100000000000000 + + + + + + + Width: + + + + + + + -99.989999999999995 + + + 0.100000000000000 + + + + + + + High: + + + + + + + -99.989999999999995 + + + 0.100000000000000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + Sample Details + + + + + + Number Density + + + + + + + Thickness + + + + + + + Chemical Formula + + + + + + + Å^3 + + + 0.100000000000000 + + + 0.100000000000000 + + + + + + + cm + + + 0.100000000000000 + + + 0.100000000000000 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Output + + + + + + + 0 + 0 + + + + false + + + + 255 + 255 + 255 + + + + + + + + + Property + + + + + Value + + + + + + + + + + + + + + 0 + 0 + + + + + 25 + 25 + + + + + 25 + 25 + + + + <html><head/><body><p>Opens the help page for the interface.</p></body></html> + + + ? + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + <html><head/><body><p>Runs the sample transmission calculation.</p></body></html> + + + Calculate + + + + + + + + + + + MantidQt::MantidWidgets::PreviewPlot + QWidget +
MantidQtMantidWidgets/PreviewPlot.h
+ 1 +
+
+ + cbBinningType + spSingleLow + spSingleWidth + spSingleHigh + leMultiple + leChemicalFormula + spNumberDensity + spThickness + twResults + pbCalculate + + + + + cbBinningType + currentIndexChanged(int) + swBinningTypes + setCurrentIndex(int) + + + 98 + 54 + + + 308 + 54 + + + + +
diff --git a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h index 8356e3821fc0..0a9c44070a14 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/UserInputValidator.h @@ -71,9 +71,14 @@ namespace MantidQt bool checkRangeIsEnclosed(const QString & outerName, std::pair outer, const QString & innerName, std::pair inner); /// Check that the given range can be split evenly into bins of the given width. bool checkBins(double lower, double binWidth, double upper, double tolerance = 0.00000001); + /// Checks two values are not equal + bool checkNotEqual(const QString & name, double x, double y = 0.0, double tolerance = 0.00000001); /// Add a custom error message to the list. void addErrorMessage(const QString & message); + /// Sets a validation label + void setErrorLabel(QLabel * errorLabel, bool valid); + /// Returns an error message which contains all the error messages raised by the check functions. QString generateErrorMessage(); /// Checks to see if all input is valid @@ -82,6 +87,7 @@ namespace MantidQt private: /// Any raised error messages. QStringList m_errorMessages; + }; } } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp index a527a211365f..2220d18b31e6 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp @@ -233,6 +233,14 @@ void DirectConvertToEnergy::instrumentLoadingDone(bool error) */ void DirectConvertToEnergy::userSelectInstrument(const QString& prefix) { + // Search for files for the current selected instrument + m_uiForm.runFiles->setInstrumentOverride(prefix); + m_uiForm.mapFile->setInstrumentOverride(prefix); + m_uiForm.whiteBeamFile->setInstrumentOverride(prefix); + m_uiForm.absRunFiles->setInstrumentOverride(prefix); + m_uiForm.absMapFile->setInstrumentOverride(prefix); + m_uiForm.absWhiteFile->setInstrumentOverride(prefix); + if ( prefix != m_curInterfaceSetup ) { // Remove the old empty instrument workspace if it is there diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ApplyCorr.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Indirect/ApplyCorr.cpp index 2f28cedf6e14..7ca36c482874 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() @@ -69,7 +60,7 @@ namespace IDA geom = "cyl"; } - QString pyInput = "from IndirectDataAnalysis import abscorFeeder, loadNexus\n"; + QString pyInput = "from IndirectDataAnalysis import abscorFeeder\n"; QString sample = m_uiForm.dsSample->getCurrentDataName(); MatrixWorkspace_const_sptr sampleWs = AnalysisDataService::Instance().retrieveWS(sample.toStdString()); @@ -111,16 +102,7 @@ namespace IDA { pyInput += "useCor = True\n"; QString corrections = m_uiForm.dsCorrections->getCurrentDataName(); - if ( !Mantid::API::AnalysisDataService::Instance().doesExist(corrections.toStdString()) ) - { - pyInput += - "corrections = loadNexus(r'" + m_uiForm.dsCorrections->getFullFilePath() + "')\n"; - } - else - { - pyInput += - "corrections = '" + corrections + "'\n"; - } + pyInput += "corrections = '" + corrections + "'\n"; } else { @@ -171,7 +153,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 +238,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..e131644b51ea 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))); @@ -112,7 +105,6 @@ namespace IDA furyAlg->setProperty("NumBins", numBins); furyAlg->setProperty("Plot", plot); - furyAlg->setProperty("Verbose", true); furyAlg->setProperty("Save", save); furyAlg->setProperty("DryRun", false); @@ -212,7 +204,6 @@ namespace IDA furyAlg->setProperty("NumBins", numBins); furyAlg->setProperty("Plot", false); - furyAlg->setProperty("Verbose", true); furyAlg->setProperty("Save", false); furyAlg->setProperty("DryRun", true); @@ -247,10 +238,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 +249,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 +298,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..127a699513cd 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..7cb65da529e0 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))); @@ -197,7 +190,7 @@ namespace MantidQt pyInput += "QLRun('"+program+"','"+sampleName+"','"+resName+"','"+resNormFile+"',"+eRange+"," " "+nBins+","+fitOps+",'"+fixedWidthFile+"',"+sequence+", " - " Save="+save+", Plot='"+plot+"', Verbose=True)\n"; + " Save="+save+", Plot='"+plot+"')\n"; runPythonScript(pyInput); @@ -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..6cd8e4e43a6a 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(); @@ -104,15 +97,12 @@ namespace MantidQt QString plot = m_uiForm.cbPlot->currentText(); pyInput += "ResNormRun('"+VanName+"', '"+ResName+"', "+ERange+", "+nBin+"," - " Save="+save+", Plot='"+plot+"', Verbose=True)\n"; + " Save="+save+", Plot='"+plot+"')\n"; runPythonScript(pyInput); // 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..78f13b6113eb 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(); @@ -132,7 +126,7 @@ namespace MantidQt QString plot = m_uiForm.cbPlot->currentText(); pyInput += "QuestRun('"+sampleName+"','"+resName+"',"+betaSig+","+eRange+","+nBins+","+fitOps+","+sequence+"," - " Save="+save+", Plot='"+plot+"', Verbose=True)\n"; + " Save="+save+", Plot='"+plot+"')\n"; runPythonScript(pyInput); } @@ -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/CustomInterfaces/src/Muon/MuonAnalysis.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp index 235660a21c44..22c2f7fd75ae 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp @@ -703,6 +703,9 @@ MatrixWorkspace_sptr MuonAnalysis::getPeriodWorkspace(PeriodType periodType, Wor */ void MuonAnalysis::userSelectInstrument(const QString& prefix) { + // Set file browsing to current instrument + m_uiForm.mwRunFiles->setInstrumentOverride(prefix); + if ( prefix != m_curInterfaceSetup ) { runClearGroupingButton(); diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp new file mode 100644 index 000000000000..c44be8a5c1cd --- /dev/null +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/SampleTransmission.cpp @@ -0,0 +1,220 @@ +//---------------------- +// Includes +//---------------------- +#include "MantidQtCustomInterfaces/SampleTransmission.h" + +#include "MantidAPI/AlgorithmManager.h" +#include "MantidKernel/Statistics.h" +#include "MantidQtAPI/HelpWindow.h" +#include "MantidQtCustomInterfaces/UserInputValidator.h" + + +namespace +{ + Mantid::Kernel::Logger g_log("SampleTransmission"); +} + +//Add this class to the list of specialised dialogs in this namespace +namespace MantidQt +{ +namespace CustomInterfaces +{ + DECLARE_SUBWINDOW(SampleTransmission); +} +} + +using namespace MantidQt::CustomInterfaces; +using namespace Mantid::API; + + +//---------------------- +// Public member functions +//---------------------- +///Constructor +SampleTransmission::SampleTransmission(QWidget *parent) : + UserSubWindow(parent), + m_algRunner(new API::AlgorithmRunner(this)) +{ + connect(m_algRunner, SIGNAL(algorithmComplete(bool)), this, SLOT(algorithmComplete(bool))); +} + + +/** + * Set up the dialog layout. + */ +void SampleTransmission::initLayout() +{ + m_uiForm.setupUi(this); + connect(m_uiForm.pbCalculate, SIGNAL(clicked()), this, SLOT(calculate())); + connect(m_uiForm.pbHelp, SIGNAL(clicked()), this, SLOT(showHelp())); + + validate(true); +} + + +/** + * Opens the Qt help page for the interface. + */ +void SampleTransmission::showHelp() +{ + MantidQt::API::HelpWindow::showCustomInterface(NULL, QString("SampleTransmissionCalculator")); +} + + +/** + * Validate user input. + * Outputs any warnings to the results log at warning level. + * + * @param silent If the results should not be logged + * @return Result of validation + */ +bool SampleTransmission::validate(bool silent) +{ + UserInputValidator uiv; + + // Valudate input binning + int wavelengthBinning = m_uiForm.cbBinningType->currentIndex(); + switch(wavelengthBinning) + { + // Single + case 0: + uiv.checkBins(m_uiForm.spSingleLow->value(), + m_uiForm.spSingleWidth->value(), + m_uiForm.spSingleHigh->value()); + break; + + // Multiple + case 1: + uiv.checkFieldIsNotEmpty("Multiple binning", + m_uiForm.leMultiple, + m_uiForm.valMultiple); + break; + } + + // Validate chemical formula + uiv.checkFieldIsNotEmpty("Chemical Formula", + m_uiForm.leChemicalFormula, + m_uiForm.valChemicalFormula); + + // Ensure number density is not zero + uiv.setErrorLabel(m_uiForm.valNumberDensity, + uiv.checkNotEqual("Number Density", m_uiForm.spNumberDensity->value())); + + // Ensure thickness is not zero + uiv.setErrorLabel(m_uiForm.valThickness, + uiv.checkNotEqual("Thickness", m_uiForm.spThickness->value())); + + // Give error message + if(!silent && !uiv.isAllInputValid()) + showInformationBox(uiv.generateErrorMessage()); + + return uiv.isAllInputValid(); +} + + +/** + * Performs a calculation with the current settings + */ +void SampleTransmission::calculate() +{ + // Do not try to run with invalid input + if(!validate()) + return; + + // Create the transmission calculation algorithm + IAlgorithm_sptr transCalcAlg = AlgorithmManager::Instance().create("CalculateSampleTransmission"); + transCalcAlg->initialize(); + + // Set the wavelength binning based on type set in UI + int wavelengthBinning = m_uiForm.cbBinningType->currentIndex(); + switch(wavelengthBinning) + { + // Single + case 0: + { + QStringList params; + params << m_uiForm.spSingleLow->text() + << m_uiForm.spSingleWidth->text() + << m_uiForm.spSingleHigh->text(); + QString binString = params.join(","); + transCalcAlg->setProperty("WavelengthRange", binString.toStdString()); + break; + } + + // Multiple + case 1: + transCalcAlg->setProperty("WavelengthRange", m_uiForm.leMultiple->text().toStdString()); + break; + } + + // Set sample material properties + transCalcAlg->setProperty("ChemicalFormula", m_uiForm.leChemicalFormula->text().toStdString()); + transCalcAlg->setProperty("NumberDensity", m_uiForm.spNumberDensity->value()); + transCalcAlg->setProperty("Thickness", m_uiForm.spThickness->value()); + + transCalcAlg->setProperty("OutputWorkspace", "CalculatedSampleTransmission"); + + // Clear the previous results + m_uiForm.twResults->clear(); + m_uiForm.ppTransmission->clear(); + + // Run algorithm + m_algRunner->startAlgorithm(transCalcAlg); +} + + +/** + * Handles completion of the calculation algorithm. + * + * @param error If the algorithm exited with an error + */ +void SampleTransmission::algorithmComplete(bool error) +{ + using namespace Mantid::Kernel; + + // Ignore errors + if(error) + { + showInformationBox("Transmission calculation failed.\nSee Results Log for details."); + return; + } + + MatrixWorkspace_sptr ws = + AnalysisDataService::Instance().retrieveWS("CalculatedSampleTransmission"); + + // Fill the output table + double scattering = ws->dataY(1)[0]; + QTreeWidgetItem *scatteringItem = new QTreeWidgetItem(); + scatteringItem->setText(0, "Scattering"); + scatteringItem->setText(1, QString::number(scattering)); + m_uiForm.twResults->addTopLevelItem(scatteringItem); + + QTreeWidgetItem *transmissionItem = new QTreeWidgetItem(); + transmissionItem->setText(0, "Transmission"); + m_uiForm.twResults->addTopLevelItem(transmissionItem); + transmissionItem->setExpanded(true); + + std::vector transmissionData = ws->dataY(0); + Statistics stats = getStatistics(transmissionData); + + QMap transmissionStats; + transmissionStats["Min"] = stats.minimum; + transmissionStats["Max"] = stats.maximum; + transmissionStats["Mean"] = stats.mean; + transmissionStats["Median"] = stats.median; + transmissionStats["Std. Dev."] = stats.standard_deviation; + + for(auto it = transmissionStats.begin(); it != transmissionStats.end(); ++it) + { + QTreeWidgetItem *item = new QTreeWidgetItem(); + item->setText(0, it.key()); + item->setText(1, QString::number(it.value())); + transmissionItem->addChild(item); + } + + m_uiForm.twResults->resizeColumnToContents(0); + + // Plot transmission curve on preview plot + m_uiForm.ppTransmission->addSpectrum("Transmission", "CalculatedSampleTransmission", 0); + m_uiForm.ppTransmission->resizeX(); +} diff --git a/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp b/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp index ae7bba5358be..649917e064f7 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp +++ b/Code/Mantid/MantidQt/CustomInterfaces/src/UserInputValidator.cpp @@ -45,13 +45,13 @@ namespace MantidQt { if(field->text() == "") { - errorLabel->setText("*"); + setErrorLabel(errorLabel, false); m_errorMessages.append(name + " has been left blank."); return false; } else { - errorLabel->setText(""); + setErrorLabel(errorLabel, true); return true; } } @@ -72,12 +72,12 @@ namespace MantidQt if( fieldState == QValidator::Acceptable ) { - errorLabel->setText(""); + setErrorLabel(errorLabel, true); return true; } else { - errorLabel->setText("*"); + setErrorLabel(errorLabel, false); m_errorMessages.append(errorMessage); return false; } @@ -254,6 +254,32 @@ namespace MantidQt return true; } + /** + * Checks two values are not equal. + * + * @param name Name of value + * @param x First value + * @param y Second value (defaults to zero) + * @param tolerance Tolerance to which to compare + * @return True if input was valid + */ + bool UserInputValidator::checkNotEqual(const QString & name, double x, double y, double tolerance) + { + double delta = x - y; + + if(std::abs(delta) <= tolerance) + { + std::stringstream msg; + msg << name.toStdString() << " (" << x << ")" + << " should not be equal to " << y << "."; + QString msgStr = QString::fromStdString(msg.str()); + m_errorMessages.append(msgStr); + return false; + } + + return true; + } + /** * Add a custom error message to the list. * @@ -273,7 +299,7 @@ namespace MantidQt if( m_errorMessages.isEmpty() ) return ""; - return "Please correct the following:\n\n" + m_errorMessages.join("\n"); + return "Please correct the following:\n" + m_errorMessages.join("\n"); } /** @@ -285,5 +311,36 @@ namespace MantidQt { return m_errorMessages.isEmpty(); } + + /** + * Sets a validation label that is displyed next to the widget on the UI. + * + * @param errorLabel Label to change + * @param valid If the input was valid + */ + void UserInputValidator::setErrorLabel(QLabel * errorLabel, bool valid) + { + // Do nothing if no error label was provided + if(errorLabel == NULL) + return; + + if(!valid) + { + // Set the label to be red + QPalette palette = errorLabel->palette(); + palette.setColor(errorLabel->foregroundRole(), Qt::red); + errorLabel->setPalette(palette); + + errorLabel->setText("*"); + } + else + { + errorLabel->setText(""); + } + + // Only show the label if input is invalid + errorLabel->setVisible(!valid); + } + } } diff --git a/Code/Mantid/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h b/Code/Mantid/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h index 4ed7c14a14e9..775ef03668e4 100644 --- a/Code/Mantid/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h +++ b/Code/Mantid/MantidQt/CustomInterfaces/test/UserInputValidatorTest.h @@ -32,7 +32,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite UserInputValidator uiv; TS_ASSERT(!uiv.checkBins(0.6, -0.1, 1.8)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nBin width must be a positive value."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBin width must be a positive value."); } void test_zeroWidthRebin() @@ -40,7 +40,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite UserInputValidator uiv; TS_ASSERT(!uiv.checkBins(0.6, 0.0, 1.8)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nBin width must be non-zero."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBin width must be non-zero."); } void test_zeroRangeRebin() @@ -48,7 +48,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite UserInputValidator uiv; TS_ASSERT(!uiv.checkBins(0.6, 0.1, 0.6)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nBinning ranges must be non-zero."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBinning ranges must be non-zero."); } void test_reverseRangeRebin() @@ -56,7 +56,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite UserInputValidator uiv; TS_ASSERT(!uiv.checkBins(1.8, 0.1, 0.6)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nThe start of a binning range must be less than the end."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nThe start of a binning range must be less than the end."); } void test_binsNotFactorsRebin() @@ -64,7 +64,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite UserInputValidator uiv; TS_ASSERT(!uiv.checkBins(0.0, 0.2, 0.7)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nBin width must allow for even splitting of the range."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nBin width must allow for even splitting of the range."); } void test_validRange() @@ -81,7 +81,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite std::pair range(10, 5); TS_ASSERT(!uiv.checkValidRange("test range", range)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nThe start of test range must be less than the end."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nThe start of test range must be less than the end."); } void test_invalidRangeZeroWidth() @@ -90,7 +90,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite std::pair range(5, 5); TS_ASSERT(!uiv.checkValidRange("test range", range)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\ntest range must have a non-zero width."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\ntest range must have a non-zero width."); } void test_nonOverlappingRanges() @@ -109,7 +109,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite std::pair rangeB(3, 8); TS_ASSERT(!uiv.checkRangesDontOverlap(rangeA, rangeB)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nThe ranges must not overlap: [1,5], [3,8]."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nThe ranges must not overlap: [1,5], [3,8]."); } void test_enclosedRange() @@ -128,7 +128,7 @@ class UserInputValidatorTest : public CxxTest::TestSuite std::pair inner(3, 15); TS_ASSERT(!uiv.checkRangeIsEnclosed("outer range", outer, "inner range", inner)); TS_ASSERT(!uiv.isAllInputValid()); - TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\n\nouter range must completely enclose inner range."); + TS_ASSERT_EQUALS(uiv.generateErrorMessage(), "Please correct the following:\nouter range must completely enclose inner range."); } }; 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/InstrumentSelector.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/InstrumentSelector.cpp index 4b9a072704eb..166517650604 100644 --- a/Code/Mantid/MantidQt/MantidWidgets/src/InstrumentSelector.cpp +++ b/Code/Mantid/MantidQt/MantidWidgets/src/InstrumentSelector.cpp @@ -37,7 +37,7 @@ namespace MantidWidgets */ InstrumentSelector::InstrumentSelector(QWidget *parent, bool init) : QComboBox(parent), m_changeObserver(*this, &InstrumentSelector::handleConfigChange), - m_techniques(), m_currentFacility(NULL), m_init(init), m_storeChanges(true), + m_techniques(), m_currentFacility(NULL), m_init(init), m_storeChanges(false), m_updateOnFacilityChange(true), m_selectedInstrument() { setEditable(false); diff --git a/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp b/Code/Mantid/MantidQt/MantidWidgets/src/PreviewPlot.cpp new file mode 100644 index 000000000000..b235a3935591 --- /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 curveName 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 ws Pointer to the workspace + * @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 given workspace from the plot given a pointer to it. + * + * If multiple curves are plotted form the same workspace then all will be 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 given workspace from the plot given its name. + * + * @param curveName 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 curve 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 on 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 given 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 ws 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/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp b/Code/Mantid/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp index aa5929add3b7..0eebd21b630b 100644 --- a/Code/Mantid/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp +++ b/Code/Mantid/MantidQt/SliceViewer/src/ConcretePeaksPresenter.cpp @@ -451,7 +451,7 @@ void ConcretePeaksPresenter::setPeakSizeIntoProjection(const double fraction) { double ConcretePeaksPresenter::getPeakSizeOnProjection() const { double result = 0; - if (m_viewPeaks != NULL && m_viewPeaks->positionOnly()) { + if (m_viewPeaks != NULL && (m_peaksWS->getNumberPeaks() > 0) && m_viewPeaks->positionOnly()) { result = m_viewPeaks->getOccupancyInView(); } return result; @@ -459,7 +459,7 @@ double ConcretePeaksPresenter::getPeakSizeOnProjection() const { double ConcretePeaksPresenter::getPeakSizeIntoProjection() const { double result = 0; - if (m_viewPeaks != NULL && m_viewPeaks->positionOnly()) { + if (m_viewPeaks != NULL && (m_peaksWS->getNumberPeaks() > 0) && m_viewPeaks->positionOnly()) { result = m_viewPeaks->getOccupancyIntoView(); } return result; diff --git a/Code/Mantid/MantidQt/SliceViewer/test/MockObjects.h b/Code/Mantid/MantidQt/SliceViewer/test/MockObjects.h index da6b3e1a4c57..42cb6aa2ddcf 100644 --- a/Code/Mantid/MantidQt/SliceViewer/test/MockObjects.h +++ b/Code/Mantid/MantidQt/SliceViewer/test/MockObjects.h @@ -200,9 +200,9 @@ class MockPeakTransformFactory : public PeakTransformFactory MOCK_METHOD0(findDetector, bool()); MOCK_METHOD2(setQSampleFrame, - void(Mantid::Kernel::V3D QSampleFrame, double detectorDistance)); + void(Mantid::Kernel::V3D QSampleFrame, boost::optional detectorDistance)); MOCK_METHOD2(setQLabFrame, - void(Mantid::Kernel::V3D QLabFrame, double detectorDistance)); + void(Mantid::Kernel::V3D QLabFrame, boost::optional detectorDistance)); MOCK_METHOD1(setWavelength, void(double wavelength)); MOCK_CONST_METHOD0(getWavelength, diff --git a/Code/Mantid/Testing/Data/SystemTest/HRP39187.RAW.md5 b/Code/Mantid/Testing/Data/SystemTest/HRP39187.RAW.md5 new file mode 100644 index 000000000000..6736dcddd7b0 --- /dev/null +++ b/Code/Mantid/Testing/Data/SystemTest/HRP39187.RAW.md5 @@ -0,0 +1 @@ +6aa506e83ba085964781b480d71c59fe diff --git a/Code/Mantid/Testing/Data/SystemTest/HRP39191.RAW.md5 b/Code/Mantid/Testing/Data/SystemTest/HRP39191.RAW.md5 new file mode 100644 index 000000000000..d9d1923775b2 --- /dev/null +++ b/Code/Mantid/Testing/Data/SystemTest/HRP39191.RAW.md5 @@ -0,0 +1 @@ +e422e2456884b0bd4c686e5d883f9d57 diff --git a/Code/Mantid/Testing/Data/SystemTest/hrpd_new_072_01_corr.cal.md5 b/Code/Mantid/Testing/Data/SystemTest/hrpd_new_072_01_corr.cal.md5 new file mode 100644 index 000000000000..37c71d5dbfe1 --- /dev/null +++ b/Code/Mantid/Testing/Data/SystemTest/hrpd_new_072_01_corr.cal.md5 @@ -0,0 +1 @@ +21f937d9b1bfc5032d3fbf8f85920c15 diff --git a/Test/PerformanceTests/.gitignore b/Code/Mantid/Testing/PerformanceTests/.gitignore similarity index 100% rename from Test/PerformanceTests/.gitignore rename to Code/Mantid/Testing/PerformanceTests/.gitignore diff --git a/Test/PerformanceTests/Mantid.systemtests.properties.template b/Code/Mantid/Testing/PerformanceTests/Mantid.systemtests.properties.template similarity index 100% rename from Test/PerformanceTests/Mantid.systemtests.properties.template rename to Code/Mantid/Testing/PerformanceTests/Mantid.systemtests.properties.template diff --git a/Test/PerformanceTests/README.txt b/Code/Mantid/Testing/PerformanceTests/README.txt similarity index 100% rename from Test/PerformanceTests/README.txt rename to Code/Mantid/Testing/PerformanceTests/README.txt diff --git a/Test/PerformanceTests/analysis.py b/Code/Mantid/Testing/PerformanceTests/analysis.py similarity index 100% rename from Test/PerformanceTests/analysis.py rename to Code/Mantid/Testing/PerformanceTests/analysis.py diff --git a/Test/PerformanceTests/check_performance.py b/Code/Mantid/Testing/PerformanceTests/check_performance.py similarity index 100% rename from Test/PerformanceTests/check_performance.py rename to Code/Mantid/Testing/PerformanceTests/check_performance.py diff --git a/Test/PerformanceTests/make_report.py b/Code/Mantid/Testing/PerformanceTests/make_report.py similarity index 100% rename from Test/PerformanceTests/make_report.py rename to Code/Mantid/Testing/PerformanceTests/make_report.py diff --git a/Test/PerformanceTests/reporters.py b/Code/Mantid/Testing/PerformanceTests/reporters.py similarity index 100% rename from Test/PerformanceTests/reporters.py rename to Code/Mantid/Testing/PerformanceTests/reporters.py diff --git a/Test/PerformanceTests/setup.py b/Code/Mantid/Testing/PerformanceTests/setup.py similarity index 100% rename from Test/PerformanceTests/setup.py rename to Code/Mantid/Testing/PerformanceTests/setup.py diff --git a/Test/PerformanceTests/sqlresults.py b/Code/Mantid/Testing/PerformanceTests/sqlresults.py similarity index 100% rename from Test/PerformanceTests/sqlresults.py rename to Code/Mantid/Testing/PerformanceTests/sqlresults.py diff --git a/Test/PerformanceTests/testresult.py b/Code/Mantid/Testing/PerformanceTests/testresult.py similarity index 100% rename from Test/PerformanceTests/testresult.py rename to Code/Mantid/Testing/PerformanceTests/testresult.py diff --git a/Test/PerformanceTests/xunit_to_sql.py b/Code/Mantid/Testing/PerformanceTests/xunit_to_sql.py similarity index 100% rename from Test/PerformanceTests/xunit_to_sql.py rename to Code/Mantid/Testing/PerformanceTests/xunit_to_sql.py diff --git a/Code/Mantid/Testing/SystemTests/lib/systemtests/algorithm_decorator.py b/Code/Mantid/Testing/SystemTests/lib/systemtests/algorithm_decorator.py new file mode 100644 index 000000000000..91c0fd54546d --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/lib/systemtests/algorithm_decorator.py @@ -0,0 +1,61 @@ +import inspect +import re + +def make_decorator(algorithm_to_decorate): + """ + Dynamically create a builder pattern style decorator around a Mantid algorithm. + This allows you to separate out setting algorithm parameters from the actual method execution. Parameters may be reset multiple times. + + Usage: + rebin = make_decorator(Rebin) + rebin.set_Params([0, 0.1, 1]) + .... + rebin.execute() + + Arguments: + algorithm_to_decorate: The mantid.simpleapi algorithm to decorate. + + + + """ + + class Decorator(object): + + def __init__(self, alg_subject): + self.__alg_subject = alg_subject + self.__parameters__ = dict() + + def execute(self, additional=None, verbose=False): + if verbose: + print "Algorithm Parameters:" + print self.__parameters__ + print + out = self.__alg_subject(**self.__parameters__) + return out + + def set_additional(self, additional): + self.__parameters__.update(**additional) + + def add_getter_setter(type, name): + + def setter(self, x): + self.__parameters__[name] = x + + def getter(self): + return self.__parameters__[name] + + setattr(type, "set_" + name, setter) + setattr(type, "get_" + name, getter) + + + argspec = inspect.getargspec(algorithm_to_decorate) + for parameter in argspec.varargs.split(','): + m = re.search('(^\w+)', parameter) # Take the parameter key part from the defaults given as 'key=value' + if m: + parameter = m.group(0).strip() + m = re.search('\w+$', parameter) # strip off any leading numerical values produced by argspec + if m: + parameter = m.group(0).strip() + add_getter_setter(Decorator, m.group(0).strip()) + + return Decorator(algorithm_to_decorate) diff --git a/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py b/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py new file mode 100644 index 000000000000..31aa6f54b281 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/lib/systemtests/stresstesting.py @@ -0,0 +1,1023 @@ +''' +Mantid stress testing framework. This module contains all of the necessary code +to run sets of stress tests on the Mantid framework by executing scripts directly +or by importing them into MantidPlot. + +Copyright © 2009 STFC Rutherford Appleton Laboratories + +This file is part of Mantid. + +Mantid is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 3 of the License, or +(at your option) any later version. + +Mantid is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . + +File change history is stored at: . +''' +import sys +import os +import types +import re +import time +import datetime +import platform +import subprocess +import tempfile +import imp +import inspect +import abc +import numpy +import unittest + +# Path to this file +THIS_MODULE_DIR = os.path.dirname(os.path.realpath(__file__)) + +######################################################################### +# The base test class. +######################################################################### +class MantidStressTest(unittest.TestCase): + '''Defines a base class for stress tests, providing functions + that should be overridden by inheriting classes to perform tests. + ''' + + # Define a delimiter when reporting results + DELIMITER = '|' + + # Define a prefix for reporting results + PREFIX = 'RESULT' + + def __init__(self): + super(MantidStressTest, self).__init__() + # A list of things not to check when validating + self.disableChecking = [] + # Whether or not to strip off whitespace when doing simple ascii diff + self.stripWhitespace = True + # Tolerance + self.tolerance = 0.00000001 + # Store the resident memory of the system (in MB) before starting the test + import mantid.api + mantid.api.FrameworkManager.clear() + from mantid.kernel import MemoryStats + self.memory = MemoryStats().residentMem()/1024 + + def runTest(self): + raise NotImplementedError('"runTest(self)" should be overridden in a derived class') + + def skipTests(self): + ''' + Override this to return True when the tests should be skipped for some + reason. + See also: requiredFiles() and requiredMemoryMB() + ''' + return False + + def validate(self): + ''' + Override this to provide a pair of workspaces which should be checked for equality + by the doValidation method. + The overriding method should return a pair of strings. This could be two workspace + names, e.g. return 'workspace1','workspace2', or a workspace name and a nexus + filename (which must have nxs suffix), e.g. return 'workspace1','GEM00001.nxs'. + ''' + return None + + def requiredFiles(self): + ''' + Override this method if you want to require files for the test. + Return a list of files. + ''' + return [] + + def requiredMemoryMB(self): + ''' + Override this method to specify the amount of free memory, + in megabytes, that is required to run the test. + The test is skipped if there is not enough memory. + ''' + return 0 + + def validateMethod(self): + ''' + Override this to specify which validation method to use. Look at the validate* methods to + see what allowed values are. + ''' + return "WorkspaceToNeXus" + + def maxIterations(self): + '''Override this to perform more than 1 iteration of the implemented test.''' + return 1 + + def reportResult(self, name, value): + ''' + Send a result to be stored as a name,value pair + ''' + print self.PREFIX + self.DELIMITER + name + self.DELIMITER + str(value) + '\n', + + def __verifyRequiredFile(self, filename): + '''Return True if the specified file name is findable by Mantid.''' + from mantid.api import FileFinder + + # simple way is just getFullPath which never uses archive search + if os.path.exists(FileFinder.getFullPath(filename)): + return True + + # try full findRuns which will use archive search if it is turned on + try: + candidates = FileFinder.findRuns(filename) + for item in candidates: + if os.path.exists(item): + return True + except RuntimeError, e: + return False + + + # file was not found + return False + + def __verifyRequiredFiles(self): + # first see if there is anything to do + reqFiles = self.requiredFiles() + if len(reqFiles) <= 0: + return + + # by default everything is ok + foundAll = True + + # initialize mantid so it can get the data directories to look in + import mantid + # check that all of the files exist + for filename in reqFiles: + if not self.__verifyRequiredFile(filename): + print "Missing required file: '%s'" % filename + foundAll = False + + if not foundAll: + sys.exit(PythonTestRunner.SKIP_TEST) + + def __verifyMemory(self): + """ Do we need to skip due to lack of memory? """ + required = self.requiredMemoryMB() + if required <= 0: + return + + # Check if memory is available + from mantid.kernel import MemoryStats + MB_avail = MemoryStats().availMem()/(1024.) + if (MB_avail < required): + print "Insufficient memory available to run test! %g MB available, need %g MB." % (MB_avail,required) + sys.exit(PythonTestRunner.SKIP_TEST) + + def execute(self): + ''' + Run the defined number of iterations of this test + ''' + # Do we need to skip due to missing files? + self.__verifyRequiredFiles() + + self.__verifyMemory() + + # A custom check for skipping the tests for other reasons + if self.skipTests(): + sys.exit(PythonTestRunner.SKIP_TEST) + + # Start timer + start = time.time() + countmax = self.maxIterations() + 1 + for i in range(1, countmax): + istart = time.time() + self.runTest() + delta_t = time.time() - istart + self.reportResult('iteration time_taken', str(i) + ' %.2f' % delta_t) + delta_t = float(time.time() - start) + # Finish + #self.reportResult('time_taken', '%.2f' % delta_t) + + def __prepASCIIFile(self, filename): + """ + Prepare an ascii file for comparison using difflib. + """ + handle = open(filename, mode='r') + stuff = handle.readlines() + if self.stripWhitespace: + stuff = [line.strip() for line in stuff] + handle.close() + return stuff + + def validateASCII(self): + """ + Validate ASCII files using difflib. + """ + (measured, expected) = self.validate() + measured = self.__prepASCIIFile(measured) + expected = self.__prepASCIIFile(expected) + + # calculate the difference + import difflib + diff = difflib.Differ().compare(measured, expected) + result = [] + for line in diff: + if line.startswith('+') or line.startswith('-') or line.startswith('?'): + result.append(line) + + # print the difference + if len(result) > 0: + if self.stripWhitespace: + msg = "(whitespace striped from ends)" + else: + msg = "" + print "******************* Difference in files", msg + print "\n".join(result) + print "*******************" + return False + else: + return True + + def validateWorkspaceToNeXus(self): + ''' + Assumes the second item from self.validate() is a nexus file and loads it + to compare to the supplied workspace. + ''' + valNames = list(self.validate()) + from mantid.simpleapi import Load + numRezToCheck=len(valNames) + mismatchName=None; + + validationResult =True; + for ik in range(0,numRezToCheck,2): # check All results + workspace2 = valNames[ik+1] + if workspace2.endswith('.nxs'): + Load(Filename=workspace2,OutputWorkspace="RefFile") + workspace2 = "RefFile" + else: + raise RuntimeError("Should supply a NeXus file: %s" % workspace2) + valPair=(valNames[ik],"RefFile"); + if numRezToCheck>2: + mismatchName = valNames[ik]; + + if not(self.validateWorkspaces(valPair,mismatchName)): + validationResult = False; + print 'Workspace {0} not equal to its reference file'.format(valNames[ik]); + #end check All results + + return validationResult; + + def validateWorkspaceToWorkspace(self): + ''' + Assumes the second item from self.validate() is an existing workspace + to compare to the supplied workspace. + ''' + valNames = list(self.validate()) + return self.validateWorkspaces(valNames) + + def validateWorkspaces(self, valNames=None,mismatchName=None): + ''' + Performs a check that two workspaces are equal using the CheckWorkspacesMatch + algorithm. Loads one workspace from a nexus file if appropriate. + Returns true if: the workspaces match + OR the validate method has not been overridden. + Returns false if the workspace do not match. The reason will be in the log. + ''' + if valNames is None: + valNames = self.validate() + + from mantid.simpleapi import SaveNexus, AlgorithmManager + checker = AlgorithmManager.create("CheckWorkspacesMatch") + checker.setLogging(True) + checker.setPropertyValue("Workspace1",valNames[0]) + checker.setPropertyValue("Workspace2",valNames[1]) + checker.setPropertyValue("Tolerance", str(self.tolerance)) + if hasattr(self,'tolerance_is_reller') and self.tolerance_is_reller: + checker.setPropertyValue("ToleranceRelerr", "1") + for d in self.disableChecking: + checker.setPropertyValue("Check"+d,"0") + checker.execute() + if checker.getPropertyValue("Result") != 'Success!': + print self.__class__.__name__ + if mismatchName: + SaveNexus(InputWorkspace=valNames[0],Filename=self.__class__.__name__+mismatchName+'-mismatch.nxs') + else: + SaveNexus(InputWorkspace=valNames[0],Filename=self.__class__.__name__+'-mismatch.nxs') + return False + + return True + + def doValidation(self): + """ + Perform validation. This selects which validation method to use by the result + of validateMethod() and validate(). If validate() is not overridden this will + return True. + """ + # if no validation is specified then it must be ok + validation = self.validate() + if validation is None: + return True + + # if a simple boolean then use this + if type(validation) == bool: + return validation + # or numpy boolean + if type(validation) == numpy.bool_: + return bool(validation) + + # switch based on validation methods + method = self.validateMethod() + if method is None: + return True # don't validate + method = method.lower() + if "validateworkspacetonexus".endswith(method): + return self.validateWorkspaceToNeXus() + elif "validateworkspacetoworkspace".endswith(method): + return self.validateWorkspaceToWorkspace() + elif "validateascii".endswith(method): + return self.validateASCII() + else: + raise RuntimeError("invalid validation method '%s'" % self.validateMethod()) + + def returnValidationCode(self,code): + """ + Calls doValidation() and returns 0 in success and code if failed. This will be + used as return code from the calling python subprocess + """ + if self.doValidation(): + retcode = 0 + else: + retcode = code + if retcode == 0: + self._success = True + else: + self._success = False + # Now the validation is complete we can clear out all the stored data and check memory usage + import mantid.api + mantid.api.FrameworkManager.clear() + # Get the resident memory again and work out how much it's gone up by (in MB) + from mantid.kernel import MemoryStats + memorySwallowed = MemoryStats().residentMem()/1024 - self.memory + # Store the result + self.reportResult('memory footprint increase', memorySwallowed ) + return retcode + + def succeeded(self): + """ + Returns true if the test has been run and it succeeded, false otherwise + """ + if hasattr(self, '_success'): + return self._success + else: + return False + + def cleanup(self): + ''' + This function is called after a test has completed and can be used to + clean up, i.e. remove workspaces etc + ''' + pass + + + def assertDelta(self, value, expected, delta, msg=""): + """ + Check that a value is within +- delta of the expected value + """ + # Build the error message + if msg != "": msg += " " + msg += "Expected %g == %g within +- %g." % (value, expected, delta) + + if (value > expected+delta) or (value < expected-delta): + raise Exception(msg) + + def assertLessThan(self, value, expected, msg=""): + """ + Check that a value is < expected. + """ + # Build the error message + if msg != "": msg += " " + msg += "Expected %g < %g " % (value, expected) + + if (value >= expected): + raise Exception(msg) + + def assertGreaterThan(self, value, expected, msg=""): + """ + Check that a value is > expected. + """ + # Build the error message + if msg != "": msg += " " + msg += "Expected %g > %g " % (value, expected) + + if (value <= expected): + raise Exception(msg) + + +######################################################################### +# A class to store the results of a test +######################################################################### +class TestResult(object): + ''' + Stores the results of each test so that they can be reported later. + ''' + + def __init__(self): + self._results = [] + self.name = '' + self.filename = '' + self.date = '' + self.status = '' + self.time_taken = '' + self.total_time = '' + self.output = '' + self.err = '' + + def addItem(self, item): + ''' + Add an item to the store, this should be a list containing 2 entries: [Name, Value] + ''' + self._results.append(item) + + def resultLogs(self): + ''' + Get the map storing the results + ''' + return self._results + +######################################################################### +# A base class to support report results in an appropriate manner +######################################################################### +class ResultReporter(object): + ''' + A base class for results reporting. In order to get the results in an + appropriate form, subclass this class and implement the dispatchResults + method. + ''' + + def __init__(self): + '''Initialize a class instance, e.g. connect to a database''' + pass + + def dispatchResults(self, result): + raise NotImplementedError('"dispatchResults(self, result)" should be overridden in a derived class') + +######################################################################### +# A class to report results as formatted text output +######################################################################### +class TextResultReporter(ResultReporter): + ''' + Report the results of a test using standard out + ''' + + def dispatchResults(self, result): + ''' + Print the results to standard out + ''' + nstars = 30 + print '*' * nstars + for t in result.resultLogs(): + print '\t' + str(t[0]).ljust(15) + '-> ', str(t[1]) + print '*' * nstars + +######################################################################### +# A class to report results as junit xml +######################################################################### +from xmlreporter import XmlResultReporter + +######################################################################### +# A base class for a TestRunner +######################################################################### +class PythonTestRunner(object): + ''' + A base class to serve as a wrapper to actually run the tests in a specific + environment, i.e. console, gui + ''' + SUCCESS_CODE = 0 + GENERIC_FAIL_CODE = 1 + SEGFAULT_CODE = 139 + VALIDATION_FAIL_CODE = 99 + NOT_A_TEST = 98 + SKIP_TEST = 97 + + def __init__(self, need_escaping = False): + self._mtdpy_header = '' + self._test_dir = '' + # Get the path that this module resides in so that the tests know about it + self._framework_path = THIS_MODULE_DIR + # A string to prefix the code with + self._code_prefix = '' + self._using_escape = need_escaping + + def commandString(self, pycode): + ''' + Return the appropriate command to pass to subprocess.Popen + ''' + raise NotImplementedError('"commandString(self)" should be overridden in a derived class') + + def setMantidDir(self, mtdheader_dir): + # Store the path to mantid module + self._mtdpy_header = os.path.abspath(mtdheader_dir).replace('\\','/') + + def setTestDir(self, test_dir): + self._test_dir = os.path.abspath(test_dir).replace('\\','/') + + def createCodePrefix(self): + if self._using_escape == True: + esc = '\\' + else: + esc = '' + + self._code_prefix = 'import sys, time;' + self._code_prefix += 'sys.path.insert(0, ' + esc + '"' + self._mtdpy_header + esc + '");' + \ + 'sys.path.append(' + esc + '"' + self._framework_path + esc + '");' + \ + 'sys.path.append(' + esc + '"' + self._test_dir + esc + '");' + + def getCodePrefix(self): + ''' + Return a prefix to the code that will be executed + ''' + return self._code_prefix + + def spawnSubProcess(self, cmd): + ''' + Spawn a new process and run the given command within it + ''' + + proc = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, bufsize=-1) + std_out = "" + std_err = "" + for line in proc.stdout: + print line, + std_out += line + proc.wait() + + return proc.returncode, std_out, std_err + + def start(self, pycode): + ''' + Run the given test code in a new subprocess + ''' + raise NotImplementedError('"run(self, pycode)" should be overridden in a derived class') + +######################################################################### +# A runner class to execute the tests on using the command line interface +######################################################################### +class PythonConsoleRunner(PythonTestRunner): + ''' + This class executes tests within a Mantid environment inside a standalone python + interpreter + ''' + + def __init__(self): + PythonTestRunner.__init__(self, True) + + def start(self, pycode): + ''' + Run the code in a new instance of a python interpreter + ''' + return self.spawnSubProcess(sys.executable + ' -c \"' + self.getCodePrefix() + pycode + '\"') + +######################################################################### +# A runner class to execute the tests on using the command line interface +######################################################################### +class MantidPlotTestRunner(PythonTestRunner): + ''' + This class executes tests within the Python scripting environment inside + MantidPlot + ''' + + def __init__(self, mtdplot_dir): + PythonTestRunner.__init__(self) + mtdplot_bin = mtdplot_dir + '/MantidPlot' + if os.name == 'nt': + mtdplot_bin += '.exe' + self._mtdplot_bin = os.path.abspath(mtdplot_bin).replace('\\','/') + + def start(self, pycode): + ''' + Run the code in a new instance of the MantidPlot scripting environment + ''' + # The code needs wrapping in a temporary file so that it can be passed + # to MantidPlot, along with the redirection of the scripting output to + # stdout + # On Windows, just using the file given back by tempfile doesn't work + # as the name is mangled to a short version where all characters after + # a space are replace by ~. So on windows use put the file in the + # current directory + if os.name == 'nt': + loc = '.' + else: + loc = '' + # MG 11/09/2009: I tried the simple tempfile.NamedTemporaryFile() method + # but this didn't work on Windows so I had to be a little long winded + # about it + fd, tmpfilepath = tempfile.mkstemp(suffix = '.py', dir = loc, text=True) + + os.write(fd, 'import sys\nsys.stdout = sys.__stdout__\n' + self.getCodePrefix() + pycode) + retcode, output, err = self.spawnSubProcess('"' +self._mtdplot_bin + '" -xq \'' + tmpfilepath + '\'') + # Remove the temporary file + os.close(fd) + os.remove(tmpfilepath) + return retcode, output, err + +######################################################################### +# A class to tie together a test and its results +######################################################################### +class TestSuite(object): + ''' + Tie together a test and its results. + ''' + def __init__(self, modname, testname, filename = None): + self._modname = modname + self._fullname = modname + # A None testname indicates the source did not load properly + # It has come this far so that it gets reported as a proper failure + # by the framework + if testname is not None: + self._fullname += '.' + testname + + self._result = TestResult() + # Add some results that are not linked to the actually test itself + self._result.name = self._fullname + if filename: + self._result.filename = filename + else: + self._result.filename = self._fullname + self._result.addItem(['test_name', self._fullname]) + sysinfo = platform.uname() + self._result.addItem(['host_name', sysinfo[1]]) + self._result.addItem(['environment', self.envAsString()]) + self._result.status = 'skipped' # the test has been skipped until it has been executed + + name = property(lambda self: self._fullname) + status = property(lambda self: self._result.status) + + def envAsString(self): + if os.name == 'nt': + system = platform.system().lower()[:3] + arch = platform.architecture()[0][:2] + env = system + arch + elif os.name == 'mac': + env = platform.mac_ver()[0] + else: + env = platform.dist()[0] + return env + + def markAsSkipped(self, reason): + self.setOutputMsg(reason) + self._result.status = 'skipped' + + def execute(self, runner): + print time.strftime("%a, %d %b %Y %H:%M:%S", time.localtime()) + ': Executing ' + self._fullname + pycode = 'import ' + self._modname + ';'\ + + 'systest = ' + self._fullname + '();'\ + + 'systest.execute();'\ + + 'retcode = systest.returnValidationCode('+str(PythonTestRunner.VALIDATION_FAIL_CODE)+');'\ + + 'systest.cleanup();'\ + + 'sys.exit(retcode)' + # Start the new process + self._result.date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + self._result.addItem(['test_date',self._result.date]) + retcode, output, err = runner.start(pycode) + + + if retcode == PythonTestRunner.SUCCESS_CODE: + status = 'success' + elif retcode == PythonTestRunner.GENERIC_FAIL_CODE: + # This is most likely an algorithm failure, but it's not certain + status = 'algorithm failure' + elif retcode == PythonTestRunner.VALIDATION_FAIL_CODE: + status = 'failed validation' + elif retcode == PythonTestRunner.SEGFAULT_CODE: + status = 'crashed' + elif retcode == PythonTestRunner.SKIP_TEST: + status = 'skipped' + elif retcode < 0: + status = 'hung' + else: + status = 'unknown' + + # Check return code and add result + self._result.status = status + self._result.addItem(['status', status]) + # Dump std out so we know what happened + print output + self._result.output = output + all_lines = output.split('\n') + # Find the test results + for line in all_lines: + entries = line.split(MantidStressTest.DELIMITER) + if len(entries) == 3 and entries[0] == MantidStressTest.PREFIX: + self._result.addItem([entries[1], entries[2]]) + + def setOutputMsg(self, msg=None): + if msg is not None: + self._result.output = msg + + def reportResults(self, reporters): + for r in reporters: + r.dispatchResults(self._result) + +######################################################################### +# The main API class +######################################################################### +class TestManager(object): + '''A manager class that is responsible for overseeing the testing process. + This is the main interaction point for the framework. + ''' + + def __init__(self, test_loc, runner = PythonConsoleRunner(), output = [TextResultReporter()], + testsInclude=None, testsExclude=None): + '''Initialize a class instance''' + + # Check whether the MANTIDPATH variable is set + mtdheader_dir = os.getenv("MANTIDPATH") + if mtdheader_dir is None: + raise RuntimeError('MANTIDPATH variable not be found. Please ensure Mantid is installed correctly.') + + # Runners and reporters + self._runner = runner + self._reporters = output + + # Init mantid + sys.path.append(os.path.abspath(mtdheader_dir).replace('\\','/')) + runner.setMantidDir(mtdheader_dir) + + # If given option is a directory + if os.path.isdir(test_loc) == True: + test_dir = os.path.abspath(test_loc).replace('\\','/') + sys.path.append(test_dir) + runner.setTestDir(test_dir) + self._tests = self.loadTestsFromDir(test_dir) + else: + if os.path.exists(test_loc) == False: + print 'Cannot find file ' + test_loc + '.py. Please check the path.' + exit(2) + test_dir = os.path.abspath(os.path.dirname(test_loc)).replace('\\','/') + sys.path.append(test_dir) + runner.setTestDir(test_dir) + self._tests = self.loadTestsFromModule(os.path.basename(test_loc)) + + if len(self._tests) == 0: + print 'No tests defined in ' + test_dir + '. Please ensure all test classes sub class stresstesting.MantidStressTest.' + exit(2) + + self._passedTests = 0 + self._skippedTests = 0 + self._failedTests = 0 + self._lastTestRun = 0 + + self._testsInclude = testsInclude + self._testsExclude = testsExclude + + # Create a prefix to use when executing the code + runner.createCodePrefix() + + totalTests = property(lambda self: len(self._tests)) + skippedTests = property(lambda self: (self.totalTests - self._passedTests - self._failedTests)) + passedTests = property(lambda self: self._passedTests) + failedTests = property(lambda self: self._failedTests) + + def __shouldTest(self, suite): + if self._testsInclude is not None: + if not self._testsInclude in suite.name: + suite.markAsSkipped("NotIncludedTest") + return False + if self._testsExclude is not None: + if self._testsExclude in suite.name: + suite.markAsSkipped("ExcludedTest") + return False + return True + + def executeTests(self): + # Get the defined tests + for suite in self._tests: + if self.__shouldTest(suite): + suite.execute(self._runner) + if suite.status == "success": + self._passedTests += 1 + elif suite.status == "skipped": + self._skippedTests += 1 + else: + self._failedTests += 1 + suite.reportResults(self._reporters) + self._lastTestRun += 1 + + def markSkipped(self, reason=None): + for suite in self._tests[self._lastTestRun:]: + suite.setOutputMsg(reason) + suite.reportResults(self._reporters) # just let people know you were skipped + + def loadTestsFromDir(self, test_dir): + ''' Load all of the tests defined in the given directory''' + entries = os.listdir(test_dir) + tests = [] + regex = re.compile('^.*\.py$', re.IGNORECASE) + for file in entries: + if regex.match(file) != None: + tests.extend(self.loadTestsFromModule(os.path.join(test_dir,file))) + return tests + + def loadTestsFromModule(self, filename): + ''' + Load test classes from the given module object which has been + imported with the __import__ statement + ''' + modname = os.path.basename(filename) + modname = modname.split('.py')[0] + path = os.path.dirname(filename) + pyfile = open(filename, 'r') + tests = [] + try: + mod = imp.load_module(modname, pyfile, filename, ("","",imp.PY_SOURCE)) + mod_attrs = dir(mod) + for key in mod_attrs: + value = getattr(mod, key) + if key is "MantidStressTest" or not inspect.isclass(value): + continue + if self.isValidTestClass(value): + test_name = key + tests.append(TestSuite(modname, test_name, filename)) + except Exception: + # Error loading the source, add fake unnamed test so that an error + # will get generated when the tests are run and it will be counted properly + tests.append(TestSuite(modname, None, filename)) + finally: + pyfile.close() + return tests + + def isValidTestClass(self, class_obj): + """Returns true if the test is a valid test class. It is valid + if: the class subclassses MantidStressTest and has no abstract methods + """ + if not issubclass(class_obj, MantidStressTest): + return False + # Check if the get_reference_file is abstract or not + if hasattr(class_obj, "__abstractmethods__"): + if len(class_obj.__abstractmethods__) == 0: + return True + else: + return False + else: + return True + +######################################################################### +# Class to handle the environment +######################################################################### +class MantidFrameworkConfig: + + def __init__(self, mantidDir=None, sourceDir=None, + data_dirs="", save_dir = "", + loglevel='information', archivesearch=False): + # force the environment variable + if mantidDir is not None: + if os.path.isfile(mantidDir): + mantidDir = os.path.split(mantidDir)[0] + os.environ['MANTIDPATH'] = mantidDir + + # add it to the python path + directory = os.getenv("MANTIDPATH") + if directory is None: + raise RuntimeError("MANTIDPATH not found.") + else: + sys.path.append(directory) + if not os.path.isdir(os.path.join(directory, "mantid")): + raise RuntimeError("Did not find mantid package in %s" % directory) + + self.__sourceDir = self.__locateSourceDir(sourceDir) + + # add location of stress tests + self.__testDir = self.__locateTestsDir() + + # add location of the analysis tests + sys.path.insert(0,self.__locateTestsDir()) + + # setup the rest of the magic directories + self.__saveDir = save_dir + if not os.path.exists(save_dir): + print "Making directory %s to save results" % save_dir + os.mkdir(save_dir) + + else: + if not os.path.isdir(save_dir): + raise RuntimeError("%s is not a directory" % save_dir) + + # assume a string is already semicolon-seaprated + if type(data_dirs) == str: + self.__dataDirs = data_dirs + self.__dataDirs += ";%s" % self.__saveDir + else: + data_path = "" + data_dirs.append(self.__saveDir) + for direc in data_dirs: + if not os.path.exists(direc): + raise RuntimeError('Directory ' + direc + ' was not found.') + search_dir = direc.replace('\\','/') + if not search_dir.endswith('/'): + search_dir += '/' + data_path += search_dir + ';' + #endfor + self.__dataDirs = data_path + + # set the log level + self.__loglevel = loglevel + self.__datasearch = archivesearch + + def __locateSourceDir(self, suggestion): + if suggestion is None: + loc = os.path.abspath(__file__) + suggestion = os.path.split(loc)[0] # get the directory + loc = os.path.abspath(suggestion) + loc = os.path.normpath(loc) + + if os.path.isdir(loc): + return loc + else: + raise RuntimeError("Failed to find source directory") + + def __locateTestsDir(self): + loc = os.path.join(self.__sourceDir, "..", "..", "tests", "analysis") + loc = os.path.abspath(loc) + if os.path.isdir(loc): + return loc + else: + raise RuntimeError("Expected the analysis tests directory at '%s' but it is not a directory " % loc) + + def __getDataDirsAsString(self): + return self._dataDirs + + def __moveFile(self, src, dst): + if os.path.exists(src): + import shutil + shutil.move(src, dst) + + def __copyFile(self, src, dst): + if os.path.exists(src): + import shutil + shutil.copyfile(src, dst) + + saveDir = property(lambda self: self.__saveDir) + testDir = property(lambda self: self.__testDir) + + def config(self): + + # Start mantid + import mantid + from mantid.kernel import config + + # backup the existing user properties so we can step all over it + self.__userPropsFile = config.getUserFilename() + self.__userPropsFileBackup = self.__userPropsFile + ".bak" + self.__userPropsFileSystest = self.__userPropsFile + ".systest" + self.__moveFile(self.__userPropsFile, self.__userPropsFileBackup) + + # Make sure we only save these keys here + config.reset() + + # Up the log level so that failures can give useful information + config['logging.loggers.root.level'] = self.__loglevel + # Set the correct search path + config['datasearch.directories'] = self.__dataDirs + + # Save path + config['defaultsave.directory'] = self.__saveDir + + # Do not show paraview dialog + config['paraview.ignore'] = "1" + + # Do not update instrument definitions + config['UpdateInstrumentDefinitions.OnStartup'] = "0" + + # Disable usage reports + config['usagereports.enabled'] = "0" + + # Case insensitive + config['filefinder.casesensitive'] = 'Off' + + # datasearch + if self.__datasearch: + config["datasearch.searcharchive"] = 'On' + + # Save this configuration + config.saveConfig(self.__userPropsFile) + + def restoreconfig(self): + self.__moveFile(self.__userPropsFile, self.__userPropsFileSystest) + self.__moveFile(self.__userPropsFileBackup, self.__userPropsFile) + + +#============================================================================== +def envAsString(): + """Returns a string describing the environment + (platform) of this test.""" + if os.name == 'nt': + system = platform.system().lower()[:3] + arch = platform.architecture()[0][:2] + env = system + arch + elif os.name == 'mac': + env = platform.mac_ver()[0] + else: + env = platform.dist()[0] + "-" + platform.dist()[1] + return env diff --git a/Code/Mantid/Testing/SystemTests/lib/systemtests/xmlreporter.py b/Code/Mantid/Testing/SystemTests/lib/systemtests/xmlreporter.py new file mode 100644 index 000000000000..a991fe30f7df --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/lib/systemtests/xmlreporter.py @@ -0,0 +1,86 @@ +import os +import sys +from xml.dom.minidom import getDOMImplementation +import stresstesting + +class XmlResultReporter(stresstesting.ResultReporter): + + _time_taken = 0.0 + _failures = [] + _skipped = [] + + def __init__(self, showSkipped=True): + self._doc = getDOMImplementation().createDocument(None,'testsuite',None) + self._show_skipped = showSkipped + + def reportStatus(self): + return len(self._failures) == 0 + + def getResults(self): + # print the command line summary version of the results + self._failures.sort() + self._skipped.sort() + print + if self._show_skipped and len(self._skipped) > 0: + print "SKIPPED:" + for test in self._skipped: + print test.name + if len(self._failures) > 0: + print "FAILED:" + for test in self._failures: + print test.name + + # return the xml document version + docEl = self._doc.documentElement + docEl.setAttribute('name','SystemTests') + docEl.setAttribute('tests',str(len(docEl.childNodes))) + docEl.setAttribute('failures',str(len(self._failures))) + docEl.setAttribute('skipped', str(len(self._skipped))) + docEl.setAttribute('time',str(self._time_taken)) + return self._doc.toxml() + + def dispatchResults(self, result): + ''' This relies on the order and names of the items to give the correct output ''' + test_name = result.name.split('.') + if len(test_name) > 1: + class_name = '.'.join(test_name[:-1]) + name = test_name[-1] + else: + class_name = result.name + name = result.name + elem = self._doc.createElement('testcase') + elem.setAttribute('classname',"SystemTests." + class_name) + elem.setAttribute('name',name) + if result.status == 'skipped': + self._skipped.append(result) + skipEl = self._doc.createElement('skipped') + if len(result.output) > 0: + if "Missing required file" in result.output: + skipEl.setAttribute('message', "MissingRequiredFile") + else: + skipEl.setAttribute('message', result.output) + skipEl.appendChild(self._doc.createTextNode(result.output)) + elem.appendChild(skipEl) + elif result.status != 'success': + self._failures.append(result) + failEl = self._doc.createElement('failure') + failEl.setAttribute('file',result.filename) + output = '' + if len(result.output) > 0: + output += result.output + if len(output) > 0: + failEl.appendChild(self._doc.createTextNode(output)) + elem.appendChild(failEl) + else: + time_taken = 0.0 + for t in result.resultLogs(): + if t[0] == 'iteration time_taken': + time_taken = float(t[1].split(' ')[1]) + self._time_taken += time_taken + if t[0] == 'memory footprint increase': + memEl = self._doc.createElement('memory') + memEl.appendChild(self._doc.createTextNode(t[1])) + elem.appendChild(memEl) + elem.setAttribute('time',str(time_taken)) + elem.setAttribute('totalTime',str(time_taken)) + self._doc.documentElement.appendChild(elem) diff --git a/Code/Mantid/Testing/SystemTests/scripts/.gitignore b/Code/Mantid/Testing/SystemTests/scripts/.gitignore new file mode 100644 index 000000000000..a2eca9a1a72a --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/.gitignore @@ -0,0 +1,2 @@ +datasearch-directories.txt +defaultsave-directory.txt diff --git a/Code/Mantid/Testing/SystemTests/scripts/CMakeLists.txt b/Code/Mantid/Testing/SystemTests/scripts/CMakeLists.txt new file mode 100644 index 000000000000..ba4866680fca --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/CMakeLists.txt @@ -0,0 +1,28 @@ +###################################################################### +# Write out a files containing +# - the data search directories +# - the default save directory +# These will be read by the MantidConfig class to configure the +# properties file +###################################################################### +# Data search directories +set(DATA_DIRS "") +# Input data +set(SYSTEM_TEST_DATA_DIR ${ExternalData_BINARY_ROOT}/Testing/Data/SystemTest) +list(APPEND DATA_DIRS ${SYSTEM_TEST_DATA_DIR}) +list(APPEND DATA_DIRS ${SYSTEM_TEST_DATA_DIR}/LOQ) +list(APPEND DATA_DIRS ${SYSTEM_TEST_DATA_DIR}/SANS2D) +list(APPEND DATA_DIRS ${SYSTEM_TEST_DATA_DIR}/PEARL) +# Reference results +list(APPEND DATA_DIRS ${ExternalData_BINARY_ROOT}/Testing/SystemTests/tests/analysis/reference) + +# Output to file +# If this is changed, make sure to update the .gitignore in this directory +set(DATA_DIRS_FILE ${CMAKE_CURRENT_LIST_DIR}/datasearch-directories.txt) +# The quotes are important as CMake translates the list to a semicolon-separated string +file(WRITE ${DATA_DIRS_FILE} "${DATA_DIRS}") + +# Default save directory +set(SAVE_DIR ${CMAKE_CURRENT_BINARY_DIR} ) +set(SAVE_DIR_FILE ${CMAKE_CURRENT_LIST_DIR}/defaultsave-directory.txt) +file(WRITE ${SAVE_DIR_FILE} "${SAVE_DIR}") diff --git a/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py b/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py new file mode 100644 index 000000000000..620d4e5e7563 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/InstallerTests.py @@ -0,0 +1,130 @@ +"""Finds a package, installs it and runs the tests against it. +""" +import os +import sys +import platform +import shutil +import subprocess +from getopt import getopt + +from mantidinstaller import (createScriptLog, log, stop, failure, scriptfailure, + get_installer, run) + +THIS_MODULE_DIR = os.path.dirname(os.path.realpath(__file__)) +SAVE_DIR_LIST_PATH = os.path.join(THIS_MODULE_DIR, "defaultsave-directory.txt") + +try: + opt, argv = getopt(sys.argv[1:],'d:nohvR:l:') +except: + opt = [('-h','')] + +if ('-h','') in opt: + print "Usage: %s [OPTIONS]" % os.path.basename(sys.argv[0]) + print + print "Valid options are:" + print " -d Directory to look for packages. Defaults to current working directory" + print " -n Run tests without installing Mantid (it must be already installed)" + print " -o Output to the screen instead of log files" + print " -h Display the usage" + print " -R Optionally only run the test matched by the regex" + print " -l Log level" + sys.exit(0) + +doInstall = True +test_regex = None +out2stdout = False +log_level = 'notice' +package_dir = os.getcwd() +for option, arg in opt: + if option == '-n': + doInstall = False + if option == '-o': + out2stdout = True + if option == '-R' and arg != "": + test_regex = arg + if option == '-l' and arg != "": + log_level = arg + if option == '-d' and arg != "": + package_dir = arg + +# Log to the configured default save directory +with open(SAVE_DIR_LIST_PATH, 'r') as f_handle: + output_dir = f_handle.read().strip() + +createScriptLog(os.path.join(output_dir, "TestScript.log")) +testRunLogPath = os.path.join(output_dir, "test_output.log") +testRunErrPath = os.path.join(output_dir, "test_errors.log") + +log('Starting system tests') +log('Searching for packages in ' + package_dir) +installer = get_installer(package_dir, doInstall) + +# Install the found package +if doInstall: + log("Installing package '%s'" % installer.mantidInstaller) + try: + installer.install() + log("Application path " + installer.mantidPlotPath) + installer.no_uninstall = False + except Exception,err: + scriptfailure("Installing failed. "+str(err)) +else: + installer.no_uninstall = True + +# Ensure MANTIDPATH points at this directory so that +# the correct properties file is loaded +mantidPlotDir = os.path.dirname(installer.mantidPlotPath) +log('MantidPlot directory %s' % mantidPlotDir) +log('Pointing MANTIDPATH at MantidPlot directory %s' % mantidPlotDir) +os.environ["MANTIDPATH"] = mantidPlotDir + +try: + # Keep hold of the version that was run + version = run(installer.mantidPlotPath + ' -v') + version_tested = open(os.path.join(output_dir,'version_tested.log'),'w') + if version and len(version) > 0: + version_tested.write(version) + version_tested.close() +except Exception, err: + scriptfailure('Version test failed: '+str(err), installer) + +try: + # Now get the revision number/git commit ID (remove the leading 'g' that isn't part of it) + revision = run(installer.mantidPlotPath + ' -r').lstrip('g') + revision_tested = open(os.path.join(output_dir, 'revision_tested.log'), 'w') + if revision and len(version) > 0: + revision_tested.write(revision) + revision_tested.close() +except Exception, err: + scriptfailure('Revision test failed: '+str(err), installer) + +log("Running system tests. Log files are: '%s' and '%s'" % (testRunLogPath,testRunErrPath)) +try: + # Pick the correct Mantid along with the bundled python on windows + run_test_cmd = "%s %s/runSystemTests.py --loglevel=%s --mantidpath=%s" % \ + (installer.python_cmd, THIS_MODULE_DIR, log_level, mantidPlotDir) + if test_regex is not None: + run_test_cmd += " -R " + test_regex + if out2stdout: + p = subprocess.Popen(run_test_cmd, shell=True) # no PIPE: print on screen for debugging + p.wait() + else: + p = subprocess.Popen(run_test_cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True) + out,err = p.communicate() # waits for p to finish + testsRunLog = open(testRunLogPath,'w') + if out: + testsRunLog.write(out) + testsRunLog.close() + testsRunErr = open(testRunErrPath,'w') + if err: + testsRunErr.write(err) + testsRunErr.close() + if p.returncode != 0: + failure(installer) +except Exception, exc: + scriptfailure(str(exc),installer) +except: + failure(installer) + +# Test run completed successfully +stop(installer) diff --git a/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py new file mode 100644 index 000000000000..88a6aeb13457 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/mantidinstaller.py @@ -0,0 +1,277 @@ +"""Defines classes for handling installation +""" +import platform +import os +import glob +import sys +import subprocess + +scriptLog = None + +def createScriptLog(path): + global scriptLog + scriptLog = open(path,'w') + +def stop(installer): + ''' Save the log, uninstall the package and exit with error code 0 ''' + try: + installer.uninstall() + except Exception, exc: + log("Could not uninstall package %s: %s" % (installer.mantidInstaller, str(exc))) + scriptLog.close() + sys.exit(0) + +def log(txt): + ''' Write text to the script log file ''' + if scriptLog is None: + return + if txt and len(txt) > 0: + scriptLog.write(txt) + if not txt.endswith('\n'): + scriptLog.write('\n') + print txt + +def failure(installer): + ''' Report failure of test(s), try to uninstall package and exit with code 1 ''' + try: + installer.uninstall() + except Exception, exc: + log("Could not uninstall package %s: %s" % (installer.mantidInstaller, str(exc))) + pass + + log('Tests failed') + print 'Tests failed' + sys.exit(1) + +def scriptfailure(txt, installer=None): + '''Report failure of this script, try to uninstall package and exit with code 1 ''' + if txt: + log(txt) + if installer is not None: + try: + installer.uninstall() + except Exception: + log("Could not uninstall package %s " % self.mantidInstaller) + scriptLog.close() + sys.exit(1) + + +def get_installer(package_dir, do_install=True): + """ + Creates the correct class for the current platform + @param package_dir :: The directory to search for packages + @param do_install :: True if installation is to be performed + """ + system = platform.system() + if system == 'Windows': + return NSISInstaller(package_dir, do_install) + elif system == 'Linux': + dist = platform.dist() + if dist[0] == 'Ubuntu': + return DebInstaller(package_dir, do_install) + elif dist[0] == 'redhat': + return RPMInstaller(package_dir, do_install) + else: + scriptfailure('Unknown Linux flavour: %s' % str(dist)) + elif system == 'Darwin': + return DMGInstaller(package_dir, do_install) + else: + raise scriptfailure("Unsupported platform") + +def run(cmd): + """Run a command in a subprocess""" + try: + p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) + out = p.communicate()[0] + if p.returncode != 0: + raise Exception('Returned with code '+str(p.returncode)+'\n'+out) + except Exception,err: + log('Error in subprocess %s:\n' % str(err)) + raise + log(out) + return out + + +class MantidInstaller(object): + """ + Base-class for installer objects + """ + mantidInstaller = None + mantidPlotPath = None + no_uninstall = False + python_cmd = "python" + + def __init__(self, package_dir, filepattern, + do_install): + """Initialized with a pattern to + find a path to an installer + """ + if not do_install: + return + # Glob for packages + matches = glob.glob(os.path.join(package_dir, filepattern)) + if len(matches) > 0: + # This will put the release mantid packages at the start and the nightly ones at the end + # with increasing version numbers + matches.sort() + # Make sure we don't get Vates + for match in matches: + if 'vates'in match: + matches.remove(match) + # Take the last one as it will have the highest version number + if len(matches) > 0: + self.mantidInstaller = os.path.join(os.getcwd(), matches[-1]) + log("Using installer " + self.mantidInstaller) + else: + raise RuntimeError('Unable to find installer package in "%s"' % os.getcwd()) + + def install(self): + self.do_install() + + def do_install(self): + raise NotImplementedError("Override the do_install method") + + def uninstall(self): + if not self.no_uninstall: + self.do_uninstall() + + def do_uninstall(self): + raise NotImplementedError("Override the do_uninstall method") + +class NSISInstaller(MantidInstaller): + """Uses an NSIS installer + to install Mantid + """ + + def __init__(self, package_dir, do_install): + MantidInstaller.__init__(self, package_dir, 'Mantid-*-win*.exe', do_install) + self.mantidPlotPath = 'C:/MantidInstall/bin/MantidPlot.exe' + self.python_cmd = "C:/MantidInstall/bin/python.exe" + + def do_install(self): + """ + The NSIS installer spawns a new process and returns immediately. + We use the start command with the /WAIT option to make it stay around + until completion. + The chained "&& exit 1" ensures that if the return code of the + installer > 0 then the resulting start process exits with a return code + of 1 so we can pick this up as a failure + """ + run('start "Installer" /wait ' + self.mantidInstaller + ' /S') + + def do_uninstall(self): + "Runs the uninstall exe" + uninstall_path = 'C:/MantidInstall/Uninstall.exe' + run('start "Uninstaller" /wait ' + uninstall_path + ' /S') + +class DebInstaller(MantidInstaller): + """Uses a deb package to install mantid + """ + + def __init__(self, package_dir, do_install): + MantidInstaller.__init__(self, package_dir, 'mantid*.deb', do_install) + package = os.path.basename(self.mantidInstaller) + if 'mantidnightly' in package: + self.mantidPlotPath = '/opt/mantidnightly/bin/MantidPlot' + elif 'mantidunstable' in package: + self.mantidPlotPath = '/opt/mantidunstable/bin/MantidPlot' + else: + self.mantidPlotPath = '/opt/Mantid/bin/MantidPlot' + + def do_install(self): + """Uses gdebi to run the install + """ + run('sudo gdebi -n ' + self.mantidInstaller) + + def do_uninstall(self): + """Removes the debian package + """ + package_name = os.path.basename(self.mantidInstaller).split("_")[0] + run('sudo dpkg --purge %s' % package_name) + +class RPMInstaller(MantidInstaller): + """Uses a rpm package to install mantid + """ + + def __init__(self, package_dir, do_install): + MantidInstaller.__init__(self, package_dir, 'mantid*.rpm', do_install) + package = os.path.basename(self.mantidInstaller) + if 'mantidnightly' in package: + self.mantidPlotPath = '/opt/mantidnightly/bin/MantidPlot' + elif 'mantidunstable' in package: + self.mantidPlotPath = '/opt/mantidunstable/bin/MantidPlot' + else: + self.mantidPlotPath = '/opt/Mantid/bin/MantidPlot' + + def do_install(self): + """Uses yum to run the install. Current user must be in sudoers + """ + try: + run('sudo yum -y install ' + self.mantidInstaller) + except Exception, exc: + # This reports an error if the same package is already installed + if 'is already installed' in str(exc): + log("Current version is up-to-date, continuing.\n") + pass + else: + raise + + def do_uninstall(self): + """Removes the rpm package + """ + package_name = os.path.basename(self.mantidInstaller).split("-")[0] + run('sudo yum -y erase %s' % package_name) + + +class DMGInstaller(MantidInstaller): + """Uses an OS X dmg file to install mantid + """ + def __init__(self, package_dir, do_install): + MantidInstaller.__init__(self, package_dir, 'mantid-*.dmg', do_install) + self.mantidPlotPath = '/Applications/MantidPlot.app/Contents/MacOS/MantidPlot' + # only necessary on 10.8 build + if int(platform.release().split('.')[0]) < 13: + os.environ['DYLD_LIBRARY_PATH'] = '/Applications/MantidPlot.app/Contents/MacOS' + + def do_install(self): + """Mounts the dmg and copies the application into the right place. + """ + p = subprocess.Popen(['hdiutil','attach',self.mantidInstaller],stdin=subprocess.PIPE,stdout=subprocess.PIPE) + p.stdin.write('yes') # This accepts the GPL + p.communicate()[0] # This captures (and discards) the GPL text + mantidInstallerName = os.path.basename(self.mantidInstaller) + mantidInstallerName = mantidInstallerName.replace('.dmg','') + run('sudo cp -r /Volumes/'+ mantidInstallerName+'/MantidPlot.app /Applications/' ) + run('hdiutil detach /Volumes/'+ mantidInstallerName+'/') + + def do_uninstall(self): + run('sudo rm -fr /Applications/MantidPlot.app/') + +#------------------------------------------------------------------------------- +# Main +#------------------------------------------------------------------------------- +# If called as a standalone script then this can be used to install/uninstall +# Mantid +if __name__ == "__main__": + import optparse + parser = optparse.OptionParser("Usage: %prog ", + description="Commands available: install, uninstall") + (options, args) = parser.parse_args() + # All arguments are required + if len(args) != 2: + parser.print_help() + sys.exit(1) + + command, package_dir = args[0], args[1] + package_dir = os.path.abspath(package_dir) + print package_dir + installer = get_installer(package_dir) + if command.lower() == "install": + print "Installing package '%s'" % installer.mantidInstaller + installer.install() + elif command.lower() == "uninstall": + print "Removing package '%s'" % installer.mantidInstaller + installer.uninstall() + else: + raise RuntimeError("Invalid command '%s'. Options are: install, uninstall" % command) + diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/README.txt b/Code/Mantid/Testing/SystemTests/scripts/performance/README.txt new file mode 100644 index 000000000000..717d3e96cfe6 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/README.txt @@ -0,0 +1 @@ +This is basically a fork of the performance test support code in the main Mantid repository (https://github.com/mantidproject/mantid/tree/master/Test/PerformanceTests) to enable performance monitoring of the system tests in a similar fashion. diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/analysis.py b/Code/Mantid/Testing/SystemTests/scripts/performance/analysis.py new file mode 100644 index 000000000000..c6d3429fae11 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/analysis.py @@ -0,0 +1,699 @@ +""" Module containing functions for test +performance analyis, plotting, and saving +to other formats (CSV, PDF) """ + +import testresult +import os +import sys +import sqlresults +from sqlresults import get_results +import matplotlib +from pylab import * +import numpy as np +import datetime +import random + +# This is the date string format as returned by the database +DATE_STR_FORMAT = "%Y-%m-%d %H:%M:%S.%f" + +#============================================================================================ +def get_orderby_clause(last_num): + """Returns a order by clause that limits to the last # revisions """ + if last_num > 0: + return " ORDER BY revision DESC limit %d" % last_num + else: + return '' + + +#============================================================================================ +def get_data(name='', type='', x_field='revision', y_field='runtime', last_num=-1): + """Get the test runtime/iteration as a function of an X variable. + + Parameters + ---------- + name :: full name of the test + type :: type of test to filter by + x_field :: name of the field for the X axis. + e.g. 'revision' (default) + or 'date' : exact date/time of launch + or 'index' : using the date, but returning an index of build # + instead of the date (better scaling) + last_num :: only get the last this-many entries from the table, sorted by revision. + if < 0, then get everything + + Returns + ------- + x :: list of X values, sorted increasing + y :: list of runtime/iteration for each x + """ + + results = get_results(name, type, where_clause='', orderby_clause=get_orderby_clause(last_num)) + + # Data dict. Key = X variable; Value = (iterations total, runtime total) + data = {} + for res in results: + # Get the x field value + if x_field == 'index': + x = res['date'] + else: + x = res[x_field] + + if data.has_key(x): + old = data[x] + iters = old[0] + 1 # Iterations + runtime = old[1] + res[y_field] + else: + iters = 1 + runtime = res[y_field] + # Save the # of iterations and runtime + data[x] = (iters, runtime) + + # Now make a sorted list of (x, runtime/iteration) + sorted = [(x, y[1]/y[0]) for (x,y) in data.items()] + sorted.sort() + + x = [a for (a,b) in sorted] + # For index, convert into an integer index + if x_field == 'index': + x = range( len(x) ) + y = [b for (a,b) in sorted] + + return (x,y) + + +#============================================================================================ +def get_unique_fields(results, field): + """Given a list of TestResult, return a + list of all unique values of 'field'""" + out = set() + for res in results: + out.add( res[field] ) + return list(out) + +#============================================================================================ +def get_results_matching(results, field, value): + """Given a list of TestResult, + return a list of TestResult's where 'field' matches 'value'.""" + out = [] + for res in results: + if res[field] == value: + out.append(res) + return out + + +#============================================================================================ +def smart_ticks(index, values): + """On the current figure, set the ticks at X positions + given by index, with value given by values (ints). + But it tries to space them out in a reasonable way. + """ + if type(values[0]).__name__ == "unicode": + # Make the array of dates + dates = [] + for val in values: + try: + datetime.datetime.strptime(val, DATE_STR_FORMAT) + dates.append(val) + except: + pass + if len(dates) == 0: return + td = dates[-1] - dates[0] + if (td < datetime.timedelta(hours=1)): + values_str = [d.strftime("%M:%S") for d in dates] + elif (td < datetime.timedelta(days=1)): + values_str = [d.strftime("%H:%M") for d in dates] + else: + values_str = [d.strftime("%m-%d, %H:%M") for d in dates] + else: + # convert to list of strings + values_str = [str(val) for val in values] + + if len(values_str) == 0: return + + w = gcf().get_figwidth()*gcf().get_dpi() + spacing = w/len(index) + + tick_index = [] + tick_strings = [] + + space_available = 0 + for i in xrange(len(index)): + s = str(values_str[i]); + s_width = (len(s)+1) * 12.0 # About 12 pixels per letter? And add a space + space_available +=spacing + if space_available >= s_width: + space_available = 0 + tick_index.append(i) + tick_strings.append(s) + + xticks( tick_index, tick_strings ) + + + +#============================================================================================ +def plot_success_count(type='system', last_num=-1, x_field='revision'): + """ Plot the count of successful/failed tests vs revision number + + Parameters + ---------- + type :: 'system', or 'performance' + """ + results = get_results('', type, where_clause='', orderby_clause=get_orderby_clause(last_num)) + revisions = get_unique_fields(results, x_field) + + # Go through each revision + success = [] + fail = [] + for revision in revisions: + these = get_results_matching(results, x_field, revision) + succeeded = 0 + failed = 0 + for res in these: + if res["success"]: + succeeded += 1 + else: + failed += 1 + # Keep the list of them + success.append(succeeded) + fail.append(failed) + + figure() + revisions = np.array(revisions) + fail = np.array(fail) + success = np.array(success) + + index = np.arange(len(revisions)) +# p1 = bar(index, fail, color='r') +# p2 = bar(index, success, color='g', bottom=fail) +# legend( (p1[0], p2[0]), ('Failure', 'Success') ) + + p1 = fill_between(index, fail, 0, color='r') + p2 = fill_between(index, success+fail, fail, color='g') + #legend( (p1, p2), ('Failure', 'Success') ) + + smart_ticks( index, revisions) + + + ylabel('Success/Fail') + xlabel(x_field) + revsare = "all revs" + if last_num > 0: revsare = "last %d revs" % last_num + title("Success/Fail History of %s tests (%s)" % (type, revsare)) + + +#============================================================================================ +def plot_runtime(*args, **kwargs): + """ Call get_data() + + Parameters + ---------- + - See get_data() for the full list + """ + (x,y) = get_data(*args, **kwargs) + + figure() + index = np.arange(len(x)) + plot(index,y,'-b.') + smart_ticks( index, x) + ylabel('Runtime/iteration (sec)') + xlabel(kwargs['x_field']) + + last_num =kwargs.get('last_num',-1) + if last_num > 0: + title("Runtime History of %s (last %d revs)" % (kwargs['name'], kwargs["last_num"]) ) + else: + title("Runtime History of %s (all revs)" % kwargs['name']) + + + + +#============================================================================================ +def plot_memory(*args, **kwargs): + """ Call get_data() + + Parameters + ---------- + - See get_data() for the full list + """ + (x,y) = get_data(*args, **kwargs) + + figure() + index = np.arange(len(x)) + plot(index,y,'-b.') + smart_ticks( index, x) + ylabel("Memory 'loss' (MB)") + xlabel(kwargs['x_field']) + + last_num =kwargs.get('last_num',-1) + if last_num > 0: + title("Memory History of %s (last %d revs)" % (kwargs['name'], kwargs["last_num"]) ) + else: + title("Memory History of %s (all revs)" % kwargs['name']) + + + + + + + + + + + +# The default HTML header +default_html_header = """ + +""" + +default_html_footer = """""" + +#============================================================================================ +def make_css_file(path): + """ Make a save the report.css file to be used by all html """ + default_css = """ +table +{ +border-collapse:collapse; +background-color:FFAAAA; +} +table, th, td +{ +border: 1px solid black; +padding: 2px 6px; +} +.failedrow, .failedrow TD, .failedrow TH +{ +background-color:#FFAAAA; +color:black; +} +.alternaterow, .alternaterow TD, .alternaterow TH +{ +background-color:#FFFFAA; +color:black; +} +.error +{ +color:red; +font-weight: bold; +} + + """ + f = open(os.path.join(path, "report.css"), 'w') + f.write(default_css) + f.close() + +#============================================================================================ +def make_environment_html(res): + """Return a HTML string with details of test environment, taken from the + 'res' TestResult object""" + html = """ + + + +
Host name: %s
Environment: %s
Type of runner: %s
+ """ % (res['host'], res['environment'], res['runner']) + return html + +#============================================================================================ +def make_detailed_html_file(basedir, name, fig1, fig2, fig3, fig4, last_num): + """ Create a detailed HTML report for the named test """ + html = default_html_header + html += """

Detailed report for %s


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

Test Results

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

Environment

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

%s

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

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

Mantid System Tests Auto-Generated Report

""" + html += """

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

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

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

""" + + html += """

Run Environment

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

Test Subprojects

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

Overall Results Summary

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

Overall Success/Failure

+ # + # + # """ % (fig_path, fig_path2) + + html += default_html_footer + + f = open(os.path.join(basedir, "report.htm"), "w") + html = html.replace("\n", os.linesep) # Fix line endings for windows + f.write(html) + f.close() + + # -------- Overview of plots ------------ + f = open(os.path.join(basedir, "overview_plot.htm"), "w") + overview_html = overview_html.replace("\n", os.linesep) # Fix line endings for windows + f.write(overview_html) + f.close() + + print "Report complete!" + + + + +#============================================================================================ +if __name__ == "__main__": + sqlresults.set_database_filename("MyFakeData.db") + # Make up some test data + if 0: + if os.path.exists("MyFakeData.db"): os.remove("MyFakeData.db") + sqlresults.generate_fake_data(300) + + + generate_html_report("../Report", 50) + +# plot_runtime(name='MyFakeTest', x_field='revision') +# plot_runtime(name='MyFakeTest', x_field='date') +# plot_success_count() +# show() + diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/make_report.py b/Code/Mantid/Testing/SystemTests/scripts/performance/make_report.py new file mode 100755 index 000000000000..1934d84e2a19 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/make_report.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python + +import argparse +import sys +import os +import subprocess +import sqlite3 + +#==================================================================================== +def getSourceDir(): + """Returns the location of the source code.""" + import os + import sys + script = os.path.abspath(sys.argv[0]) + if os.path.islink(script): + script = os.path.realpath(script) + return os.path.dirname(script) + + + +def join_databases(dbfiles): + """Create a single DB joining several ones + Returns: filename created + """ + outfile = os.path.join(os.path.dirname(dbfiles[0]), "JoinedDatabases.db") + all_results = [] + # Get the results of each file + for dbfile in dbfiles: + print "Reading", dbfile + sqlresults.set_database_filename(dbfile) + these_results = sqlresults.get_results("") + all_results += these_results + # Write them into one + sqlresults.set_database_filename(outfile) + sqlresults.setup_database() + reporter = sqlresults.SQLResultReporter() + for res in all_results: + reporter.dispatchResults(res) + # Done! + return outfile + + + +#==================================================================================== +if __name__ == "__main__": + # Parse the command line + parser = argparse.ArgumentParser(description='Generates a HTML report using the Mantid System Tests results database') + + parser.add_argument('--path', dest='path', + default="./Report", + help='Path to the ouput HTML. Default "./Report".' ) + + parser.add_argument('--x_field', dest='x_field', + default="revision", + help="Field to use as the x-axis. Default: 'revision'. Other possibilities: 'date'.") + + parser.add_argument('dbfile', metavar='DBFILE', type=str, nargs='+', + default=["./MantidSystemTests.db"], + help='Required: Path to the SQL database file(s).') + + + args = parser.parse_args() + + # Import the manager definition + import analysis + import sqlresults + + if len(args.dbfile) > 1: + # Several files - join them into one big .db + dbfile = join_databases(args.dbfile) + else: + # Only one file - use it + dbfile = args.dbfile[0] + + + if not os.path.exists(dbfile): + print "Error! Could not find", dbfile + sys.exit(1) + + # This is where we look for the DB file + sqlresults.set_database_filename(dbfile) + + # Make the report + analysis.generate_html_report(args.path, 100, args.x_field) \ No newline at end of file diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/reporters.py b/Code/Mantid/Testing/SystemTests/scripts/performance/reporters.py new file mode 100644 index 000000000000..a2852ec1f4dd --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/reporters.py @@ -0,0 +1,126 @@ +import os +import sys + +######################################################################### +# A base class to support report results in an appropriate manner +######################################################################### +class ResultReporter(object): + ''' + A base class for results reporting. In order to get the results in an + appropriate form, subclass this class and implement the dispatchResults + method. + ''' + + def __init__(self): + '''Initialize a class instance, e.g. connect to a database''' + pass + + def dispatchResults(self, result): + """ + Parameters + result: a TestResult object """ + raise NotImplementedError('"dispatchResults(self, result)" should be overridden in a derived class') + + +######################################################################### +# A class to report results as formatted text output +######################################################################### +class TextResultReporter(ResultReporter): + ''' + Report the results of a test using standard out + ''' + + def dispatchResults(self, result): + ''' + Print the results to standard out + ''' + nstars = 30 + print '*' * nstars + for (name, val) in result.data.items(): + str_val = str(val) + str_val = str_val.replace("\n", " ") + if len(str_val) > 50: + str_val = str_val[:50] + " . . . " + print ' ' + name.ljust(15) + '-> ', str_val + print '*' * nstars + + +######################################################################### +# A class to report results as formatted text output +######################################################################### +class LogArchivingReporter(ResultReporter): + ''' + Report the results of a test using standard out + ''' + def __init__(self, logarchive): + # Path to a log archiving folder + self.logarchive = os.path.abspath(logarchive) + if not os.path.exists(self.logarchive): + os.mkdir(self.logarchive) + + def dispatchResults(self, result): + ''' + Print the results to standard out + ''' + fullpath = os.path.join(self.logarchive, result.get_logarchive_filename()) + f = open(fullpath, "w") + f.write(result["log_contents"]) + f.close() + +######################################################################### +# A class to report results as XML that Hudson can interpret +######################################################################### +class JUnitXMLReporter(ResultReporter): + ''' + Report the results of a test to a JUnit style XML format + that can be read by Hudson/Jenkins + ''' + + def __init__(self, path): + # Path to .xml files + self._path = path + + def dispatchResults(self, result): + ''' + Make a junit .xml file + ''' + fullpath = os.path.join(self._path, "%s.xml" % result["name"]) + f = open(fullpath, 'w') + + names = result["name"].split(".") + suitename = names[0] + testname = ".".join(names[1:]) + + failure = "" + num_failures = 0 + if not result["success"]: + failure = """\n %s + """ % (result["status"], result["log_contents"]) + num_failures = 1 + + f.write(""" + + %s + + +""" % (suitename, num_failures, testname, result["runtime"], suitename, failure) ) + + + +if __name__=="__main__": + import testresult + rep = JUnitXMLReporter(".") + + res = testresult.TestResult() + res["name"] = "MyTestTest.Test" + res["status"] = "success maybe?" + res["success"] = True + res["runtime"] = 1.234 + rep.dispatchResults(res) + + res = testresult.TestResult() + res["name"] = "MyTestTest.OtherTest" + res["status"] = "failure" + res["success"] = False + res["runtime"] = 3.456 + rep.dispatchResults(res) diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/sqlresults.py b/Code/Mantid/Testing/SystemTests/scripts/performance/sqlresults.py new file mode 100644 index 000000000000..b7eb3e4289c4 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/sqlresults.py @@ -0,0 +1,327 @@ +try: + import sqlite3 + has_sql = True +except ImportError: + has_sql = False + print "Error importing sqlite3. SQL will not work" + +import reporters +import datetime +import testresult +import os +import shutil +import math +import random + +#==================================================================================== +def getSourceDir(): + """Returns the location of the source code.""" + import os + import sys + script = os.path.abspath(sys.argv[0]) + if os.path.islink(script): + script = os.path.realpath(script) + return os.path.dirname(script) + + +#===================================================================== +# These are the table fields, in order +TABLE_FIELDS = ['date', 'name', 'type', 'host', 'environment', 'runner', + 'revision', 'commitid', 'runtime', 'cpu_fraction', + 'memory_change', 'success', + 'status', 'logarchive', 'variables'] + +#===================================================================== +# The default path to the database file +database_file = os.path.join(getSourceDir(), "MantidSystemTests.db") + +#===================================================================== +def get_database_filename(): + """Return the path to the database to use """ + return database_file + +#===================================================================== +def set_database_filename(value): + """Override the default database location""" + global database_file + database_file = value + +#===================================================================== +def SQLgetConnection(): + """ Get a connection to the SQL database """ + # These are automatic conversion factors + return sqlite3.connect(get_database_filename()) + + +#===================================================================== +def get_TestResult_from_row(row): + """Return a filled TestResult object from a "row" + obtained by selecting * from the TestRuns table + Returns + ------- + result :: TestResult object, with an extra + .testID member containing the ID into the table (testID field) + """ + res = testresult.TestResult() + res.testID = row[0] + # ------ Get each entry in the table --------- + for i in xrange(len(TABLE_FIELDS)): + res[TABLE_FIELDS[i]] = row[i+1] + + return (res) + + +#===================================================================== +def get_latest_result(name=''): + """Returns a TestResult object corresponding to the + last result in the table + Parameters + ---------- + name :: optional, test name to filter by""" + db = SQLgetConnection() + c = db.cursor() + where = "" + if name != "": where = " WHERE name='%s'" % name + query = """SELECT * FROM TestRuns %s ORDER BY testID DESC LIMIT 1;""" % where + c.execute(query) + # Get all rows - there should be only one + rows = c.fetchall() + c.close() + + if len(rows) > 0: + res = get_TestResult_from_row(rows[0]) + return res + else: + return None + +#===================================================================== +def get_results(name, type="", where_clause='', orderby_clause=''): + """Return a list of testresult.TestResult objects + generated from looking up in the table + Parameters: + name: test name to search for. Empty string = don't limit by name + type: limit by type; default empty string means = don't limit by type. + get_log : set to True to retrieve the log_contents too. + where_clause : an additional SQL "where" clause to further limit the search. + Do not include the WHERE keyword! + e.g "date > 2010 AND environment='mac'". + orderby_clause : a clause to order and/or limit the results. + e.g. "ORDER BY revision DESC limit 100" to get only the latest 100 revisions. + """ + out = [] + + db = SQLgetConnection() + c = db.cursor() + + query = "SELECT * FROM TestRuns " + + # Build up the where clause + where_clauses = [] + if name != "": + where_clauses.append(" name = '%s'" % name) + if (type != ""): + where_clauses.append(" type = '%s'" % type) + if (where_clause != ""): + where_clauses.append(" (" + where_clause + ")") + # Add it to the query + if len(where_clauses) > 0: + query += "WHERE " + " AND ".join(where_clauses) + # Now the ordering clause + query += " " + orderby_clause + + c.execute(query) + + # Get all rows + rows = c.fetchall() + + for row in rows: + # Turn the row into TestResult + res = get_TestResult_from_row(row) + + out.append(res) + c.close() + return out + + +#===================================================================== +def get_all_field_values(field_name, where_clause=""): + """Return a list of every entry of the given + field (e.g. 'name' or 'environment'). + Parameters: + field_name: field/column name to search for. + where_clause : an additional SQL "where" clause to further limit the search. + Do not include the WHERE keyword! + e.g "date > 2010 AND environment='mac'". + + """ + db = SQLgetConnection() + c = db.cursor() + + query = "SELECT (%s) FROM TestRuns " % field_name + if (where_clause != ""): + query += "WHERE " + where_clause + + c.execute(query) + + # Get all rows + rows = c.fetchall() + + out = [x for (x,) in rows] + + return out + +#===================================================================== +def get_latest_revison(): + """ Return the latest revision number """ + # Now get the latest revision + db = SQLgetConnection() + c = db.cursor() + query = "SELECT (revision) FROM Revisions ORDER BY revision DESC LIMIT 1;" + c.execute(query) + rows = c.fetchall() + if (len(rows)>0): + return int(rows[0][0]) + else: + return 0 + +#===================================================================== +def add_revision(): + """ Adds an entry with the current date/time to the table. + Retrieve the index of that entry = the "revision". + Returns the current revision""" + db = SQLgetConnection() + c = db.cursor() + query = "INSERT INTO Revisions VALUES(NULL, '%s');" % str(datetime.datetime.now()) + c.execute(query) + db.commit() + return get_latest_revison() + + +#===================================================================== +def get_all_test_names(where_clause=""): + """Returns a set containing all the UNIQUE test names in the database. + ---- + where_clause: Do not include the WHERE keyword! """ + return set(get_all_field_values('name', where_clause)) + + +#===================================================================== +def setup_database(): + """ Routine to set up the mysql database the first time. + WARNING: THIS DELETES ANY TABLES ALREADY THERE + """ + print "Setting up SQL database at",get_database_filename() + if os.path.exists(get_database_filename()): + print "Creating a backup at", get_database_filename()+".bak" + shutil.copyfile(get_database_filename(), get_database_filename()+".bak") + + db = SQLgetConnection() + + c = db.cursor() + try: + c.execute("DROP TABLE TestRuns;") + c.execute("DROP TABLE Revisions;") + except: + print "Error dropping tables. Perhaps one does not exist (this is normal on first run)." + + c.execute("""CREATE TABLE TestRuns ( + testID INTEGER PRIMARY KEY, + date DATETIME, name VARCHAR(60), type VARCHAR(20), + host VARCHAR(30), environment VARCHAR(50), runner VARCHAR(20), + revision INT, commitid VARCHAR(45), + runtime DOUBLE, cpu_fraction DOUBLE, memory_change INT, + success BOOL, + status VARCHAR(50), logarchive VARCHAR(80), + variables VARCHAR(200) + ); """) + + # Now a table that is just one entry per run (a fake "revision") + + c.execute("""CREATE TABLE Revisions ( + revision INTEGER PRIMARY KEY, + date DATETIME + ); """) + + +########################################################################### +# A class to report the results of stress tests to the Mantid Test database +# (requires sqlite3 module) +########################################################################### +class SQLResultReporter(reporters.ResultReporter): + ''' + Send the test results to the Mantid test results database + ''' + + def __init__(self): + pass + + + def dispatchResults(self, result): + ''' + Construct the SQL commands and send them to the databse + ''' + dbcxn = SQLgetConnection() + cur = dbcxn.cursor() + #last_id = dbcxn.insert_id() + + # Create the field for the log archive name + result["logarchive"] = result.get_logarchive_filename() + + valuessql = "INSERT INTO TestRuns VALUES(NULL, " + + # Insert the test results in the order of the table + for field in TABLE_FIELDS: + val = result[field] + # Make into a string + val_str = str(val) + + # Booleans must be 0 or 1 + if type(val).__name__ == "bool": + val_str = ["0", "1"][val] + + valuessql += "'" + val_str + "'," + + valuessql = valuessql.rstrip(',') + valuessql += ');' + cur.execute(valuessql) + # Save test id for iteration table + test_id = cur.lastrowid + + # Commit and close the connection + dbcxn.commit() + cur.close() + dbcxn.close() + + +#============================================================================================ +def generate_fake_data(num_extra = 0): + """ Make up some data for a database """ + print "Generating fake data..." + setup_database() + rep = SQLResultReporter() + for timer in [9400, 9410,9411, 9412] + range(9420,9440) + [9450, 9466] + range(9450, 9450+num_extra): + rev = add_revision() + for name in ["Project1.MyFakeTest", "Project1.AnotherFakeTest", "Project2.FakeTest", "Project2.OldTest"]: + if (name != "Project2.OldTest"): + result = testresult.TestResult() + result["name"] = name + result["date"] = datetime.datetime.now() + datetime.timedelta(days=timer, minutes=timer) + result["log_contents"] = "Revision %d" % rev + result["runtime"] = timer/10.0 + random.randrange(-2,2) + result["commitid"] = rev #'926bf82e36b4c90c95efc3f1151725696273de5a' + result["success"] = (random.randint(0,10) > 0) + result["status"] = ["failed","success"][result["success"]] + result["revision"] = rev + rep.dispatchResults(result) + print "... Fake data made." + + +#===================================================================== +if __name__ == "__main__": + set_database_filename("SqlResults.test.db") + generate_fake_data() + + res = get_latest_result() + print res + + diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/testresult.py b/Code/Mantid/Testing/SystemTests/scripts/performance/testresult.py new file mode 100644 index 000000000000..fd772de16a3d --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/testresult.py @@ -0,0 +1,120 @@ +''' +Data object for a TestResult + +Copyright © 2009 STFC Rutherford Appleton Laboratories + +This file is part of Mantid. + +Mantid is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 3 of the License, or +(at your option) any later version. + +Mantid is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . + +File change history is stored at: . +''' + +import sys +import os +import reporters +import re +import time +import datetime +import platform +import subprocess +import tempfile +import sqlresults +import numpy as np + + + + +######################################################################### +######################################################################### +def envAsString(): + """ Return the environment as a string """ + if os.name == 'nt': + system = platform.system().lower()[:3] + arch = platform.architecture()[0][:2] + env = system + arch + elif os.name == 'mac': + env = platform.mac_ver()[0] + else: + env = " ".join(platform.dist()) + return env + + +######################################################################### +# A class to store the results of a test +######################################################################### +class TestResult(object): + ''' + Stores the results of each test so that they can be reported later. + ''' + + def __init__(self, + date = datetime.datetime.now(), + name="", + type="system", + host=platform.uname()[1], + environment=envAsString(), + runner="", + commitid='', + revision=0, + runtime=0.0, + speed_up=0.0, + cpu_fraction=0.0, + memory_change=0, + iterations=1, + success=False, + status="", + log_contents="", + variables=""): + """ Fill the TestResult object with the contents """ + self.data = {} + self.data["date"] = date + self.data["name"] = name + self.data["type"] = type + self.data["host"] = host + self.data["environment"] = environment + self.data["runner"] = runner + self.data["revision"] = revision + self.data["commitid"] = commitid + self.data["runtime"] = runtime + self.data["cpu_fraction"] = cpu_fraction + self.data["memory_change"] = memory_change + self.data["success"] = success + self.data["status"] = status + self.data["log_contents"] = log_contents + self.data["variables"] = variables + + + def get_logarchive_filename(self): + "Return a bare filename that will hold the archived log contents" + s = str(self.data["date"]) + s = s.replace(" ", "_") + s = s.replace(":", "-") + return "%s.%s.log" % (s, self.data["name"]) + + def __getitem__(self, key): + return self.data[key] + + def __setitem__(self, key, value): + self.data.__setitem__(key, value) + + def getData(self): + ''' Get the map storing the results ''' + return self.data + + def __str__(self): + return str(self.data) + + + diff --git a/Code/Mantid/Testing/SystemTests/scripts/performance/xunit_to_sql.py b/Code/Mantid/Testing/SystemTests/scripts/performance/xunit_to_sql.py new file mode 100755 index 000000000000..e70c27d91c99 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/performance/xunit_to_sql.py @@ -0,0 +1,137 @@ +#!/usr/bin/env python +""" Module to convert XUnit XML to SQL database of test results of the same type used +by python system tests """ + +import argparse +import sys +import os +import sqlresults +from testresult import TestResult, envAsString +from xml.dom.minidom import parse, parseString +import re +import time +import datetime +import platform +import subprocess +import tempfile +import sqlresults +import numpy as np +import glob + +# Global SQL result reporter +sql_reporter = None +# Variables string for all tests +variables = "" +revision = 0 +commitid = '' + +def handle_testcase(case, suite_name): + """ Handle one test case and save it to DB""" + # Build the full name (Project.Suite.Case) + name = case.getAttribute("classname") + "." + case.getAttribute("name") + try: + time = float(case.getAttribute("time")) + except: + time = 0.0 + try: + total_time = float(case.getAttribute("totalTime")) + except: + total_time = 0.0 + try: + cpu_fraction = float(case.getAttribute("CPUFraction")) + except: + cpu_fraction = 0.0 + try: + memory_change = int(case.getElementsByTagName("memory").item(0).firstChild.nodeValue) + except: + memory_change = 0 + + + tr = TestResult(date = datetime.datetime.now(), + name=name, + type="performance", + host=platform.uname()[1], + environment=envAsString(), + runner="runSystemTests.py", + revision=revision, + commitid=commitid, + runtime=time, + cpu_fraction=cpu_fraction, + memory_change=memory_change, + success=True, + status="", + log_contents="", + variables=variables) + #print tr.data + # Now report it to SQL + sql_reporter.dispatchResults(tr) + +def handle_suite(suite): + """ Handle all the test cases in a suite """ + suite_name = suite.getAttribute("name") + cases = suite.getElementsByTagName("testcase") + for case in cases: + handle_testcase(case, suite_name) + + +def convert_xml(filename): + """Convert a single XML file to SQL db""" + # Parse the xml + print "Reading", filename + doc = parse(filename) + suites = doc.getElementsByTagName("testsuite") + for suite in suites: + handle_suite(suite) + + +#==================================================================================== +if __name__ == "__main__": + # Parse the command line + parser = argparse.ArgumentParser(description='Add the contents of Xunit-style XML test result files to a SQL database.') + + parser.add_argument('--db', dest='db', + default="./MantidPerformanceTests.db", + help='Full path to the SQLite database holding the results (default "./MantidPerformanceTests.db"). The database will be created if it does not exist.') + + parser.add_argument('--variables', dest='variables', + default="", + help='Optional string of comma-separated "VAR1NAME=VALUE,VAR2NAME=VALUE2" giving some parameters used, e.g. while building.') + + parser.add_argument('--commit', dest='commitid', + default="", + help='Commit ID of the current build (a 40-character SHA string).') + + parser.add_argument('xmlpath', metavar='XMLPATH', type=str, nargs='+', + default="", + help='Required: Path to the Xunit XML files.') + + args = parser.parse_args() + + # Setup the SQL database but only if it does not exist + sqlresults.set_database_filename(args.db) + if not os.path.exists(args.db): + sqlresults.setup_database() + # Set up the reporter + sql_reporter = sqlresults.SQLResultReporter() + + variables = args.variables + # Add a new revision and get the "revision" number + revision = sqlresults.add_revision() + # Save the commitid + commitid = args.commitid + + # If a directory has been provided, look there for all of the XML files + if os.path.isdir(args.xmlpath[0]): + xmldir = args.xmlpath[0] + if not os.path.isabs(xmldir): + xmldir = os.path.abspath(xmldir) + xmlfiles = glob.glob(os.path.join(xmldir, '*.xml')) + else: + xmlfiles = args.xmlpath + + # Convert each file + for file in xmlfiles: + convert_xml(file) + + + diff --git a/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py new file mode 100755 index 000000000000..3db730daaf48 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/scripts/runSystemTests.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python + +import os +# set up the command line options +VERSION = "1.1" +THIS_MODULE_DIR = os.path.dirname(os.path.realpath(__file__)) +DEFAULT_FRAMEWORK_LOC = os.path.realpath(os.path.join(THIS_MODULE_DIR, "..","lib","systemtests")) +DATA_DIRS_LIST_PATH = os.path.join(THIS_MODULE_DIR, "datasearch-directories.txt") +SAVE_DIR_LIST_PATH = os.path.join(THIS_MODULE_DIR, "defaultsave-directory.txt") + +info = [] +info.append("This program will configure mantid run all of the system tests located in") +info.append("the 'tests/analysis' directory.") +info.append("This program will create a temporary 'Mantid.user.properties' file which") +info.append("it will rename to 'Mantid.user.properties.systest' upon completion. The") +info.append("current version of the code does not print to stdout while the test is") +info.append("running, so the impatient user may ^C to kill the process. In this case") +info.append("all of the tests that haven't been run will be marked as skipped in the") +info.append("full logs.") + +import optparse +parser = optparse.OptionParser("Usage: %prog [options]", None, + optparse.Option, VERSION, 'error', ' '.join(info)) +parser.add_option("-m", "--mantidpath", dest="mantidpath", + help="Location of mantid build") +parser.add_option("", "--email", action="store_true", + help="send an email with test status.") +parser.add_option("", "--frameworkLoc", + help="location of the stress test framework (default=%s)" % DEFAULT_FRAMEWORK_LOC) +parser.add_option("", "--disablepropmake", action="store_false", dest="makeprop", + help="By default this will move your properties file out of the way and create a new one. This option turns off this behavior.") +parser.add_option("-R", "--tests-regex", dest="testsInclude", + help="String specifying which tests to run. Simply uses 'string in testname'.") +parser.add_option("-E", "--excluderegex", dest="testsExclude", + help="String specifying which tests to not run. Simply uses 'string in testname'.") +loglevelChoices=["error", "warning", "notice", "information", "debug"] +parser.add_option("-l", "--loglevel", dest="loglevel", + choices=loglevelChoices, + help="Set the log level for test running: [" + ', '.join(loglevelChoices) + "]") +parser.add_option("", "--showskipped", dest="showskipped", action="store_true", + help="List the skipped tests.") +parser.add_option("-d", "--datapaths", dest="datapaths", + help="A semicolon-separated list of directories to search for data") +parser.add_option("-s", "--savedir", dest="savedir", + help="A directory to use for the Mantid save path") +parser.add_option("", "--archivesearch", dest="archivesearch", action="store_true", + help="Turn on archive search for file finder.") +parser.set_defaults(frameworkLoc=DEFAULT_FRAMEWORK_LOC, mantidpath=None, makeprop=True, + loglevel="information") +(options, args) = parser.parse_args() + +# import the stress testing framework +import sys +import os +import platform +sys.path.append(options.frameworkLoc) +import stresstesting + +# Make sure the specified MantidFramework is picked up +# Use specified option if given +mantid_module_path = None +if options.mantidpath is not None: + mantid_module_path = options.mantidpath +elif os.path.exists("MantidFramework"): + pass # Current directory is in the already +elif 'MANTIDPATH' in os.environ: + mantid_module_path = os.environ['MANTIDPATH'] +else: + pass + +# Ensure that this is the one that is picked +sys.path.insert(0, mantid_module_path) + +# On Windows & OSX we need to ensure the mantid libraries in bin/Contents/MacOS can be found. +# Must be done before first import of mantid. This is the same as what a user would have to do to +# import mantid in a vanilla python session +# Unfortunately Python seems to know the path separator on each platform but +# not the dynamic library path variable name +if platform.system() == 'Windows': + path_var = "PATH" +# only necessary on 10.8 build +elif platform.system() == 'Darwin' and int(platform.release().split('.')[0]) < 13 : + path_var = "DYLD_LIBRARY_PATH" +else: + path_var = None +# Set the path +if path_var: + os.environ[path_var] = mantid_module_path + os.pathsep + os.environ.get(path_var, "") + +# Configure mantid +# Parse files containing the search and save directories, unless otherwise given +data_paths = options.datapaths +if data_paths is None or data_paths == "": + with open(DATA_DIRS_LIST_PATH, 'r') as f_handle: + data_paths = f_handle.read().strip() + +save_dir = options.savedir +if save_dir is None or save_dir == "": + with open(SAVE_DIR_LIST_PATH, 'r') as f_handle: + save_dir = f_handle.read().strip() +# Configure properties file +mtdconf = stresstesting.MantidFrameworkConfig(mantid_module_path, loglevel=options.loglevel, + data_dirs=data_paths, save_dir=save_dir, + archivesearch=options.archivesearch) +if options.makeprop: + mtdconf.config() + +# run the tests +reporter = stresstesting.XmlResultReporter(showSkipped=options.showskipped) +mgr = stresstesting.TestManager(mtdconf.testDir, output = [reporter], + testsInclude=options.testsInclude, testsExclude=options.testsExclude) +try: + mgr.executeTests() +except KeyboardInterrupt: + mgr.markSkipped("KeyboardInterrupt") + +# report the errors +success = reporter.reportStatus() +xml_report = open(os.path.join(mtdconf.saveDir, "TEST-systemtests.xml"),'w') +xml_report.write(reporter.getResults()) +xml_report.close() + +# put the configuration back to its original state +if options.makeprop: + mtdconf.restoreconfig() + +print +if mgr.skippedTests == mgr.totalTests: + print "All tests were skipped" + success = False # fail if everything was skipped +else: + percent = 1.-float(mgr.failedTests)/float(mgr.totalTests-mgr.skippedTests) + percent = int(100. * percent) + print "%d%s tests passed, %d tests failed out of %d (%d skipped)" % \ + (percent, '%', mgr.failedTests, (mgr.totalTests-mgr.skippedTests), mgr.skippedTests) +print 'All tests passed? ' + str(success) +if not success: + sys.exit(1) diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/HRPDPowderDiffraction.py b/Code/Mantid/Testing/SystemTests/tests/analysis/HRPDPowderDiffraction.py new file mode 100644 index 000000000000..7ed7c9ccaa7d --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/tests/analysis/HRPDPowderDiffraction.py @@ -0,0 +1,75 @@ +import stresstesting +from mantid.simpleapi import * + +''' Simply tests that our LoadRaw and LoadISISNexus algorithms produce the same workspace''' +class HRPDPowderDiffraction(stresstesting.MantidStressTest): + + def requiredFiles(self): + return ["HRP39191.RAW", "hrpd_new_072_01_corr.cal", "HRP39187.RAW", 'HRPDPowderDiffraction.nxs'] + + def runTest(self): + #Load the Vanadium + LoadRaw(Filename="HRP39191.RAW",OutputWorkspace="Vanadium") + #mask out the vanadium peaks + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="19970",XMax="20140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="39970",XMax="40140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="59970",XMax="60140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="79970",XMax="80140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="99970",XMax="100140") + #align vanadium detectors + AlignDetectors(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",CalibrationFile="hrpd_new_072_01_corr.cal") + #normalise by current + NormaliseByCurrent(InputWorkspace="Vanadium",OutputWorkspace="Vanadium") + #correct for solid angle + SolidAngle(InputWorkspace="Vanadium",OutputWorkspace="Corr") + Divide(LHSWorkspace="Vanadium",RHSWorkspace="Corr",OutputWorkspace="Vanadium") + #Multiply the solid angle by the integrated vanadium flux between 1.4 and 3 Angstrom + ConvertUnits(InputWorkspace="Vanadium",OutputWorkspace="flux",Target="Wavelength") + Integration(InputWorkspace="flux",OutputWorkspace="flux",RangeLower="1.4",RangeUpper="3") + Multiply(LHSWorkspace="Corr",RHSWorkspace="flux",OutputWorkspace="Corr") + #adjust the correction down by a factor of 1000 + CreateSingleValuedWorkspace(OutputWorkspace="Sc",DataValue="1000") + Divide(LHSWorkspace="Corr",RHSWorkspace="Sc",OutputWorkspace="Corr") + #Load the Vanadium - a second time + LoadRaw(Filename="HRP39191.RAW",OutputWorkspace="Vanadium") + #mask out the vanadium peaks + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="19970",XMax="20140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="39970",XMax="40140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="59970",XMax="60140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="79970",XMax="80140") + MaskBins(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",XMin="99970",XMax="100140") + #align vanadium detectors + AlignDetectors(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",CalibrationFile="hrpd_new_072_01_corr.cal") + #normalise by current + NormaliseByCurrent(InputWorkspace="Vanadium",OutputWorkspace="Vanadium") + #correct by accumulated correction - solid angle/(1000*flux(1.4 - 3 Angstrom)) + Divide(LHSWorkspace="Vanadium",RHSWorkspace="Corr",OutputWorkspace="Vanadium") + #Load the vanadium empty + LoadRaw(Filename="HRP39187.RAW",OutputWorkspace="VEmpty") + #mask out the vanadium peaks + MaskBins(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",XMin="19970",XMax="20140") + MaskBins(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",XMin="39970",XMax="40140") + MaskBins(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",XMin="59970",XMax="60140") + MaskBins(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",XMin="79970",XMax="80140") + MaskBins(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",XMin="99970",XMax="100140") + #align vanadium empty detectors + AlignDetectors(InputWorkspace="VEmpty",OutputWorkspace="VEmpty",CalibrationFile="hrpd_new_072_01_corr.cal") + #correct by accumulated correction - solid angle/(1000*flux(1.4 - 3 Angstrom)) + Divide(LHSWorkspace="VEmpty",RHSWorkspace="Corr",OutputWorkspace="VEmpty") + #normalise by current + NormaliseByCurrent(InputWorkspace="VEmpty",OutputWorkspace="VEmpty") + #Subtract Vanadium empty from the Vanadium + Minus(LHSWorkspace="Vanadium",RHSWorkspace="VEmpty",OutputWorkspace="Vanadium") + #Convert to wavelength + ConvertUnits(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",Target="Wavelength") + #Correct for cylinderAbsorption + CylinderAbsorption(InputWorkspace="Vanadium",OutputWorkspace="Transmission",CylinderSampleHeight="2",CylinderSampleRadius="0.4",AttenuationXSection="5.1",ScatteringXSection="5.08",SampleNumberDensity="0.072",NumberOfSlices="10",NumberOfAnnuli="10",NumberOfWavelengthPoints="100") + Divide(LHSWorkspace="Vanadium",RHSWorkspace="Transmission",OutputWorkspace="Vanadium") + #convert to dspacing and focuss + ConvertUnits(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",Target="dSpacing") + DiffractionFocussing(InputWorkspace="Vanadium",OutputWorkspace="Vanadium",GroupingFileName="hrpd_new_072_01_corr.cal") + + def validate(self): + # Fitting parameters not saved to ParameterMap + self.disableChecking.append("Instrument") + return 'Vanadium','HRPDPowderDiffraction.nxs' diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/HRPDPowderDiffraction.nxs.md5 b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/HRPDPowderDiffraction.nxs.md5 new file mode 100644 index 000000000000..0cc9b76c87b6 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/HRPDPowderDiffraction.nxs.md5 @@ -0,0 +1 @@ +078a0d8d4c9f0aa5b2ece6099e13b0b9 diff --git a/Code/Mantid/Testing/SystemTests/tests/analysis/reference/README.md b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/README.md new file mode 100644 index 000000000000..820b616aa6b0 --- /dev/null +++ b/Code/Mantid/Testing/SystemTests/tests/analysis/reference/README.md @@ -0,0 +1 @@ +This directory stores the content links to the reference files for the system tests diff --git a/Code/Mantid/TestingTools/CMakeLists.txt b/Code/Mantid/Testing/Tools/CMakeLists.txt similarity index 100% rename from Code/Mantid/TestingTools/CMakeLists.txt rename to Code/Mantid/Testing/Tools/CMakeLists.txt diff --git a/Code/Mantid/TestingTools/cxxtest/COPYING b/Code/Mantid/Testing/Tools/cxxtest/COPYING similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/COPYING rename to Code/Mantid/Testing/Tools/cxxtest/COPYING diff --git a/Code/Mantid/TestingTools/cxxtest/README b/Code/Mantid/Testing/Tools/cxxtest/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/README rename to Code/Mantid/Testing/Tools/cxxtest/README diff --git a/Code/Mantid/TestingTools/cxxtest/TODO b/Code/Mantid/Testing/Tools/cxxtest/TODO similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/TODO rename to Code/Mantid/Testing/Tools/cxxtest/TODO diff --git a/Code/Mantid/TestingTools/cxxtest/Versions b/Code/Mantid/Testing/Tools/cxxtest/Versions similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/Versions rename to Code/Mantid/Testing/Tools/cxxtest/Versions diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/AUTHORS b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/AUTHORS similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/AUTHORS rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/AUTHORS diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/cxxtest.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/cxxtest.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/cxxtest.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/cxxtest.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/default_env/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/default_env/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/requirement.hpp b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/requirement.hpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/requirement.hpp rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/requirement.hpp diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/test_bar.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/test_bar.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/test_bar.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/test_bar.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/test_foo.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/test_foo.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/empty_source_list/test_foo.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/empty_source_list/test_foo.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/eprouvette.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/eprouvette.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/eprouvette.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/eprouvette.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/expanding_#/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/expanding_#/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/requirement.cpp b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/requirement.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/requirement.cpp rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/requirement.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/requirement.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/requirement.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/requirement.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/requirement.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/test_bar.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/test_bar.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/test_bar.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/test_bar.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/test_foo.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/test_foo.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing/src/test_foo.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing/src/test_foo.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.cc b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.cc similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.cc rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.cc diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.hh b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.hh similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.hh rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hello.hh diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hellotest.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hellotest.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/hellotest.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/hellotest.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/main.cpp b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/main.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/globbing_edmundo/main.cpp rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/globbing_edmundo/main.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/not-with-pedantic.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/not-with-pedantic.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/not-with-pedantic.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/not-with-pedantic.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/only_with_ansi.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/only_with_ansi.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/only_with_ansi.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CCFLAGS/src/only_with_ansi.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/src/not-with-pedantic.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/src/not-with-pedantic.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/src/not-with-pedantic.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/include_CXXFLAGS/src/not-with-pedantic.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.cpp b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.cpp rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/requirement.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_bar.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_bar.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_bar.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_bar.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_foo.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_foo.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_foo.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/multifile_tests/src/test_foo.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppath.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppath.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppath.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppath.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppathdir/include.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppathdir/include.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppathdir/include.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/need_cpppath/src/cpppathdir/include.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/nonstandard_cxxtest_dir/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/cxxtest/CrazyRunner.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/cxxtest/CrazyRunner.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/cxxtest/CrazyRunner.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/cxxtest/CrazyRunner.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/src/failtest.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/src/failtest.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/printer_propagation/src/failtest.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/printer_propagation/src/failtest.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/README b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/README similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/README rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/README diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.cpp b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.cpp rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/requirement.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_bar.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_bar.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_bar.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_bar.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_foo.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_foo.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_foo.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/recursive_sources/src/test_foo.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppath.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppath.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppath.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppath.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppathdir/include.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppathdir/include.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppathdir/include.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/string_cpppath/src/cpppathdir/include.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/TestDef.py b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/TestDef.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/TestDef.py rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/TestDef.py diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppath.t.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppath.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppath.t.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppath.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppathdir/include.h b/Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppathdir/include.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppathdir/include.h rename to Code/Mantid/Testing/Tools/cxxtest/build_tools/SCons/test/target_syntax/src/cpppathdir/include.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest.spec b/Code/Mantid/Testing/Tools/cxxtest/cxxtest.spec similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest.spec rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest.spec diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Descriptions.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Descriptions.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Descriptions.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Descriptions.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Descriptions.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Descriptions.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Descriptions.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Descriptions.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/DummyDescriptions.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/DummyDescriptions.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/DummyDescriptions.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/DummyDescriptions.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/DummyDescriptions.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/DummyDescriptions.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/DummyDescriptions.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/DummyDescriptions.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/ErrorFormatter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/ErrorFormatter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/ErrorFormatter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/ErrorFormatter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/ErrorPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/ErrorPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/ErrorPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/ErrorPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Flags.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Flags.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Flags.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Flags.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/GlobalFixture.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/GlobalFixture.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/GlobalFixture.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/GlobalFixture.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/GlobalFixture.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/GlobalFixture.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/GlobalFixture.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/GlobalFixture.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Gui.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Gui.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Gui.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Gui.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/LinkedList.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/LinkedList.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/LinkedList.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/LinkedList.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/LinkedList.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/LinkedList.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/LinkedList.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/LinkedList.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/MantidFormatter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/MantidFormatter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/MantidFormatter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/MantidFormatter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/MantidPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/MantidPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/MantidPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/MantidPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Mock.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Mock.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Mock.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Mock.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/ParenPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/ParenPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/ParenPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/ParenPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/QtGui.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/QtGui.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/QtGui.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/QtGui.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/RealDescriptions.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/RealDescriptions.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/RealDescriptions.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/RealDescriptions.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/RealDescriptions.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/RealDescriptions.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/RealDescriptions.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/RealDescriptions.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Root.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Root.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Root.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Root.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/SelfTest.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/SelfTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/SelfTest.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/SelfTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/StdHeaders.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdHeaders.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/StdHeaders.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdHeaders.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/StdTestSuite.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdTestSuite.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/StdTestSuite.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdTestSuite.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/StdValueTraits.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdValueTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/StdValueTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdValueTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/StdioFilePrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdioFilePrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/StdioFilePrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdioFilePrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/StdioPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdioPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/StdioPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/StdioPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TeeListener.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TeeListener.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TeeListener.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TeeListener.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestListener.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestListener.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestListener.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestListener.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestMain.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestMain.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestMain.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestMain.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestRunner.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestRunner.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestRunner.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestRunner.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestSuite.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestSuite.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestSuite.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestSuite.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestSuite.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestSuite.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestSuite.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestSuite.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestTracker.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestTracker.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestTracker.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestTracker.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/TestTracker.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestTracker.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/TestTracker.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/TestTracker.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/ValueTraits.cpp b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/ValueTraits.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/ValueTraits.cpp rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/ValueTraits.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/ValueTraits.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/ValueTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/ValueTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/ValueTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/Win32Gui.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/Win32Gui.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/Win32Gui.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/Win32Gui.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/WrappedTestSuite.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/WrappedTestSuite.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/WrappedTestSuite.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/WrappedTestSuite.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/X11Gui.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/X11Gui.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/X11Gui.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/X11Gui.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/XUnitPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/XUnitPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/XUnitPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/XUnitPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/XmlFormatter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/XmlFormatter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/XmlFormatter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/XmlFormatter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/XmlPrinter.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/XmlPrinter.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/XmlPrinter.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/XmlPrinter.h diff --git a/Code/Mantid/TestingTools/cxxtest/cxxtest/YesNoRunner.h b/Code/Mantid/Testing/Tools/cxxtest/cxxtest/YesNoRunner.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/cxxtest/YesNoRunner.h rename to Code/Mantid/Testing/Tools/cxxtest/cxxtest/YesNoRunner.h diff --git a/Code/Mantid/TestingTools/cxxtest/docs/.cvsignore b/Code/Mantid/Testing/Tools/cxxtest/docs/.cvsignore similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/.cvsignore rename to Code/Mantid/Testing/Tools/cxxtest/docs/.cvsignore diff --git a/Code/Mantid/TestingTools/cxxtest/docs/Makefile b/Code/Mantid/Testing/Tools/cxxtest/docs/Makefile similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/Makefile rename to Code/Mantid/Testing/Tools/cxxtest/docs/Makefile diff --git a/Code/Mantid/TestingTools/cxxtest/docs/convert.pl b/Code/Mantid/Testing/Tools/cxxtest/docs/convert.pl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/convert.pl rename to Code/Mantid/Testing/Tools/cxxtest/docs/convert.pl diff --git a/Code/Mantid/TestingTools/cxxtest/docs/guide.texi b/Code/Mantid/Testing/Tools/cxxtest/docs/guide.texi similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/guide.texi rename to Code/Mantid/Testing/Tools/cxxtest/docs/guide.texi diff --git a/Code/Mantid/TestingTools/cxxtest/docs/qt.png b/Code/Mantid/Testing/Tools/cxxtest/docs/qt.png similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/qt.png rename to Code/Mantid/Testing/Tools/cxxtest/docs/qt.png diff --git a/Code/Mantid/TestingTools/cxxtest/docs/qt2.png b/Code/Mantid/Testing/Tools/cxxtest/docs/qt2.png similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/qt2.png rename to Code/Mantid/Testing/Tools/cxxtest/docs/qt2.png diff --git a/Code/Mantid/TestingTools/cxxtest/docs/texinfo.tex b/Code/Mantid/Testing/Tools/cxxtest/docs/texinfo.tex similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/texinfo.tex rename to Code/Mantid/Testing/Tools/cxxtest/docs/texinfo.tex diff --git a/Code/Mantid/TestingTools/cxxtest/docs/win32.png b/Code/Mantid/Testing/Tools/cxxtest/docs/win32.png similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/win32.png rename to Code/Mantid/Testing/Tools/cxxtest/docs/win32.png diff --git a/Code/Mantid/TestingTools/cxxtest/docs/x11.png b/Code/Mantid/Testing/Tools/cxxtest/docs/x11.png similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/docs/x11.png rename to Code/Mantid/Testing/Tools/cxxtest/docs/x11.png diff --git a/Code/Mantid/TestingTools/cxxtest/get_revision_from_cvs.pl b/Code/Mantid/Testing/Tools/cxxtest/get_revision_from_cvs.pl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/get_revision_from_cvs.pl rename to Code/Mantid/Testing/Tools/cxxtest/get_revision_from_cvs.pl diff --git a/Code/Mantid/TestingTools/cxxtest/python/README.txt b/Code/Mantid/Testing/Tools/cxxtest/python/README.txt similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/README.txt rename to Code/Mantid/Testing/Tools/cxxtest/python/README.txt diff --git a/Code/Mantid/TestingTools/cxxtest/python/cxxtest/__init__.py b/Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/cxxtest/__init__.py rename to Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/__init__.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/cxxtest/__release__.py b/Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/__release__.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/cxxtest/__release__.py rename to Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/__release__.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtest_misc.py b/Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtest_misc.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtest_misc.py rename to Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtest_misc.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtest_parser.py b/Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtest_parser.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtest_parser.py rename to Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtest_parser.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtestgen.py b/Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtestgen.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/cxxtest/cxxtestgen.py rename to Code/Mantid/Testing/Tools/cxxtest/python/cxxtest/cxxtestgen.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/ez_setup.py b/Code/Mantid/Testing/Tools/cxxtest/python/ez_setup.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/ez_setup.py rename to Code/Mantid/Testing/Tools/cxxtest/python/ez_setup.py diff --git a/Code/Mantid/TestingTools/cxxtest/python/scripts/cxxtestgen b/Code/Mantid/Testing/Tools/cxxtest/python/scripts/cxxtestgen similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/scripts/cxxtestgen rename to Code/Mantid/Testing/Tools/cxxtest/python/scripts/cxxtestgen diff --git a/Code/Mantid/TestingTools/cxxtest/python/setup.py b/Code/Mantid/Testing/Tools/cxxtest/python/setup.py similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/python/setup.py rename to Code/Mantid/Testing/Tools/cxxtest/python/setup.py diff --git a/Code/Mantid/TestingTools/cxxtest/sample/.cvsignore b/Code/Mantid/Testing/Tools/cxxtest/sample/.cvsignore similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/.cvsignore rename to Code/Mantid/Testing/Tools/cxxtest/sample/.cvsignore diff --git a/Code/Mantid/TestingTools/cxxtest/sample/Construct b/Code/Mantid/Testing/Tools/cxxtest/sample/Construct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/Construct rename to Code/Mantid/Testing/Tools/cxxtest/sample/Construct diff --git a/Code/Mantid/TestingTools/cxxtest/sample/CreatedTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/CreatedTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/CreatedTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/CreatedTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/DeltaTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/DeltaTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/DeltaTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/DeltaTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/EnumTraits.h b/Code/Mantid/Testing/Tools/cxxtest/sample/EnumTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/EnumTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/EnumTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/ExceptionTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/ExceptionTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/ExceptionTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/ExceptionTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/FixtureTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/FixtureTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/FixtureTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/FixtureTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/Makefile.PL b/Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.PL similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/Makefile.PL rename to Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.PL diff --git a/Code/Mantid/TestingTools/cxxtest/sample/Makefile.bcc32 b/Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.bcc32 similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/Makefile.bcc32 rename to Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.bcc32 diff --git a/Code/Mantid/TestingTools/cxxtest/sample/Makefile.msvc b/Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.msvc similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/Makefile.msvc rename to Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.msvc diff --git a/Code/Mantid/TestingTools/cxxtest/sample/Makefile.unix b/Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.unix similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/Makefile.unix rename to Code/Mantid/Testing/Tools/cxxtest/sample/Makefile.unix diff --git a/Code/Mantid/TestingTools/cxxtest/sample/MessageTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/MessageTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/MessageTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/MessageTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/SCons/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/sample/SCons/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/SCons/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/sample/SCons/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/sample/SCons/include/stack.h b/Code/Mantid/Testing/Tools/cxxtest/sample/SCons/include/stack.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/SCons/include/stack.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/SCons/include/stack.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/SCons/src/stack.c b/Code/Mantid/Testing/Tools/cxxtest/sample/SCons/src/stack.c similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/SCons/src/stack.c rename to Code/Mantid/Testing/Tools/cxxtest/sample/SCons/src/stack.c diff --git a/Code/Mantid/TestingTools/cxxtest/sample/SCons/tests/stack_test.h b/Code/Mantid/Testing/Tools/cxxtest/sample/SCons/tests/stack_test.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/SCons/tests/stack_test.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/SCons/tests/stack_test.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/SimpleTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/SimpleTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/SimpleTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/SimpleTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/TraitsTest.h b/Code/Mantid/Testing/Tools/cxxtest/sample/TraitsTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/TraitsTest.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/TraitsTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/aborter.tpl b/Code/Mantid/Testing/Tools/cxxtest/sample/aborter.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/aborter.tpl rename to Code/Mantid/Testing/Tools/cxxtest/sample/aborter.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/sample/file_printer.tpl b/Code/Mantid/Testing/Tools/cxxtest/sample/file_printer.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/file_printer.tpl rename to Code/Mantid/Testing/Tools/cxxtest/sample/file_printer.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/sample/gui/GreenYellowRed.h b/Code/Mantid/Testing/Tools/cxxtest/sample/gui/GreenYellowRed.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/gui/GreenYellowRed.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/gui/GreenYellowRed.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/Dice.cpp b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/Dice.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/Dice.cpp rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/Dice.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/Dice.h b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/Dice.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/Dice.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/Dice.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/Makefile b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/Makefile similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/Makefile rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/Makefile diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/MockStdlib.h b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/MockStdlib.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/MockStdlib.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/MockStdlib.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/T/stdlib.h b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/T/stdlib.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/T/stdlib.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/T/stdlib.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/TestDice.h b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/TestDice.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/TestDice.h rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/TestDice.h diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/mock_stdlib.cpp b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/mock_stdlib.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/mock_stdlib.cpp rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/mock_stdlib.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/real_stdlib.cpp b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/real_stdlib.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/real_stdlib.cpp rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/real_stdlib.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/mock/roll.cpp b/Code/Mantid/Testing/Tools/cxxtest/sample/mock/roll.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/mock/roll.cpp rename to Code/Mantid/Testing/Tools/cxxtest/sample/mock/roll.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_1_Run.dsp b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_1_Run.dsp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_1_Run.dsp rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_1_Run.dsp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_2_Build.dsp b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_2_Build.dsp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_2_Build.dsp rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_2_Build.dsp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_3_Generate.dsp b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_3_Generate.dsp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_3_Generate.dsp rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_3_Generate.dsp diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_Workspace.dsw b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_Workspace.dsw similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/CxxTest_Workspace.dsw rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/CxxTest_Workspace.dsw diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/FixFiles.bat b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/FixFiles.bat similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/FixFiles.bat rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/FixFiles.bat diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/Makefile b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/Makefile similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/Makefile rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/Makefile diff --git a/Code/Mantid/TestingTools/cxxtest/sample/msvc/ReadMe.txt b/Code/Mantid/Testing/Tools/cxxtest/sample/msvc/ReadMe.txt similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/msvc/ReadMe.txt rename to Code/Mantid/Testing/Tools/cxxtest/sample/msvc/ReadMe.txt diff --git a/Code/Mantid/TestingTools/cxxtest/sample/only.tpl b/Code/Mantid/Testing/Tools/cxxtest/sample/only.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/only.tpl rename to Code/Mantid/Testing/Tools/cxxtest/sample/only.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/sample/parts/.cvsignore b/Code/Mantid/Testing/Tools/cxxtest/sample/parts/.cvsignore similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/parts/.cvsignore rename to Code/Mantid/Testing/Tools/cxxtest/sample/parts/.cvsignore diff --git a/Code/Mantid/TestingTools/cxxtest/sample/parts/Makefile.unix b/Code/Mantid/Testing/Tools/cxxtest/sample/parts/Makefile.unix similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/parts/Makefile.unix rename to Code/Mantid/Testing/Tools/cxxtest/sample/parts/Makefile.unix diff --git a/Code/Mantid/TestingTools/cxxtest/sample/winddk/Makefile b/Code/Mantid/Testing/Tools/cxxtest/sample/winddk/Makefile similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/winddk/Makefile rename to Code/Mantid/Testing/Tools/cxxtest/sample/winddk/Makefile diff --git a/Code/Mantid/TestingTools/cxxtest/sample/winddk/Makefile.inc b/Code/Mantid/Testing/Tools/cxxtest/sample/winddk/Makefile.inc similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/winddk/Makefile.inc rename to Code/Mantid/Testing/Tools/cxxtest/sample/winddk/Makefile.inc diff --git a/Code/Mantid/TestingTools/cxxtest/sample/winddk/RunTests.tpl b/Code/Mantid/Testing/Tools/cxxtest/sample/winddk/RunTests.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/winddk/RunTests.tpl rename to Code/Mantid/Testing/Tools/cxxtest/sample/winddk/RunTests.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/sample/winddk/SOURCES b/Code/Mantid/Testing/Tools/cxxtest/sample/winddk/SOURCES similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/winddk/SOURCES rename to Code/Mantid/Testing/Tools/cxxtest/sample/winddk/SOURCES diff --git a/Code/Mantid/TestingTools/cxxtest/sample/yes_no_runner.cpp b/Code/Mantid/Testing/Tools/cxxtest/sample/yes_no_runner.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/sample/yes_no_runner.cpp rename to Code/Mantid/Testing/Tools/cxxtest/sample/yes_no_runner.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/.cvsignore b/Code/Mantid/Testing/Tools/cxxtest/test/.cvsignore similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/.cvsignore rename to Code/Mantid/Testing/Tools/cxxtest/test/.cvsignore diff --git a/Code/Mantid/TestingTools/cxxtest/test/AborterNoThrow.h b/Code/Mantid/Testing/Tools/cxxtest/test/AborterNoThrow.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/AborterNoThrow.h rename to Code/Mantid/Testing/Tools/cxxtest/test/AborterNoThrow.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/BadTest.h b/Code/Mantid/Testing/Tools/cxxtest/test/BadTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/BadTest.h rename to Code/Mantid/Testing/Tools/cxxtest/test/BadTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Comments.h b/Code/Mantid/Testing/Tools/cxxtest/test/Comments.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Comments.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Comments.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DeepAbort.h b/Code/Mantid/Testing/Tools/cxxtest/test/DeepAbort.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DeepAbort.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DeepAbort.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DefaultAbort.h b/Code/Mantid/Testing/Tools/cxxtest/test/DefaultAbort.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DefaultAbort.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DefaultAbort.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DefaultTraits.h b/Code/Mantid/Testing/Tools/cxxtest/test/DefaultTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DefaultTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DefaultTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DoubleCall.h b/Code/Mantid/Testing/Tools/cxxtest/test/DoubleCall.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DoubleCall.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DoubleCall.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DynamicAbort.h b/Code/Mantid/Testing/Tools/cxxtest/test/DynamicAbort.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DynamicAbort.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DynamicAbort.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/DynamicMax.h b/Code/Mantid/Testing/Tools/cxxtest/test/DynamicMax.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/DynamicMax.h rename to Code/Mantid/Testing/Tools/cxxtest/test/DynamicMax.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/EmptySuite.h b/Code/Mantid/Testing/Tools/cxxtest/test/EmptySuite.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/EmptySuite.h rename to Code/Mantid/Testing/Tools/cxxtest/test/EmptySuite.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Exceptions.h b/Code/Mantid/Testing/Tools/cxxtest/test/Exceptions.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Exceptions.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Exceptions.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Factor.h b/Code/Mantid/Testing/Tools/cxxtest/test/Factor.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Factor.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Factor.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/ForceNoEh.h b/Code/Mantid/Testing/Tools/cxxtest/test/ForceNoEh.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/ForceNoEh.h rename to Code/Mantid/Testing/Tools/cxxtest/test/ForceNoEh.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GfSetUpFails.h b/Code/Mantid/Testing/Tools/cxxtest/test/GfSetUpFails.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GfSetUpFails.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GfSetUpFails.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GfSetUpThrows.h b/Code/Mantid/Testing/Tools/cxxtest/test/GfSetUpThrows.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GfSetUpThrows.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GfSetUpThrows.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GfTearDownFails.h b/Code/Mantid/Testing/Tools/cxxtest/test/GfTearDownFails.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GfTearDownFails.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GfTearDownFails.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GfTearDownThrows.h b/Code/Mantid/Testing/Tools/cxxtest/test/GfTearDownThrows.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GfTearDownThrows.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GfTearDownThrows.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GlobalFixtures.h b/Code/Mantid/Testing/Tools/cxxtest/test/GlobalFixtures.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GlobalFixtures.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GlobalFixtures.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GoodSuite.h b/Code/Mantid/Testing/Tools/cxxtest/test/GoodSuite.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GoodSuite.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GoodSuite.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/GuiWait.h b/Code/Mantid/Testing/Tools/cxxtest/test/GuiWait.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/GuiWait.h rename to Code/Mantid/Testing/Tools/cxxtest/test/GuiWait.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/HaveStd.h b/Code/Mantid/Testing/Tools/cxxtest/test/HaveStd.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/HaveStd.h rename to Code/Mantid/Testing/Tools/cxxtest/test/HaveStd.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/IncludeTest.h b/Code/Mantid/Testing/Tools/cxxtest/test/IncludeTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/IncludeTest.h rename to Code/Mantid/Testing/Tools/cxxtest/test/IncludeTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Int64.h b/Code/Mantid/Testing/Tools/cxxtest/test/Int64.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Int64.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Int64.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/LessThanEquals.h b/Code/Mantid/Testing/Tools/cxxtest/test/LessThanEquals.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/LessThanEquals.h rename to Code/Mantid/Testing/Tools/cxxtest/test/LessThanEquals.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/LongLong.h b/Code/Mantid/Testing/Tools/cxxtest/test/LongLong.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/LongLong.h rename to Code/Mantid/Testing/Tools/cxxtest/test/LongLong.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/LongTraits.h b/Code/Mantid/Testing/Tools/cxxtest/test/LongTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/LongTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/test/LongTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Makefile b/Code/Mantid/Testing/Tools/cxxtest/test/Makefile similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Makefile rename to Code/Mantid/Testing/Tools/cxxtest/test/Makefile diff --git a/Code/Mantid/TestingTools/cxxtest/test/MaxDump.h b/Code/Mantid/Testing/Tools/cxxtest/test/MaxDump.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/MaxDump.h rename to Code/Mantid/Testing/Tools/cxxtest/test/MaxDump.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/MockTest.h b/Code/Mantid/Testing/Tools/cxxtest/test/MockTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/MockTest.h rename to Code/Mantid/Testing/Tools/cxxtest/test/MockTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/NoEh.h b/Code/Mantid/Testing/Tools/cxxtest/test/NoEh.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/NoEh.h rename to Code/Mantid/Testing/Tools/cxxtest/test/NoEh.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Part1.h b/Code/Mantid/Testing/Tools/cxxtest/test/Part1.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Part1.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Part1.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Part2.h b/Code/Mantid/Testing/Tools/cxxtest/test/Part2.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Part2.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Part2.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Relation.h b/Code/Mantid/Testing/Tools/cxxtest/test/Relation.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Relation.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Relation.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/SameData.h b/Code/Mantid/Testing/Tools/cxxtest/test/SameData.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/SameData.h rename to Code/Mantid/Testing/Tools/cxxtest/test/SameData.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/SameZero.h b/Code/Mantid/Testing/Tools/cxxtest/test/SameZero.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/SameZero.h rename to Code/Mantid/Testing/Tools/cxxtest/test/SameZero.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/SetUpWorldFails.h b/Code/Mantid/Testing/Tools/cxxtest/test/SetUpWorldFails.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/SetUpWorldFails.h rename to Code/Mantid/Testing/Tools/cxxtest/test/SetUpWorldFails.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/SetUpWorldThrows.h b/Code/Mantid/Testing/Tools/cxxtest/test/SetUpWorldThrows.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/SetUpWorldThrows.h rename to Code/Mantid/Testing/Tools/cxxtest/test/SetUpWorldThrows.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Something.h b/Code/Mantid/Testing/Tools/cxxtest/test/Something.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Something.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Something.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/StlTraits.h b/Code/Mantid/Testing/Tools/cxxtest/test/StlTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/StlTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/test/StlTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/TearDownWorldFails.h b/Code/Mantid/Testing/Tools/cxxtest/test/TearDownWorldFails.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/TearDownWorldFails.h rename to Code/Mantid/Testing/Tools/cxxtest/test/TearDownWorldFails.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/TearDownWorldThrows.h b/Code/Mantid/Testing/Tools/cxxtest/test/TearDownWorldThrows.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/TearDownWorldThrows.h rename to Code/Mantid/Testing/Tools/cxxtest/test/TearDownWorldThrows.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/ThrowNoStd.h b/Code/Mantid/Testing/Tools/cxxtest/test/ThrowNoStd.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/ThrowNoStd.h rename to Code/Mantid/Testing/Tools/cxxtest/test/ThrowNoStd.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/ThrowNoStd.tpl b/Code/Mantid/Testing/Tools/cxxtest/test/ThrowNoStd.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/ThrowNoStd.tpl rename to Code/Mantid/Testing/Tools/cxxtest/test/ThrowNoStd.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/test/ThrowsAssert.h b/Code/Mantid/Testing/Tools/cxxtest/test/ThrowsAssert.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/ThrowsAssert.h rename to Code/Mantid/Testing/Tools/cxxtest/test/ThrowsAssert.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/TraitsTest.h b/Code/Mantid/Testing/Tools/cxxtest/test/TraitsTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/TraitsTest.h rename to Code/Mantid/Testing/Tools/cxxtest/test/TraitsTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/Tsm.h b/Code/Mantid/Testing/Tools/cxxtest/test/Tsm.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/Tsm.h rename to Code/Mantid/Testing/Tools/cxxtest/test/Tsm.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/UserTraits.h b/Code/Mantid/Testing/Tools/cxxtest/test/UserTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/UserTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/test/UserTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/UserTraits.tpl b/Code/Mantid/Testing/Tools/cxxtest/test/UserTraits.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/UserTraits.tpl rename to Code/Mantid/Testing/Tools/cxxtest/test/UserTraits.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/test/VoidTraits.h b/Code/Mantid/Testing/Tools/cxxtest/test/VoidTraits.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/VoidTraits.h rename to Code/Mantid/Testing/Tools/cxxtest/test/VoidTraits.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/WideCharTest.h b/Code/Mantid/Testing/Tools/cxxtest/test/WideCharTest.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/WideCharTest.h rename to Code/Mantid/Testing/Tools/cxxtest/test/WideCharTest.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/WorldFixtures.h b/Code/Mantid/Testing/Tools/cxxtest/test/WorldFixtures.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/WorldFixtures.h rename to Code/Mantid/Testing/Tools/cxxtest/test/WorldFixtures.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/abort.out b/Code/Mantid/Testing/Tools/cxxtest/test/abort.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/abort.out rename to Code/Mantid/Testing/Tools/cxxtest/test/abort.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/activate.tpl b/Code/Mantid/Testing/Tools/cxxtest/test/activate.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/activate.tpl rename to Code/Mantid/Testing/Tools/cxxtest/test/activate.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/test/anything.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/anything.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/anything.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/anything.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/comments.out b/Code/Mantid/Testing/Tools/cxxtest/test/comments.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/comments.out rename to Code/Mantid/Testing/Tools/cxxtest/test/comments.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/cxxtest/DummyGui.h b/Code/Mantid/Testing/Tools/cxxtest/test/cxxtest/DummyGui.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/cxxtest/DummyGui.h rename to Code/Mantid/Testing/Tools/cxxtest/test/cxxtest/DummyGui.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/default_abort.out b/Code/Mantid/Testing/Tools/cxxtest/test/default_abort.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/default_abort.out rename to Code/Mantid/Testing/Tools/cxxtest/test/default_abort.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/eh_normals.out b/Code/Mantid/Testing/Tools/cxxtest/test/eh_normals.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/eh_normals.out rename to Code/Mantid/Testing/Tools/cxxtest/test/eh_normals.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/error.out b/Code/Mantid/Testing/Tools/cxxtest/test/error.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/error.out rename to Code/Mantid/Testing/Tools/cxxtest/test/error.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/factor.out b/Code/Mantid/Testing/Tools/cxxtest/test/factor.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/factor.out rename to Code/Mantid/Testing/Tools/cxxtest/test/factor.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/.cvsignore b/Code/Mantid/Testing/Tools/cxxtest/test/fake/.cvsignore similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/.cvsignore rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/.cvsignore diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/X11/Xlib.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/X11/Xlib.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/X11/Xlib.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/X11/Xlib.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/X11/Xutil.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/X11/Xutil.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/X11/Xutil.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/X11/Xutil.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/commctrl.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/commctrl.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/commctrl.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/commctrl.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qapplication.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qapplication.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qapplication.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qapplication.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qglobal.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qglobal.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qglobal.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qglobal.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qlabel.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qlabel.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qlabel.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qlabel.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qlayout.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qlayout.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qlayout.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qlayout.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qmessagebox.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qmessagebox.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qmessagebox.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qmessagebox.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qpixmap.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qpixmap.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qpixmap.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qpixmap.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qprogressbar.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qprogressbar.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qprogressbar.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qprogressbar.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qstatusbar.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qstatusbar.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qstatusbar.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qstatusbar.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qstring.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qstring.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qstring.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qstring.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/qwidget.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/qwidget.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/qwidget.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/qwidget.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/fake/windows.h b/Code/Mantid/Testing/Tools/cxxtest/test/fake/windows.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/fake/windows.h rename to Code/Mantid/Testing/Tools/cxxtest/test/fake/windows.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/gfsuf.out b/Code/Mantid/Testing/Tools/cxxtest/test/gfsuf.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gfsuf.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gfsuf.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gfsut.out b/Code/Mantid/Testing/Tools/cxxtest/test/gfsut.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gfsut.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gfsut.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gftdf.out b/Code/Mantid/Testing/Tools/cxxtest/test/gftdf.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gftdf.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gftdf.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gftdt.out b/Code/Mantid/Testing/Tools/cxxtest/test/gftdt.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gftdt.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gftdt.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gfxs.out b/Code/Mantid/Testing/Tools/cxxtest/test/gfxs.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gfxs.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gfxs.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/good.out b/Code/Mantid/Testing/Tools/cxxtest/test/good.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/good.out rename to Code/Mantid/Testing/Tools/cxxtest/test/good.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gui.out b/Code/Mantid/Testing/Tools/cxxtest/test/gui.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gui.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gui.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/gui_paren.out b/Code/Mantid/Testing/Tools/cxxtest/test/gui_paren.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/gui_paren.out rename to Code/Mantid/Testing/Tools/cxxtest/test/gui_paren.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/include.out b/Code/Mantid/Testing/Tools/cxxtest/test/include.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/include.out rename to Code/Mantid/Testing/Tools/cxxtest/test/include.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/int64.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/int64.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/int64.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/int64.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/int64.out b/Code/Mantid/Testing/Tools/cxxtest/test/int64.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/int64.out rename to Code/Mantid/Testing/Tools/cxxtest/test/int64.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/longlong.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/longlong.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/longlong.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/longlong.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/longlong.out b/Code/Mantid/Testing/Tools/cxxtest/test/longlong.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/longlong.out rename to Code/Mantid/Testing/Tools/cxxtest/test/longlong.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/main.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/main.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/main.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/main.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/max.out b/Code/Mantid/Testing/Tools/cxxtest/test/max.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/max.out rename to Code/Mantid/Testing/Tools/cxxtest/test/max.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/normal.out b/Code/Mantid/Testing/Tools/cxxtest/test/normal.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/normal.out rename to Code/Mantid/Testing/Tools/cxxtest/test/normal.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/paren.out b/Code/Mantid/Testing/Tools/cxxtest/test/paren.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/paren.out rename to Code/Mantid/Testing/Tools/cxxtest/test/paren.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/parts.out b/Code/Mantid/Testing/Tools/cxxtest/test/parts.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/parts.out rename to Code/Mantid/Testing/Tools/cxxtest/test/parts.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/preamble.out b/Code/Mantid/Testing/Tools/cxxtest/test/preamble.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/preamble.out rename to Code/Mantid/Testing/Tools/cxxtest/test/preamble.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/preamble.tpl b/Code/Mantid/Testing/Tools/cxxtest/test/preamble.tpl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/preamble.tpl rename to Code/Mantid/Testing/Tools/cxxtest/test/preamble.tpl diff --git a/Code/Mantid/TestingTools/cxxtest/test/runner.out b/Code/Mantid/Testing/Tools/cxxtest/test/runner.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/runner.out rename to Code/Mantid/Testing/Tools/cxxtest/test/runner.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/std.out b/Code/Mantid/Testing/Tools/cxxtest/test/std.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/std.out rename to Code/Mantid/Testing/Tools/cxxtest/test/std.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/stl.out b/Code/Mantid/Testing/Tools/cxxtest/test/stl.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/stl.out rename to Code/Mantid/Testing/Tools/cxxtest/test/stl.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/stpltpl.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/stpltpl.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/stpltpl.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/stpltpl.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/suite.out b/Code/Mantid/Testing/Tools/cxxtest/test/suite.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/suite.out rename to Code/Mantid/Testing/Tools/cxxtest/test/suite.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/suite_test.out b/Code/Mantid/Testing/Tools/cxxtest/test/suite_test.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/suite_test.out rename to Code/Mantid/Testing/Tools/cxxtest/test/suite_test.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/suwf.out b/Code/Mantid/Testing/Tools/cxxtest/test/suwf.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/suwf.out rename to Code/Mantid/Testing/Tools/cxxtest/test/suwf.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/suwt.out b/Code/Mantid/Testing/Tools/cxxtest/test/suwt.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/suwt.out rename to Code/Mantid/Testing/Tools/cxxtest/test/suwt.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/tdwf.out b/Code/Mantid/Testing/Tools/cxxtest/test/tdwf.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/tdwf.out rename to Code/Mantid/Testing/Tools/cxxtest/test/tdwf.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/tdwt.out b/Code/Mantid/Testing/Tools/cxxtest/test/tdwt.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/tdwt.out rename to Code/Mantid/Testing/Tools/cxxtest/test/tdwt.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/test.pl b/Code/Mantid/Testing/Tools/cxxtest/test/test.pl similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/test.pl rename to Code/Mantid/Testing/Tools/cxxtest/test/test.pl diff --git a/Code/Mantid/TestingTools/cxxtest/test/throw.out b/Code/Mantid/Testing/Tools/cxxtest/test/throw.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/throw.out rename to Code/Mantid/Testing/Tools/cxxtest/test/throw.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/tpltpl.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/tpltpl.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/tpltpl.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/tpltpl.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/unit/LinkedList_test.t.h b/Code/Mantid/Testing/Tools/cxxtest/test/unit/LinkedList_test.t.h similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/unit/LinkedList_test.t.h rename to Code/Mantid/Testing/Tools/cxxtest/test/unit/LinkedList_test.t.h diff --git a/Code/Mantid/TestingTools/cxxtest/test/unit/SConstruct b/Code/Mantid/Testing/Tools/cxxtest/test/unit/SConstruct similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/unit/SConstruct rename to Code/Mantid/Testing/Tools/cxxtest/test/unit/SConstruct diff --git a/Code/Mantid/TestingTools/cxxtest/test/user.out b/Code/Mantid/Testing/Tools/cxxtest/test/user.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/user.out rename to Code/Mantid/Testing/Tools/cxxtest/test/user.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/wchar.cpp b/Code/Mantid/Testing/Tools/cxxtest/test/wchar.cpp similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/wchar.cpp rename to Code/Mantid/Testing/Tools/cxxtest/test/wchar.cpp diff --git a/Code/Mantid/TestingTools/cxxtest/test/wchar.out b/Code/Mantid/Testing/Tools/cxxtest/test/wchar.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/wchar.out rename to Code/Mantid/Testing/Tools/cxxtest/test/wchar.out diff --git a/Code/Mantid/TestingTools/cxxtest/test/wildcard.out b/Code/Mantid/Testing/Tools/cxxtest/test/wildcard.out similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/test/wildcard.out rename to Code/Mantid/Testing/Tools/cxxtest/test/wildcard.out diff --git a/Code/Mantid/TestingTools/cxxtest/www/cn-project-pages/snippets/HtmlSnippet1.html b/Code/Mantid/Testing/Tools/cxxtest/www/cn-project-pages/snippets/HtmlSnippet1.html similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/www/cn-project-pages/snippets/HtmlSnippet1.html rename to Code/Mantid/Testing/Tools/cxxtest/www/cn-project-pages/snippets/HtmlSnippet1.html diff --git a/Code/Mantid/TestingTools/cxxtest/www/cn-project-pages/snippets/page.xml b/Code/Mantid/Testing/Tools/cxxtest/www/cn-project-pages/snippets/page.xml similarity index 100% rename from Code/Mantid/TestingTools/cxxtest/www/cn-project-pages/snippets/page.xml rename to Code/Mantid/Testing/Tools/cxxtest/www/cn-project-pages/snippets/page.xml diff --git a/Code/Mantid/TestingTools/generatetestmain.py b/Code/Mantid/Testing/Tools/generatetestmain.py similarity index 100% rename from Code/Mantid/TestingTools/generatetestmain.py rename to Code/Mantid/Testing/Tools/generatetestmain.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/CHANGES b/Code/Mantid/Testing/Tools/gmock-1.6.0/CHANGES similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/CHANGES rename to Code/Mantid/Testing/Tools/gmock-1.6.0/CHANGES diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/CMakeLists.txt b/Code/Mantid/Testing/Tools/gmock-1.6.0/CMakeLists.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/CMakeLists.txt rename to Code/Mantid/Testing/Tools/gmock-1.6.0/CMakeLists.txt diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/CONTRIBUTORS b/Code/Mantid/Testing/Tools/gmock-1.6.0/CONTRIBUTORS similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/CONTRIBUTORS rename to Code/Mantid/Testing/Tools/gmock-1.6.0/CONTRIBUTORS diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/COPYING b/Code/Mantid/Testing/Tools/gmock-1.6.0/COPYING similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/COPYING rename to Code/Mantid/Testing/Tools/gmock-1.6.0/COPYING diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/Makefile.am b/Code/Mantid/Testing/Tools/gmock-1.6.0/Makefile.am similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/Makefile.am rename to Code/Mantid/Testing/Tools/gmock-1.6.0/Makefile.am diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/Makefile.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/Makefile.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/Makefile.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/Makefile.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/README b/Code/Mantid/Testing/Tools/gmock-1.6.0/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/README rename to Code/Mantid/Testing/Tools/gmock-1.6.0/README diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/aclocal.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/aclocal.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/aclocal.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/aclocal.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.guess b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.guess similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.guess rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.guess diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.h.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.h.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.h.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.h.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.sub b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.sub similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/config.sub rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/config.sub diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/depcomp b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/depcomp similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/depcomp rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/depcomp diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/install-sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/install-sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/install-sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/install-sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/ltmain.sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/ltmain.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/ltmain.sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/ltmain.sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/build-aux/missing b/Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/missing similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/build-aux/missing rename to Code/Mantid/Testing/Tools/gmock-1.6.0/build-aux/missing diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/configure b/Code/Mantid/Testing/Tools/gmock-1.6.0/configure similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/configure rename to Code/Mantid/Testing/Tools/gmock-1.6.0/configure diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/configure.ac b/Code/Mantid/Testing/Tools/gmock-1.6.0/configure.ac similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/configure.ac rename to Code/Mantid/Testing/Tools/gmock-1.6.0/configure.ac diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock-gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock-gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock-gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock-gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock/gmock.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock/gmock.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock/gmock.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock/gmock.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock_main.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gmock_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gmock_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/fused-src/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/fused-src/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/CHANGES b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CHANGES similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/CHANGES rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CHANGES diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/CMakeLists.txt b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CMakeLists.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/CMakeLists.txt rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CMakeLists.txt diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/CONTRIBUTORS b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CONTRIBUTORS similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/CONTRIBUTORS rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/CONTRIBUTORS diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/COPYING b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/COPYING similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/COPYING rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/COPYING diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/Makefile.am b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/Makefile.am similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/Makefile.am rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/Makefile.am diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/Makefile.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/Makefile.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/Makefile.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/Makefile.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/README b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/README rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/README diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/aclocal.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/aclocal.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/aclocal.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/aclocal.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.guess b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.guess similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.guess rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.guess diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.h.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.h.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.h.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.h.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.sub b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.sub similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/config.sub rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/config.sub diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/depcomp b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/depcomp similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/depcomp rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/depcomp diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/install-sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/install-sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/install-sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/install-sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/ltmain.sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/ltmain.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/ltmain.sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/ltmain.sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/missing b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/missing similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/build-aux/missing rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/build-aux/missing diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/cmake/internal_utils.cmake b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/cmake/internal_utils.cmake similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/cmake/internal_utils.cmake rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/cmake/internal_utils.cmake diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest.cbproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest.groupproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest.groupproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest.groupproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest.groupproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_all.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_all.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_link.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_link.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_link.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_link.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_main.cbproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_main.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_main.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_main.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_unittest.cbproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_unittest.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/codegear/gtest_unittest.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/codegear/gtest_unittest.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/configure b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/configure similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/configure rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/configure diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/configure.ac b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/configure.ac similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/configure.ac rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/configure.ac diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest_main.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/fused-src/gtest/gtest_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/fused-src/gtest/gtest_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-death-test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-death-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-death-test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-death-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-message.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-message.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-message.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-message.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-param-test.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-printers.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-printers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-printers.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-printers.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-spi.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-spi.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-spi.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-spi.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-test-part.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-test-part.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-test-part.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-test-part.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-typed-test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-typed-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest-typed-test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest-typed-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest_pred_impl.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest_pred_impl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest_pred_impl.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest_pred_impl.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest_prod.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest_prod.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/gtest_prod.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/gtest_prod.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-death-test-internal.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-death-test-internal.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-death-test-internal.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-death-test-internal.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-filepath.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-filepath.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-filepath.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-filepath.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-internal.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-internal.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-internal.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-internal.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-linked_ptr.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-linked_ptr.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-linked_ptr.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-linked_ptr.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-param-util.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-port.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-port.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-port.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-port.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-string.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-string.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-string.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-string.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-tuple.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/include/gtest/internal/gtest-type-util.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/acx_pthread.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/acx_pthread.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/acx_pthread.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/acx_pthread.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/gtest.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/gtest.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/gtest.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/gtest.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/libtool.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/libtool.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/libtool.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/libtool.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltoptions.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltoptions.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltoptions.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltoptions.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltsugar.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltsugar.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltsugar.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltsugar.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltversion.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltversion.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/ltversion.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/ltversion.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/lt~obsolete.m4 b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/lt~obsolete.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/m4/lt~obsolete.m4 rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/m4/lt~obsolete.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest-md.sln b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest-md.sln similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest-md.sln rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest-md.sln diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest-md.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest-md.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest-md.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest-md.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest.sln b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest.sln similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest.sln rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest.sln diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_main-md.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_main-md.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_main-md.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_main-md.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_main.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_main.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_main.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_main.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_prod_test-md.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_prod_test-md.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_prod_test-md.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_prod_test-md.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_prod_test.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_prod_test.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_prod_test.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_prod_test.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_unittest-md.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_unittest-md.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_unittest-md.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_unittest-md.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_unittest.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_unittest.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/msvc/gtest_unittest.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/msvc/gtest_unittest.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/prime_tables.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/prime_tables.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/prime_tables.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/prime_tables.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample10_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample10_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample10_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample10_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample1_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample1_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample2_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample2_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample3-inl.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample3-inl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample3-inl.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample3-inl.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample3_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample3_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample3_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample3_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample4_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample4_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample5_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample5_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample5_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample5_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample6_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample6_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample6_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample6_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample7_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample7_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample7_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample7_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample8_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample8_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample8_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample8_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample9_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample9_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/samples/sample9_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/samples/sample9_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/fuse_gtest_files.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/fuse_gtest_files.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/fuse_gtest_files.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/fuse_gtest_files.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/gen_gtest_pred_impl.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/gen_gtest_pred_impl.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/gen_gtest_pred_impl.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/gen_gtest_pred_impl.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/gtest-config.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/gtest-config.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/gtest-config.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/gtest-config.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/pump.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/pump.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/scripts/pump.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/scripts/pump.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-death-test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-death-test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-death-test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-death-test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-filepath.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-filepath.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-filepath.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-filepath.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-internal-inl.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-internal-inl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-internal-inl.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-internal-inl.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-port.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-port.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-port.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-port.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-printers.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-printers.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-printers.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-printers.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-test-part.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-test-part.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-test-part.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-test-part.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-typed-test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-typed-test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest-typed-test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest-typed-test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest_main.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/src/gtest_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/src/gtest_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-death-test_ex_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-death-test_ex_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-death-test_ex_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-death-test_ex_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-death-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-death-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-death-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-death-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-filepath_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-filepath_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-filepath_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-filepath_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-linked_ptr_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-linked_ptr_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-linked_ptr_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-linked_ptr_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-listener_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-listener_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-listener_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-listener_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-message_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-message_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-message_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-message_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-options_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-options_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-options_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-options_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test_test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-param-test_test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-param-test_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-port_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-port_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-port_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-port_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-printers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-printers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-printers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-printers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-test-part_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-test-part_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-test-part_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-test-part_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-tuple_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-tuple_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-tuple_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-tuple_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test_test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-typed-test_test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-typed-test_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-unittest-api_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-unittest-api_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest-unittest-api_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest-unittest-api_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_all_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_all_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_all_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_all_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_break_on_failure_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_catch_exceptions_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_color_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_color_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_color_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_color_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_color_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_color_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_color_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_color_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_env_var_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_env_var_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_env_var_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_env_var_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_env_var_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_env_var_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_env_var_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_env_var_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_environment_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_environment_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_environment_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_environment_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_filter_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_filter_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_filter_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_filter_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_filter_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_filter_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_filter_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_filter_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_help_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_help_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_help_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_help_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_help_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_help_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_help_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_help_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_list_tests_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_main_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_main_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_main_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_main_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_no_test_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_no_test_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_no_test_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_no_test_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test_golden_lin.txt b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test_golden_lin.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_output_test_golden_lin.txt rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_output_test_golden_lin.txt diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_pred_impl_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_pred_impl_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_pred_impl_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_pred_impl_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_prod_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_prod_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_prod_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_prod_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_repeat_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_repeat_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_repeat_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_repeat_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_shuffle_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_shuffle_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_shuffle_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_shuffle_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_shuffle_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_shuffle_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_shuffle_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_shuffle_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_sole_header_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_sole_header_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_sole_header_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_sole_header_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_stress_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_stress_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_stress_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_stress_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_test_utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_ex_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_ex_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_ex_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_ex_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_throw_on_failure_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_uninitialized_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_uninitialized_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_uninitialized_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_uninitialized_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_uninitialized_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_uninitialized_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_uninitialized_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_uninitialized_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfile1_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfile1_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfile1_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfile1_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfile2_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfile2_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfile2_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfile2_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfiles_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfiles_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_outfiles_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_outfiles_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_output_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/gtest_xml_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/gtest_xml_test_utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/production.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/production.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/production.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/production.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/production.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/production.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/test/production.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/test/production.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/DebugProject.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/DebugProject.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/DebugProject.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/DebugProject.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/FrameworkTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/FrameworkTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/FrameworkTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/FrameworkTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/General.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/General.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/General.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/General.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/ReleaseProject.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/ReleaseProject.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/ReleaseProject.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/ReleaseProject.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/TestTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/TestTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Config/TestTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Config/TestTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Resources/Info.plist b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Resources/Info.plist similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Resources/Info.plist rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Resources/Info.plist diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/Info.plist b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/Info.plist similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/Info.plist rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/Info.plist diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/runtests.sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/runtests.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/runtests.sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/runtests.sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Scripts/runtests.sh b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Scripts/runtests.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Scripts/runtests.sh rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Scripts/runtests.sh diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Scripts/versiongenerate.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Scripts/versiongenerate.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/Scripts/versiongenerate.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/Scripts/versiongenerate.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/gtest.xcodeproj/project.pbxproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/gtest.xcodeproj/project.pbxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/gtest/xcode/gtest.xcodeproj/project.pbxproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/gtest/xcode/gtest.xcodeproj/project.pbxproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-actions.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-cardinalities.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-cardinalities.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-cardinalities.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-cardinalities.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-actions.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-actions.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-actions.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-actions.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-actions.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-function-mockers.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-matchers.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-generated-nice-strict.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-matchers.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-matchers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-matchers.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-matchers.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-more-actions.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-more-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-more-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-more-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-spec-builders.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-spec-builders.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock-spec-builders.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock-spec-builders.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/gmock.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/gmock.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h.pump b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-generated-internal-utils.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-internal-utils.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-internal-utils.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-internal-utils.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-internal-utils.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-port.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-port.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/include/gmock/internal/gmock-port.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/include/gmock/internal/gmock-port.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock.sln b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock.sln similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock.sln rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock.sln diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_config.vsprops b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_config.vsprops similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_config.vsprops rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_config.vsprops diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_main.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_main.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_main.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_main.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_test.vcproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_test.vcproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2005/gmock_test.vcproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2005/gmock_test.vcproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock.sln b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock.sln similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock.sln rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock.sln diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock.vcxproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock.vcxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock.vcxproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock.vcxproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_config.props b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_config.props similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_config.props rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_config.props diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_main.vcxproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_main.vcxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_main.vcxproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_main.vcxproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_test.vcxproj b/Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_test.vcxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/msvc/2010/gmock_test.vcxproj rename to Code/Mantid/Testing/Tools/gmock-1.6.0/msvc/2010/gmock_test.vcxproj diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/fuse_gmock_files.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/fuse_gmock_files.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/fuse_gmock_files.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/fuse_gmock_files.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/COPYING b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/COPYING similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/COPYING rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/COPYING diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/README b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/README rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/README diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/README.cppclean b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/README.cppclean similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/README.cppclean rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/README.cppclean diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/__init__.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/__init__.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/__init__.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/ast.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/ast.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/ast.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/ast.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/gmock_class.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/gmock_class.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/gmock_class.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/gmock_class.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/keywords.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/keywords.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/keywords.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/keywords.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/tokenize.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/tokenize.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/tokenize.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/tokenize.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/utils.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/cpp/utils.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/cpp/utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/gmock_gen.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/gmock_gen.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/generator/gmock_gen.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/generator/gmock_gen.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/scripts/gmock-config.in b/Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/gmock-config.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/scripts/gmock-config.in rename to Code/Mantid/Testing/Tools/gmock-1.6.0/scripts/gmock-config.in diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-all.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-cardinalities.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-cardinalities.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-cardinalities.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-cardinalities.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-internal-utils.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-internal-utils.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-internal-utils.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-internal-utils.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-matchers.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-matchers.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-matchers.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-matchers.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-spec-builders.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-spec-builders.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock-spec-builders.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock-spec-builders.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/src/gmock_main.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/src/gmock_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/src/gmock_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-cardinalities_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-cardinalities_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-cardinalities_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-cardinalities_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-function-mockers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-function-mockers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-function-mockers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-function-mockers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-internal-utils_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-internal-utils_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-internal-utils_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-internal-utils_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-matchers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-matchers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-generated-matchers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-generated-matchers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-internal-utils_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-internal-utils_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-internal-utils_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-internal-utils_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-matchers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-matchers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-matchers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-matchers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-more-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-more-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-more-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-more-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-nice-strict_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-nice-strict_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-nice-strict_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-nice-strict_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-port_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-port_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-port_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-port_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-spec-builders_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-spec-builders_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock-spec-builders_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock-spec-builders_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_all_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_all_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_all_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_all_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_leak_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_leak_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_leak_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_leak_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_leak_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_leak_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_leak_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_leak_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link_test.h b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_link_test.h rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_link_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test_golden.txt b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test_golden.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_output_test_golden.txt rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_output_test_golden.txt diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_test.cc b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.6.0/test/gmock_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.6.0/test/gmock_test_utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/CHANGES b/Code/Mantid/Testing/Tools/gmock-1.7.0/CHANGES similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/CHANGES rename to Code/Mantid/Testing/Tools/gmock-1.7.0/CHANGES diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/CMakeLists.txt b/Code/Mantid/Testing/Tools/gmock-1.7.0/CMakeLists.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/CMakeLists.txt rename to Code/Mantid/Testing/Tools/gmock-1.7.0/CMakeLists.txt diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/CONTRIBUTORS b/Code/Mantid/Testing/Tools/gmock-1.7.0/CONTRIBUTORS similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/CONTRIBUTORS rename to Code/Mantid/Testing/Tools/gmock-1.7.0/CONTRIBUTORS diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/LICENSE b/Code/Mantid/Testing/Tools/gmock-1.7.0/LICENSE similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/LICENSE rename to Code/Mantid/Testing/Tools/gmock-1.7.0/LICENSE diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/Makefile.am b/Code/Mantid/Testing/Tools/gmock-1.7.0/Makefile.am similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/Makefile.am rename to Code/Mantid/Testing/Tools/gmock-1.7.0/Makefile.am diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/Makefile.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/Makefile.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/Makefile.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/Makefile.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/README b/Code/Mantid/Testing/Tools/gmock-1.7.0/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/README rename to Code/Mantid/Testing/Tools/gmock-1.7.0/README diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/aclocal.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/aclocal.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/aclocal.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/aclocal.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.guess b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.guess similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.guess rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.guess diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.h.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.h.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.h.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.h.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.sub b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.sub similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/config.sub rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/config.sub diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/depcomp b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/depcomp similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/depcomp rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/depcomp diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/install-sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/install-sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/install-sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/install-sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/ltmain.sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/ltmain.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/ltmain.sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/ltmain.sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/build-aux/missing b/Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/missing similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/build-aux/missing rename to Code/Mantid/Testing/Tools/gmock-1.7.0/build-aux/missing diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/configure b/Code/Mantid/Testing/Tools/gmock-1.7.0/configure similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/configure rename to Code/Mantid/Testing/Tools/gmock-1.7.0/configure diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/configure.ac b/Code/Mantid/Testing/Tools/gmock-1.7.0/configure.ac similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/configure.ac rename to Code/Mantid/Testing/Tools/gmock-1.7.0/configure.ac diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock-gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock-gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock-gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock-gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock/gmock.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock/gmock.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock/gmock.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock/gmock.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock_main.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gmock_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gmock_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/fused-src/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/fused-src/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/CHANGES b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CHANGES similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/CHANGES rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CHANGES diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/CMakeLists.txt b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CMakeLists.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/CMakeLists.txt rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CMakeLists.txt diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/CONTRIBUTORS b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CONTRIBUTORS similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/CONTRIBUTORS rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/CONTRIBUTORS diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/LICENSE b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/LICENSE similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/LICENSE rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/LICENSE diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/Makefile.am b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/Makefile.am similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/Makefile.am rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/Makefile.am diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/Makefile.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/Makefile.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/Makefile.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/Makefile.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/README b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/README rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/README diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/aclocal.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/aclocal.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/aclocal.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/aclocal.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.guess b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.guess similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.guess rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.guess diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.h.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.h.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.h.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.h.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.sub b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.sub similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/config.sub rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/config.sub diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/depcomp b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/depcomp similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/depcomp rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/depcomp diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/install-sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/install-sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/install-sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/install-sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/ltmain.sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/ltmain.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/ltmain.sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/ltmain.sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/missing b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/missing similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/build-aux/missing rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/build-aux/missing diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/cmake/internal_utils.cmake b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/cmake/internal_utils.cmake similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/cmake/internal_utils.cmake rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/cmake/internal_utils.cmake diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest.cbproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest.groupproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest.groupproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest.groupproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest.groupproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_all.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_all.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_link.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_link.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_link.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_link.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_main.cbproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_main.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_main.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_main.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_unittest.cbproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_unittest.cbproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/codegear/gtest_unittest.cbproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/codegear/gtest_unittest.cbproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/configure b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/configure similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/configure rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/configure diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/configure.ac b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/configure.ac similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/configure.ac rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/configure.ac diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest_main.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/fused-src/gtest/gtest_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/fused-src/gtest/gtest_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-death-test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-death-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-death-test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-death-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-message.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-message.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-message.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-message.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-param-test.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-printers.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-printers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-printers.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-printers.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-spi.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-spi.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-spi.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-spi.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-test-part.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-test-part.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-test-part.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-test-part.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-typed-test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-typed-test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest-typed-test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest-typed-test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest_pred_impl.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest_pred_impl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest_pred_impl.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest_pred_impl.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest_prod.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest_prod.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/gtest_prod.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/gtest_prod.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-death-test-internal.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-death-test-internal.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-death-test-internal.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-death-test-internal.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-filepath.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-filepath.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-filepath.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-filepath.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-internal.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-internal.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-internal.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-internal.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-linked_ptr.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-linked_ptr.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-linked_ptr.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-linked_ptr.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util-generated.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-param-util.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-port.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-port.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-port.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-port.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-string.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-string.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-string.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-string.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-tuple.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/include/gtest/internal/gtest-type-util.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/acx_pthread.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/acx_pthread.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/acx_pthread.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/acx_pthread.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/gtest.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/gtest.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/gtest.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/gtest.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/libtool.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/libtool.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/libtool.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/libtool.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltoptions.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltoptions.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltoptions.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltoptions.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltsugar.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltsugar.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltsugar.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltsugar.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltversion.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltversion.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/ltversion.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/ltversion.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/lt~obsolete.m4 b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/lt~obsolete.m4 similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/m4/lt~obsolete.m4 rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/m4/lt~obsolete.m4 diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/prime_tables.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/prime_tables.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/prime_tables.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/prime_tables.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample10_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample10_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample10_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample10_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample1_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample1_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample2_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample2_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample3-inl.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample3-inl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample3-inl.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample3-inl.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample3_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample3_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample3_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample3_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample4_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample4_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample5_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample5_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample5_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample5_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample6_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample6_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample6_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample6_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample7_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample7_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample7_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample7_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample8_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample8_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample8_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample8_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample9_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample9_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/samples/sample9_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/samples/sample9_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/fuse_gtest_files.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/fuse_gtest_files.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/fuse_gtest_files.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/fuse_gtest_files.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/gen_gtest_pred_impl.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/gen_gtest_pred_impl.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/gen_gtest_pred_impl.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/gen_gtest_pred_impl.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/gtest-config.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/gtest-config.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/gtest-config.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/gtest-config.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/pump.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/pump.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/scripts/pump.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/scripts/pump.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-all.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-death-test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-death-test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-death-test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-death-test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-filepath.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-filepath.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-filepath.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-filepath.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-internal-inl.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-internal-inl.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-internal-inl.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-internal-inl.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-port.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-port.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-port.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-port.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-printers.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-printers.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-printers.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-printers.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-test-part.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-test-part.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-test-part.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-test-part.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-typed-test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-typed-test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest-typed-test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest-typed-test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest_main.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/src/gtest_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/src/gtest_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-death-test_ex_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-death-test_ex_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-death-test_ex_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-death-test_ex_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-death-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-death-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-death-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-death-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-filepath_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-filepath_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-filepath_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-filepath_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-linked_ptr_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-linked_ptr_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-linked_ptr_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-linked_ptr_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-listener_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-listener_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-listener_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-listener_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-message_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-message_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-message_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-message_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-options_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-options_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-options_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-options_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test_test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-param-test_test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-param-test_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-port_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-port_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-port_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-port_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-printers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-printers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-printers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-printers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-test-part_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-test-part_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-test-part_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-test-part_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-tuple_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-tuple_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-tuple_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-tuple_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test_test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-typed-test_test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-typed-test_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-unittest-api_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-unittest-api_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest-unittest-api_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest-unittest-api_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_all_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_all_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_all_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_all_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_break_on_failure_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_catch_exceptions_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_color_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_color_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_color_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_color_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_color_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_color_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_color_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_color_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_env_var_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_env_var_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_env_var_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_env_var_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_env_var_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_env_var_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_env_var_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_env_var_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_environment_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_environment_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_environment_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_environment_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_filter_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_filter_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_filter_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_filter_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_filter_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_filter_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_filter_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_filter_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_help_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_help_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_help_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_help_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_help_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_help_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_help_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_help_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_list_tests_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_main_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_main_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_main_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_main_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_no_test_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_no_test_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_no_test_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_no_test_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test_golden_lin.txt b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test_golden_lin.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_output_test_golden_lin.txt rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_output_test_golden_lin.txt diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_pred_impl_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_pred_impl_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_pred_impl_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_pred_impl_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_premature_exit_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_premature_exit_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_premature_exit_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_premature_exit_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_prod_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_prod_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_prod_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_prod_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_repeat_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_repeat_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_repeat_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_repeat_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_shuffle_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_shuffle_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_shuffle_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_shuffle_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_shuffle_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_shuffle_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_shuffle_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_shuffle_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_sole_header_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_sole_header_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_sole_header_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_sole_header_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_stress_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_stress_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_stress_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_stress_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_test_utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_ex_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_ex_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_ex_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_ex_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_throw_on_failure_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_uninitialized_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_uninitialized_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_uninitialized_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_uninitialized_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_uninitialized_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_uninitialized_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_uninitialized_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_uninitialized_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_unittest.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_unittest.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_unittest.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_unittest.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfile1_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfile1_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfile1_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfile1_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfile2_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfile2_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfile2_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfile2_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfiles_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfiles_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_outfiles_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_outfiles_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_output_unittest_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/gtest_xml_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/gtest_xml_test_utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/production.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/production.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/production.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/production.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/production.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/production.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/test/production.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/test/production.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/DebugProject.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/DebugProject.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/DebugProject.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/DebugProject.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/FrameworkTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/FrameworkTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/FrameworkTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/FrameworkTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/General.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/General.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/General.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/General.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/ReleaseProject.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/ReleaseProject.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/ReleaseProject.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/ReleaseProject.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/StaticLibraryTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/TestTarget.xcconfig b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/TestTarget.xcconfig similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Config/TestTarget.xcconfig rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Config/TestTarget.xcconfig diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Resources/Info.plist b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Resources/Info.plist similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Resources/Info.plist rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Resources/Info.plist diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/Info.plist b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/Info.plist similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/Info.plist rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/Info.plist diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/WidgetFramework.xcodeproj/project.pbxproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/runtests.sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/runtests.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/runtests.sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/runtests.sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Samples/FrameworkSample/widget_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Scripts/runtests.sh b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Scripts/runtests.sh similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Scripts/runtests.sh rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Scripts/runtests.sh diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Scripts/versiongenerate.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Scripts/versiongenerate.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/Scripts/versiongenerate.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/Scripts/versiongenerate.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/gtest.xcodeproj/project.pbxproj b/Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/gtest.xcodeproj/project.pbxproj similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/gtest/xcode/gtest.xcodeproj/project.pbxproj rename to Code/Mantid/Testing/Tools/gmock-1.7.0/gtest/xcode/gtest.xcodeproj/project.pbxproj diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-actions.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-cardinalities.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-cardinalities.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-cardinalities.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-cardinalities.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-actions.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-actions.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-actions.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-actions.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-actions.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-function-mockers.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-matchers.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-generated-nice-strict.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-matchers.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-matchers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-matchers.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-matchers.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-more-actions.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-more-actions.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-more-actions.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-more-actions.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-more-matchers.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-more-matchers.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-more-matchers.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-more-matchers.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-spec-builders.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-spec-builders.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock-spec-builders.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock-spec-builders.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/gmock.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/gmock.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h.pump b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h.pump similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h.pump rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-generated-internal-utils.h.pump diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-internal-utils.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-internal-utils.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-internal-utils.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-internal-utils.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-port.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-port.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/include/gmock/internal/gmock-port.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/include/gmock/internal/gmock-port.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/msvc/2005/gmock_config.vsprops b/Code/Mantid/Testing/Tools/gmock-1.7.0/msvc/2005/gmock_config.vsprops similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/msvc/2005/gmock_config.vsprops rename to Code/Mantid/Testing/Tools/gmock-1.7.0/msvc/2005/gmock_config.vsprops diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/msvc/2010/gmock_config.props b/Code/Mantid/Testing/Tools/gmock-1.7.0/msvc/2010/gmock_config.props similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/msvc/2010/gmock_config.props rename to Code/Mantid/Testing/Tools/gmock-1.7.0/msvc/2010/gmock_config.props diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/fuse_gmock_files.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/fuse_gmock_files.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/fuse_gmock_files.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/fuse_gmock_files.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/LICENSE b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/LICENSE similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/LICENSE rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/LICENSE diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/README b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/README similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/README rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/README diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/README.cppclean b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/README.cppclean similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/README.cppclean rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/README.cppclean diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/__init__.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/__init__.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/__init__.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/ast.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/ast.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/ast.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/ast.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/gmock_class.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/gmock_class.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/gmock_class.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/gmock_class.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/keywords.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/keywords.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/keywords.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/keywords.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/tokenize.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/tokenize.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/tokenize.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/tokenize.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/utils.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/cpp/utils.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/cpp/utils.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/gmock_gen.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/gmock_gen.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/generator/gmock_gen.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/generator/gmock_gen.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/scripts/gmock-config.in b/Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/gmock-config.in similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/scripts/gmock-config.in rename to Code/Mantid/Testing/Tools/gmock-1.7.0/scripts/gmock-config.in diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-all.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-all.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-all.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-all.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-cardinalities.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-cardinalities.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-cardinalities.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-cardinalities.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-internal-utils.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-internal-utils.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-internal-utils.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-internal-utils.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-matchers.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-matchers.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-matchers.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-matchers.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-spec-builders.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-spec-builders.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock-spec-builders.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock-spec-builders.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/src/gmock_main.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock_main.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/src/gmock_main.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/src/gmock_main.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-cardinalities_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-cardinalities_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-cardinalities_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-cardinalities_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-function-mockers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-function-mockers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-function-mockers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-function-mockers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-internal-utils_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-internal-utils_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-internal-utils_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-internal-utils_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-matchers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-matchers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-generated-matchers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-generated-matchers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-internal-utils_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-internal-utils_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-internal-utils_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-internal-utils_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-matchers_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-matchers_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-matchers_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-matchers_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-more-actions_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-more-actions_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-more-actions_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-more-actions_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-nice-strict_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-nice-strict_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-nice-strict_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-nice-strict_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-port_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-port_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-port_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-port_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-spec-builders_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-spec-builders_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock-spec-builders_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock-spec-builders_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_all_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_all_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_all_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_all_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_ex_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_ex_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_ex_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_ex_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_leak_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_leak_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_leak_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_leak_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_leak_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_leak_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_leak_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_leak_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link2_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link2_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link2_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link2_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link_test.h b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link_test.h similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_link_test.h rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_link_test.h diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test.py diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test_.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test_.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test_.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test_.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test_golden.txt b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test_golden.txt similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_output_test_golden.txt rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_output_test_golden.txt diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_stress_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_stress_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_stress_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_stress_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_test.cc b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_test.cc similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_test.cc rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_test.cc diff --git a/Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_test_utils.py b/Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_test_utils.py similarity index 100% rename from Code/Mantid/TestingTools/gmock-1.7.0/test/gmock_test_utils.py rename to Code/Mantid/Testing/Tools/gmock-1.7.0/test/gmock_test_utils.py diff --git a/Code/Mantid/TestingTools/pyunit_gen/pyunit_gen.py b/Code/Mantid/Testing/Tools/pyunit_gen/pyunit_gen.py similarity index 100% rename from Code/Mantid/TestingTools/pyunit_gen/pyunit_gen.py rename to Code/Mantid/Testing/Tools/pyunit_gen/pyunit_gen.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/LICENSE b/Code/Mantid/Testing/Tools/unittest-xml-reporting/LICENSE similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/LICENSE rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/LICENSE diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/MANIFEST.in b/Code/Mantid/Testing/Tools/unittest-xml-reporting/MANIFEST.in similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/MANIFEST.in rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/MANIFEST.in diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/README.rst b/Code/Mantid/Testing/Tools/unittest-xml-reporting/README.rst similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/README.rst rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/README.rst diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/fabfile.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/fabfile.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/fabfile.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/fabfile.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/setup.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/setup.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/setup.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/setup.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/__init__.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/__init__.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/__init__.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/extra/__init__.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/extra/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/extra/__init__.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/extra/__init__.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/extra/djangotestrunner.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/extra/djangotestrunner.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/extra/djangotestrunner.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/extra/djangotestrunner.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/__init__.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/__init__.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/__init__.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/__init__.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/errord_test_case.xml b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/errord_test_case.xml similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/errord_test_case.xml rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/errord_test_case.xml diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/failed_test_case.xml b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/failed_test_case.xml similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/failed_test_case.xml rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/failed_test_case.xml diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/mixed_test_case.xml b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/mixed_test_case.xml similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/mixed_test_case.xml rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/mixed_test_case.xml diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/successful_test_case.xml b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/successful_test_case.xml similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/successful_test_case.xml rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/fixtures/successful_test_case.xml diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/testsuite.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/testsuite.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/testsuite.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/testsuite.py diff --git a/Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/testsuite_cases.py b/Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/testsuite_cases.py similarity index 100% rename from Code/Mantid/TestingTools/unittest-xml-reporting/src/xmlrunner/tests/testsuite_cases.py rename to Code/Mantid/Testing/Tools/unittest-xml-reporting/src/xmlrunner/tests/testsuite_cases.py diff --git a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/MDEWRebinningCutterOperator/CMakeLists.txt b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/MDEWRebinningCutterOperator/CMakeLists.txt index de4001a08005..605bc5c0a1e6 100644 --- a/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/MDEWRebinningCutterOperator/CMakeLists.txt +++ b/Code/Mantid/Vates/ParaviewPlugins/ParaViewFilters/MDEWRebinningCutterOperator/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required( VERSION 2.6) +cmake_minimum_required( VERSION 2.8.12 ) project( MantidParaViewMDEWRebinningCutter ) add_paraview_plugin( MantidParaViewMDEWRebinningCutterSMPlugin "1.0" diff --git a/Code/Mantid/Vates/VatesAPI/CMakeLists.txt b/Code/Mantid/Vates/VatesAPI/CMakeLists.txt index 72465397a248..8384d524d947 100644 --- a/Code/Mantid/Vates/VatesAPI/CMakeLists.txt +++ b/Code/Mantid/Vates/VatesAPI/CMakeLists.txt @@ -1,5 +1,5 @@ # This is mainly here so you don't get a complaint when running cmake -cmake_minimum_required( VERSION 2.6 ) +cmake_minimum_required( VERSION 2.8.12 ) project( VatesAPI ) diff --git a/Code/Mantid/Vates/VatesAPI/test/runTests.sh b/Code/Mantid/Vates/VatesAPI/test/runTests.sh deleted file mode 100755 index b223a9bad41b..000000000000 --- a/Code/Mantid/Vates/VatesAPI/test/runTests.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/bin/bash -# Simple script to build and run the tests. -# Will run all tests in the directory if no arguments are supplied, -# or alternatively just the test files given as arguments. -# -# You will need to have the directories containing the Mantid -# .so libraries in your LD_LIBRARY_PATH environment variable -# -# Author: Owen Arnold 02/12/2010 -# - -# Clean up any old executable -rm -rf runner.* - -echo "Generating the source file from the test header files..." -# Chaining all tests together can have effects that you don't think of -# - it's always a good idea to run your new/changed test on its own -test_files="" -if [ $# -eq 0 ]; then - test_files=*.h -else - test_files=$* -fi - -cxxtestgen=../../../../Third_Party/src/cxxtest/cxxtestgen.py -python $cxxtestgen --runner=MantidPrinter -o runner.cpp $test_files - - -echo "Compiling the test executable..." - -#TODO set path properly -mantid_libpath=~/workspace/MantidDebug/bin -#TODO set path properly -vtk_libpath=/usr/local/2.1.1/linux-x86_64/lib -#TODO set path properly -gmock_libpath=../../../TestingTools/lib/ubuntu-10.10 - -g++ -O0 -g3 -DBOOST_DATE_TIME_POSIX_TIME_STD_CONFIG -o runner.exe runner.cpp -I../../../Framework/Kernel/inc -I../../../Framework/MDAlgorithms/inc -I../../../Framework/API/inc -I../inc/VisitPlugins -I/usr/local/2.1.1/linux-x86_64/include/vtk/include/vtk-5.0 -I../../../Framework/Geometry/inc -I ../inc \ - -I ../../../../Third_Party/src/cxxtest -I ../../../../Third_Party/include -I ../../../TestingTools/include -L$vtk_libpath -L$mantid_libpath -L$gmock_libpath -lvtkCommon -lvtkFiltering -lMantidKernel -lMantidGeometry -lMantidAPI -lboost_date_time-mt -lgmock -lMantidMDAlgorithms -lMantidDataObjects -lMantidVisitPresenters -lhdf5 -Wno-deprecated - -echo - -echo "Running the tests..." -ln ../../../Framework/Build/Tests/*.properties . -LD_LIBRARY_PATH=$vtk_libpath:$mantid_libpath:$LD_LIBRARY_PATH ./runner.exe -#valgrind --leak-check=full --show-reachable=yes --track-origins=yes ~/mantid/Code/Vates/VisitPresenters/test/runner.exe -echo - -# Remove the generated files to ensure that they're not inadvertently run -# when something in the chain has failed. -echo "Cleaning up..." -rm -f *.properties -rm -f *Test.log -rm -f *.so -echo "Done." diff --git a/Code/Mantid/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h b/Code/Mantid/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h index 025bf2135fd1..5e4fb59411a2 100644 --- a/Code/Mantid/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h +++ b/Code/Mantid/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h @@ -36,7 +36,7 @@ class MockPeaksWorkspace : public PeaksWorkspace MOCK_METHOD1(addPeak, void (const IPeak& ipeak)); MOCK_METHOD1(getPeak, Mantid::DataObjects::Peak & (int peakNum)); MOCK_CONST_METHOD1(getPeak, const Mantid::DataObjects::Peak & (int peakNum)); - MOCK_CONST_METHOD2(createPeak, Mantid::API::IPeak* (Mantid::Kernel::V3D QLabFrame, double detectorDistance)); + MOCK_CONST_METHOD2(createPeak, Mantid::API::IPeak* (Mantid::Kernel::V3D QLabFrame, boost::optional detectorDistance)); }; //===================================================================================== diff --git a/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt b/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt index 974b1551cf30..0b35b412adfe 100644 --- a/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt +++ b/Code/Mantid/Vates/VatesSimpleGui/StandAloneExec/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required( VERSION 2.8 ) +cmake_minimum_required( VERSION 2.8.12 ) project( VatesSimpleGui ) set( PROJECT_NAME VatesSimpleGui ) diff --git a/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst b/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst new file mode 100644 index 000000000000..ab768f8c24c9 --- /dev/null +++ b/Code/Mantid/docs/source/algorithms/AddPeakHKL-v1.rst @@ -0,0 +1,62 @@ + +.. algorithm:: + +.. summary:: + +.. alias:: + +.. properties:: + +Description +----------- + +Add a peak in the HKL frame to an existing :ref:`PeaksWorkspace `. The OrientedLattice must be provided and the Goniometer should be set correctly before running the algorithm. + +The peak is added to the existing PeaksWorkspace. Run information and goniometer setting and the UB matrix are taken from the provided PeaksWorkspace. + + +Usage +----- + +**Example - AddPeakHKL** + +.. testcode:: AddPeakHKLExample + + import os + import numpy + import mantid.kernel + + # Create an instrument workspace + inst_dir = config.getInstrumentDirectory() + sxd_ws = LoadEmptyInstrument(os.path.join(inst_dir, "SXD_Definition.xml")) + AddSampleLog(sxd_ws, 'run_number', '1', 'Number') + + # Create a peaks workspace from the instrument workspace + peak_ws = CreatePeaksWorkspace(InstrumentWorkspace=sxd_ws, NumberOfPeaks=0) + peak_ws.mutableRun().addProperty('run_number', sxd_ws.run().getProperty('run_number'), True) + + # Apply a UB + ub = numpy.array([[-0.15097235, 0.09164432, 0.00519473], [ 0.0831895, 0.14123681, -0.06719047], [-0.03845029, -0.05534039, -0.1633801 ]]) + SetUB(peak_ws, UB=ub) + + # Add a new peak + AddPeakHKL(peak_ws, [2, 0, -4]) + + # Get info on newly added peak + peak = peak_ws.getPeak(0) + print 'Peak wavelength', round(peak.getWavelength(), 4) + print 'Peak detector id', peak.getDetectorID() + print 'Peak run number', peak.getRunNumber() + print 'Peak HKL', peak.getHKL() + +Output: + +.. testoutput:: AddPeakHKLExample + + Peak wavelength 1.8423 + Peak detector id 25766 + Peak run number 1 + Peak HKL [2,0,-4] + +.. categories:: + diff --git a/Code/Mantid/docs/source/algorithms/CalculateSampleTransmission-v1.rst b/Code/Mantid/docs/source/algorithms/CalculateSampleTransmission-v1.rst index 1c23cbd58680..770b301f127a 100644 --- a/Code/Mantid/docs/source/algorithms/CalculateSampleTransmission-v1.rst +++ b/Code/Mantid/docs/source/algorithms/CalculateSampleTransmission-v1.rst @@ -17,6 +17,8 @@ The sample chemical formula is input for the :ref:`SetSampleMaterial number density & thickness is input to then calculate the percentage scattering & transmission. +A flat plate sample which is perpendicular to the beam is assumed. + Usage ----- diff --git a/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst b/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst index 7eaaace49bfb..207d22da111a 100644 --- a/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst +++ b/Code/Mantid/docs/source/algorithms/GenerateEventsFilter-v1.rst @@ -70,6 +70,12 @@ this algorithm: workspace index associated. These workspace indices are incremented by 1 from 0 along with their orders in time. +- A series of filters for multiple continuous time intervals, which + have various lengths of period. + Each of them has an individual workspace index associated. + These workspace indices are incremented by 1 from 0 along with their + order in time. + - A filter containing one or multiple time intervals according to a specified log value. Any log value of the time that falls into the selected time intervals is equal or within the tolerance of a user @@ -81,9 +87,35 @@ this algorithm: equal or within the tolerance of the log value as v\_0 + n x delta\_v +/- tolerance\_v. +Generate event filters by time +############################## + +Event filters can be created by defining start time, stop time and time intervals. +The three input properties for them are *StartTime*, *StopTime* and *TimeInterval*, +respectively. + +*TimeInterval* accepts an array of doubles. +If the array size is zero, then there will be one and only splitter will be +created from *StartTime* and *StopTime*. +If the size of the array is one, then all event splitters will have the same duration +of time. +In general if the array is composed as :math:`t_1, t_2, \cdots, t_n`, +and :math:`T_0` is the run start time, +then the event splitters will have the time boudaries as + +.. math:: (T_0, T_0+t_1), (T_0+t_1, T_0+t_1+t_2), \cdots, (T_0+\sum_{i=1}^{n-1}t_i, T_0+\sum_{i=1}^nt_i), (T_0+\sum_{i=1}^nt_i, T_0+\sum_{i=1}^nt_i+t_1), \cdots + +until the stop time is reached. + +Unit of time +============ + +There are three types of units that are supported for time. +They are second, nanosecond and percentage of duration from *StartTime* to *StopTime*. + Generate event filters by sample log value -========================================== +########################################## The sample log will be divided to intervals as :math:`v_0, v_1, \cdots, v_{i-1}, v_i, v_{i+1}, \cdots`. All log entries, whose values falls into range :math:`[v_j, v_{j+1})`, will be assigned to @@ -91,7 +123,7 @@ a same workspace group. About how log value is recorded -############################### +=============================== SNS DAS records log values upon its changing. The frequency of log sampling is significantly faster than change of the log, i.e., sample @@ -101,7 +133,7 @@ log value changes as step functions. The option to do interpolation is not supported at this moment. Comparison to FilterByLogValue -############################## +============================== 1. If the first log value is within the specified range and the first log time is after run star time, FilterByLogValue assumes that the log 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/algorithms/IntegrateEllipsoids-v1.rst b/Code/Mantid/docs/source/algorithms/IntegrateEllipsoids-v1.rst index ef8e0f5483f0..c64b003e7668 100644 --- a/Code/Mantid/docs/source/algorithms/IntegrateEllipsoids-v1.rst +++ b/Code/Mantid/docs/source/algorithms/IntegrateEllipsoids-v1.rst @@ -110,7 +110,7 @@ added to the list of events for a peak provided that the fractional :math:`Q` -vector) is closer to the :math:`h,k,l` of that peak, than to the :math:`h,k,l` of any other peak AND the :math:`Q` -vector for that event is within the specified -radius of the :math:`Q` -vector for that peak. +radius of the :math:`Q` -vector for that peak. This technique makes the algorithm suitable for nuclear peaks, but may not be suitable for magnetic peaks. When the lists of events near the peaks have been built, the three principal axes of the set of events near each peak are found, and the @@ -155,6 +155,8 @@ ellipsoid. The outer surface of the background ellipsoidal shell is an ellipsoidal surface with the same relative axis lengths as the inner surface. +This algorithm uses principle component analysis to determine the principle axis for each peak. For the event list (QLab) associated with each peak, the algorithm determines a covariance matrix, and uses that to establish eigenvectors corresponding to the principle axis (all orthogonal). The sizes of each principle axis are used define the region of which events will be counted/integrated from those already associated with each peak. + Usage ------ diff --git a/Code/Mantid/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst b/Code/Mantid/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst index 4783efc33ea0..7e1340f2dfcb 100644 --- a/Code/Mantid/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst +++ b/Code/Mantid/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst @@ -9,12 +9,9 @@ Description ----------- -Load parameters from a GSAS instrument file into a table workspace +Load Ikeda-Carpenter PV parameters from a GSAS instrument file into a table workspace or a workspace group. -Later developments of this algorithm will enable these parameters to be -put into the instrument of a wotrkspace for either Ikeda-Carpender -pseudo-Voigt translated into :ref:`IkedaCarpenterPV ` or -back-to-back-exponential pseudo-Voigt translated into +Later developments of this algorithm will enable to load back-to-back-exponential pseudo-Voigt parameters translated into :ref:`BackToBackExponential `. @@ -28,8 +25,6 @@ Usage .. testcode:: ExLoadGSASInstrumentFileSimple # We load a GSAS Instrument file with 2 Banks - # which will suit MUSR00015189 at a later stage of devolpment - tws = LoadGSASInstrumentFile("GSAS_2bank.prm") #Print first four rows @@ -46,4 +41,47 @@ Output: {'Name': 'Alph1','Value_1': 0.21, 'Value_2': 0.22} {'Name': 'Beta0','Value_1': 31.79, 'Value_2': 31.79} + +**Example - Run LoadGSASInstrumentFile and put parameters into workspace** + +.. include:: ../usagedata-note.txt + +.. testcode:: ExLoadGSASInstrumentFileWorkspace + + # First we load MUSR00015189 workspace group + Load("MUSR00015189",OutputWorkspace="groupWs") + groupWs=mtd["groupWs"] + # We clear instrument parameters... + ClearInstrumentParameters(groupWs) + + # ...and check they do not exist + instrument = groupWs.getItem(0).getInstrument() + print "Alpha0 parameter exists: ", instrument.hasParameter("Alpha0") + print "Beta0 parameter exists: ", instrument.hasParameter("Beta0") + print "SigmaSquared parameter exists: " , instrument.hasParameter("SigmaSquared") + + # Now we load a GSAS Instrument file with 2 Banks into the workspace... + print "\nLoading parameters from GSAS\n" + tws = LoadGSASInstrumentFile(Filename="GSAS_2bank.prm",UseBankIDsInFile=True,Workspace=groupWs,Banks=[1,2]) + + # ...and check parameters are there again + instrument = groupWs.getItem(0).getInstrument() + print "Alpha0 parameter exists: ", instrument.hasParameter("Alpha0") + print "Beta0 parameter exists: ", instrument.hasParameter("Beta0") + print "SigmaSquared parameter exists: " , instrument.hasParameter("SigmaSquared") + +Output: + +.. testoutput:: ExLoadGSASInstrumentFileWorkspace + + Alpha0 parameter exists: False + Beta0 parameter exists: False + SigmaSquared parameter exists: False + + Loading parameters from GSAS + + Alpha0 parameter exists: True + Beta0 parameter exists: True + SigmaSquared parameter exists: True + .. categories:: diff --git a/Code/Mantid/docs/source/algorithms/MDNormDirectSC-v1.rst b/Code/Mantid/docs/source/algorithms/MDNormDirectSC-v1.rst index 3044493549f1..d59635e54692 100644 --- a/Code/Mantid/docs/source/algorithms/MDNormDirectSC-v1.rst +++ b/Code/Mantid/docs/source/algorithms/MDNormDirectSC-v1.rst @@ -63,8 +63,9 @@ Usage AlignedDim0="[H,0,0],-0.2,1.6,100", AlignedDim1="DeltaE,-1.5,3.,100", ) - normalized=histoData/histoNorm - print "The normalization workspace shape is "+str(histoNorm.getSignalArray().shape) + normalized=histoData/histoNorm + histoShape=histoNorm.getSignalArray().shape + print "The normalization workspace shape is (%d, %d)" % histoShape print "Out of those elements, "+str(nonzero(histoNorm.getSignalArray())[0].size)+" are nonzero" .. testoutput:: MDNormDirectSCExample diff --git a/Code/Mantid/docs/source/algorithms/PlotAsymmetryByLogValue-v1.rst b/Code/Mantid/docs/source/algorithms/PlotAsymmetryByLogValue-v1.rst index 0b65fd8ae3dd..f091f41e8c53 100644 --- a/Code/Mantid/docs/source/algorithms/PlotAsymmetryByLogValue-v1.rst +++ b/Code/Mantid/docs/source/algorithms/PlotAsymmetryByLogValue-v1.rst @@ -141,4 +141,22 @@ Output: Y values (asymmetry): [ 0.14542059 0.13674275 0.12017568] X values (sample magn. field): [ 1350. 1360. 1370.] +**Example - Calculating asymmetry as a function of the sample mean temperature:** + +.. testcode:: ExLogValueFunction + + ws = PlotAsymmetryByLogValue(FirstRun="MUSR00015189", + LastRun="MUSR00015191", + LogValue="sample_temp", + Function="Mean") + print "Y values (asymmetry):", ws.readY(0) + print "X values (sample magn. field):", ws.readX(0) + +Output: + +.. testoutput:: ExLogValueFunction + + Y values (asymmetry): [ 0.15004357 0.14289412 0.12837688] + X values (sample magn. field): [ 290. 290. 290.] + .. categories:: diff --git a/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst b/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst index 3715ca27c786..19e0858e28f7 100644 --- a/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst +++ b/Code/Mantid/docs/source/algorithms/SaveIsawPeaks-v1.rst @@ -9,7 +9,9 @@ Description ----------- -Save a PeaksWorkspace to a ISAW-style ASCII .peaks file. +Save a :ref:`PeaksWorkspace ` to a ISAW-style ASCII .peaks file. + +The :ref:`PeaksWorkspace ` consists of individual Peaks, each of which has an individual PeakShape relating to the way the workspace has been integrated. The PeakShape information is not saved out in the ISAW peaks format. To save the full peak information, use the NeXus format :ref:`SaveNexus `. Usage ----- diff --git a/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst b/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst index fc238c47314c..57b0f920bea2 100644 --- a/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst +++ b/Code/Mantid/docs/source/algorithms/StartLiveData-v1.rst @@ -77,9 +77,9 @@ you can do by your available memory and CPUs. Usage ----- -**Example:** +**Example 1:** -.. testcode:: exStartLiveData +.. testcode:: exStartLiveDataEvent from threading import Thread import time @@ -135,9 +135,77 @@ Usage Output: -.. testoutput:: exStartLiveData +.. testoutput:: exStartLiveDataEvent :options: +ELLIPSIS, +NORMALIZE_WHITESPACE The workspace contains ... events + + +**Example 2:** + +.. testcode:: exStartLiveDataHisto + + from threading import Thread + import time + + def startFakeDAE(): + # This will generate 5 periods of histogram data, 10 spectra in each period, + # 100 bins in each spectrum + try: + FakeISISHistoDAE(NPeriods=5,NSpectra=10,NBins=100) + except RuntimeError: + pass + + def captureLive(): + ConfigService.setFacility("TEST_LIVE") + + # Start a Live data listener updating every second, + # that replaces the results each time with those of the last second. + # Load only spectra 2,4, and 6 from periods 1 and 3 + StartLiveData(Instrument='ISIS_Histogram', OutputWorkspace='wsOut', UpdateEvery=1, + AccumulationMethod='Replace', PeriodList=[1,3],SpectraList=[2,4,6]) + + # give it a couple of seconds before stopping it + time.sleep(2) + + # This will cancel both algorithms + # you can do the same in the GUI + # by clicking on the details button on the bottom right + AlgorithmManager.newestInstanceOf("MonitorLiveData").cancel() + AlgorithmManager.newestInstanceOf("FakeISISHistoDAE").cancel() + #-------------------------------------------------------------------------------------------------- + + oldFacility = ConfigService.getFacility().name() + thread = Thread(target = startFakeDAE) + thread.start() + time.sleep(2) # give it a small amount of time to get ready + if not thread.is_alive(): + raise RuntimeError("Unable to start FakeDAE") + + try: + captureLive() + except Exception, exc: + print "Error occurred starting live data" + finally: + thread.join() # this must get hit + + # put back the facility + ConfigService.setFacility(oldFacility) + + #get the ouput workspace + wsOut = mtd["wsOut"] + print "The workspace contains %i periods" % wsOut.getNumberOfEntries() + print "Each period contains %i spectra" % wsOut.getItem(0).getNumberHistograms() + time.sleep(1) + +Output: + +.. testoutput:: exStartLiveDataHisto + :options: +ELLIPSIS, +NORMALIZE_WHITESPACE + + The workspace contains ... periods + Each period contains ... spectra + + .. categories:: diff --git a/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst b/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst index 582398fdb5b5..e6a32575ab9a 100644 --- a/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst +++ b/Code/Mantid/docs/source/concepts/PeaksWorkspace.rst @@ -1,12 +1,10 @@ -.. _PeaksWorkspace: - PeaksWorkspace -============== +=============== The PeaksWorkspace is a special Workspace that holds a list of single crystal Peak objects. Creating a PeaksWorkspace -------------------------- +-------------------------- * :ref:`FindPeaksMD ` will find peaks in reciprocal space in a :ref:`MDWorkspace `. * :ref:`FindSXPeaks ` will find peaks in detector space. @@ -16,15 +14,16 @@ Creating a PeaksWorkspace * :ref:`CreatePeaksWorkspace ` will create an empty PeaksWorkspace that you can then edit. Viewing a PeaksWorkspace ------------------------- +-------------------------- * Double-click a PeaksWorkspace to see the full list of data of each Peak object. * In MantidPlot, you can drag/drop a PeaksWorkspace from the list of workspaces onto the `Instrument View `__ . This will overlay the peaks onto the detector face. -* Right-click a PeaksWorkspace and select the menu to show the peak positions in 3D in the `VatesSimpleInterface `__ . +* Right-click a PeaksWorkspace and select the menu to show the peak positions in 3D in the `VatesSimpleInterface `__ * In paraview, you can load a .Peaks file loader plugin to view a PeaksWorkspace. +* `PeaksViewer `__ in the `SliceViewer `__ The Peak Object ---------------- +-------------------------- Each peak object contains several pieces of information. Not all of them are necessary: @@ -34,14 +33,27 @@ Each peak object contains several pieces of information. Not all of them are nec * Goniometer rotation matrix (for finding Q in the sample frame) * Integrated intensity and error (optional) * Row/column of detector (only for :ref:`RectangularDetectors ` ) +* An integration shape (see below) + +The Peak Shape +~~~~~~~~~~~~~~~ + +Each Peak object contains a PeakShape. Only the integration algorithms which act on, and return PeaksWorkspaces set the shape of the peaks. The PeakShape is owned by the Peak, not the PeaksWorkspace, so when PeaksWorkspaces are split, or concatinated, the integration shapes are unaltered. Aside from the Null Peak Shape, each peak shape contains at least the following information. + +* The algorithm used to perform the integration +* The version of the algorithm used to perform the integration +* The frame in which the integration has been performed + +Subtypes of PeakShape will then provide additional information. For example PeakShapeSpherical provides the radius as well as background inner, and background outer radius. + -Using PeaksWorkspace's in Python --------------------------------- +Using PeaksWorkspaces in Python +--------------------------------- The PeaksWorkspace and Peak objects are exposed to python. PeaksWorkspace Python Interface -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code-block:: python @@ -64,7 +76,7 @@ Or you can create a new peak in this way: .. code-block:: python qlab = V3D(1.23, 3.45, 2.22) # Q in the lab frame of the peak - detector_distance = 2.5 # sample-detector distance in meters + detector_distance = 2.5 # sample-detector distance in meters. Detector distances are optional. Calculated in not provided. p = pws.createPeak(qlab, detector_distance) # The peak can later be added to the workspace pws.addPeak(p) @@ -87,6 +99,7 @@ Once you have a handle on a peak "p" you have several methods to query/modify it wl = p.getWavelength() tof = p.getTOF() d = p.getDSpacing() + shape = p.getPeakShape() -.. categories:: Concepts \ No newline at end of file +.. categories:: Concepts 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/fitfunctions/DynamicKuboToyabe.rst b/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst new file mode 100644 index 000000000000..5dc384cf2170 --- /dev/null +++ b/Code/Mantid/docs/source/fitfunctions/DynamicKuboToyabe.rst @@ -0,0 +1,33 @@ +.. _func-DynamicKuboToyabe: + +================= +DynamicKuboToyabe +================= + +.. index:: DynamicKuboToyabe + +Description +----------- + +Dynamic Kubo Toyabe fitting function for use by Muon scientists defined +by + +.. math:: G_z \left(t\right) = g_z\left(t\right) e^{-\nu t} + \nu \int_0^t g_z\left(\tau\right) e^{-\nu\tau} G_z\left(t-\tau\right) d\tau + +where :math:`g_z\left(t\right)` is the static KT function, and :math:`\nu` the muon hopping rate. + +| In zero field, :math:`B_0=0`: + +.. math:: g_z\left(t\right) = \mbox{A} \Bigg[ \frac{1}{3} + \frac{2}{3} \left( 1 - {\Delta}^2 {t}^2 \right) e^{-\frac{1}{2}\Delta^2 t^2} \Bigg] + +| In the presence of a longitudinal field, :math:`B_0=\omega_0 /\left(2\pi \gamma_{\mu}\right)>0`: + +.. math:: g_z\left(t\right) = \mbox{A} \Bigg[ 1 - 2\frac{\Delta^2}{\omega_0^2}\Big(1-cos(\omega_0 t)e^{-\frac{1}{2}\Delta^2 t^2}\Big) + 2\frac{\Delta^4}{\omega_0^4}\omega_0\int_0^\tau \sin(\omega_0\tau)e^{-\frac{1}{2}\Delta^2\tau^2}d\tau \Bigg] + +Note: The static function in longitudinal field will be implemented soon. In the meantime, please fix the external field :math:`B_0` (F parameter) to 0. + +.. attributes:: + +.. properties:: + +.. categories:: 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. | +------------------+----------------------------------------------------------+ diff --git a/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst b/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst new file mode 100644 index 000000000000..8034599e9609 --- /dev/null +++ b/Code/Mantid/docs/source/interfaces/SampleTransmissionCalculator.rst @@ -0,0 +1,60 @@ +Sample Transmission Calculator +============================== + +.. contents:: Table of Contents + :local: + +Overview +-------- + +.. interface:: Sample Transmission Calculator + :align: right + :width: 350 + +The sample transmission calculator allows the calculation of the sample +transmission and scattering over a given wavelength range for a particular +sample material and geometry. + +This UI is a front end for the :ref:`CalculateSampleTransmission +` algorithm. + +The algorithm assumes a flat plate sample which is perpendicular to the beam. + +Input Wavelength +~~~~~~~~~~~~~~~~ + +.. interface:: Sample Transmission Calculator + :widget: gbRangeBinning + :align: right + :width: 350 + +The wavelength range to calculate transmission over can be given either by +providing a single binning range in the format of a start, width and end value or +by providing a bin parameter string as used in the :ref:`Rebin ` +algorithm. + +Sample Details +~~~~~~~~~~~~~~ + +.. interface:: Sample Transmission Calculator + :widget: gbSampleDetails + :align: right + :width: 350 + +The sample details required are the chemical formula which is to be given in the +format expected by the :ref:`SetSampleMaterial ` +algorithm, number density in :math:`\mathrm{\AA{}}^3` and thickness in :math:`cm`. + +Output +~~~~~~ + +.. interface:: Sample Transmission Calculator + :widget: gbOutput + :align: right + :width: 350 + +The output is given in a plot of the transmission percentage over wavelength and +a table of statistics for the transmission (maximum, minimum, mean, median and +standard deviation) as well as the scattering percentage for all wavelengths. + +.. categories:: Interfaces General diff --git a/Code/Mantid/instrument/CNCS_Definition.xml b/Code/Mantid/instrument/CNCS_Definition.xml index 9ba469baa2b1..aeb052269537 100644 --- a/Code/Mantid/instrument/CNCS_Definition.xml +++ b/Code/Mantid/instrument/CNCS_Definition.xml @@ -1,5 +1,5 @@ - + @@ -187,350 +187,350 @@ - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - + diff --git a/Code/Mantid/instrument/CNCS_Definition_20140808-20150129.xml b/Code/Mantid/instrument/CNCS_Definition_20140808-20150129.xml new file mode 100644 index 000000000000..cb3e5151f3d8 --- /dev/null +++ b/Code/Mantid/instrument/CNCS_Definition_20140808-20150129.xml @@ -0,0 +1,729 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py index bbcc5e81cd3d..3938be682040 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Tube Calibration Demonstration for MAPS instrument. @@ -268,17 +269,17 @@ def improvingCalibrationOfListOfTubes(filename): # it is defined as the mean values around the neighbours define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717], # the first one was bad - 37: [6.36, 80.9347, 122.941, 165.104, 248.32], # the first one was bad - 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ], # the last one was bad - check if we can inprove - 75: [14.4285, 90.087, 128.987, 167.047, 242.62], # the last one was bad - check if we can inprove - 181: [11.726, 94.0496, 137.816, 180, 255], # the third peak was lost - 186:[11.9382, 71.5203, 107, 147.727, 239.041], #lost the second peak - 234: [4.84, 82.7824, 123.125, 163.945, 241.877], # the first one was bad - 235: [4.84, 80.0077, 121.002, 161.098, 238.502], # the first one was bad - 245: [9.88089, 93.0593, 136.911, 179.5, 255], # the third peak was bad - 273: [18.3711, 105.5, 145.5, 181.6, 243.252],# lost first and third peaks - 345: [4.6084, 87.0351, 128.125, 169.923, 245.3] # the last one was bad - } + 37: [6.36, 80.9347, 122.941, 165.104, 248.32], # the first one was bad + 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ], # the last one was bad - check if we can inprove + 75: [14.4285, 90.087, 128.987, 167.047, 242.62], # the last one was bad - check if we can inprove + 181: [11.726, 94.0496, 137.816, 180, 255], # the third peak was lost + 186:[11.9382, 71.5203, 107, 147.727, 239.041], #lost the second peak + 234: [4.84, 82.7824, 123.125, 163.945, 241.877], # the first one was bad + 235: [4.84, 80.0077, 121.002, 161.098, 238.502], # the first one was bad + 245: [9.88089, 93.0593, 136.911, 179.5, 255], # the third peak was bad + 273: [18.3711, 105.5, 145.5, 181.6, 243.252], # lost first and third peaks + 345: [4.6084, 87.0351, 128.125, 169.923, 245.3] # the last one was bad + } calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, fitPar=fitPar, outputPeak=True, overridePeaks=define_peaks) @@ -317,7 +318,7 @@ def calibrateB2Window(filename): fitPar.setAutomatic(True) # == Get the calibration and put results into calibration table == - calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, + calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,\ fitPar=fitPar, outputPeak=True, plotTube=[b2_range[0], b2_range[-1]], rangeList=b2_range) ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable) @@ -372,10 +373,10 @@ def findThoseTubesThatNeedSpecialCareForCalibration(filename): data = numpy.zeros((n,5)) line = 0 for row in peakTable: - data_row = [row['Peak%d'%(i)] for i in [1,2,3,4,5]] - data[line,:] = data_row - peaksId[line] = row['TubeId'] - line+=1 + data_row = [row['Peak%d'%(i)] for i in [1,2,3,4,5]] + data[line,:] = data_row + peaksId[line] = row['TubeId'] + line+=1 # data now has all the peaks positions for each tube # the mean value is the expected value for the peak position for each tube expected_peak_pos = numpy.mean(data,axis=0) @@ -402,7 +403,7 @@ def findThoseTubesThatNeedSpecialCareForCalibration(filename): print 'Calibrating again only these tubes' #let's confir that our suspect works CalibInstWS = loadingStep(filename) - calibrationTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, + calibrationTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,\ fitPar=fitPar, rangeList= problematic_tubes, plotTube=problematic_tubes) # plot the FittedTube agains TubePlot for each detector and you will see that there were problems on those tubes. @@ -450,16 +451,16 @@ def completeCalibration(filename): # 245: [9.88089, 93.0593, 136.911, 179.5, 255], # the third peak was bad # 273: [18.3711, 105.5, 145.5, 181.6, 243.252],# lost first and third peaks # 345: [4.6084, 87.0351, 128.125, 169.923, 245.3]} # the last one was bad - define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717], - 37: [6.36, 80.9347, 122.941, 165.104, 248.32], - 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ], - 75: [14.4285, 90.087, 128.987, 167.047, 242.62], - 181: [11.726, 94.0496, 137.816, 180, 255], - 186:[11.9382, 71.5203, 107, 147.727, 239.041], - 234: [4.84, 82.7824, 123.125, 163.945, 241.877], - 235: [4.84, 80.0077, 121.002, 161.098, 238.502], - 245: [9.88089, 93.0593, 136.911, 179.5, 255], - 273: [18.3711, 105.5, 145.5, 181.6, 243.252], + define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717],\ + 37: [6.36, 80.9347, 122.941, 165.104, 248.32],\ + 71: [8.62752, 85.074, 124.919, 164.116, 246.82 ],\ + 75: [14.4285, 90.087, 128.987, 167.047, 242.62],\ + 181: [11.726, 94.0496, 137.816, 180, 255],\ + 186:[11.9382, 71.5203, 107, 147.727, 239.041],\ + 234: [4.84, 82.7824, 123.125, 163.945, 241.877],\ + 235: [4.84, 80.0077, 121.002, 161.098, 238.502],\ + 245: [9.88089, 93.0593, 136.911, 179.5, 255],\ + 273: [18.3711, 105.5, 145.5, 181.6, 243.252],\ 345: [4.6084, 87.0351, 128.125, 169.923, 245.3]} b2_window = range(196,212) + range(222,233) @@ -472,7 +473,7 @@ def completeCalibration(filename): # the group that have 3 stripts are all the tubes except the b2 window and e window. range_3_strips = numpy.setdiff1d(aux, e1_window) - calibrationTable, peak3Table= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, + calibrationTable, peak3Table= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,\ fitPar=fitPar, outputPeak=True, overridePeaks=define_peaks, rangeList=range_3_strips) # now calibrate the b2_window REMOVE SECOND PEAK @@ -486,12 +487,12 @@ def completeCalibration(filename): # apply the calibration for the b2_window 2 strips values calibrationTable, peak2Table = tube.calibrate(CalibInstWS, CalibratedComponent, - knownPos, #these parameters now have only 4 points - funcFactor, - fitPar=fitPar, - outputPeak=True, - calibTable = calibrationTable, # it will append to the calibTable - rangeList = b2_window) + knownPos, #these parameters now have only 4 points + funcFactor, + fitPar=fitPar, + outputPeak=True, + calibTable = calibrationTable, # it will append to the calibTable + rangeList = b2_window) ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py index 6cf35b16c19e..3a4d057be909 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # @@ -15,7 +16,8 @@ # Set initial parameters for peak finding ExpectedHeight = -1000.0 # Expected Height of Gaussian Peaks (initial value of fit parameter) ExpectedWidth = 8.0 # Expected width of Gaussian peaks in pixels (initial value of fit parameter) -ExpectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0] # Expected positions of the edges and Gaussian peaks in pixels (initial values of fit parameters) +ExpectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0] +# Expected positions of the edges and Gaussian peaks in pixels (initial values of fit parameters) # Set what we want to calibrate (e.g whole intrument or one door ) CalibratedComponent = 'B1_window' # Calibrate B1 window @@ -43,7 +45,7 @@ # == Get the calibration and put results into calibration table == # also put peaks into PeakFile -calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm, +calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm,\ fitPar=fitPar, outputPeak=True) print "Got calibration (new positions of detectors) " diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py index b721f3915971..43aa7bb692f6 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # @@ -44,7 +45,7 @@ # == Get the calibration and put results into calibration table == -calibrationTable, peakTable = tube.calibrate(CalibInstWS, thisTubeSet, knownPos, funcForm, +calibrationTable, peakTable = tube.calibrate(CalibInstWS, thisTubeSet, knownPos, funcForm,\ outputPeak=True) print "Got calibration (new positions of detectors) " diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py index a9ba0154f912..7970f60cea8a 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # @@ -34,7 +35,7 @@ # == Get the calibration and put results into calibration table == -calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponents, knownPos, funcForm, +calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponents, knownPos, funcForm,\ outputPeak=True) print "Got calibration (new positions of detectors) " diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py index fbc21f214aa7..758a3ea29bc4 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py index b213d898120b..f0e0a43f1f2f 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py index 2ef635744983..297626c6a3eb 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this # diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py index dddf9ce9f258..4fb14c18ea79 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Tube Calibration Demonstration program for MERLIN. @@ -53,10 +54,10 @@ def analisePeakTable(pTable, peaksName='Peaks'): data = numpy.zeros((n,peaks)) line = 0 for row in pTable: - data_row = [row['Peak%d'%(i)] for i in range(1,peaks+1)] - data[line,:] = data_row - peaksId[line] = row['TubeId'] - line+=1 + data_row = [row['Peak%d'%(i)] for i in range(1,peaks+1)] + data[line,:] = data_row + peaksId[line] = row['TubeId'] + line+=1 # data now has all the peaks positions for each tube # the mean value is the expected value for the peak position for each tube expected_peak_pos = numpy.mean(data,axis=0) @@ -73,60 +74,60 @@ def analisePeakTable(pTable, peaksName='Peaks'): def calibrateMerlin(filename): # == Set parameters for calibration == - rangeLower = 3000 # Integrate counts in each spectra from rangeLower to rangeUpper - rangeUpper = 20000 # + rangeLower = 3000 # Integrate counts in each spectra from rangeLower to rangeUpper + rangeUpper = 20000 # # Get calibration raw file and integrate it - rawCalibInstWS = LoadRaw(filename) #'raw' in 'rawCalibInstWS' means unintegrated. - print "Integrating Workspace" - CalibInstWS = Integration( rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper ) - DeleteWorkspace(rawCalibInstWS) - print "Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate" + rawCalibInstWS = LoadRaw(filename) #'raw' in 'rawCalibInstWS' means unintegrated. + print "Integrating Workspace" + CalibInstWS = Integration( rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper ) + DeleteWorkspace(rawCalibInstWS) + print "Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate" # the known positions are given in pixels inside the tubes and transformed to provide the positions # with the center of the tube as the origin - knownPositions = 2.92713867188*(numpy.array([ 27.30074322, 92.5, 294.65178585, 362.37861919 , 512.77103043 ,663.41425323, 798.3223896, 930.9, 997.08480835])/1024 - 0.5) - funcForm = numpy.array([2,2,1,1,1,1,1,2,2],numpy.int8) + knownPositions = 2.92713867188*(numpy.array([ 27.30074322, 92.5, 294.65178585, 362.37861919 , 512.77103043 ,663.41425323, 798.3223896, 930.9, 997.08480835])/1024 - 0.5) + funcForm = numpy.array([2,2,1,1,1,1,1,2,2],numpy.int8) # The calibration will follow different steps for sets of tubes # For the door9, the best points to define the known positions are the 1st edge, 5 peaks, last edge. - points7 = knownPositions[[0,2,3,4,5,6,8]] - points7func = funcForm[[0,2,3,4,5,6,8]] + points7 = knownPositions[[0,2,3,4,5,6,8]] + points7func = funcForm[[0,2,3,4,5,6,8]] - door9pos = points7 - door9func = points7func - CalibratedComponent = 'MERLIN/door9' # door9 + door9pos = points7 + door9func = points7func + CalibratedComponent = 'MERLIN/door9' # door9 # == Get the calibration and put results into calibration table == # also put peaks into PeakFile - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door9pos, door9func, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door9pos, door9func, outputPeak=True, - margin=30, - rangeList=range(20) # because 20, 21, 22, 23 are defective detectors - ) - print "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt" - analisePeakTable(peakTable, 'door9_tube1_peaks') + margin=30, + rangeList=range(20) # because 20, 21, 22, 23 are defective detectors + ) + print "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt" + analisePeakTable(peakTable, 'door9_tube1_peaks') # For the door8, the best points to define the known positions are the 1st edge, 5 peaks, last_edge - door8pos = points7 - door8func = points7func - CalibratedComponent = 'MERLIN/door8' - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door8pos, + door8pos = points7 + door8func = points7func + CalibratedComponent = 'MERLIN/door8' + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door8pos, door8func, outputPeak = True, #change to peakTable to append to peakTable calibTable = calibrationTable, margin = 30) - analisePeakTable(peakTable, 'door8_peaks') + analisePeakTable(peakTable, 'door8_peaks') # For the doors 7,6,5,4, 2, 1 we may use the 9 points - doorpos = knownPositions - doorfunc = funcForm - CalibratedComponent = ['MERLIN/door%d'%(i) for i in [7,6,5,4, 2, 1]] - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, - doorfunc, - outputPeak = True, - calibTable = calibrationTable, + doorpos = knownPositions + doorfunc = funcForm + CalibratedComponent = ['MERLIN/door%d'%(i) for i in [7,6,5,4, 2, 1]] + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos,\ + doorfunc,\ + outputPeak = True,\ + calibTable = calibrationTable,\ margin = 30) - analisePeakTable(peakTable, 'door1to7_peaks') + analisePeakTable(peakTable, 'door1to7_peaks') # The door 3 is a special case, because it is composed by diffent kind of tubes. # door 3 tubes: 5_8, 5_7, 5_6, 5_5, 5_4, 5_3, 5_2, 5_1, 4_8, 4_7, 4_6, 4_5, 4_4, 4_3, 4_2, 4_1, 3_8, 3_7, 3_6, 3_5, 3_4 @@ -138,87 +139,87 @@ def calibrateMerlin(filename): # NOTE: the smaller tubes they have length = 1.22879882813, but 1024 detectors # so we have to correct the known positiosn by multiplying by its lenght and dividing by the longer dimension - from tube_calib_fit_params import TubeCalibFitParams + from tube_calib_fit_params import TubeCalibFitParams # calibrating tubes 1_x - CalibratedComponent = ['MERLIN/door3/tube_1_%d'%(i) for i in range(1,9)] + CalibratedComponent = ['MERLIN/door3/tube_1_%d'%(i) for i in range(1,9)] - half_diff_center = (2.92713867188 -1.22879882813)/2 # difference among the expected center position for both tubes + half_diff_center = (2.92713867188 -1.22879882813)/2 # difference among the expected center position for both tubes # here a little bit of attempts is necessary. The efective center position and lengh is different for the calibrated tube, that # is the reason, the calibrated values of the smaller tube does not seems aligned with the others. By, finding the 'best' half_diff_center # value, the alignment occurs nicely. - half_diff_center = 0.835 # + half_diff_center = 0.835 # # the knownpositions were given with the center of the bigger tube as origin, to convert # to the center of the upper tube as origin is necessary to subtract them with the half_diff_center - doorpos = knownPositions[[5,6,7,8]] - half_diff_center - doorfunc = [1,1,2,2] + doorpos = knownPositions[[5,6,7,8]] - half_diff_center + doorfunc = [1,1,2,2] # for the smal tubes, automatically searching for the peak position in pixel was not working quite well, # so we will give the aproximate position for these tubes through fitPar argument - fitPar = TubeCalibFitParams([216, 527, 826, 989]) - fitPar.setAutomatic(True) - - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, - doorfunc, - outputPeak = True, - fitPar = fitPar, - calibTable = calibrationTable, + fitPar = TubeCalibFitParams([216, 527, 826, 989]) + fitPar.setAutomatic(True) + + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos,\ + doorfunc,\ + outputPeak = True,\ + fitPar = fitPar,\ + calibTable = calibrationTable,\ margin = 30) - analisePeakTable(peakTable, 'door3_tube1_peaks') + analisePeakTable(peakTable, 'door3_tube1_peaks') # calibrating tubes 2_x - CalibratedComponent = ['MERLIN/door3/tube_2_%d'%(i) for i in range(1,9)] + CalibratedComponent = ['MERLIN/door3/tube_2_%d'%(i) for i in range(1,9)] # the knownpositions were given with the center of the bigger tube as origin, to convert # to the center of the lower tube as origin is necessary to sum them with (len_big - len_small)/2 - doorpos = knownPositions[[0,1,2,3]] + half_diff_center + doorpos = knownPositions[[0,1,2,3]] + half_diff_center # print doorpos - doorfunc = [2,2,1,1] + doorfunc = [2,2,1,1] # for the smal tubes, automatically searching for the peak position in pixel was not working quite well, # so we will give the aproximate position for these tubes through fitPar argument - fitPar = TubeCalibFitParams([50, 202, 664, 815]) - fitPar.setAutomatic(True) - - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, - doorfunc, - outputPeak = True, - calibTable = calibrationTable, - fitPar = fitPar, + fitPar = TubeCalibFitParams([50, 202, 664, 815]) + fitPar.setAutomatic(True) + + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos,\ + doorfunc,\ + outputPeak = True,\ + calibTable = calibrationTable,\ + fitPar = fitPar,\ margin = 30) - analisePeakTable(peakTable, 'door3_tube2_peaks') + analisePeakTable(peakTable, 'door3_tube2_peaks') # calibrating tubes 3_3,3_2,3_1 - CalibratedComponent = ['MERLIN/door3/tube_3_%d'%(i) for i in [1,2,3]] - doorpos = knownPositions[[0,1,2,3,5,6,7,8]] - doorfunc = funcForm[[0,1,2,3,5,6,7,8]] - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, - doorfunc, - outputPeak = True, - calibTable = calibrationTable, + CalibratedComponent = ['MERLIN/door3/tube_3_%d'%(i) for i in [1,2,3]] + doorpos = knownPositions[[0,1,2,3,5,6,7,8]] + doorfunc = funcForm[[0,1,2,3,5,6,7,8]] + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos,\ + doorfunc,\ + outputPeak = True,\ + calibTable = calibrationTable,\ margin = 30) - analisePeakTable(peakTable, 'door3_123_peaks') + analisePeakTable(peakTable, 'door3_123_peaks') # calibrating others inside door3 # 5_8, 5_7, 5_6, 5_5, 5_4, 5_3, 5_2, 5_1, 4_8, 4_7, 4_6, 4_5, 4_4, 4_3, 4_2, 4_1, 3_8, 3_7, 3_6, 3_5, 3_4 - part_3 = ['MERLIN/door3/tube_3_%d'%(i) for i in [4,5,6,7,8]] - part_4 = ['MERLIN/door3/tube_4_%d'%(i) for i in range(1,9)] - part_5 = ['MERLIN/door3/tube_5_%d'%(i) for i in range(1,9)] - CalibratedComponent = part_3 + part_4 + part_5 - doorpos = knownPositions - doorfunc = funcForm - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos, - doorfunc, - outputPeak = True, - calibTable = calibrationTable, + part_3 = ['MERLIN/door3/tube_3_%d'%(i) for i in [4,5,6,7,8]] + part_4 = ['MERLIN/door3/tube_4_%d'%(i) for i in range(1,9)] + part_5 = ['MERLIN/door3/tube_5_%d'%(i) for i in range(1,9)] + CalibratedComponent = part_3 + part_4 + part_5 + doorpos = knownPositions + doorfunc = funcForm + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, doorpos,\ + doorfunc,\ + outputPeak = True,\ + calibTable = calibrationTable,\ margin = 30) - analisePeakTable(peakTable, 'door3_peaks') + analisePeakTable(peakTable, 'door3_peaks') # == Apply the Calibation == - ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable) - print "Applied calibration" + ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable) + print "Applied calibration" # == Save workspace == #SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoMerlinResult.nxs',"Result of Running TCDemoMerlin.py") @@ -226,5 +227,5 @@ def calibrateMerlin(filename): if __name__=="__main__": - filename = 'MER12024.raw' # Calibration run ( found in \\isis\inst$\NDXMERLIN\Instrument\data\cycle_11_5 ) - calibrateMerlin(filename) + filename = 'MER12024.raw' # Calibration run ( found in \\isis\inst$\NDXMERLIN\Instrument\data\cycle_11_5 ) + calibrateMerlin(filename) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py index b040e44f5390..399335faf64f 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MERLIN # @@ -67,7 +68,7 @@ def CalibrateMerlin(RunNumber): # == Get the calibration and put results into calibration table == # also put peaks into PeakFile - calibrationTable,peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm, + calibrationTable,peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm,\ outputPeak=True, fitPar=fitPar, plotTube=range(0,280,20)) print "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt" diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish0.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish0.py index 6fd05fb722c6..515be0cd67a9 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish0.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish0.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM - Execute this # diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish1.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish1.py index 527e692073b5..49b55f4aeb62 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish1.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish1.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM - Execute this # diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py index 9fa967b803d5..85711023f698 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR WISH # @@ -17,7 +18,7 @@ from tube_spec import TubeSpec -def CalibrateWish( run_per_panel_list): +def CalibrateWish(run_per_panel_list): ''' :param run_per_panel_list: is a list of tuples with the run number and the associated panel @@ -68,7 +69,7 @@ def CalibrateWish( run_per_panel_list): # copy data from the current panel to the whole_instrument for i in range(tube_set.getNumTubes()): for spec_num in tube_set.getTube(i): - whole_instrument.setY(spec_num,ws.dataY(spec_num)) + whole_instrument.setY(spec_num,ws.dataY(spec_num)) # calibrate the whole_instrument with the last calibrated panel which has the calibration accumulation # of all the others @@ -79,6 +80,6 @@ def CalibrateWish( run_per_panel_list): if __name__ == "__main__": - # this file is found on cycle_11_1 - run_per_panel_list = [ (17706, 'panel01'), (17705, 'panel02'), (17701, 'panel03'), (17702, 'panel04'), (17695, 'panel05')] - CalibrateWish(run_per_panel_list) + # this file is found on cycle_11_1 + run_per_panel_list = [ (17706, 'panel01'), (17705, 'panel02'), (17701, 'panel03'), (17702, 'panel04'), (17695, 'panel05')] + CalibrateWish(run_per_panel_list) diff --git a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py index 404bbd6ef09d..66d4f301bf89 100644 --- a/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py +++ b/Code/Mantid/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR WISH # @@ -7,7 +8,6 @@ import tube from mantid.simpleapi import * -from tube_calib_fit_params import TubeCalibFitParams def CalibrateWish( RunNumber, PanelNumber): ''' @@ -39,14 +39,14 @@ def CalibrateWish( RunNumber, PanelNumber): # Get the calibration and put it into the calibration table #calibrate the lower tubes - calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, lower_tube, funcForm, + calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, lower_tube, funcForm,\ rangeList = range(0,76), outputPeak=True) #calibrate the upper tubes calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, upper_tube, funcForm, rangeList = range(76,152), - calibTable=calibrationTable, #give the calibration table to append data - outputPeak = peakTable #give peak table to append data + calibTable=calibrationTable,#give the calibration table to append data + outputPeak = peakTable#give peak table to append data ) print "Got calibration (new positions of detectors)" @@ -67,6 +67,6 @@ def CalibrateWish( RunNumber, PanelNumber): # ==== End of CalibrateWish() ==== if __name__ == "__main__": # this file is found on cycle_11_1 - RunNumber = 17701 - PanelNumber = '03' - CalibrateWish(RunNumber, PanelNumber) + RunNumber = 17701 + PanelNumber = '03' + CalibrateWish(RunNumber, PanelNumber) diff --git a/Code/Mantid/scripts/Calibration/ideal_tube.py b/Code/Mantid/scripts/Calibration/ideal_tube.py index 086cb3c22de2..61f61b076efa 100644 --- a/Code/Mantid/scripts/Calibration/ideal_tube.py +++ b/Code/Mantid/scripts/Calibration/ideal_tube.py @@ -5,8 +5,8 @@ # This class is the ideal tube, which specifies where the peaks formed by slits or edges should occur # Author: Karl Palmen ISIS -class IdealTube: - """ +class IdealTube(object): + """ The IdealTube specifies where the peaks formed by slits or edges should occur. They can be considered as the known positions as well. @@ -27,40 +27,40 @@ class IdealTube: * :meth:`~ideal_tube.IdealTube.getFunctionalForms` """ - def __init__( self ): + def __init__( self ): """ Create empty instance """ self.positions = numpy.ndarray((0)) # position of the points in metres self.functionalForms = [] # function form of points 1=peak 2=edge. peaks assumed if []. - def setArray ( self, array ): - """ + def setArray ( self, array ): + """ Construct an ideal tube directly from an array of positions :param points: Array of points where the peaks should be in Metres """ - self.positions =numpy.array( array) + self.positions =numpy.array( array) - def setForm(self, form): - """Define the functional form for the peaks""" - self.functionalForms = form + def setForm(self, form): + """Define the functional form for the peaks""" + self.functionalForms = form - def setPositionsAndForm ( self, pos, form ): - """ + def setPositionsAndForm ( self, pos, form ): + """ Construct and ideal tube directly from an array of positions and functional forms :param pos: Array of points where the peaks or edges should be in Metres :param form: Array of functional forms of the points 1=peak, 2=edge """ - self.positions = numpy.array(pos ) - self.functionalForms = form + self.positions = numpy.array(pos ) + self.functionalForms = form - def constructTubeFor3PointsMethod( self, idealAP, idealBP, idealCP, activeTubeLen ): - """ + def constructTubeFor3PointsMethod( self, idealAP, idealBP, idealCP, activeTubeLen ): + """ Construct and ideal tube for Merlin 3-point calibration :param idealAP: Ideal left (AP) in pixels @@ -70,22 +70,23 @@ def constructTubeFor3PointsMethod( self, idealAP, idealBP, idealCP, activeTubeLe """ #Contruct Ideal tube for 3 point calibration of MERLIN standard tube (code could be put into a function) - pixelLen = activeTubeLen/1024 # Pixel length + pixelLen = activeTubeLen/1024 # Pixel length # we then convert idealAP, idealCP and idealBP to Y coordinates and put into ideal tube array - self.positions = numpy.array([ idealAP*pixelLen - activeTubeLen/2, idealCP*pixelLen - activeTubeLen/2, idealBP*pixelLen - activeTubeLen/2]) - self.functionalForms = [ 2, 1, 2 ] + self.positions = numpy.array([ idealAP*pixelLen - activeTubeLen/2,\ + idealCP*pixelLen - activeTubeLen/2, idealBP*pixelLen - activeTubeLen/2]) + self.functionalForms = [ 2, 1, 2 ] - def getArray( self ): - """ + def getArray( self ): + """ Reurn the array of of points where the peaks should be in Metres """ - return self.positions + return self.positions - def getFunctionalForms( self ): - """ + def getFunctionalForms( self ): + """ Reurn the array of of points where the peaks should be in Metres """ - return self.functionalForms + return self.functionalForms diff --git a/Code/Mantid/scripts/Calibration/tube.py b/Code/Mantid/scripts/Calibration/tube.py index 4fc377c7a44c..263b033675d9 100644 --- a/Code/Mantid/scripts/Calibration/tube.py +++ b/Code/Mantid/scripts/Calibration/tube.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ ========================= Definition of Calibration @@ -555,7 +556,7 @@ def calibrate(ws, tubeSet, knownPositions, funcForm, **kwargs): for i in range(len(idealTube.getArray())): outputPeak.addColumn(type='float',name='Peak%d'%(i+1)) - getCalibration(ws, tubeSet, calibTable, fitPar, idealTube, outputPeak, + getCalibration(ws, tubeSet, calibTable, fitPar, idealTube, outputPeak,\ overridePeaks, excludeShortTubes, plotTube, rangeList, polinFit) if deletePeakTableAfter: diff --git a/Code/Mantid/scripts/Calibration/tube_calib.py b/Code/Mantid/scripts/Calibration/tube_calib.py index cc6aeda7652c..8d1d31d46c7c 100644 --- a/Code/Mantid/scripts/Calibration/tube_calib.py +++ b/Code/Mantid/scripts/Calibration/tube_calib.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This file is concerned with calibrating a specified set of tubes @@ -36,16 +37,16 @@ def createTubeCalibtationWorkspaceByWorkspaceIndexList ( integratedWorkspace, ou """ nSpectra = len(workspaceIndexList) - if( nSpectra < 1): + if nSpectra < 1: return pixelNumbers = [] integratedPixelCounts = [] pixel = 1 #integratedWorkspace. for i in workspaceIndexList: - pixelNumbers.append(pixel) - pixel = pixel + 1 - integratedPixelCounts.append( integratedWorkspace.dataY(i)[0] ) + pixelNumbers.append(pixel) + pixel = pixel + 1 + integratedPixelCounts.append( integratedWorkspace.dataY(i)[0] ) CreateWorkspace(dataX=pixelNumbers,dataY=integratedPixelCounts, OutputWorkspace=outputWorkspace) #if (showPlot): @@ -150,7 +151,7 @@ def fitGaussian(fitPar, index, ws, outputWs): fit_msg = 'name=LinearBackground,A0=%f;name=Gaussian,Height=%f,PeakCentre=%f,Sigma=%f'%(background, height, centre, width) - Fit(InputWorkspace=ws, Function=fit_msg, + Fit(InputWorkspace=ws, Function=fit_msg,\ StartX = str(start), EndX=str(end), Output=outputWs) peakIndex = 3 @@ -199,7 +200,7 @@ def getPoints ( IntegratedWorkspace, funcForms, fitParams, whichTube, showPlot=F # Create input workspace for fitting ## get all the counts for the integrated workspace inside the tube countsY = numpy.array([IntegratedWorkspace.dataY(i)[0] for i in whichTube]) - if (len(countsY) == 0): + if len(countsY) == 0: return getPointsWs = CreateWorkspace(range(len(countsY)),countsY,OutputWorkspace='TubePlot') calibPointWs = 'CalibPoint' @@ -210,23 +211,23 @@ def getPoints ( IntegratedWorkspace, funcForms, fitParams, whichTube, showPlot=F # Loop over the points for i in range(len(funcForms)): - if funcForms[i] == 2: + if funcForms[i] == 2: # find the edge position - peakIndex = fitEdges(fitParams, i, getPointsWs, calibPointWs) - else: - peakIndex = fitGaussian(fitParams, i, getPointsWs, calibPointWs) + peakIndex = fitEdges(fitParams, i, getPointsWs, calibPointWs) + else: + peakIndex = fitGaussian(fitParams, i, getPointsWs, calibPointWs) # get the peak centre - peakCentre = mtd[calibPointWs + '_Parameters'].row(peakIndex).items()[1][1] - results.append(peakCentre) + peakCentre = mtd[calibPointWs + '_Parameters'].row(peakIndex).items()[1][1] + results.append(peakCentre) - if showPlot: - ws = mtd[calibPointWs + '_Workspace'] - fitt_y_values.append(copy.copy(ws.dataY(1))) - fitt_x_values.append(copy.copy(ws.dataX(1))) + if showPlot: + ws = mtd[calibPointWs + '_Workspace'] + fitt_y_values.append(copy.copy(ws.dataY(1))) + fitt_x_values.append(copy.copy(ws.dataX(1))) if showPlot: - FittedData = CreateWorkspace(numpy.hstack(fitt_x_values), + FittedData = CreateWorkspace(numpy.hstack(fitt_x_values),\ numpy.hstack(fitt_y_values)) return results @@ -302,7 +303,7 @@ def correctTubeToIdealTube( tubePoints, idealTubePoints, nDets, TestMode=False, #print "correctTubeToIdealTube" # Check the arguments - if ( len(tubePoints) != len(idealTubePoints) ): + if len(tubePoints) != len(idealTubePoints) : print "Number of points in tube", len(tubePoints),"must equal number of points in ideal tube", len(idealTubePoints) return xResult @@ -311,28 +312,28 @@ def correctTubeToIdealTube( tubePoints, idealTubePoints, nDets, TestMode=False, usedIdealTubePoints = [] missedTubePoints = [] # Used for diagnostic print only for i in range(len(tubePoints)): - if( tubePoints[i] > 0.0 and tubePoints[i] < nDets): + if tubePoints[i] > 0.0 and tubePoints[i] < nDets: usedTubePoints.append( tubePoints[i] ) usedIdealTubePoints.append ( idealTubePoints[i] ) else: missedTubePoints.append(i+1) # State number of rogue slit points, if any - if( len(tubePoints) != len(usedTubePoints)): + if len(tubePoints) != len(usedTubePoints): print "Only",len(usedTubePoints),"out of",len(tubePoints)," slit points used. Missed",missedTubePoints # Check number of usable points - if( len(usedTubePoints) < 3): + if len(usedTubePoints) < 3: print "Too few usable points in tube",len(usedTubePoints) return [] # Fit quadratic to ideal tube points CreateWorkspace(dataX=usedTubePoints,dataY=usedIdealTubePoints, OutputWorkspace="PolyFittingWorkspace") try: - Fit(InputWorkspace="PolyFittingWorkspace",Function='name=Polynomial,n=%d'%(polinFit),StartX=str(0.0),EndX=str(nDets),Output="QF") + Fit(InputWorkspace="PolyFittingWorkspace",Function='name=Polynomial,n=%d'%(polinFit),StartX=str(0.0),EndX=str(nDets),Output="QF") except: - print "Fit failed" - return [] + print "Fit failed" + return [] paramQF = mtd['QF_Parameters'] @@ -345,11 +346,11 @@ def correctTubeToIdealTube( tubePoints, idealTubePoints, nDets, TestMode=False, # In test mode, shove the pixels that are closest to the reckoned peaks # to the position of the first detector so that the resulting gaps can be seen. - if( TestMode ): + if TestMode : print "TestMode code" for i in range( len(usedTubePoints) ): #print "used point",i,"shoving pixel",int(usedTubePoints[i]) - xResult[ int(usedTubePoints[i]) ] = xResult[0] + xResult[ int(usedTubePoints[i]) ] = xResult[0] # print xResult return xResult @@ -376,15 +377,15 @@ def getCalibratedPixelPositions( ws, tubePts, idealTubePts, whichTube, peakTestM detPositions = [] #Get position of first and last pixel of tube nDets = len(whichTube) - if( nDets < 1): + if nDets < 1: return detIDs, detPositions # Correct positions of detectors in tube by quadratic fit pixels = correctTubeToIdealTube ( tubePts, idealTubePts, nDets, TestMode=peakTestMode, polinFit=polinFit ) #print pixels - if( len(pixels) != nDets): - print "Tube correction failed." - return detIDs, detPositions + if len(pixels) != nDets: + print "Tube correction failed." + return detIDs, detPositions baseInstrument = ws.getInstrument().getBaseInstrument() # Get tube unit vector # get the detector from the baseInstrument, in order to get the positions @@ -394,7 +395,7 @@ def getCalibratedPixelPositions( ws, tubePts, idealTubePts, whichTube, peakTestM d0pos,dNpos = det0.getPos(),detN.getPos() ## identical to norm of vector: |dNpos - d0pos| tubeLength = det0.getDistance(detN) - if( tubeLength <= 0.0): + if tubeLength <= 0.0: print "Zero length tube cannot be calibrated, calibration failed." return detIDs, detPositions #unfortunatelly, the operation '/' is not defined in V3D object, so @@ -501,13 +502,13 @@ def getCalibration( ws, tubeSet, calibTable, fitPar, iTube, peaksTable, all_skipped.update(skipped) print "Calibrating tube", i+1,"of",nTubes, tubeSet.getTubeName(i) - if ( len(wht) < 1 ): - print "Unable to get any workspace indices (spectra) for this tube. Tube",tubeSet.getTubeName(i),"not calibrated." + if len(wht) < 1 : + print "Unable to get any workspace indices (spectra) for this tube. Tube",tubeSet.getTubeName(i),"not calibrated." #skip this tube - continue + continue # Calibribate the tube, if possible - if (tubeSet.getTubeLength(i) <= excludeShortTubes): + if tubeSet.getTubeLength(i) <= excludeShortTubes: #skip this tube continue @@ -536,7 +537,7 @@ def getCalibration( ws, tubeSet, calibTable, fitPar, iTube, peaksTable, detIDList, detPosList = getCalibratedPixelPositions( ws, actualTube, iTube.getArray(), wht, peaksTestMode, polinFit) #save the detector positions to calibTable - if( len(detIDList) == len(wht)): # We have corrected positions + if len(detIDList) == len(wht): # We have corrected positions for j in range(len(wht)): nextRow = {'Detector ID': detIDList[j], 'Detector Position': detPosList[j] } calibTable.addRow ( nextRow ) @@ -586,20 +587,20 @@ def getCalibrationFromPeakFile ( ws, calibTable, iTube, PeakFile ): wht, _ = tube.getTube(0) print "Calibrating tube", i+1 ,"of", nTubes, TubeName #, " length", tubeSet.getTubeLength(i) - if ( len(wht) < 1 ): + if len(wht) < 1 : print "Unable to get any workspace indices for this tube. Calibration abandoned." return detIDList, detPosList = getCalibratedPixelPositions( ws, actualTube, idealTube, wht) #print len(wht) - if( len(detIDList) == len(wht)): # We have corrected positions + if len(detIDList) == len(wht): # We have corrected positions for j in range(len(wht)): nextRow = {'Detector ID': detIDList[j], 'Detector Position': detPosList[j] } calibTable.addRow ( nextRow ) - if(nTubes == 0): - return + if nTubes == 0: + return # Delete temporary workspaces for getting new detector positions DeleteWorkspace('PolyFittingWorkspace') @@ -611,7 +612,7 @@ def getCalibrationFromPeakFile ( ws, calibTable, iTube, PeakFile ): ## implement this function def constructIdealTubeFromRealTube( ws, tube, fitPar, funcForm ): - """ + """ Construct an ideal tube from an actual tube (assumed ideal) :param ws: integrated workspace @@ -622,32 +623,32 @@ def constructIdealTubeFromRealTube( ws, tube, fitPar, funcForm ): """ # Get workspace indices - idealTube = IdealTube() + idealTube = IdealTube() - nTubes = tube.getNumTubes() - if(nTubes < 1): - raise RuntimeError("Invalid tube specification received by constructIdealTubeFromRealTube") - elif(nTubes > 1): - print "Specification has several tubes. The ideal tube will be based on the first tube",tube.getTubeName(0) + nTubes = tube.getNumTubes() + if nTubes < 1: + raise RuntimeError("Invalid tube specification received by constructIdealTubeFromRealTube") + elif nTubes > 1: + print "Specification has several tubes. The ideal tube will be based on the first tube",tube.getTubeName(0) - wht, _ = tube.getTube(0) + wht, _ = tube.getTube(0) # print wht # Check tube - if ( len(wht) < 1 ): + if len(wht) < 1 : raise RuntimeError("Unable to get any workspace indices for this tube. Cannot use as ideal tube.") # Get actual tube on which ideal tube is based - actualTube = getPoints ( ws, funcForm, fitPar, wht) - print "Actual tube that ideal tube is to be based upon",actualTube + actualTube = getPoints ( ws, funcForm, fitPar, wht) + print "Actual tube that ideal tube is to be based upon",actualTube # Get ideal tube based on this actual tube - try: - idealTube.setArray(actualTube) - except: - msg = "Attempted to create ideal tube based on actual tube" + str(actualTube) - msg += "Unable to create ideal tube." - msg += "Please choose another tube for constructIdealTubeFromRealTube()." - raise RuntimeError(msg) - return idealTube + try: + idealTube.setArray(actualTube) + except: + msg = "Attempted to create ideal tube based on actual tube" + str(actualTube) + msg += "Unable to create ideal tube." + msg += "Please choose another tube for constructIdealTubeFromRealTube()." + raise RuntimeError(msg) + return idealTube diff --git a/Code/Mantid/scripts/Calibration/tube_calib_fit_params.py b/Code/Mantid/scripts/Calibration/tube_calib_fit_params.py index 3610244e9a7a..3a2ccca35605 100644 --- a/Code/Mantid/scripts/Calibration/tube_calib_fit_params.py +++ b/Code/Mantid/scripts/Calibration/tube_calib_fit_params.py @@ -1,7 +1,7 @@ from mantid.simpleapi import * from mantid.kernel import * -class TubeCalibFitParams: +class TubeCalibFitParams(object): # This class is to take the fitting method and parameters for fitting the peaks crated by the calibration slits etc # and to deliver them to TubeCalib, so it can fit the peaks appropriately diff --git a/Code/Mantid/scripts/Calibration/tube_spec.py b/Code/Mantid/scripts/Calibration/tube_spec.py index e22d27871c9e..64fcc9642109 100644 --- a/Code/Mantid/scripts/Calibration/tube_spec.py +++ b/Code/Mantid/scripts/Calibration/tube_spec.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * from mantid.kernel import * @@ -91,7 +92,7 @@ def setTubeSpecByStringArray( self, tubeSpecArray ): """ for i in range(len(tubeSpecArray)): - self.setTubeSpecByString(tubeSpecArray[i]) + self.setTubeSpecByString(tubeSpecArray[i]) def getInstrumentName (self): @@ -106,27 +107,27 @@ def isTube(self, comp): :rtype: Value, true if component passes test as being a tube """ # We simply assume it's a tube if it has a large number of children - if( hasattr( comp, "nelements")): - return (comp.nelements() >= self.minNumDetsInTube ) + if hasattr( comp, "nelements"): + return comp.nelements() >= self.minNumDetsInTube else: - return False + return False def searchForTubes(self, comp): - """ + """ Searches the component for tubes and saves them in array, appending if array is not empty. :param comp: the component """ # Go through all descendents that are not a descendent of a tube and if it's a tube, store and count it. - if self.isTube( comp ): - self.tubes.append( comp ) + if self.isTube( comp ): + self.tubes.append( comp ) #print "Tube found", comp.getName() # If not tube, Search children, if any - else: - if( hasattr( comp, "nelements")): - for i in range(comp.nelements()): - self.searchForTubes(comp[i]) + else: + if hasattr( comp, "nelements"): + for i in range(comp.nelements()): + self.searchForTubes(comp[i]) def getNumTubes(self): @@ -135,16 +136,16 @@ def getNumTubes(self): :rtype: Value, number of tubes (-1 for erroneous specification) """ - if(self.numTubes >= 0): + if self.numTubes >= 0: return self.numTubes # We have a negative number set in self.numTubes, so we search for tubes comps = self.getComponents() - if( comps == []): + if comps == []: return self.numTubes for i in range( len(comps)): - self.searchForTubes(comps[i]) + self.searchForTubes(comps[i]) self.numTubes = len(self.tubes) return self.numTubes @@ -156,7 +157,7 @@ def getComponent ( self ): :rtype: instrument component """ - if( self.componentArray != []): + if self.componentArray != []: return self.componentArray[0] # We look for the component @@ -164,8 +165,8 @@ def getComponent ( self ): comp = self.inst.getComponentByName(self.componentNameArray[0]) - if( comp ): - self.componentArray.append(comp) + if comp : + self.componentArray.append(comp) return self.componentArray[0] @@ -176,16 +177,16 @@ def getComponents ( self ): :rtype: array of instrument components """ - if( self.componentArray != []): + if self.componentArray != []: return self.componentArray # We look for the components for i in range( len(self.componentNameArray)): - print "Looking for", self.componentNameArray[i] + print "Looking for", self.componentNameArray[i] - comp = self.inst.getComponentByName(self.componentNameArray[i]) + comp = self.inst.getComponentByName(self.componentNameArray[i]) - if( comp ): + if comp : self.componentArray.append(comp) else: print "Did not find", self.componentNameArray[i] @@ -213,30 +214,30 @@ def getDetectorInfoFromTube( self, tubeIx ): :rtype: ID of first detector, number of detectors and step between detectors +1 or -1 """ nTubes = self.getNumTubes() - if(nTubes < 0): - print "Error in listing tubes" - return 0, 0, 1 - if(tubeIx < 0 or tubeIx >= nTubes): - print "Tube index",tubeIx,"out of range 0 to",nTubes - return 0, 0, 1 + if nTubes < 0: + print "Error in listing tubes" + return 0, 0, 1 + if tubeIx < 0 or tubeIx >= nTubes: + print "Tube index",tubeIx,"out of range 0 to",nTubes + return 0, 0, 1 comp = self.tubes[tubeIx] - if(comp != 0): + if comp != 0: firstDet = comp[0].getID() numDet = comp.nelements() # Allow for reverse numbering of Detectors lastDet = comp[numDet-1].getID() - if (lastDet < firstDet): - step = -1 - if( firstDet - lastDet + 1 != numDet): - print "Detector number range",firstDet-lastDet+1," not equal to number of detectors",numDet - print "Detectors not numbered continuously in this tube. Calibration will fail for this tube." + if lastDet < firstDet: + step = -1 + if firstDet - lastDet + 1 != numDet: + print "Detector number range",firstDet-lastDet+1," not equal to number of detectors",numDet + print "Detectors not numbered continuously in this tube. Calibration will fail for this tube." else: - step = 1 - if( lastDet - firstDet + 1 != numDet): - print "Detector number range",lastDet-firstDet+1," not equal to number of detectors",numDet - print "Detectors not numbered continuously in this tube. Calibration will fail for this tube." + step = 1 + if lastDet - firstDet + 1 != numDet: + print "Detector number range",lastDet-firstDet+1," not equal to number of detectors",numDet + print "Detectors not numbered continuously in this tube. Calibration will fail for this tube." #print "First dectector ", firstDet," Last detector ", firstDet+numDet-1, "Number of detectors ", numDet #print "First dectector ", firstDet," Last detector ", comp[numDet-1].getID() @@ -256,16 +257,16 @@ def getTubeLength( self, tubeIx ): """ nTubes = self.getNumTubes() - if(nTubes < 0): + if nTubes < 0: print "Error in listing tubes" return 0.0 - if(tubeIx < 0 or tubeIx >= nTubes): + if tubeIx < 0 or tubeIx >= nTubes: print "Tube index",tubeIx,"out of range 0 to",nTubes return 0.0 comp = self.tubes[tubeIx] - if(comp != 0): + if comp != 0: firstDet = comp[0].getID() numDet = comp.nelements() return comp[0].getDistance( comp[numDet-1] ) @@ -285,16 +286,16 @@ def getTubeName ( self, tubeIx ): :rtype: Name of tube as in IDF or 'unknown' if not found. """ nTubes = self.getNumTubes() - if(nTubes < 0): - print "Error in listing tubes" - return 'Unknown' - if(tubeIx < 0 or tubeIx >= nTubes): - print "Tube index",tubeIx,"out of range 0 to",nTubes - return 'Unknown' + if nTubes < 0: + print "Error in listing tubes" + return 'Unknown' + if tubeIx < 0 or tubeIx >= nTubes: + print "Tube index",tubeIx,"out of range 0 to",nTubes + return 'Unknown' comp = self.tubes[tubeIx] - if(comp != 0): + if comp != 0: return comp.getFullName() else: print self.componentNameArray[0], tubeIx, "not found" @@ -322,17 +323,17 @@ def getTubeByString(self, tubeIx): sp = self.ws.getSpectrum(sampleIndex) detids = sp.getDetectorIDs() numDetsPerWkID = len(detids) - if( numDetsPerWkID != 1): + if numDetsPerWkID != 1: print "We have",numDetsPerWkID,"detectors per workspace index. 1 is required." print "cannot obtain range of workspace indices for this tube in this workspace" return wkIds, skipped # Go and get workspace Indices - if(step == -1): + if step == -1: startDet = firstDet - numDet + 1 else: startDet = firstDet - if( numDet > 0): + if numDet > 0: for i in range (0, self.ws.getNumberHistograms(), numDet): try: deti = self.ws.getDetector(i) @@ -340,13 +341,13 @@ def getTubeByString(self, tubeIx): skipped.append(i) continue detID = deti.getID() - if (detID >= startDet and detID < startDet+numDet): + if detID >= startDet and detID < startDet+numDet: iPixel = detID - firstDet wkIds = range( i - iPixel, i - iPixel + step*numDet, step) # print "Workspace indices",i-iPixel,"to",i-iPixel+numDet-1 #print firstDet, numDet - if (numDet > 0): + if numDet > 0: return wkIds, skipped else: print "specified tube has no detectors." @@ -363,7 +364,7 @@ def getTube(self, tubeIx): :rtype: list of indices """ nTubes = self.getNumTubes() - if( (0 <= tubeIx) & (tubeIx < nTubes) ): + if (0 <= tubeIx) & (tubeIx < nTubes) : return self.getTubeByString(tubeIx) else: print "Tube", tubeIx, "out of range 0 to",self.numTubes,"." diff --git a/Code/Mantid/scripts/CrystalTools/PeakReport.py b/Code/Mantid/scripts/CrystalTools/PeakReport.py index d7efe450ce81..c7a28c6c3e59 100644 --- a/Code/Mantid/scripts/CrystalTools/PeakReport.py +++ b/Code/Mantid/scripts/CrystalTools/PeakReport.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This is a module for creating peak integration reports. """ @@ -8,7 +9,7 @@ from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import * -class PeakReport: +class PeakReport(object): """ Peak Report is a class used to creating one or more peak integration reports as PDFs. """ diff --git a/Code/Mantid/scripts/DGS_Reduction.py b/Code/Mantid/scripts/DGS_Reduction.py index f0c080f1d434..0413c2158f5f 100644 --- a/Code/Mantid/scripts/DGS_Reduction.py +++ b/Code/Mantid/scripts/DGS_Reduction.py @@ -1,8 +1,8 @@ +#pylint: disable=invalid-name """ Script used to start the DGS reduction GUI from MantidPlot """ from reduction_application import ReductionGUI -from PyQt4 import QtCore, uic reducer = ReductionGUI(instrument_list=["ARCS", "CNCS", "HYSPEC", "MAPS", "MARI", "MERLIN", "SEQUOIA"]) diff --git a/Code/Mantid/scripts/Engineering/EnginXUtils.py b/Code/Mantid/scripts/Engineering/EnginXUtils.py index 4aa0d044a4d7..26a6d6e9c505 100644 --- a/Code/Mantid/scripts/Engineering/EnginXUtils.py +++ b/Code/Mantid/scripts/Engineering/EnginXUtils.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import os from mantid.api import * @@ -18,13 +19,13 @@ def getDetIDsForBank(bank): detIDs = set() for i in range(grouping.getNumberHistograms()): - if grouping.readY(i)[0] == bank: - detIDs.add(grouping.getDetector(i).getID()) + if grouping.readY(i)[0] == bank: + detIDs.add(grouping.getDetector(i).getID()) DeleteWorkspace(grouping) if len(detIDs) == 0: - raise Exception('Unknown bank') + raise Exception('Unknown bank') return detIDs @@ -34,12 +35,11 @@ def getWsIndicesForBank(bank, ws): detIDs = getDetIDsForBank(bank) def isIndexInBank(index): - try: - det = ws.getDetector(index) - return (det.getID() in detIDs) - except: - return False + try: + det = ws.getDetector(index) + return det.getID() in detIDs + except: + return False return filter(isIndexInBank, range(0, ws.getNumberHistograms())) - diff --git a/Code/Mantid/scripts/Examples/HRPDDialog_Example.py b/Code/Mantid/scripts/Examples/HRPDDialog_Example.py index ba375bc86c97..80d97b05c2b9 100644 --- a/Code/Mantid/scripts/Examples/HRPDDialog_Example.py +++ b/Code/Mantid/scripts/Examples/HRPDDialog_Example.py @@ -1,6 +1,7 @@ +#pylint: disable=invalid-name # First a function definition for the Loading algorithms which loads the data and immediately aligns the detectors -def LoadAndAlign(type, outputArea): - LoadRawDialog(OutputWorkspace=outputArea, Message = "Enter path to the file containing the " + type) +def LoadAndAlign(_type, outputArea): + LoadRawDialog(OutputWorkspace=outputArea, Message = "Enter path to the file containing the " + _type) AlignDetectorsDialog(InputWorkspace=outputArea, OutputWorkspace=outputArea,Message="Enter path to calibration file") # ========== The script starts here ============ @@ -14,7 +15,8 @@ def LoadAndAlign(type, outputArea): transWorkspace="Transmission" #The input workspace needs to be in units of wavelength for the CylinderAbsorption algorithm ConvertUnits(InputWorkspace=dataWorkspace, OutputWorkspace=dataWorkspace, Target="Wavelength") -CylinderAbsorptionDialog(InputWorkspace=dataWorkspace, OutputWorkspace=transWorkspace,SampleNumberDensity="0.072",ScatteringXSection="5.08",AttenuationXSection="5.1",Message="Enter size parameters") +CylinderAbsorptionDialog(InputWorkspace=dataWorkspace, OutputWorkspace=transWorkspace,SampleNumberDensity="0.072",\ + ScatteringXSection="5.08",AttenuationXSection="5.1",Message="Enter size parameters") Divide(dataWorkspace, transWorkspace, OutputWorkspace=dataWorkspace) # === Save as a Nexus file === diff --git a/Code/Mantid/scripts/Examples/InstrumentView_Example.py b/Code/Mantid/scripts/Examples/InstrumentView_Example.py index d3be938cbe73..0571ba5c39c2 100644 --- a/Code/Mantid/scripts/Examples/InstrumentView_Example.py +++ b/Code/Mantid/scripts/Examples/InstrumentView_Example.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # Example: Instrument view control # diff --git a/Code/Mantid/scripts/Examples/PlotAsymmetryByLogValue_Example.py b/Code/Mantid/scripts/Examples/PlotAsymmetryByLogValue_Example.py index 12c2e9763851..b9ea09ffbcfd 100644 --- a/Code/Mantid/scripts/Examples/PlotAsymmetryByLogValue_Example.py +++ b/Code/Mantid/scripts/Examples/PlotAsymmetryByLogValue_Example.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # ----------------------------------------------------- # Runs PlotAssymetryByLogValue algorithm # and plots the output in MantidPlot using a Python diff --git a/Code/Mantid/scripts/Examples/SampleLogs_Demo.py b/Code/Mantid/scripts/Examples/SampleLogs_Demo.py index 84e9856211da..b1c54bb46fd4 100644 --- a/Code/Mantid/scripts/Examples/SampleLogs_Demo.py +++ b/Code/Mantid/scripts/Examples/SampleLogs_Demo.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # Example: Retrieving log information from a data set # diff --git a/Code/Mantid/scripts/Examples/SimpleMtdCommands_Example.py b/Code/Mantid/scripts/Examples/SimpleMtdCommands_Example.py index 08702ddd09f6..ed5b145a58cd 100644 --- a/Code/Mantid/scripts/Examples/SimpleMtdCommands_Example.py +++ b/Code/Mantid/scripts/Examples/SimpleMtdCommands_Example.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # Example: Basic Mantid commands # diff --git a/Code/Mantid/scripts/Examples/SolidAngle_Example.py b/Code/Mantid/scripts/Examples/SolidAngle_Example.py index 7243aa427424..5b692ebf80a9 100644 --- a/Code/Mantid/scripts/Examples/SolidAngle_Example.py +++ b/Code/Mantid/scripts/Examples/SolidAngle_Example.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ##------------------------------------------------------------------------- ## ## Example: Calculating the solid angle for a spectrum with respect to the diff --git a/Code/Mantid/scripts/Examples/StripPeaks.py b/Code/Mantid/scripts/Examples/StripPeaks.py index d86bca436fbc..32bd47a83b62 100644 --- a/Code/Mantid/scripts/Examples/StripPeaks.py +++ b/Code/Mantid/scripts/Examples/StripPeaks.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # MantidPlot example script # # Using StripPeaks + dialog boxes diff --git a/Code/Mantid/scripts/Examples/TableWorkspace_Example.py b/Code/Mantid/scripts/Examples/TableWorkspace_Example.py index 6f139c8fff2f..1e92cfbd40cc 100644 --- a/Code/Mantid/scripts/Examples/TableWorkspace_Example.py +++ b/Code/Mantid/scripts/Examples/TableWorkspace_Example.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # Perform some algorithms LoadRaw(Filename="GEM40979.raw",OutputWorkspace="GEM40979") AlignDetectors("GEM40979",OutputWorkspace="aligned",CalibrationFile="offsets_2006_cycle064.cal") diff --git a/Code/Mantid/scripts/FilterEvents.py b/Code/Mantid/scripts/FilterEvents.py index ef661b20f72e..f05876cec2c0 100644 --- a/Code/Mantid/scripts/FilterEvents.py +++ b/Code/Mantid/scripts/FilterEvents.py @@ -1,14 +1,15 @@ +#pylint: disable=invalid-name from FilterEvents import eventFilterGUI from PyQt4 import QtGui import sys -def qapp(): - if QtGui.QApplication.instance(): - app = QtGui.QApplication.instance() - else: - app = QtGui.QApplication(sys.argv) - return app - +def qapp(): + if QtGui.QApplication.instance(): + _app = QtGui.QApplication.instance() + else: + _app = QtGui.QApplication(sys.argv) + return _app + app = qapp() reducer = eventFilterGUI.MainWindow() #the main ui class in this file is called MainWindow diff --git a/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py b/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py index 183e6d9a55be..509e7462fbea 100644 --- a/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py +++ b/Code/Mantid/scripts/FilterEvents/MplFigureCanvas.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui import matplotlib @@ -6,7 +7,7 @@ from matplotlib.figure import Figure class Qt4MplCanvas(FigureCanvas): - """ A customized Qt widget for matplotlib figure. + """ A customized Qt widget for matplotlib figure. It can be used to replace GraphicsView of QtGui """ def __init__(self, parent): @@ -21,7 +22,7 @@ def __init__(self, parent): self.setParent(parent) # Set size policy to be able to expanding and resizable with frame - FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, + FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding,\ QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) @@ -29,7 +30,7 @@ def __init__(self, parent): return def plot(self, x, y): - """ Plot a set of data + """ Plot a set of data Argument: - x: numpy array X - y: numpy array Y @@ -41,6 +42,6 @@ def plot(self, x, y): return def getPlot(self): - """ reture figure's axes to expose the matplotlib figure to PyQt client + """ reture figure's axes to expose the matplotlib figure to PyQt client """ return self.axes diff --git a/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py b/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py index f041fd467936..19d9b11778f4 100644 --- a/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py +++ b/Code/Mantid/scripts/FilterEvents/Ui_ErrorMessage.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ErrorMessage.ui' diff --git a/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py b/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py index 9b19740180a2..4825002090f6 100644 --- a/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py +++ b/Code/Mantid/scripts/FilterEvents/Ui_MainWindow.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'MainWindow.ui' @@ -7,8 +8,8 @@ # # WARNING! All changes made in this file will be lost! -from PyQt4 import QtCore, QtGui -from MplFigureCanvas import Qt4MplCanvas +from PyQt4 import QtCore, QtGui +from MplFigureCanvas import Qt4MplCanvas try: diff --git a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py index 49d9cc7973c7..cc246846f9aa 100644 --- a/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py +++ b/Code/Mantid/scripts/FilterEvents/eventFilterGUI.py @@ -1,21 +1,17 @@ -import math +#pylint: disable=invalid-name import numpy -from Ui_MainWindow import Ui_MainWindow #import line for the UI python class +from FilterEvents.Ui_MainWindow import Ui_MainWindow #import line for the UI python class from PyQt4 import QtCore, QtGui from PyQt4.QtCore import * from PyQt4.QtGui import * -import matplotlib -from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas -from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar -from matplotlib.figure import Figure -from matplotlib.pyplot import gcf, setp +from matplotlib.pyplot import setp import mantid import mantid.simpleapi as api import mantid.kernel -from mantid.simpleapi import AnalysisDataService +from mantid.simpleapi import AnalysisDataService from mantid.kernel import ConfigService @@ -37,7 +33,7 @@ class MyPopErrorMsg(QWidget): def __init__(self): """ Init """ - import Ui_ErrorMessage as errui + import FilterEvents.Ui_ErrorMessage as errui QWidget.__init__(self) @@ -62,29 +58,29 @@ def quit(self): return - def XpaintEvent(self, e): + def XpaintEvent(self, _): """ ??? """ - import Ui_ErrorMessage as errui + import FilterEvents.Ui_ErrorMessage as errui self.ui = errui.Ui_Dialog() self.ui.setupUi(self) return -class MainWindow(QtGui.QMainWindow): +class MainWindow(QtGui.QMainWindow): """ Class of Main Window (top) Copy to ui.setupUI # Version 3.0 + Import for Ui_MainWindow.py - from MplFigureCanvas import Qt4MplCanvas + from MplFigureCanvas import Qt4MplCanvas # Replace 'self.graphicsView = QtGui.QtGraphicsView' with the following self.graphicsView = Qt4MplCanvas(self.centralwidget) self.mainplot = self.graphicsView.getPlot() - + # Version 2.0 + Import import matplotlib from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas @@ -109,10 +105,12 @@ class MainWindow(QtGui.QMainWindow): self.ui.graphicsView.setGeometry(QtCore.QRect(40, 230, 821, 411)) self.ui.graphicsView.setObjectName(_fromUtf8("graphicsView")) - """ - + """ + + _errMsgWindow = None + def __init__(self, parent=None): - """ Intialization and set up + """ Intialization and set up """ # Base class QtGui.QMainWindow.__init__(self,parent) @@ -121,11 +119,11 @@ def __init__(self, parent=None): config = ConfigService.Instance() self._instrument = config["default.instrument"] - # Central widget + # Central widget self.centralwidget = QtGui.QWidget(self) - # UI Window (from Qt Designer) - self.ui = Ui_MainWindow() + # UI Window (from Qt Designer) + self.ui = Ui_MainWindow() self.ui.setupUi(self) # Do initialize plotting @@ -163,12 +161,12 @@ def __init__(self, parent=None): self.ui.horizontalSlider_2.setTracking(True) self.ui.horizontalSlider_2.setTickPosition(QSlider.NoTicks) self.connect(self.ui.horizontalSlider_2, SIGNAL('valueChanged(int)'), self.move_rightSlider) - - # self.connect(self.ui.lineEdit_3, QtCore.SIGNAL("textChanged(QString)"), - # self.set_startTime) + + # self.connect(self.ui.lineEdit_3, QtCore.SIGNAL("textChanged(QString)"), + # self.set_startTime) self.ui.lineEdit_3.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_3)) - self.connect(self.ui.pushButton_setT0, QtCore.SIGNAL("clicked()"), self.set_startTime) - # self.connect(self.ui.lineEdit_4, QtCore.SIGNAL("textChanged(QString)"), + self.connect(self.ui.pushButton_setT0, QtCore.SIGNAL("clicked()"), self.set_startTime) + # self.connect(self.ui.lineEdit_4, QtCore.SIGNAL("textChanged(QString)"), # self.set_stopTime) self.ui.lineEdit_4.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_4)) self.connect(self.ui.pushButton_setTf, QtCore.SIGNAL("clicked()"), self.set_stopTime) @@ -194,11 +192,11 @@ def __init__(self, parent=None): self.ui.lineEdit_7.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_7)) self.ui.lineEdit_8.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_8)) self.ui.lineEdit_9.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_9)) - - self.connect(self.ui.lineEdit_5, QtCore.SIGNAL("textChanged(QString)"), - self.set_minLogValue) - self.connect(self.ui.lineEdit_6, QtCore.SIGNAL("textChanged(QString)"), - self.set_maxLogValue) + + self.connect(self.ui.lineEdit_5, QtCore.SIGNAL("textChanged(QString)"),\ + self.set_minLogValue) + self.connect(self.ui.lineEdit_6, QtCore.SIGNAL("textChanged(QString)"),\ + self.set_maxLogValue) dirchangeops = ["Both", "Increase", "Decrease"] self.ui.comboBox_4.addItems(dirchangeops) @@ -230,7 +228,7 @@ def __init__(self, parent=None): self.ui.checkBox_from1.setChecked(False) self.ui.checkBox_groupWS.setChecked(True) - self.connect(self.ui.comboBox_tofCorr, SIGNAL('currentIndexChanged(int)'), self.showHideEi) + self.connect(self.ui.comboBox_tofCorr, SIGNAL('currentIndexChanged(int)'), self.showHideEi) self.connect(self.ui.pushButton_refreshCorrWSList, SIGNAL('clicked()'), self._searchTableWorkspaces) self.ui.lineEdit_Ei.setValidator(QtGui.QDoubleValidator(self.ui.lineEdit_Ei)) @@ -254,8 +252,8 @@ def __init__(self, parent=None): # Side information self.ui.label_mean.hide() self.ui.label_meanvalue.hide() - self.ui.label_avg.hide() - self.ui.label_timeAvgValue.hide() + self.ui.label_avg.hide() + self.ui.label_timeAvgValue.hide() self.ui.label_freq.hide() self.ui.label_freqValue.hide() self.ui.label_logname.hide() @@ -263,15 +261,15 @@ def __init__(self, parent=None): self.ui.label_logsize.hide() self.ui.label_logsizevalue.hide() - # Default + # Default self._defaultdir = os.getcwd() # self.ui.InputVal.setValidator(QtGui.QDoubleValidator(self.ui.InputVal)) - + # QtCore.QObject.connect(self.ui.convert, QtCore.SIGNAL("clicked()"), self.convert ) # QtCore.QObject.connect(self.ui.inputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) # QtCore.QObject.connect(self.ui.outputUnits, QtCore.SIGNAL("currentIndexChanged(QString)"), self.setInstrumentInputs ) - # self.setInstrumentInputs() + # self.setInstrumentInputs() ##defaults @@ -284,7 +282,7 @@ def on_mouseDownEvent(self, event): x = event.xdata y = event.ydata - if x is not None and y is not None: + if x is not None and y is not None: msg = "You've clicked on a bar with coords:\n %f, %f" % (x, y) QMessageBox.information(self, "Click!", msg) @@ -302,7 +300,7 @@ def computeMock(self): vecx = [] vecy = [] - + x = x0 while x < xf: y = 0.0 @@ -317,9 +315,9 @@ def computeMock(self): def move_leftSlider(self): - """ Re-setup left range line in figure. - Triggered by a change in Qt Widget. NO EVENT is required. - """ + """ Re-setup left range line in figure. + Triggered by a change in Qt Widget. NO EVENT is required. + """ newx = self.ui.horizontalSlider.value() if newx <= self._rightSlideValue and newx != self._leftSlideValue: # Allowed value: move the value bar @@ -349,12 +347,12 @@ def set_startTime(self): """ inps = str(self.ui.lineEdit_3.text()) print "Starting time = %s" % (inps) - + xlim = self.ui.mainplot.get_xlim() if inps == "": # Empty. Use default newtime0 = xlim[0] - else: + else: newtime0 = float(inps) # Convert to integer slide value @@ -390,18 +388,18 @@ def set_startTime(self): self.ui.graphicsView.draw() - # Set the value to left slider + # Set the value to left slider self.ui.horizontalSlider.setValue(self._leftSlideValue) - # Reset the value of line edit - if resetT is True: + # Reset the value of line edit + if resetT is True: self.ui.lineEdit_3.setText(str(newtime0)) return def move_rightSlider(self): - """ Re-setup left range line in figure. - Triggered by a change in Qt Widget. NO EVENT is required. - """ + """ Re-setup left range line in figure. + Triggered by a change in Qt Widget. NO EVENT is required. + """ newx = self.ui.horizontalSlider_2.value() if newx >= self._leftSlideValue and newx != self._rightSlideValue: # Allowed value: move the value bar @@ -430,13 +428,13 @@ def set_stopTime(self): """ inps = str(self.ui.lineEdit_4.text()) print "Stopping time = %s" % (inps) - + xlim = self.ui.mainplot.get_xlim() if inps == "": # Empty. Use default newtimef = xlim[1] else: - # Parse + # Parse newtimef = float(inps) # Convert to integer slide value @@ -449,8 +447,8 @@ def set_stopTime(self): # Correct value resetT = True - if irightvalue >= 100: - irightvalue == 100 + if irightvalue > 100: + irightvalue = 100 elif irightvalue < self._leftSlideValue: irightvalue = self._leftSlideValue else: @@ -469,7 +467,7 @@ def set_stopTime(self): self.ui.graphicsView.draw() - # Set the value to left slider + # Set the value to left slider self.ui.horizontalSlider_2.setValue(self._rightSlideValue) # Reset to line edit @@ -479,9 +477,9 @@ def set_stopTime(self): return def move_lowerSlider(self): - """ Re-setup upper range line in figure. - Triggered by a change in Qt Widget. NO EVENT is required. - """ + """ Re-setup upper range line in figure. + Triggered by a change in Qt Widget. NO EVENT is required. + """ inewy = self.ui.verticalSlider_2.value() print "LowerSlider is set with value %d vs. class variable %d" % (inewy, self._lowerSlideValue) @@ -509,7 +507,7 @@ def move_lowerSlider(self): self.ui.graphicsView.draw() # Set line edit input - if setLineEdit is True: + if setLineEdit is True: # Change value to line edit (5) self.ui.lineEdit_5.setText(str(newy)) # Reset the class variable @@ -523,11 +521,11 @@ def set_minLogValue(self): print "Minimum Log Value = %s" %(str(self.ui.lineEdit_5.text())) ylim = self.ui.mainplot.get_ylim() - + if str(self.ui.lineEdit_5.text()) == "": # Empty. Default to minY newminY = ylim[0] - else: + else: # Non empty. Parse newminY = float(self.ui.lineEdit_5.text()) @@ -551,7 +549,7 @@ def set_minLogValue(self): # Move the vertical line lowerx = self.ui.mainplot.get_xlim() - lowery = [newminY, newminY] + lowery = [newminY, newminY] setp(self.lowerslideline, xdata=lowerx, ydata=lowery) self.ui.graphicsView.draw() @@ -568,9 +566,9 @@ def set_minLogValue(self): return def move_upperSlider(self): - """ Re-setup upper range line in figure. - Triggered by a change in Qt Widget. NO EVENT is required. - """ + """ Re-setup upper range line in figure. + Triggered by a change in Qt Widget. NO EVENT is required. + """ inewy = self.ui.verticalSlider.value() # Return w/o change @@ -640,7 +638,7 @@ def set_maxLogValue(self): # Move the vertical line upperx = self.ui.mainplot.get_xlim() - uppery = [newmaxY, newmaxY] + uppery = [newmaxY, newmaxY] setp(self.upperslideline, xdata=upperx, ydata=uppery) self.ui.graphicsView.draw() @@ -658,7 +656,7 @@ def set_maxLogValue(self): def browse_File(self): """ Open a file dialog to get file """ - filename = QtGui.QFileDialog.getOpenFileName(self, 'Input File Dialog', + filename = QtGui.QFileDialog.getOpenFileName(self, 'Input File Dialog',\ self._defaultdir, "Data (*.nxs *.dat);;All files (*.*)") self.ui.lineEdit.setText(str(filename)) @@ -699,10 +697,10 @@ def use_existWS(self): """ wsname = str(self.ui.comboBox.currentText()) - try: + try: dataws = AnalysisDataService.retrieve(wsname) self._importDataWorkspace(dataws) - except KeyError: + except KeyError: pass # Reset GUI @@ -725,7 +723,7 @@ def plotLogValue(self): vecvalue = samplelog.value # check - if len(vectimes) == 0: + if len(vectimes) == 0: print "Empty log!" # Convert absolute time to relative time in seconds @@ -748,7 +746,7 @@ def plotLogValue(self): self.ui.mainplot.set_xlim(xlim[0], xlim[1]) self.ui.mainplot.set_ylim(ylim[0], ylim[1]) - setp(self.mainline, xdata=vecreltimes, ydata=vecvalue) + setp(self.mainline, xdata=vecreltimes, ydata=vecvalue) samunit = samplelog.units if len(samunit) == 0: @@ -767,7 +765,7 @@ def plotLogValue(self): self.ui.verticalSlider_2.setValue(self._lowerSlideValue) self.ui.lineEdit_5.setText("") - setp(self.upperslideline, xdata=xlim, ydata=[ylim[1], ylim[1]]) + setp(self.upperslideline, xdata=xlim, ydata=[ylim[1], ylim[1]]) self._upperSlideValue = 100 self.ui.verticalSlider.setValue(self._upperSlideValue) self.ui.lineEdit_6.setText("") @@ -785,8 +783,8 @@ def plotLogValue(self): self.ui.label_mean.show() self.ui.label_meanvalue.show() - self.ui.label_avg.show() - self.ui.label_timeAvgValue.show() + self.ui.label_avg.show() + self.ui.label_timeAvgValue.show() self.ui.label_freq.show() self.ui.label_freqValue.show() self.ui.label_logname.show() @@ -803,7 +801,7 @@ def plotLogValue(self): # Set suggested processing scheme if numentries > HUGE_FAST: self.ui.checkBox_fastLog.setCheckState(True) - if numentries > HUGE_PARALLEL: + if numentries > HUGE_PARALLEL: self.ui.checkBox_doParallel.setCheckState(True) else: self.ui.checkBox_doParallel.setCheckState(False) @@ -817,7 +815,7 @@ def plotLogValue(self): def _importDataWorkspace(self, dataws): """ Import data workspace for filtering """ - if dataws is None: + if dataws is None: return # Plot time counts @@ -827,7 +825,7 @@ def _importDataWorkspace(self, dataws): failure! \n%s\n" % (str(dataws), errmsg) self._setErrorMsg(errmsg) return False - + # Import log self._sampleLogNames = [""] @@ -837,19 +835,19 @@ def _importDataWorkspace(self, dataws): pv = p.value if isinstance(pv, numpy.ndarray): times = p.times - if len(times) > 1: + if len(times) > 1: self._sampleLogNames.append(p.name) # ENDFOR(p) - # Set up sample log + # Set up sample log self.ui.comboBox_2.clear() self.ui.comboBox_2.addItems(self._sampleLogNames) # Side information self.ui.label_mean.hide() self.ui.label_meanvalue.hide() - self.ui.label_avg.hide() - self.ui.label_timeAvgValue.hide() + self.ui.label_avg.hide() + self.ui.label_timeAvgValue.hide() self.ui.label_freq.hide() self.ui.label_freqValue.hide() @@ -858,12 +856,12 @@ def _importDataWorkspace(self, dataws): self.ui.label_lognamevalue.hide() # Set dataws to class variable - self._dataWS = dataws + self._dataWS = dataws return True def scanEventWorkspaces(self): - """ + """ """ wsnames = AnalysisDataService.getObjectNames() @@ -874,7 +872,7 @@ def scanEventWorkspaces(self): eventwsnames.append(wsname) # ENDFOR - if len(eventwsnames) > 0: + if len(eventwsnames) > 0: self.ui.comboBox.clear() self.ui.comboBox.addItems(eventwsnames) @@ -894,7 +892,7 @@ def _loadFile(self, filename): if runnumber <= 0: print "Run number cannot be less or equal to zero. User gives %s. " % (filename) return None - else: + else: ishort = config.getInstrument(self._instrument).shortName() filename = "%s_%s" %(ishort, filename) wsname = filename + "_event" @@ -922,22 +920,22 @@ def _loadFile(self, filename): return None # Load - try: + try: ws = api.Load(Filename=filename, OutputWorkspace=wsname) except: ws = None return ws - + def _plotTimeCounts(self, wksp): - """ Plot time/counts + """ Plot time/counts """ import datetime # Rebin events by pulse time try: # Get run start and run stop - if wksp.getRun().hasProperty("run_start"): + if wksp.getRun().hasProperty("run_start"): runstart = wksp.getRun().getProperty("run_start").value else: runstart = wksp.getRun().getProperty("proton_charge").times[0] @@ -945,11 +943,11 @@ def _plotTimeCounts(self, wksp): runstart = str(runstart).split(".")[0].strip() runstop = str(runstop).split(".")[0].strip() - + t0 = datetime.datetime.strptime(runstart, "%Y-%m-%dT%H:%M:%S") tf = datetime.datetime.strptime(runstop, "%Y-%m-%dT%H:%M:%S") - - # Calcualte + + # Calcualte dt = tf-t0 timeduration = dt.days*3600*24 + dt.seconds @@ -959,7 +957,7 @@ def _plotTimeCounts(self, wksp): sumwsname = "_Summed_%s"%(str(wksp)) if AnalysisDataService.doesExist(sumwsname) is False: - sumws = api.RebinByPulseTimes(InputWorkspace=wksp, OutputWorkspace = sumwsname, + sumws = api.RebinByPulseTimes(InputWorkspace=wksp, OutputWorkspace = sumwsname,\ Params="0, %f, %d"%(timeres, timeduration)) sumws = api.SumSpectra(InputWorkspace=sumws, OutputWorkspace=str(sumws)) sumws = api.ConvertToPointData(InputWorkspace=sumws, OutputWorkspace=str(sumws)) @@ -976,7 +974,7 @@ def _plotTimeCounts(self, wksp): ymin = min(vecy) ymax = max(vecy) - # Reset graph + # Reset graph self.ui.mainplot.set_xlim(xmin, xmax) self.ui.mainplot.set_ylim(ymin, ymax) @@ -984,16 +982,16 @@ def _plotTimeCounts(self, wksp): self.ui.mainplot.set_ylabel('Counts', fontsize=13) # Set up main line - setp(self.mainline, xdata=vecx, ydata=vecy) + setp(self.mainline, xdata=vecx, ydata=vecy) # Reset slide newslidery = [min(vecy), max(vecy)] newleftx = xmin + (xmax-xmin)*self._leftSlideValue*0.01 - setp(self.leftslideline, xdata=[newleftx, newleftx], ydata=newslidery) + setp(self.leftslideline, xdata=[newleftx, newleftx], ydata=newslidery) newrightx = xmin + (xmax-xmin)*self._rightSlideValue*0.01 - setp(self.rightslideline, xdata=[newrightx, newrightx], ydata=newslidery) + setp(self.rightslideline, xdata=[newrightx, newrightx], ydata=newslidery) self.ui.graphicsView.draw() @@ -1020,17 +1018,17 @@ def filterByTime(self): title = str(self.ui.lineEdit_title.text()) - """ Debug + """ Debug for k in kwargs.keys(): print k, kwargs[k], type(kwargs[k]) print "Input workspace = ", str(self._dataWS) END DB """ - splitws, infows = api.GenerateEventsFilter( - InputWorkspace = self._dataWS, - UnitOfTime = "Seconds", - TitleOfSplitters = title, - OutputWorkspace = splitwsname, + splitws, infows = api.GenerateEventsFilter(\ + InputWorkspace = self._dataWS,\ + UnitOfTime = "Seconds",\ + TitleOfSplitters = title,\ + OutputWorkspace = splitwsname,\ InformationWorkspace = splitinfowsname, **kwargs) self.splitWksp(splitws, infows) @@ -1073,22 +1071,22 @@ def filterByLogValue(self): if self.ui.lineEdit_8.text() != "": logvaluetol = float(self.ui.lineEdit_8.text()) kwargs["LogValueTolerance"] = logvaluetol - + splitwsname = str(self._dataWS) + "_splitters" splitinfowsname = str(self._dataWS) + "_info" title = str(self.ui.lineEdit_title.text()) - splitws, infows = api.GenerateEventsFilter( - InputWorkspace = self._dataWS, - UnitOfTime = "Seconds", - TitleOfSplitters = title, - OutputWorkspace = splitwsname, - LogName = samplelog, + splitws, infows = api.GenerateEventsFilter(\ + InputWorkspace = self._dataWS,\ + UnitOfTime = "Seconds",\ + TitleOfSplitters = title,\ + OutputWorkspace = splitwsname,\ + LogName = samplelog,\ InformationWorkspace = splitinfowsname, **kwargs) - try: + try: self.splitWksp(splitws, infows) except Exception as mtderror: self._setErrorMsg("Splitting Failed!\n %s" % (str(mtderror))) @@ -1119,19 +1117,19 @@ def splitWksp(self, splitws, infows): if len(outbasewsname) == 0: outbasewsname = "tempsplitted" self.ui.lineEdit_outwsname.setText(outbasewsname) - - api.FilterEvents( - InputWorkspace = self._dataWS, - SplitterWorkspace = splitws, - InformationWorkspace = infows, - OutputWorkspaceBaseName = outbasewsname, - GroupWorkspaces = dogroupws, - FilterByPulseTime = filterbypulse, - CorrectionToSample = corr2sample, - SpectrumWithoutDetector = how2skip, - SplitSampleLogs = splitsamplelog, - OutputWorkspaceIndexedFrom1 = startfrom1, - OutputTOFCorrectionWorkspace = 'TOFCorrTable', **kwargs) + + api.FilterEvents(\ + InputWorkspace = self._dataWS,\ + SplitterWorkspace = splitws,\ + InformationWorkspace = infows,\ + OutputWorkspaceBaseName = outbasewsname,\ + GroupWorkspaces = dogroupws,\ + FilterByPulseTime = filterbypulse,\ + CorrectionToSample = corr2sample,\ + SpectrumWithoutDetector = how2skip,\ + SplitSampleLogs = splitsamplelog,\ + OutputWorkspaceIndexedFrom1 = startfrom1,\ + OutputTOFCorrectionWorkspace = 'TOFCorrTable', **kwargs) return @@ -1173,12 +1171,12 @@ def _searchTableWorkspaces(self): tablewsnames = [] for wsname in wsnames: wksp = AnalysisDataService.retrieve(wsname) - if isinstance(wksp, mantid.api._api.ITableWorkspace): + if isinstance(wksp, mantid.api._api.ITableWorkspace): tablewsnames.append(wsname) # ENDFOR self.ui.comboBox_corrWS.clear() - if len(tablewsnames) > 0: + if len(tablewsnames) > 0: self.ui.comboBox_corrWS.addItems(tablewsnames) return @@ -1193,7 +1191,7 @@ def _clearErrorMsg(self): def _setErrorMsg(self, errmsg): """ Clear error message - """ + """ #self.ui.plainTextEdit_ErrorMsg.setPlainText(errmsg) #self.ui.label_error.show() @@ -1206,7 +1204,7 @@ def _setErrorMsg(self, errmsg): def _resetGUI(self, resetfilerun=False, resetwslist=False): - """ Reset GUI including all text edits and etc. + """ Reset GUI including all text edits and etc. """ if resetfilerun is True: self.ui.lineEdit.clear() @@ -1231,7 +1229,7 @@ def _resetGUI(self, resetfilerun=False, resetwslist=False): ylim = self.ui.mainplot.get_ylim() miny = ylim[0] maxy = ylim[1] - xlim = self.ui.mainplot.get_xlim() + xlim = self.ui.mainplot.get_xlim() setp(self.lowerslideline, xdata=xlim, ydata=[miny, miny]) setp(self.upperslideline, xdata=xlim, ydata=[maxy, maxy]) self.ui.graphicsView.draw() @@ -1251,7 +1249,7 @@ def _resetGUI(self, resetfilerun=False, resetwslist=False): self.ui.checkBox_doParallel.setCheckState(False) self.ui.comboBox_skipSpectrum.setCurrentIndex(0) - + self.ui.checkBox_filterByPulse.setCheckState(False) self.ui.checkBox_from1.setCheckState(False) self.ui.checkBox_groupWS.setCheckState(True) diff --git a/Code/Mantid/scripts/ISIS_Reflectometry.py b/Code/Mantid/scripts/ISIS_Reflectometry.py index 223b2c98b0ab..f06283585df5 100644 --- a/Code/Mantid/scripts/ISIS_Reflectometry.py +++ b/Code/Mantid/scripts/ISIS_Reflectometry.py @@ -1,8 +1,7 @@ +#pylint: disable=invalid-name """ Script used to start the ISIS Reflectomery GUI from MantidPlot """ -from PyQt4 import QtGui -#, QtCore from ui.reflectometer import refl_gui ui = refl_gui.ReflGui() diff --git a/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py b/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py index 478deaad9031..3db587f22559 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py +++ b/Code/Mantid/scripts/Inelastic/Direct/CommonFunctions.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import mantid from mantid.simpleapi import * from mantid import api @@ -7,7 +8,7 @@ class switch(object): - """ Helper class providing nice switch statement""" + """ Helper class providing nice switch statement""" def __init__(self, value): self.value = value self.fall = False @@ -16,7 +17,7 @@ def __iter__(self): """Return the match method once, then stop""" yield self.match raise StopIteration - + def match(self, *args): """Indicate whether or not to enter a case suite""" if self.fall or not args: @@ -25,4 +26,4 @@ def match(self, *args): self.fall = True return True else: - return False \ No newline at end of file + return False diff --git a/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py b/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py index b8f8a243a226..ea76a73778e2 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py +++ b/Code/Mantid/scripts/Inelastic/Direct/DirectEnergyConversion.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * from mantid.kernel import funcreturns from mantid import geometry,api @@ -26,7 +27,7 @@ def setup_reducer(inst_name,reload_instrument=False): class DirectEnergyConversion(object): """ - Performs a convert to energy assuming the provided instrument is + Performs a convert to energy assuming the provided instrument is an direct inelastic geometry instrument The class defines various methods to allow users to convert their @@ -34,7 +35,7 @@ class DirectEnergyConversion(object): Usage: >>red = DirectEnergyConversion('InstrumentName') - and then: + and then: >>red.convert_to_energy(wb_run,sample_run,ei_guess,rebin) or >>red.convert_to_energy(wb_run,sample_run,ei_guess,rebin,**arguments) @@ -42,7 +43,7 @@ class DirectEnergyConversion(object): >>red.convert_to_energy(wb_run,sample_run,ei_guess,rebin,mapfile,**arguments) or >>red.prop_man.sample_run = run number - >>red.prop_man.wb_run = Whitebeam + >>red.prop_man.wb_run = Whitebeam >>red.prop_man.incident_energy = energy guess >>red.prop_man.energy_bins = [min_val,step,max_val] >>red.convert_to_energy() @@ -51,14 +52,14 @@ class DirectEnergyConversion(object): Whitebeam run number or file name or workspace sample_run sample run number or file name or workspace ei_guess suggested value for incident energy of neutrons in direct inelastic instrument - energy_bins energy binning requested for resulting spe workspace. + energy_bins energy binning requested for resulting spe workspace. mapfile Mapfile -- if absent/'default' the defaults from IDF are used monovan_run If present will do the absolute units normalization. Number of additional parameters specified in **kwargs is usually requested for this. If they are absent, program uses defaults, but the defaults (e.g. sample_mass or sample_rmm ) are usually incorrect for a particular run. arguments The dictionary containing additional keyword arguments. - The list of allowed additional arguments is defined in InstrName_Parameters.xml + The list of allowed additional arguments is defined in InstrName_Parameters.xml file, located in: MantidPlot->View->Preferences->Mantid->Directories->Parameter Definitions @@ -87,13 +88,13 @@ class DirectEnergyConversion(object): bkgd_range =[15000,19000] :integration range for background tests - second_white - If provided an additional set of tests is performed on this. + second_white - If provided an additional set of tests is performed on this. (default = None) hardmaskPlus - A file specifying those spectra that should be masked without testing (default=None) tiny - Minimum threshold for acceptance (default = 1e-10) large - Maximum threshold for acceptance (default = 1e10) - bkgd_range - A list of two numbers indicating the background range + bkgd_range - A list of two numbers indicating the background range (default=instrument defaults) diag_van_median_rate_limit_lo - Lower bound defining outliers as fraction of median value (default = 0.01) diag_van_median_rate_limit_hi - Upper bound defining outliers as fraction of median value (default = 100.) @@ -133,7 +134,7 @@ class DirectEnergyConversion(object): """ #------------------------------------------------------------------------------- def diagnose(self, white,diag_sample=None,**kwargs): - """ run diagnostics on the provided workspaces. + """ run diagnostics on the provided workspaces. this method does some additional processing before moving on to the diagnostics: 1) Computes the white beam integrals, converting to energy @@ -177,325 +178,325 @@ def diagnose(self, white,diag_sample=None,**kwargs): bleed_pixels - If the bleed test is on then this is the number of pixels ignored within the bleed test diagnostic """ - lhs_names = funcreturns.lhs_info('names') - if len(lhs_names) > 0: - var_name = lhs_names[0] - else: - var_name = "diag_mask" + lhs_names = funcreturns.lhs_info('names') + if len(lhs_names) > 0: + var_name = lhs_names[0] + else: + var_name = "diag_mask" # modify properties using input arguments - self.prop_man.set_input_parameters(**kwargs) + self.prop_man.set_input_parameters(**kwargs) # obtain proper run descriptor in case it is not a run descriptor but # something else - white = self.get_run_descriptor(white) + white = self.get_run_descriptor(white) # return all diagnostics parameters - diag_params = self.prop_man.get_diagnostics_parameters() + diag_params = self.prop_man.get_diagnostics_parameters() - if self.use_hard_mask_only: - if mtd.doesExist('hard_mask_ws'): - diag_mask = mtd['hard_mask_ws'] - else: # build hard mask + if self.use_hard_mask_only: + if mtd.doesExist('hard_mask_ws'): + diag_mask = mtd['hard_mask_ws'] + else: # build hard mask # in this peculiar way we can obtain working mask which # accounts for initial data grouping in the # data file. SNS or 1 to 1 maps may probably avoid this # stuff and can load masks directly - white_data = white.get_ws_clone('white_ws_clone') + white_data = white.get_ws_clone('white_ws_clone') - diag_mask = LoadMask(Instrument=self.instr_name,InputFile=self.hard_mask_file, + diag_mask = LoadMask(Instrument=self.instr_name,InputFile=self.hard_mask_file,\ OutputWorkspace='hard_mask_ws') - MaskDetectors(Workspace=white_data, MaskedWorkspace=diag_mask) - DeleteWorkspace(diag_mask) - diag_mask,masked_list = ExtractMask(InputWorkspace=white_data) - DeleteWorkspace(Workspace='white_ws_clone') + MaskDetectors(Workspace=white_data, MaskedWorkspace=diag_mask) + DeleteWorkspace(diag_mask) + diag_mask,masked_list = ExtractMask(InputWorkspace=white_data) + DeleteWorkspace(Workspace='white_ws_clone') - return diag_mask + return diag_mask # Get the white beam vanadium integrals - whiteintegrals = self.do_white(white, None, None) # No grouping yet - if self.second_white: - second_white = self.second_white - other_whiteintegrals = self.do_white(PropertyManager.second_white, None, None) # No grouping yet - self.second_white = other_whiteintegrals + whiteintegrals = self.do_white(white, None, None) # No grouping yet + if self.second_white: + second_white = self.second_white + other_whiteintegrals = self.do_white(PropertyManager.second_white, None, None) # No grouping yet + self.second_white = other_whiteintegrals # Get the background/total counts from the sample run if present - if diag_sample: - diag_sample = self.get_run_descriptor(diag_sample) + if diag_sample: + diag_sample = self.get_run_descriptor(diag_sample) # If the bleed test is requested then we need to pass in the # sample_run as well - if self.bleed_test: + if self.bleed_test: # initiate reference to reducer to be able to work with Run # Descriptors - diagnostics.__Reducer__ = self - diag_params['sample_run'] = diag_sample + diagnostics.__Reducer__ = self + diag_params['sample_run'] = diag_sample # Set up the background integrals for diagnostic purposes - result_ws = self.normalise(diag_sample, self.normalise_method) + result_ws = self.normalise(diag_sample, self.normalise_method) #>>> here result workspace is being processed -- not touching #result ws - bkgd_range = self.background_test_range - background_int = Integration(result_ws, - RangeLower=bkgd_range[0],RangeUpper=bkgd_range[1], + bkgd_range = self.background_test_range + background_int = Integration(result_ws,\ + RangeLower=bkgd_range[0],RangeUpper=bkgd_range[1],\ IncludePartialBins=True) - total_counts = Integration(result_ws, IncludePartialBins=True) - background_int = ConvertUnits(background_int, Target="Energy",EMode='Elastic', AlignBins=0) - self.prop_man.log("Diagnose: finished convertUnits ",'information') + total_counts = Integration(result_ws, IncludePartialBins=True) + background_int = ConvertUnits(background_int, Target="Energy",EMode='Elastic', AlignBins=0) + self.prop_man.log("Diagnose: finished convertUnits ",'information') - background_int *= self.scale_factor - diagnostics.normalise_background(background_int, whiteintegrals, + background_int *= self.scale_factor + diagnostics.normalise_background(background_int, whiteintegrals,\ diag_params.get('second_white',None)) - diag_params['background_int'] = background_int - diag_params['sample_counts'] = total_counts + diag_params['background_int'] = background_int + diag_params['sample_counts'] = total_counts # Check how we should run diag - diag_spectra_blocks = self.diag_spectra - if diag_spectra_blocks is None: + diag_spectra_blocks = self.diag_spectra + if diag_spectra_blocks is None: # Do the whole lot at once - diagnostics.diagnose(whiteintegrals, **diag_params) - else: - for index, bank in enumerate(diag_spectra_blocks): - diag_params['start_index'] = bank[0] - 1 - diag_params['end_index'] = bank[1] - 1 - diagnostics.diagnose(whiteintegrals, **diag_params) - - if 'sample_counts' in diag_params: - DeleteWorkspace(Workspace='background_int') - DeleteWorkspace(Workspace='total_counts') - if 'second_white' in diag_params: - DeleteWorkspace(Workspace=diag_params['second_white']) + diagnostics.diagnose(whiteintegrals, **diag_params) + else: + for index, bank in enumerate(diag_spectra_blocks): + diag_params['start_index'] = bank[0] - 1 + diag_params['end_index'] = bank[1] - 1 + diagnostics.diagnose(whiteintegrals, **diag_params) + + if 'sample_counts' in diag_params: + DeleteWorkspace(Workspace='background_int') + DeleteWorkspace(Workspace='total_counts') + if 'second_white' in diag_params: + DeleteWorkspace(Workspace=diag_params['second_white']) # Extract a mask workspace - diag_mask, det_ids = ExtractMask(InputWorkspace=whiteintegrals,OutputWorkspace=var_name) + diag_mask, det_ids = ExtractMask(InputWorkspace=whiteintegrals,OutputWorkspace=var_name) - DeleteWorkspace(Workspace=whiteintegrals) + DeleteWorkspace(Workspace=whiteintegrals) #TODO do we need this? #self.spectra_masks = diag_mask - return diag_mask + return diag_mask #------------------------------------------------------------------------------- def convert_to_energy(self,wb_run=None,sample_run=None,ei_guess=None,rebin=None,map_file=None, monovan_run=None,wb_for_monovan_run=None,**kwargs): - """ One step conversion of run into workspace containing information about energy transfer + """ One step conversion of run into workspace containing information about energy transfer - """ + """ # Support for old reduction interface: - self.prop_man.set_input_parameters_ignore_nan\ + self.prop_man.set_input_parameters_ignore_nan\ (wb_run=wb_run,sample_run=sample_run,incident_energy=ei_guess,energy_bins=rebin, map_file=map_file,monovan_run=monovan_run,wb_for_monovan_run=wb_for_monovan_run) # - self.prop_man.set_input_parameters(**kwargs) + self.prop_man.set_input_parameters(**kwargs) # output workspace name. - try: - n,r = funcreturns.lhs_info('both') - out_ws_name = r[0] - except: - out_ws_name = None + try: + n,r = funcreturns.lhs_info('both') + out_ws_name = r[0] + except: + out_ws_name = None # inform user on what parameters have changed from script or gui # if monovan present, check if abs_norm_ parameters are set - self.prop_man.log_changed_values('notice') - prop_man = self.prop_man + self.prop_man.log_changed_values('notice') + prop_man = self.prop_man #process complex parameters - start_time = time.time() + start_time = time.time() # check if reducer can find all non-run files necessary for the reduction # before starting long run. #TODO: # Reducer.check_necessary_files(monovan_run) - PropertyManager.sample_run.set_action_suffix('') - sample_ws = PropertyManager.sample_run.get_workspace() + PropertyManager.sample_run.set_action_suffix('') + sample_ws = PropertyManager.sample_run.get_workspace() # Update reduction properties which may change in the workspace but have # not been modified from input parameters. # E.g. detector number have changed - oldChanges = self.prop_man.getChangedProperties() - allChanges = self.prop_man.update_defaults_from_instrument(sample_ws.getInstrument()) - workspace_defined_prop = allChanges.difference(oldChanges) - if len(workspace_defined_prop) > 0: - prop_man.log("****************************************************************") - prop_man.log('*** Sample run {0} properties change default reduction properties: '.\ + oldChanges = self.prop_man.getChangedProperties() + allChanges = self.prop_man.update_defaults_from_instrument(sample_ws.getInstrument()) + workspace_defined_prop = allChanges.difference(oldChanges) + if len(workspace_defined_prop) > 0: + prop_man.log("****************************************************************") + prop_man.log('*** Sample run {0} properties change default reduction properties: '.\ format(PropertyManager.sample_run.get_ws_name())) - prop_man.log_changed_values('notice',False,oldChanges) - prop_man.log("****************************************************************") + prop_man.log_changed_values('notice',False,oldChanges) + prop_man.log("****************************************************************") - masking = None - masks_done = False - if not prop_man.run_diagnostics: - header = "*** Diagnostics including hard masking is skipped " - masks_done = True + masking = None + masks_done = False + if not prop_man.run_diagnostics: + header = "*** Diagnostics including hard masking is skipped " + masks_done = True #if Reducer.save_and_reuse_masks : # SAVE AND REUSE MASKS - if self.spectra_masks: - masks_done = True + if self.spectra_masks: + masks_done = True #-------------------------------------------------------------------------------------------------- # Diagnostics here # ------------------------------------------------------------------------------------------------- # diag the sample and detector vanadium. It will deal with hard mask only # if it is set that way - if not masks_done: - prop_man.log("======== Run diagnose for sample run ===========================",'notice') - masking = self.diagnose(PropertyManager.wb_run,PropertyManager.mask_run, + if not masks_done: + prop_man.log("======== Run diagnose for sample run ===========================",'notice') + masking = self.diagnose(PropertyManager.wb_run,PropertyManager.mask_run,\ second_white=None,print_diag_results=True) - if prop_man.use_hard_mask_only: - header = "*** Hard mask file applied to workspace with {0:d} spectra masked {1:d} spectra" - else: - header = "*** Diagnostics processed workspace with {0:d} spectra and masked {1:d} bad spectra" + if prop_man.use_hard_mask_only: + header = "*** Hard mask file applied to workspace with {0:d} spectra masked {1:d} spectra" + else: + header = "*** Diagnostics processed workspace with {0:d} spectra and masked {1:d} bad spectra" # diagnose absolute units: - if self.monovan_run != None : - if self.mono_correction_factor == None : - if self.use_sam_msk_on_monovan == True: - prop_man.log(' Applying sample run mask to mono van') - else: - if not self.use_hard_mask_only : # in this case the masking2 is different but + if self.monovan_run != None : + if self.mono_correction_factor == None : + if self.use_sam_msk_on_monovan == True: + prop_man.log(' Applying sample run mask to mono van') + else: + if not self.use_hard_mask_only : # in this case the masking2 is different but #points to the same #workspace # Should be better # solution for that. - prop_man.log("======== Run diagnose for monochromatic vanadium run ===========",'notice') + prop_man.log("======== Run diagnose for monochromatic vanadium run ===========",'notice') - masking2 = self.diagnose(PropertyManager.wb_for_monovan_run,PropertyManager.monovan_run, + masking2 = self.diagnose(PropertyManager.wb_for_monovan_run,PropertyManager.monovan_run,\ second_white = None,print_diag_results=True) - masking += masking2 - DeleteWorkspace(masking2) + masking += masking2 + DeleteWorkspace(masking2) - else: # if Reducer.mono_correction_factor != None : - pass + else: # if Reducer.mono_correction_factor != None : + pass # Very important statement propagating masks for further usage in # convert_to_energy. # This property is also directly accessible from GUI. - self.spectra_masks = masking + self.spectra_masks = masking # save mask if it does not exist and has been already loaded #if Reducer.save_and_reuse_masks and not masks_done: # SaveMask(InputWorkspace=masking,OutputFile = # mask_file_name,GroupedDetectors=True) - else: - header = '*** Using stored mask file for workspace with {0} spectra and {1} masked spectra' - masking = self.spectra_masks - + else: + header = '*** Using stored mask file for workspace with {0} spectra and {1} masked spectra' + masking = self.spectra_masks + # estimate and report the number of failing detectors - failed_sp_list,nMaskedSpectra = get_failed_spectra_list_from_masks(masking) - if masking: - nSpectra = masking.getNumberHistograms() - else: - nSpectra = 0 - prop_man.log(header.format(nSpectra,nMaskedSpectra),'notice') + failed_sp_list,nMaskedSpectra = get_failed_spectra_list_from_masks(masking) + if masking: + nSpectra = masking.getNumberHistograms() + else: + nSpectra = 0 + prop_man.log(header.format(nSpectra,nMaskedSpectra),'notice') #-------------------------------------------------------------------------------------------------- # now reduction #-------------------------------------------------------------------------------------------------- # SNS or GUI motor stuff - self.calculate_rotation(PropertyManager.sample_run.get_workspace()) + self.calculate_rotation(PropertyManager.sample_run.get_workspace()) # - if self.monovan_run != None: - MonovanCashNum = PropertyManager.monovan_run.run_number() - if self.mono_correction_factor: - calculate_abs_units = False # correction factor given, so no calculations - else: - calculate_abs_units = True - else: - MonovanCashNum = None - calculate_abs_units = False - PropertyManager.mono_correction_factor.set_cash_mono_run_number(MonovanCashNum) - - - if PropertyManager.incident_energy.multirep_mode(): - self._multirep_mode = True - ws_base = None - mono_ws_base = None - num_ei_cuts = len(self.incident_energy) - if self.check_background: + if self.monovan_run != None: + MonovanCashNum = PropertyManager.monovan_run.run_number() + if self.mono_correction_factor: + calculate_abs_units = False # correction factor given, so no calculations + else: + calculate_abs_units = True + else: + MonovanCashNum = None + calculate_abs_units = False + PropertyManager.mono_correction_factor.set_cash_mono_run_number(MonovanCashNum) + + + if PropertyManager.incident_energy.multirep_mode(): + self._multirep_mode = True + ws_base = None + mono_ws_base = None + num_ei_cuts = len(self.incident_energy) + if self.check_background: # find the count rate seen in the regions of the histograms # defined as the background regions, if the user defined such # region - ws_base = PropertyManager.sample_run.get_workspace() - bkgd_range = self.bkgd_range - bkgr_ws=self._find_or_build_bkgr_ws(ws_base,bkgd_range[0],bkgd_range[1]) - RenameWorkspace(InputWorkspace=bkgr_ws, OutputWorkspace='bkgr_ws_source') - # initialize list to store resulting workspaces to return - result = [] - else: - self._multirep_mode = False - num_ei_cuts = 0 - - cut_ind = 0 # do not do enumerate if it generates all sequence at once + ws_base = PropertyManager.sample_run.get_workspace() + bkgd_range = self.bkgd_range + bkgr_ws=self._find_or_build_bkgr_ws(ws_base,bkgd_range[0],bkgd_range[1]) + RenameWorkspace(InputWorkspace=bkgr_ws, OutputWorkspace='bkgr_ws_source') + # initialize list to store resulting workspaces to return + result = [] + else: + self._multirep_mode = False + num_ei_cuts = 0 + + cut_ind = 0 # do not do enumerate if it generates all sequence at once # -- code below uses current energy state from # PropertyManager.incident_energy - for ei_guess in PropertyManager.incident_energy: - cut_ind +=1 + for ei_guess in PropertyManager.incident_energy: + cut_ind +=1 #--------------- - if self._multirep_mode: - tof_range = self.find_tof_range_for_multirep(ws_base) - ws_base = PropertyManager.sample_run.chop_ws_part(ws_base,tof_range,self._do_early_rebinning,cut_ind,num_ei_cuts) - prop_man.log("*** Processing multirep chunk: #{0}/{1} for provisional energy: {2} meV".format(cut_ind,num_ei_cuts,ei_guess),'notice') + if self._multirep_mode: + tof_range = self.find_tof_range_for_multirep(ws_base) + ws_base = PropertyManager.sample_run.chop_ws_part(ws_base,tof_range,self._do_early_rebinning,cut_ind,num_ei_cuts) + prop_man.log("*** Processing multirep chunk: #{0}/{1} for provisional energy: {2} meV".format(cut_ind,num_ei_cuts,ei_guess),'notice') #--------------- #Run the conversion first on the sample - deltaE_ws_sample = self.mono_sample(PropertyManager.sample_run,ei_guess,PropertyManager.wb_run, + deltaE_ws_sample = self.mono_sample(PropertyManager.sample_run,ei_guess,PropertyManager.wb_run,\ self.map_file,masking) - + # calculate absolute units integral and apply it to the workspace - cashed_mono_int = PropertyManager.mono_correction_factor.get_val_from_cash(prop_man) - if MonovanCashNum != None or self.mono_correction_factor or cashed_mono_int : + cashed_mono_int = PropertyManager.mono_correction_factor.get_val_from_cash(prop_man) + if MonovanCashNum != None or self.mono_correction_factor or cashed_mono_int : # do not remove background from vanadium (sample background is not fit for that anyway) - current_bkg_opt = self.check_background - self.check_background= False - # what we want to do with absolute units: - if self.mono_correction_factor: # Correction provided. Just apply it - deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, + current_bkg_opt = self.check_background + self.check_background= False + # what we want to do with absolute units: + if self.mono_correction_factor: # Correction provided. Just apply it + deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run,\ ei_guess,PropertyManager.wb_for_monovan_run) - elif cashed_mono_int: # Correction cashed from previous run - self.mono_correction_factor = cashed_mono_int - deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, + elif cashed_mono_int: # Correction cashed from previous run + self.mono_correction_factor = cashed_mono_int + deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run,\ ei_guess,PropertyManager.wb_for_monovan_run) - self.mono_correction_factor = None - else: # Calculate corrections - if self._multirep_mode and calculate_abs_units: - mono_ws_base = PropertyManager.monovan_run.chop_ws_part(mono_ws_base,tof_range,self._do_early_rebinning, + self.mono_correction_factor = None + else: # Calculate corrections + if self._multirep_mode and calculate_abs_units: + mono_ws_base = PropertyManager.monovan_run.chop_ws_part(mono_ws_base,tof_range,self._do_early_rebinning,\ cut_ind,num_ei_cuts) - deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run, + deltaE_ws_sample = self.apply_absolute_normalization(deltaE_ws_sample,PropertyManager.monovan_run,\ ei_guess,PropertyManager.wb_for_monovan_run) - self.check_background = current_bkg_opt + self.check_background = current_bkg_opt # ensure that the sample_run name is intact with workspace - PropertyManager.sample_run.synchronize_ws(deltaE_ws_sample) + PropertyManager.sample_run.synchronize_ws(deltaE_ws_sample) # - ei = (deltaE_ws_sample.getRun().getLogData("Ei").value) + ei = (deltaE_ws_sample.getRun().getLogData("Ei").value) # PropertyManager.incident_energy.set_current(ei) # let's not do it -- # this makes subsequent calls to this method depend on # # previous calls - prop_man.log("*** Incident energy found for sample run: {0} meV".format(ei),'notice') + prop_man.log("*** Incident energy found for sample run: {0} meV".format(ei),'notice') # - self.save_results(deltaE_ws_sample) - if out_ws_name: - if self._multirep_mode: - result.append(deltaE_ws_sample) - else: # delete workspace if no output is requested - self.sample_run = None + self.save_results(deltaE_ws_sample) + if out_ws_name: + if self._multirep_mode: + result.append(deltaE_ws_sample) + else: # delete workspace if no output is requested + self.sample_run = None - results_name = deltaE_ws_sample.name() - if out_ws_name and not(self._multirep_mode): - if results_name != out_ws_name: - RenameWorkspace(InputWorkspace=results_name,OutputWorkspace=out_ws_name) - result = mtd[out_ws_name] - else: - pass + results_name = deltaE_ws_sample.name() + if out_ws_name and not self._multirep_mode: + if results_name != out_ws_name: + RenameWorkspace(InputWorkspace=results_name,OutputWorkspace=out_ws_name) + result = mtd[out_ws_name] + else: + pass - end_time = time.time() - prop_man.log("*** Elapsed time = {0} sec".format(end_time - start_time),'notice') + end_time = time.time() + prop_man.log("*** Elapsed time = {0} sec".format(end_time - start_time),'notice') # Hack for multirep mode? # if mtd.doesExist('hard_mask_ws') == True: @@ -505,15 +506,15 @@ def convert_to_energy(self,wb_run=None,sample_run=None,ei_guess=None,rebin=None, # CLEAN-up (may be worth to do in separate procedure) # Currently clear masks unconditionally TODO: cash masks with appropriate # precautions - self.spectra_masks = None + self.spectra_masks = None #self.prop_man.wb_run = None # clean up memory of the wb run (only in #case of file based wb) - if 'bkgr_ws_source' in mtd: - DeleteWorkspace('bkgr_ws_source') + if 'bkgr_ws_source' in mtd: + DeleteWorkspace('bkgr_ws_source') - return result + return result def do_white(self, run, spectra_masks=None, map_file=None): """ @@ -542,7 +543,7 @@ def mono_sample(self, mono_run, ei_guess, white_run=None, map_file=None, white_run = self.get_run_descriptor(white_run) - mono_s = self._do_mono(mono_run, ei_guess, + mono_s = self._do_mono(mono_run, ei_guess,\ white_run, map_file, spectra_masks, Tzero) # at this stage we would never need monitors for this workspace if they # were actually there @@ -552,7 +553,7 @@ def mono_sample(self, mono_run, ei_guess, white_run=None, map_file=None, #------------------------------------------------------------------------------- def calculate_rotation(self,sample_wkspace,motor=None, offset=None): """calculate psi from sample environment motor and offset - + TODO: should probably go to properties """ @@ -561,7 +562,7 @@ def calculate_rotation(self,sample_wkspace,motor=None, offset=None): offset = self.prop_man.motor_offset # - if (offset is None): + if offset is None: motor_offset = float('nan') else: motor_offset = float(offset) @@ -575,7 +576,7 @@ def calculate_rotation(self,sample_wkspace,motor=None, offset=None): self.prop_man.log("Could not find such sample environment log. Will use psi=motor_offset") motor_rotation = 0 else: - motor_rotation = float('nan') + motor_rotation = float('nan') self.prop_man.psi = motor_rotation + motor_offset #------------------------------------------------------------------------------- def get_ei(self, data_run, ei_guess): @@ -596,7 +597,7 @@ def get_ei(self, data_run, ei_guess): data_ws = data_run.get_workspace() monitor_ws = data_run.get_monitors_ws() if not monitor_ws: - raise RuntimeError("Can not find monitors workspace for workspace {0}, run N{1}".\ + raise RuntimeError("Can not find monitors workspace for workspace {0}, run N{1}".\ format(data_ws.name(),data_ws.getRunNumber())) separate_monitors = data_run.is_monws_separate() data_run.set_action_suffix('_shifted') @@ -622,8 +623,8 @@ def get_ei(self, data_run, ei_guess): # instrument is shifted in case it is shifted to this monitor (usual # case) #Find TOF range, correspondent to incident energy monitor peak - energy_rage = self.mon2_norm_energy_range - self._mon2_norm_time_range = self.get_TOF_for_energies(monitor_ws,energy_rage, + energy_rage = self.mon2_norm_energy_range + self._mon2_norm_time_range = self.get_TOF_for_energies(monitor_ws,energy_rage,\ [self.mon2_norm_spec],None,self._debug_mode) #end if separate_monitors: @@ -638,13 +639,13 @@ def get_ei(self, data_run, ei_guess): InstrumentParameter="DelayTime",Combine=True) # shift to monitor used to calculate energy transfer - spec_num = monitor_ws.getIndexFromSpectrumNumber(int(ei_mon_spectra[0])) + spec_num = monitor_ws.getIndexFromSpectrumNumber(int(ei_mon_spectra[0])) mon1_det = monitor_ws.getDetector(spec_num) mon1_pos = mon1_det.getPos() src_name = data_ws.getInstrument().getSource().getName() - MoveInstrumentComponent(Workspace=resultws_name,ComponentName= src_name, X=mon1_pos.getX(), + MoveInstrumentComponent(Workspace=resultws_name,ComponentName= src_name, X=mon1_pos.getX(), Y=mon1_pos.getY(), Z=mon1_pos.getZ(), RelativePosition=False) - + # data_run.synchronize_ws(mtd[resultws_name]) return ei, mon1_peak @@ -658,7 +659,7 @@ def remap(self, result_ws, spec_masks, map_file): if not spec_masks is None: MaskDetectors(Workspace=ws_name, MaskedWorkspace=spec_masks) if not map_file is None: - GroupDetectors(InputWorkspace=ws_name,OutputWorkspace=ws_name, + GroupDetectors(InputWorkspace=ws_name,OutputWorkspace=ws_name,\ MapFile= map_file, KeepUngroupedSpectra=0, Behaviour='Average') return mtd[ws_name] @@ -685,16 +686,16 @@ def normalise(self, run, method, range_offset=0.0,external_monitors_ws=None): method = method.lower() for case in common.switch(method): if case('monitor-1'): - method,old_ws_name = self._normalize_to_monitor1(run,old_ws_name, range_offset,external_monitors_ws) - break + method,old_ws_name = self._normalize_to_monitor1(run,old_ws_name, range_offset,external_monitors_ws) + break if case('monitor-2'): - method,old_ws_name = self._normalize_to_monitor2(run,old_ws_name, range_offset,external_monitors_ws) - break + method,old_ws_name = self._normalize_to_monitor2(run,old_ws_name, range_offset,external_monitors_ws) + break if case('current'): NormaliseByCurrent(InputWorkspace=old_ws_name,OutputWorkspace=old_ws_name) break if case(): # default - raise RuntimeError('Normalization method {0} not found. It must be one of monitor-1, monitor-2, current, or None'.format(method)) + raise RuntimeError('Normalization method {0} not found. It must be one of monitor-1, monitor-2, current, or None'.format(method)) #endCase @@ -706,32 +707,32 @@ def normalise(self, run, method, range_offset=0.0,external_monitors_ws=None): return output # def _normalize_to_monitor1(self,run,old_name,range_offset=0.0,external_monitor_ws=None): - """ Helper method implementing normalize_to_monitor1 """ + """ Helper method implementing normalize_to_monitor1 """ # get monitor's workspace separate_monitors = run.is_monws_separate() if external_monitor_ws: - separate_monitors = True - mon_ws = external_monitor_ws + separate_monitors = True + mon_ws = external_monitor_ws else: - mon_ws = run.get_monitors_ws() + mon_ws = run.get_monitors_ws() if not mon_ws: # no monitors - if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not + if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not # have monitors - self.normalise(run,'current',range_offset) - new_name = run.get_ws_name() - return ('current',new_name) - else: - raise RuntimeError('Normalise by monitor-1:: Workspace {0} for run {1} does not have monitors in it'\ + self.normalise(run,'current',range_offset) + new_name = run.get_ws_name() + return ('current',new_name) + else: + raise RuntimeError('Normalise by monitor-1:: Workspace {0} for run {1} does not have monitors in it'\ .format(run.get_ws_name(),run.__get__())) range = self.norm_mon_integration_range if self._debug_mode: - kwargs = {'NormFactorWS':'NormMon1_WS' + data_ws.getName()} + kwargs = {'NormFactorWS':'NormMon1_WS' + data_ws.getName()} else: - kwargs = {} + kwargs = {} mon_spect = self.prop_man.mon1_norm_spec if separate_monitors: @@ -746,36 +747,36 @@ def _normalize_to_monitor1(self,run,old_name,range_offset=0.0,external_monitor_w - NormaliseToMonitor(InputWorkspace=old_name,OutputWorkspace=old_name, IntegrationRangeMin=range_min, + NormaliseToMonitor(InputWorkspace=old_name,OutputWorkspace=old_name, IntegrationRangeMin=range_min, IntegrationRangeMax=range_max,IncludePartialBins=True,**kwargs) return ('monitor-1',old_name) # def _normalize_to_monitor2(self,run,old_name, range_offset=0.0,external_monitor_ws=None): - """ Helper method implementing normalize_to_monitor_2 """ + """ Helper method implementing normalize_to_monitor_2 """ # get monitor's workspace separate_monitors = run.is_monws_separate() if external_monitor_ws: - separate_monitors = True - mon_ws = external_monitor_ws + separate_monitors = True + mon_ws = external_monitor_ws else: - mon_ws = run.get_monitors_ws() + mon_ws = run.get_monitors_ws() + - if not mon_ws: # no monitors - if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not + if self.__in_white_normalization: # we can normalize wb integrals by current separately as they often do not # have monitors - self.normalise(run,'current',range_offset) - new_name = run.get_ws_name() - return ('current',new_name) - else: - raise RuntimeError('Normalize by monitor-2:: Workspace {0} for run {1} does not have monitors in it'\ + self.normalise(run,'current',range_offset) + new_name = run.get_ws_name() + return ('current',new_name) + else: + raise RuntimeError('Normalize by monitor-2:: Workspace {0} for run {1} does not have monitors in it'\ .format(run.get_ws_name(),run.__get__())) # if self._debug_mode: - kwargs = {'NormFactorWS':'NormMon2_WS' + mon_ws.getName()} + kwargs = {'NormFactorWS':'NormMon2_WS' + mon_ws.getName()} else: - kwargs = {} + kwargs = {} mon_spect = self.prop_man.mon2_norm_spec mon_index = int(mon_ws.getIndexFromSpectrumNumber(mon_spect)) @@ -787,36 +788,36 @@ def _normalize_to_monitor2(self,run,old_name, range_offset=0.0,external_monitor_ #Find TOF range, correspondent to incident energy monitor peak if self._mon2_norm_time_range: # range has been found during ei-calculations - range = self._mon2_norm_time_range - range_min = range[0] + range_offset - range_max = range[1] + range_offset - self._mon2_norm_time_range = None + range = self._mon2_norm_time_range + range_min = range[0] + range_offset + range_max = range[1] + range_offset + self._mon2_norm_time_range = None else: - mon_ws_name = mon_ws.name() #monitor's workspace and detector's workspace are e - if mon_ws_name.find('_shifted') != -1: + mon_ws_name = mon_ws.name() #monitor's workspace and detector's workspace are e + if mon_ws_name.find('_shifted') != -1: # monitor-2 normalization ranges have to be identified before the # instrument is shifted - raise RuntimeError("Instrument have been shifted but no time range has been identified. Monitor-2 normalization can not be performed ") - else: + raise RuntimeError("Instrument have been shifted but no time range has been identified. Monitor-2 normalization can not be performed ") + else: # instrument and workspace shifted, so TOF will be calculated wrt # shifted instrument - energy_rage = self.mon2_norm_energy_range - TOF_range = self.get_TOF_for_energies(mon_ws,energy_rage,[mon_spect],None,self._debug_mode) - range_min = TOF_range[0] - range_max = TOF_range[1] + energy_rage = self.mon2_norm_energy_range + TOF_range = self.get_TOF_for_energies(mon_ws,energy_rage,[mon_spect],None,self._debug_mode) + range_min = TOF_range[0] + range_max = TOF_range[1] # Normalize to monitor 2 - NormaliseToMonitor(InputWorkspace=old_name,OutputWorkspace=old_name,IntegrationRangeMin=range_min, + NormaliseToMonitor(InputWorkspace=old_name,OutputWorkspace=old_name,IntegrationRangeMin=range_min, IntegrationRangeMax=range_max,IncludePartialBins=True,**kwargs) return ('monitor-2',old_name) #------------------------------------------------------------------------------- #------------------------------------------------------------------------------- def find_tof_range_for_multirep(self,workspace): - """ Find range of tof-s (and time bin size) corresponding to the + """ Find range of tof-s (and time bin size) corresponding to the energy range requested - """ + """ if not workspace: - workspace = PropertyManager.sample_run.get_workspace() + workspace = PropertyManager.sample_run.get_workspace() spectra_id = self.prop_man.multirep_tof_specta_list if not spectra_id: @@ -839,32 +840,32 @@ def process_block(tof_range): nBlocks = len(spectra_id) if nBlocks > 1: - tof_min,t_step,tof_max = process_block(TOF_range[0]) - for ind in xrange(1,nBlocks): - tof_min1,t_step1,tof_max1 = process_block(TOF_range[ind]) - tof_min = min(tof_min,tof_min1) - tof_max = max(tof_max,tof_max1) - t_step = min(t_step,t_step1) + tof_min,t_step,tof_max = process_block(TOF_range[0]) + for ind in xrange(1,nBlocks): + tof_min1,t_step1,tof_max1 = process_block(TOF_range[ind]) + tof_min = min(tof_min,tof_min1) + tof_max = max(tof_max,tof_max1) + t_step = min(t_step,t_step1) else: - tof_min,t_step,tof_max = process_block(TOF_range) + tof_min,t_step,tof_max = process_block(TOF_range) #end return (tof_min,t_step,tof_max) # @staticmethod def get_TOF_for_energies(workspace,energy_list,specID_list,ei=None,debug_mode=False): - """ Method to find what TOF range corresponds to given energy range + """ Method to find what TOF range corresponds to given energy range for given workspace and detectors. Input: - workspace pointer to workspace with instrument attached. + workspace pointer to workspace with instrument attached. energy_list the list of input energies to process - detID_list list of detectors to find - ei incident energy. If present, TOF range is calculated in direct mode, + detID_list list of detectors to find + ei incident energy. If present, TOF range is calculated in direct mode, if not -- elastic mode - Returns: - list of TOF corresponding to input energies list. - """ + Returns: + list of TOF corresponding to input energies list. + """ template_ws_name = '_energy_range_ws' range_ws_name = '_TOF_range_ws' y = [1] * (len(energy_list) - 1) @@ -913,8 +914,8 @@ def save_results(self, workspace, save_file=None, formats=None): else: pass - prop_man = self.prop_man - + prop_man = self.prop_man + save_file,ext = os.path.splitext(save_file) if len(ext) > 1: formats.add(ext[1:]) @@ -923,27 +924,27 @@ def save_results(self, workspace, save_file=None, formats=None): for file_format in formats: for case in common.switch(file_format): if case('nxspe'): - filename = save_file + '.nxspe' - name_supported = name_orig.replace('/','of') - if name_supported != name_orig: - RenameWorkspace(InputWorkspace=name_orig,OutputWorkspace=name_supported) - SaveNXSPE(InputWorkspace=name_supported,Filename= filename, KiOverKfScaling=prop_man.apply_kikf_correction,psi=prop_man.psi) - if name_supported != name_orig: - RenameWorkspace(InputWorkspace=name_supported,OutputWorkspace=name_orig) - break + filename = save_file + '.nxspe' + name_supported = name_orig.replace('/','of') + if name_supported != name_orig: + RenameWorkspace(InputWorkspace=name_orig,OutputWorkspace=name_supported) + SaveNXSPE(InputWorkspace=name_supported,Filename= filename, KiOverKfScaling=prop_man.apply_kikf_correction,psi=prop_man.psi) + if name_supported != name_orig: + RenameWorkspace(InputWorkspace=name_supported,OutputWorkspace=name_orig) + break if case('spe'): - filename = save_file + '.spe' - SaveSPE(InputWorkspace=workspace,Filename= filename) - break + filename = save_file + '.spe' + SaveSPE(InputWorkspace=workspace,Filename= filename) + break if case('nxs'): - filename = save_file + '.nxs' - SaveNexus(InputWorkspace=workspace,Filename= filename) - break + filename = save_file + '.nxs' + SaveNexus(InputWorkspace=workspace,Filename= filename) + break if case(): # default, could also just omit condition or 'if True' - prop_man.log("Unknown file format {0} requested to save results. No saving performed this format".format(file_format)) + prop_man.log("Unknown file format {0} requested to save results. No saving performed this format".format(file_format)) ######### - @property + @property def prop_man(self): """ Return property manager containing DirectEnergyConversion parameters """ return self._propMan @@ -958,7 +959,7 @@ def prop_man(self,value): ######### @property def spectra_masks(self): - """ The property keeps a workspace with masks, stored for further usage """ + """ The property keeps a workspace with masks, stored for further usage """ # check if spectra masks is defined if hasattr(self,'_spectra_masks'): @@ -968,7 +969,7 @@ def spectra_masks(self): @spectra_masks.setter def spectra_masks(self,value): - """ set up spectra masks """ + """ set up spectra masks """ self._spectra_masks = value #------------------------------------------------------------------------------- def apply_absolute_normalization(self,sample_ws,monovan_run=None,ei_guess=None,wb_mono=None): @@ -1017,7 +1018,7 @@ def apply_absolute_normalization(self,sample_ws,monovan_run=None,ei_guess=None,w # workspace is not good for further processing any more mono_run_num = PropertyManager.monovan_run.run_number() prop_man.monovan_run = None # delete everything from memory - prop_man.monovan_run = mono_run_num + prop_man.monovan_run = mono_run_num #end prop_man.log('*** Using {0} value : {1} of absolute units correction factor (TGP)'.format(abs_norm_factor_is,absnorm_factor),'notice') prop_man.log('*******************************************************************************************','notice') @@ -1053,30 +1054,30 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): data_ws = Integration(InputWorkspace=deltaE_wkspaceName,OutputWorkspace='van_int',RangeLower=minmax[0],RangeUpper=minmax[1],IncludePartialBins='1') - + nhist = data_ws.getNumberHistograms() # extract wb integrals for combined spectra signal = [] error = [] izerc = 0 for i in range(nhist): - try: - det = data_ws.getDetector(i) - except Exception: - continue - if det.isMasked(): - continue - sig = data_ws.readY(i)[0] - err = data_ws.readE(i)[0] - if sig != sig: #ignore NaN (hopefully it will mean mask some day) - continue - if ((err <= 0) or (sig <= 0)): # count Inf and negative||zero readings. Presence of this indicates that + try: + det = data_ws.getDetector(i) + except Exception: + continue + if det.isMasked(): + continue + sig = data_ws.readY(i)[0] + err = data_ws.readE(i)[0] + if sig != sig: #ignore NaN (hopefully it will mean mask some day) + continue + if (err <= 0) or (sig <= 0): # count Inf and negative||zero readings. Presence of this indicates that # something went wrong - izerc+=1 - continue + izerc+=1 + continue - signal.append(sig) - error.append(err) + signal.append(sig) + error.append(err) #---------------- Loop finished norm_factor = {} @@ -1104,7 +1105,7 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): # n_i is the modified signal signal_sum = sum(map(lambda e: e * e,error)) weight_sum = sum(map(lambda s,e: e * e / s,signal,error)) - if(weight_sum == 0.0): + if weight_sum == 0.0: prop_man.log("WB integral has been calculated incorrectly, look at van_int workspace: {0}".format(deltaE_wkspaceName),'error') raise ArithmeticError("Division by 0 weight when calculating WB integrals from workspace {0}".format(deltaE_wkspaceName)) norm_factor['Poisson'] = signal_sum / weight_sum @@ -1113,7 +1114,7 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): # TGP suggestion from 12-2012 signal_sum = sum(map(lambda s,e: s * s / (e * e),signal,error)) weight_sum = sum(map(lambda s,e: s / (e * e),signal,error)) - if(weight_sum == 0.0): + if weight_sum == 0.0: prop_man.log("WB integral has been calculated incorrectly, look at van_int workspace: {0}".format(deltaE_wkspaceName),'error') raise ArithmeticError("Division by 0 weight when calculating WB integrals from workspace {0}".format(deltaE_wkspaceName)) norm_factor['TGP'] = signal_sum / weight_sum @@ -1135,11 +1136,11 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): # check for NaN if (norm_factor['LibISIS'] != norm_factor['LibISIS']) | (izerc != 0): # It is an error, print diagnostics: - if (norm_factor['LibISIS'] != norm_factor['LibISIS']): - log_value = '\n--------> Absolute normalization factor is NaN <----------------------------------------------\n' - else: - log_value = '\n--------> Warning, Monovanadium has zero spectra <--------------------------------------------\n' - log1_value = \ + if norm_factor['LibISIS'] != norm_factor['LibISIS']: + log_value = '\n--------> Absolute normalization factor is NaN <----------------------------------------------\n' + else: + log_value = '\n--------> Warning, Monovanadium has zero spectra <--------------------------------------------\n' + log1_value = \ "--------> Processing workspace: {0}\n"\ "--------> Monovan Integration range : min={1}, max={2} (meV)\n"\ "--------> Summed: {3} spectra with total signal: {4} and error: {5}\n"\ @@ -1149,10 +1150,10 @@ def get_abs_normalization_factor(self,deltaE_wkspaceName,ei_monovan): "--------> Abs norm factors: Sigma^2: {9}\n"\ "--------> Abs norm factors: Poisson: {10}\n"\ "--------> Abs norm factors: TGP : {11}\n"\ - .format(deltaE_wkspaceName,minmax[0],minmax[1],nhist,sum(signal),sum(error),izerc,scale_factor, + .format(deltaE_wkspaceName,minmax[0],minmax[1],nhist,sum(signal),sum(error),izerc,scale_factor,\ norm_factor['LibISIS'],norm_factor['SigSq'],norm_factor['Poisson'],norm_factor['TGP']) - log_value = log_value + log1_value - propman.log(log_value,'error') + log_value = log_value + log1_value + propman.log(log_value,'error') else: if not self._debug_mode: DeleteWorkspace(Workspace=deltaE_wkspaceName) @@ -1195,14 +1196,14 @@ def __init__(self, instr_name=None,reload_instrument=False): #end def __getattr__(self,attr_name): - """ overloaded to return values of properties non-existing in the class dictionary + """ overloaded to return values of properties non-existing in the class dictionary from the property manager class except this property already have descriptor in self class - """ - if attr_name in self._descriptors: - return object.__getattr__(self,attr_name) - else: - return getattr(self._propMan,attr_name) + """ + if attr_name in self._descriptors: + return object.__getattr__(self,attr_name) + else: + return getattr(self._propMan,attr_name) def __setattr__(self,attr_name,attr_value): """ overloaded to prohibit adding non-starting with _properties to the class instance @@ -1216,7 +1217,7 @@ def __setattr__(self,attr_name,attr_value): object.__setattr__(self,attr_name,attr_value) else: setattr(self._propMan,attr_name,attr_value) - + def initialise(self, instr,reload_instrument=False): """ Initialize the private attributes of the class and the nullify the attributes which expected @@ -1259,34 +1260,34 @@ def setup_instrument_properties(self, workspace=None,reload_instrument=False): instrument = workspace.getInstrument() name = instrument.getName() if name != self.prop_man.instr_name: - self.prop_man = PropertyManager(name,workspace) + self.prop_man = PropertyManager(name,workspace) + - def get_run_descriptor(self,run): - """ Spawn temporary run descriptor for input data given in format, - different from run descriptor. Return existing run descriptor, + """ Spawn temporary run descriptor for input data given in format, + different from run descriptor. Return existing run descriptor, if it is what provided. """ - if not isinstance(run,RunDescriptor): - tRun = copy.copy(PropertyManager._tmp_run) - tRun.__set__(None,run) - return tRun - else: - return run + if not isinstance(run,RunDescriptor): + tRun = copy.copy(PropertyManager._tmp_run) + tRun.__set__(None,run) + return tRun + else: + return run # # ------------------------------------------------------------------------------------------- # This actually does the conversion for the mono-sample and # mono-vanadium runs # # ------------------------------------------------------------------------------------------- - def _do_mono_SNS(self, data_ws, result_name, ei_guess, + def _do_mono_SNS(self, data_ws, result_name, ei_guess,\ white_run=None, map_file=None, spectra_masks=None, Tzero=None): # does not work -- retrieve from repo and fix raise NotImplementedError("Non currently implemented. Retrieve from repository" " if necessary and fix") return #------------------------------------------------------------------------------- - def _do_mono_ISIS(self, data_run, ei_guess, + def _do_mono_ISIS(self, data_run, ei_guess,\ white_run=None, map_file=None, spectra_masks=None, Tzero=None): # Do ISIS stuff for Ei @@ -1333,10 +1334,10 @@ def _do_mono_ISIS(self, data_run, ei_guess, energy_bins = PropertyManager.energy_bins.get_abs_range(self.prop_man) if energy_bins: - Rebin(InputWorkspace=result_name,OutputWorkspace=result_name,Params= energy_bins,PreserveEvents=False) - if bkgr_ws: # remove background after converting units and rebinning - RemoveBackground(InputWorkspace=result_name,OutputWorkspace=result_name,BkgWorkspace=bkgr_ws,EMode='Direct') - DeleteWorkspace(bkgr_ws) + Rebin(InputWorkspace=result_name,OutputWorkspace=result_name,Params= energy_bins,PreserveEvents=False) + if bkgr_ws: # remove background after converting units and rebinning + RemoveBackground(InputWorkspace=result_name,OutputWorkspace=result_name,BkgWorkspace=bkgr_ws,EMode='Direct') + DeleteWorkspace(bkgr_ws) else: pass # TODO: investigate way of removing background from event workspace if we want # result to be an event workspace @@ -1345,35 +1346,35 @@ def _do_mono_ISIS(self, data_run, ei_guess, if self.apply_detector_eff and energy_bins: #should detector efficiency work on event workspace too? At the moment it is #not (01/02/2015) - DetectorEfficiencyCor(InputWorkspace=result_name,OutputWorkspace=result_name) - self.prop_man.log("_do_mono: finished DetectorEfficiencyCor for : " + result_name,'information') + DetectorEfficiencyCor(InputWorkspace=result_name,OutputWorkspace=result_name) + self.prop_man.log("_do_mono: finished DetectorEfficiencyCor for : " + result_name,'information') ############# data_run.synchronize_ws(mtd[result_name]) - return + return #------------------------------------------------------------------------------- def _find_or_build_bkgr_ws(self,result_ws,bkg_range_min=None,bkg_range_max=None,time_shift=0): - """ Method calculates background workspace or restore workspace with + """ Method calculates background workspace or restore workspace with the same name as the one produced by this method from ADS - """ + """ if not bkg_range_min or not bkg_range_max: bkg_range_min,bkg_range_max = self.bkgd_range bkg_range_min += time_shift bkg_range_max += time_shift - # has to have specific name for this all working. This ws is build at the beginning of + # has to have specific name for this all working. This ws is build at the beginning of # multirep run if 'bkgr_ws_source' in mtd: bkgr_ws = CloneWorkspace(InputWorkspace='bkgr_ws_source',OutputWorkspace='bkgr_ws') - if time_shift != 0: # Workspace has probably been shifted, so to have correct units conversion + if time_shift != 0: # Workspace has probably been shifted, so to have correct units conversion # one needs to do appropriate shift here as well - CopyInstrumentParameters(result_ws,bkgr_ws) + CopyInstrumentParameters(result_ws,bkgr_ws) # Adjust the TOF such that the first monitor peak is at t=0 - ScaleX(InputWorkspace=bkgr_ws,OutputWorkspace='bkgr_ws',Operation="Add",Factor=time_shift, + ScaleX(InputWorkspace=bkgr_ws,OutputWorkspace='bkgr_ws',Operation="Add",Factor=time_shift,\ InstrumentParameter="DelayTime",Combine=True) else: - bkgr_ws = Rebin(result_ws,Params=[bkg_range_min,(bkg_range_max - bkg_range_min) * 1.001,bkg_range_max],PreserveEvents=False) - bkgr_ws = self.normalise(bkgr_ws, self.normalise_method, time_shift) + bkgr_ws = Rebin(result_ws,Params=[bkg_range_min,(bkg_range_max - bkg_range_min) * 1.001,bkg_range_max],PreserveEvents=False) + bkgr_ws = self.normalise(bkgr_ws, self.normalise_method, time_shift) return bkgr_ws @@ -1385,14 +1386,14 @@ def _do_mono(self, run, ei_guess, normalization to a white-beam vanadium run. """ - if (self._do_ISIS_reduction): - self._do_mono_ISIS(run,ei_guess, + if self._do_ISIS_reduction: + self._do_mono_ISIS(run,ei_guess,\ white_run, map_file, spectra_masks, Tzero) else: - result_name = run.set_action_suffix('_spe') - self._do_mono_SNS(run,result_name,ei_guess, + result_name = run.set_action_suffix('_spe') + self._do_mono_SNS(run,result_name,ei_guess,\ white_run, map_file, spectra_masks, Tzero) - run.synchronize_ws() + run.synchronize_ws() prop_man = self.prop_man result_name = run.get_ws_name() @@ -1405,8 +1406,8 @@ def _do_mono(self, run, ei_guess, # Make sure that our binning is consistent if prop_man.energy_bins: - bins = PropertyManager.energy_bins.get_abs_range(prop_man) - Rebin(InputWorkspace=result_name,OutputWorkspace= result_name,Params=bins) + bins = PropertyManager.energy_bins.get_abs_range(prop_man) + Rebin(InputWorkspace=result_name,OutputWorkspace= result_name,Params=bins) # Masking and grouping result_ws = mtd[result_name] @@ -1442,12 +1443,12 @@ def _get_wb_inegrals(self,run): old_log_val = targ_ws.getRun().getLogData(done_Log).value done_log_VAL = self._build_white_tag() if old_log_val == done_log_VAL: - run.synchronize_ws(targ_ws) - if self._keep_wb_workspace: + run.synchronize_ws(targ_ws) + if self._keep_wb_workspace: result = run.get_ws_clone() - else: + else: result = run.get_workspace() - return result + return result else: DeleteWorkspace(Workspace=new_ws_name) else: @@ -1483,7 +1484,7 @@ def _get_wb_inegrals(self,run): return result #------------------------------------------------------------------------------- def _build_white_tag(self): - """ build tag indicating wb-integration ranges """ + """ build tag indicating wb-integration ranges """ low,upp = self.wb_integr_range white_tag = 'NormBy:{0}_IntergatedIn:{1:0>10.2f}:{2:0>10.2f}'.format(self.normalise_method,low,upp) return white_tag @@ -1502,7 +1503,7 @@ def get_failed_spectra_list_from_masks(masked_wksp): failed_spectra = [] if masked_wksp is None: - return (failed_spectra,0) + return (failed_spectra,0) masking_wksp,sp_list = ExtractMask(masked_wksp) DeleteWorkspace(masking_wksp) @@ -1514,4 +1515,4 @@ def get_failed_spectra_list_from_masks(masked_wksp): #----------------------------------------------------------------- if __name__ == "__main__": pass - #unittest.main() \ No newline at end of file + #unittest.main() diff --git a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py index 4ff69c2b4c71..102426faa1ce 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py +++ b/Code/Mantid/scripts/Inelastic/Direct/NonIDF_Properties.py @@ -1,15 +1,16 @@ -from PropertiesDescriptors import * -from RunDescriptor import RunDescriptor,RunDescriptorDependent +#pylint: disable=invalid-name +from Direct.PropertiesDescriptors import * +from Direct.RunDescriptor import RunDescriptor,RunDescriptorDependent class NonIDF_Properties(object): - """ Class defines the interface for main properties, used in reduction, and not described in + """ Class defines the interface for main properties, used in reduction, and not described in IDF ( Instrument_Properties.xml file) - These properties are main set of properties, user have to set up - for reduction to work with defaults. + These properties are main set of properties, user have to set up + for reduction to work with defaults. - The example of such properties are run numbers, energy bins and incident energies. + The example of such properties are run numbers, energy bins and incident energies. """ # logging levels available for user @@ -21,13 +22,13 @@ class NonIDF_Properties(object): "debug" : (5,lambda (msg): logger.debug(msg))} - def __init__(self,Instrument,run_workspace=None): + def __init__(self,Instrument,run_workspace=None): """ initialize main properties, defined by the class - @parameter Instrument -- name or pointer to the instrument, + @parameter Instrument -- name or pointer to the instrument, deployed in reduction """ # - if not(run_workspace is None): + if not run_workspace is None: object.__setattr__(self,'sample_run',run_workspace) # Helper properties, defining logging options @@ -35,14 +36,14 @@ def __init__(self,Instrument,run_workspace=None): object.__setattr__(self,'_log_to_mantid',False) object.__setattr__(self,'_current_log_level',3) - + object.__setattr__(self,'_psi',float('NaN')) # SNS motor stuff which is difficult to test as I've never seen it object.__setattr__(self,'_motor_name',None) object.__setattr__(self,'_motor_offset',0) object.__setattr__(self,'_save_file_name',None) - + self._set_instrument_and_facility(Instrument,run_workspace) # set up descriptors holder class reference @@ -68,8 +69,8 @@ def log(self, msg,level="notice"): logger(msg) else: # TODO: reconcile this with Mantid. - if lev <= self._current_log_level: - print msg + if lev <= self._current_log_level: + print msg #----------------------------------------------------------------------------- # Complex properties with personal descriptors #----------------------------------------------------------------------------- @@ -93,8 +94,8 @@ def log(self, msg,level="notice"): wb_for_monovan_run = RunDescriptorDependent(wb_run,"MV_WB_"," white beam run used to calculate monovanadium integrals.\n If not explicitly set, white beam for processing run is used") # TODO: do something about it. Second white is explicitly used in # diagnostics but not accessed at all - second_white = RunDescriptor("Second white beam currently unused in the workflow despite being referred to in Diagnostics. Should it be used for Monovan Diagnostics?") - # + second_white = RunDescriptor("Second white beam currently unused in the workflow despite being referred to in Diagnostics. Should it be used for Monovan Diagnostics?") + # _tmp_run = RunDescriptor("_TMP","Property used for storing intermediate run data during reduction") # property responsible for summing runs sum_runs = SumRuns(sample_run) @@ -106,7 +107,7 @@ def getDefaultParameterValue(self,par_name): def instrument(self): if self._pInstrument is None: raise KeyError("Attempt to use uninitialized property manager") - else: + else: return self._pInstrument # #----------------------------------------------------------------------------------- @@ -122,7 +123,7 @@ def print_diag_results(self,value): # ----------------------------------------------------------------------------- @property def log_to_mantid(self): - """ Property specify if high level log should be printed to stdout or added to common Mantid log""" + """ Property specify if high level log should be printed to stdout or added to common Mantid log""" return self._log_to_mantid @log_to_mantid.setter @@ -130,11 +131,11 @@ def log_to_mantid(self,val): object.__setattr__(self,'_log_to_mantid',bool(val)) # ----------------------------------------------------------------------------- #----------------------------------------------------------------------------------- - @property + @property def psi(self): """ rotation angle (not available from IDF)""" return self._psi - @psi.setter + @psi.setter def psi(self,value): """set rotation angle (not available from IDF). This value will be saved into NXSpe file""" object.__setattr__(self,'_psi',value) @@ -170,7 +171,7 @@ def _set_instrument_and_facility(self,Instrument,run_workspace=None): if isinstance(Instrument,geometry._geometry.Instrument): instrument = Instrument instr_name = instrument.getFullName() - try: + try: new_name,full_name,facility_ = prop_helpers.check_instrument_name(None,instr_name) except KeyError: # the instrument pointer is not found in any facility but we have it after all new_name = instr_name @@ -185,7 +186,7 @@ def _set_instrument_and_facility(self,Instrument,run_workspace=None): idf_file = api.ExperimentInfo.getInstrumentFilename(full_name) tmp_ws_name = '__empty_' + full_name if not mtd.doesExist(tmp_ws_name): - LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) + LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) instrument = mtd[tmp_ws_name].getInstrument() else: raise TypeError(' neither correct instrument name nor instrument pointer provided as instrument parameter') @@ -195,7 +196,7 @@ def _set_instrument_and_facility(self,Instrument,run_workspace=None): object.__setattr__(self,'_facility',facility_) object.__setattr__(self,'_short_instr_name',new_name) - + diff --git a/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py b/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py index 6cd58050e8b7..0459aa0c1819 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py +++ b/Code/Mantid/scripts/Inelastic/Direct/PropertiesDescriptors.py @@ -1,6 +1,7 @@ +#pylint: disable=invalid-name """ File contains collection of Descriptors used to define complex - properties in NonIDF_Properties and PropertyManager classes -""" + properties in NonIDF_Properties and PropertyManager classes +""" import os from mantid.simpleapi import * @@ -17,7 +18,7 @@ class PropDescriptor(object): """ Class provides common custom interface for property descriptors """ def dependencies(self): - """ Returns the list of other properties names, this property depends on""" + """ Returns the list of other properties names, this property depends on""" return [] # end PropDescriptor @@ -26,12 +27,12 @@ def dependencies(self): #----------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------- class SumRuns(PropDescriptor): - """ Boolean property specifies if list of files provided as input for sample_run property - should be summed. + """ Boolean property specifies if list of files provided as input for sample_run property + should be summed. - It also specifies various auxiliary operations, defined for summing runs, so property + It also specifies various auxiliary operations, defined for summing runs, so property is deeply entangled with the sample_run property - """ + """ def __init__(self,sample_run_prop): # internal reference to sample run property self._sample_run = sample_run_prop @@ -47,28 +48,28 @@ def __init__(self,sample_run_prop): # def __get__(self,instance,holder_class): - if not self._holder: - self._holder = holder_class - if instance is None: - return self - return self._sum_runs + if not self._holder: + self._holder = holder_class + if instance is None: + return self + return self._sum_runs # def __set__(self,instance,value): if not self._holder: - from Direct.PropertyManager import PropertyManager - self._holder = PropertyManager - + from Direct.PropertyManager import PropertyManager + self._holder = PropertyManager + old_value = self._sum_runs if isinstance(value,bool): self._sum_runs = value self._last_ind2sum = -1 elif isinstance(value,int): if value > 0: - self._last_ind2sum = int(value) - 1 - self._sum_runs = True + self._last_ind2sum = int(value) - 1 + self._sum_runs = True else: - self._last_ind2sum = -1 - self._sum_runs = False + self._last_ind2sum = -1 + self._sum_runs = False else: self._sum_runs = bool(value) self._last_ind2sum = -1 @@ -76,29 +77,29 @@ def __set__(self,instance,value): if old_value != self._sum_runs: if len(self._run_numbers) > 0 and self._sum_runs: # clear previous state of sample_run - ind = self.get_last_ind2sum() - self._sample_run.__set__(None,self._run_numbers[ind]) + ind = self.get_last_ind2sum() + self._sample_run.__set__(None,self._run_numbers[ind]) # def set_list2add(self,runs_to_add,fnames=None,fext=None): - """Set run numbers to add together with possible file guess-es """ - if not isinstance(runs_to_add,list): - raise KeyError('Can only set list of run numbers to add') - runs = [] - for item in runs_to_add: - runs.append(int(item)) - self._run_numbers = runs - if fnames: - self._file_guess = fnames - if len(self._file_guess) != len(self._run_numbers): - self._file_guess = [''] * len(self._run_numbers) - - if fext: - self._fext = fext - if len(self._fext) != len(self._run_numbers): - self._fext = [''] * len(self._run_numbers) + """Set run numbers to add together with possible file guess-es """ + if not isinstance(runs_to_add,list): + raise KeyError('Can only set list of run numbers to add') + runs = [] + for item in runs_to_add: + runs.append(int(item)) + self._run_numbers = runs + if fnames: + self._file_guess = fnames + if len(self._file_guess) != len(self._run_numbers): + self._file_guess = [''] * len(self._run_numbers) + + if fext: + self._fext = fext + if len(self._fext) != len(self._run_numbers): + self._fext = [''] * len(self._run_numbers) # def clear_sum(self): - """Clear all defined summation""" + """Clear all defined summation""" # if last_to_sum is -1, sum all run list provided self._last_ind2sum = -1 self._sum_runs = False @@ -107,14 +108,14 @@ def clear_sum(self): self._fext = [] # def get_last_ind2sum(self): - """Get last run number contributing to sum""" + """Get last run number contributing to sum""" if self._last_ind2sum > 0: - return self._last_ind2sum + return self._last_ind2sum else: - return len(self._run_numbers) - 1 + return len(self._run_numbers) - 1 # def set_last_ind2sum(self,run_number): - """Check and set last number, contributing to summation + """Check and set last number, contributing to summation if this number is out of summation range, clear the summation """ run_number = int(run_number) @@ -126,15 +127,15 @@ def set_last_ind2sum(self,run_number): return 0 # def get_run_list2sum(self): - """Get run numbers of the files to be summed together """ + """Get run numbers of the files to be summed together """ num_to_load = len(self._run_numbers) if self._last_ind2sum > 0 and self._last_ind2sum < num_to_load: - num_to_load = self._last_ind2sum + num_to_load = self._last_ind2sum return self._run_numbers[:num_to_load] # def load_and_sum_runs(self,inst_name,monitors_with_ws): - """ Load multiple runs and sum them together """ + """ Load multiple runs and sum them together """ logger = lambda mess : (getattr(getattr(self,'_holder'),'log')\ (self._sample_run._holder,mess)) @@ -157,27 +158,27 @@ def load_and_sum_runs(self,inst_name,monitors_with_ws): for ind,run_num in enumerate(runs_to_load[1:num_to_load]): - file_h = os.path.join(self._file_guess[ind + 1],'{0}{1}{2}'.\ + file_h = os.path.join(self._file_guess[ind + 1],'{0}{1}{2}'.\ format(inst_name,run_num,self._fext[ind + 1])) - logger("*** Adding #{0}/{1}, run N: {2} ".\ + logger("*** Adding #{0}/{1}, run N: {2} ".\ format(ind + 2,num_to_load,run_num)) - term_name = '{0}_ADDITIVE_#{1}/{2}'.format(inst_name,ind + 2,num_to_load)# + term_name = '{0}_ADDITIVE_#{1}/{2}'.format(inst_name,ind + 2,num_to_load)# - wsp = self._sample_run.load_file(inst_name,term_name,False, + wsp = self._sample_run.load_file(inst_name,term_name,False,\ monitors_with_ws,False,file_hint=file_h) - wsp_name = wsp.name() - wsp_mon_name = wsp_name + '_monitors' - Plus(LHSWorkspace=sum_ws_name,RHSWorkspace=wsp_name, + wsp_name = wsp.name() + wsp_mon_name = wsp_name + '_monitors' + Plus(LHSWorkspace=sum_ws_name,RHSWorkspace=wsp_name,\ OutputWorkspace=sum_ws_name,ClearRHSWorkspace=True) - AddedRunNumbers+=',{0}'.format(run_num) - if not monitors_with_ws: - Plus(LHSWorkspace=sum_mon_name,RHSWorkspace=wsp_mon_name, + AddedRunNumbers+=',{0}'.format(run_num) + if not monitors_with_ws: + Plus(LHSWorkspace=sum_mon_name,RHSWorkspace=wsp_mon_name,\ OutputWorkspace=sum_mon_name,ClearRHSWorkspace=True) - if wsp_name in mtd: - DeleteWorkspace(wsp_name) - if wsp_mon_name in mtd: - DeleteWorkspace(wsp_mon_name) + if wsp_name in mtd: + DeleteWorkspace(wsp_name) + if wsp_mon_name in mtd: + DeleteWorkspace(wsp_mon_name) logger("*** Summing multiple runs completed ****") AddSampleLog(Workspace=sum_ws_name,LogName = 'SumOfRuns:', @@ -185,7 +186,7 @@ def load_and_sum_runs(self,inst_name,monitors_with_ws): ws = mtd[sum_ws_name] return ws # - def sum_ext(self): + def sum_ext(self): if self._sum_runs: last = self.get_last_ind2sum() sum_ext = "SumOf{0}".format(len(self._run_numbers[:last + 1])) @@ -197,82 +198,82 @@ def get_runs(self): return self._run_numbers #-------------------------------------------------------------------------------------------------------------------- class IncidentEnergy(PropDescriptor): - """ Property for incident energy or range of incident energies to be processed + """ Property for incident energy or range of incident energies to be processed - Set it up to list of values (even with single value i.e. prop_man.incident_energy=[10]) + Set it up to list of values (even with single value i.e. prop_man.incident_energy=[10]) if the energy_bins property value to be treated as relative energy ranges. - Set it up to single value (e.g. prop_man.incident_energy=10) to treat energy energy_bins + Set it up to single value (e.g. prop_man.incident_energy=10) to treat energy energy_bins as absolute energy values """ - def __init__(self): + def __init__(self): self._incident_energy = 0 self._num_energies = 1 self._cur_iter_en = 0 def __get__(self,instance,owner=None): - """ return incident energy or list of incident energies """ + """ return incident energy or list of incident energies """ if instance is None: - return self + return self - return self._incident_energy + return self._incident_energy def __set__(self,instance,value): - """ Set up incident energy or range of energies in various formats """ - if value != None: - if isinstance(value,str): - if value.find('[') > -1: - energy_list = True - value = value.translate(None, '[]').strip() - else: - energy_list = False - en_list = str.split(value,',') - if len(en_list) > 1: - rez = [] - for en_str in en_list: - val = float(en_str) - rez.append(val) - self._incident_energy = rez - else: - if energy_list: - self._incident_energy = [float(value)] - else: - self._incident_energy = float(value) - else: - if isinstance(value,list): - rez = [] - for val in value: - en_val = float(val) - if en_val <= 0: - raise KeyError("Incident energy has to be positive, but is: {0} ".format(en_val)) + """ Set up incident energy or range of energies in various formats """ + if value != None: + if isinstance(value,str): + if value.find('[') > -1: + energy_list = True + value = value.translate(None, '[]').strip() + else: + energy_list = False + en_list = str.split(value,',') + if len(en_list) > 1: + rez = [] + for en_str in en_list: + val = float(en_str) + rez.append(val) + self._incident_energy = rez + else: + if energy_list: + self._incident_energy = [float(value)] else: - rez.append(en_val) - self._incident_energy = rez + self._incident_energy = float(value) else: - self._incident_energy = float(value) - else: - raise KeyError("Incident energy have to be positive number of list of positive numbers. Got None") - + if isinstance(value,list): + rez = [] + for val in value: + en_val = float(val) + if en_val <= 0: + raise KeyError("Incident energy has to be positive, but is: {0} ".format(en_val)) + else: + rez.append(en_val) + self._incident_energy = rez + else: + self._incident_energy = float(value) + else: + raise KeyError("Incident energy have to be positive number of list of positive numbers. Got None") + # - inc_en = self._incident_energy - if isinstance(inc_en,list): - self._num_energies = len(inc_en) - for en in inc_en: - if en <= 0: - raise KeyError("Incident energy have to be positive number of list of positive numbers." + " For input argument {0} got negative value {1}".format(value,en)) - else: - self._num_energies = 1 - if inc_en <= 0: - raise KeyError("Incident energy have to be positive number of list of positive numbers." + " For value {0} got negative {1}".format(value,inc_en)) - self._cur_iter_en = 0 - + inc_en = self._incident_energy + if isinstance(inc_en,list): + self._num_energies = len(inc_en) + for en in inc_en: + if en <= 0: + raise KeyError("Incident energy have to be positive number of list of positive numbers." + " For input argument {0} got negative value {1}".format(value,en)) + else: + self._num_energies = 1 + if inc_en <= 0: + raise KeyError("Incident energy have to be positive number of list of positive numbers." + " For value {0} got negative {1}".format(value,inc_en)) + self._cur_iter_en = 0 + def multirep_mode(self): - """ return true if energy is defined as list of energies and false otherwise """ + """ return true if energy is defined as list of energies and false otherwise """ if isinstance(self._incident_energy,list): return True else: return False def get_current(self): - """ Return current energy out of range of energies""" + """ Return current energy out of range of energies""" if isinstance(self._incident_energy,list): ind = self._cur_iter_en return self._incident_energy[ind] @@ -280,8 +281,8 @@ def get_current(self): return self._incident_energy # def set_current(self,value): - """ set current energy value (used in multirep mode) to - + """ set current energy value (used in multirep mode) to + """ if isinstance(self._incident_energy,list): ind = self._cur_iter_en @@ -296,28 +297,28 @@ def __iter__(self): return self def next(self): # Python 3: def __next__(self) - """ part of iterator """ + """ part of iterator """ self._cur_iter_en += 1 ind = self._cur_iter_en if ind < self._num_energies: - if isinstance(self._incident_energy,list): - return self._incident_energy[ind] - else: - return self._incident_energy + if isinstance(self._incident_energy,list): + return self._incident_energy[ind] + else: + return self._incident_energy else: - raise StopIteration + raise StopIteration # end IncidentEnergy #----------------------------------------------------------------------------------------- class EnergyBins(PropDescriptor): - """ Energy binning, requested for final converted to energy transfer workspace. + """ Energy binning, requested for final converted to energy transfer workspace. Provide it in the form: - [min_energy,step,max_energy] if energy to process (incident_energy property ) + [min_energy,step,max_energy] if energy to process (incident_energy property ) has a single value - or + or [min_rel_enrgy,rel_step,max_rel_energy] where rel_energy is relative energy - if energy(ies) to process are list of energies. The list of energies can + if energy(ies) to process are list of energies. The list of energies can consist of single value (e.g. prop_man.incident_energy=[100]) """ @@ -330,22 +331,22 @@ def __init__(self,IncidentEnergyProp): def __get__(self,instance,owner=None): """ binning range for the result of convertToenergy procedure or list of such ranges """ if instance is None: - return self + return self return self._energy_bins def __set__(self,instance,values): - if values != None: - if isinstance(values,str): - values = values.translate(None, '[]').strip() - lst = values.split(',') - self.__set__(instance,lst) - return - else: - value = values - if len(value) != 3: - raise KeyError("Energy_bin value has to be a tuple of 3 elements or string of 3 comma-separated numbers") - value = (float(value[0]),float(value[1]),float(value[2])) + if values != None: + if isinstance(values,str): + values = values.translate(None, '[]').strip() + lst = values.split(',') + self.__set__(instance,lst) + return + else: + value = values + if len(value) != 3: + raise KeyError("Energy_bin value has to be a tuple of 3 elements or string of 3 comma-separated numbers") + value = (float(value[0]),float(value[1]),float(value[2])) # Let's not support list of multiple absolute energy bins for the # time being # nBlocks = len(value) @@ -353,51 +354,51 @@ def __set__(self,instance,values): # raise KeyError("Energy_bin value has to be either list of # n-blocks of 3 number each or string representation of this list # with numbers separated by commas") - else: - value = None + else: + value = None #TODO: implement single value settings according to rebin? - self._energy_bins = value + self._energy_bins = value def get_abs_range(self,instance=None): - """ return energies related to incident energies either as - + """ return energies related to incident energies either as + """ if self._incident_energy.multirep_mode(): # Relative energy ei = self._incident_energy.get_current() if self._energy_bins: if self.is_range_valid(): - rez = self._calc_relative_range(ei) + rez = self._calc_relative_range(ei) else: - if instance: - instance.log("*** WARNING! Got energy_bins specified as absolute values in multirep mode.\n"\ - " Will normalize these values by max value and treat as relative values ", + if instance: + instance.log("*** WARNING! Got energy_bins specified as absolute values in multirep mode.\n"\ + " Will normalize these values by max value and treat as relative values ",\ "warning") - mult = self._range / self._energy_bins[2] - rez = self._calc_relative_range(ei,mult) + mult = self._range / self._energy_bins[2] + rez = self._calc_relative_range(ei,mult) return rez else: - return None + return None else: # Absolute energy ranges - if self.is_range_valid(): - return self._energy_bins - else: - if instance: - instance.log("*** WARNING! Requested maximum binning range exceeds incident energy!\n"\ - " Will normalize binning range by max value and treat as relative range", + if self.is_range_valid(): + return self._energy_bins + else: + if instance: + instance.log("*** WARNING! Requested maximum binning range exceeds incident energy!\n"\ + " Will normalize binning range by max value and treat as relative range",\ "warning") - mult = self._range / self._energy_bins[2] - ei = self._incident_energy.get_current() - return self._calc_relative_range(ei,mult) + mult = self._range / self._energy_bins[2] + ei = self._incident_energy.get_current() + return self._calc_relative_range(ei,mult) def is_range_valid(self): - """Method verifies if binning range is consistent with incident energy """ + """Method verifies if binning range is consistent with incident energy """ if self._incident_energy.multirep_mode(): - return (self._energy_bins[2] <= self._range) + return self._energy_bins[2] <= self._range else: - return (self._energy_bins[2] <= self._incident_energy.get_current()) + return self._energy_bins[2] <= self._incident_energy.get_current() def _calc_relative_range(self,ei,range_mult=1): - """ """ + """ """ mult = range_mult * ei return (self._energy_bins[0] * mult ,self._energy_bins[1] * mult,self._energy_bins[2] * mult) @@ -410,16 +411,16 @@ class SaveFileName(PropDescriptor): See similar property get_sample_ws_name TODO: (leave only one) """ def __init__(self,Name=None): - self._file_name = Name + self._file_name = Name def __get__(self,instance,owner=None): if instance is None: - return self + return self if self._file_name: return self._file_name else: if instance.instr_name: - name = instance.short_inst_name + name = instance.short_inst_name else: name = '_EMPTY' @@ -443,26 +444,26 @@ def __set__(self,instance,value): #end SaveFileName #----------------------------------------------------------------------------------------- class InstrumentDependentProp(PropDescriptor): - """ Generic property describing some aspects of instrument (e.g. name, short name etc), + """ Generic property describing some aspects of instrument (e.g. name, short name etc), which are undefined if no instrument is defined """ def __init__(self,prop_name): self._prop_name = prop_name def __get__(self,instance,owner=None): - if instance is None: - return self + if instance is None: + return self - if instance._pInstrument is None: + if instance._pInstrument is None: raise KeyError("Attempt to use uninitialized property manager") - else: + else: return getattr(instance,self._prop_name) def __set__(self,instance,values): raise AttributeError("Property {0} can not be assigned".format(self._prop_name)) #end InstrumentDependentProp #----------------------------------------------------------------------------------------- def check_ei_bin_consistent(ei,binning_range): - """ function verifies if the energy binning is consistent with incident energies """ + """ function verifies if the energy binning is consistent with incident energies """ if isinstance(ei,list): for en in ei: range = binning_range[en] @@ -475,7 +476,7 @@ def check_ei_bin_consistent(ei,binning_range): return (True,'') #----------------------------------------------------------------------------------------- class VanadiumRMM(PropDescriptor): - """ define constant static rmm for vanadium """ + """ define constant static rmm for vanadium """ def __get__(self,instance,owner=None): """ return rmm for vanadium """ @@ -492,35 +493,35 @@ def __set__(self,instance,value): # PropertyManager #----------------------------------------------------------------------------------------- class mon2NormalizationEnergyRange(PropDescriptor): - """ Energy range to integrate signal on monitor 2 when normalized by this monitor - - This class contains relative range of energies in which the monitor-2 signal should - be integrated, and returns the energy range for integration according to + """ Energy range to integrate signal on monitor 2 when normalized by this monitor + + This class contains relative range of energies in which the monitor-2 signal should + be integrated, and returns the energy range for integration according to formula: range = [min_range*ei,max_range*ei] where ei is incident monitor energy - To find actual integration ranges one should convert these values into TOF (or + To find actual integration ranges one should convert these values into TOF (or convert monitor signal to energy) - """ + """ def __init__(self): # default range self._relative_range = [0.8,1.2] def __get__(self,instance,owner): - """ Return actual energy range from internal relative range and incident energy """ - if instance is None: - return self - return [self._relative_range[0] * instance.incident_energy,self._relative_range[1] * instance.incident_energy] + """ Return actual energy range from internal relative range and incident energy """ + if instance is None: + return self + return [self._relative_range[0] * instance.incident_energy,self._relative_range[1] * instance.incident_energy] def __set__(self,instance,val): - """ set detector calibration file using various formats """ - if isinstance(val,list): - self._relative_range = self._check_range(val,instance) - elif isinstance(val,str): - val = self._parce_string2list(val) - self.__set__(instance,val) - else: - raise KeyError('mon2_norm_energy_range needs to be initialized by two values.\n' + """ set detector calibration file using various formats """ + if isinstance(val,list): + self._relative_range = self._check_range(val,instance) + elif isinstance(val,str): + val = self._parce_string2list(val) + self.__set__(instance,val) + else: + raise KeyError('mon2_norm_energy_range needs to be initialized by two values.\n'\ 'Trying to assign value {0} of unknown type {1}'.format(val,type(val))) # def _check_range(self,val,instance): @@ -537,12 +538,12 @@ def _check_range(self,val,instance): instance.log(message,'warning') val2 = float(val[1]) if val2 < 1.1 or val2 > 1.9: - message = "Upper mon2_norm_energy_range describes upper limit of energy to integrate neutron signal after the chopper.\n"\ + message = "Upper mon2_norm_energy_range describes upper limit of energy to integrate neutron signal after the chopper.\n"\ "The limit is defined as (this value)*incident_energy. Are you sure you want to set this_value to {0}?\n".format(val2) - if val2 < 1: - raise KeyError(message) - else: - instance.log(message,'warning') + if val2 < 1: + raise KeyError(message) + else: + instance.log(message,'warning') return [val1,val2] # @@ -555,6 +556,8 @@ def _parce_string2list(self,val): #----------------------------------------------------------------------------------------- class PropertyFromRange(PropDescriptor): """ Descriptor for property, which can have one value from a list of values """ + _current_value = None + def __init__(self,availible_values,default_value): self._availible_values = availible_values self.__set__(None,default_value) @@ -562,15 +565,15 @@ def __init__(self,availible_values,default_value): def __get__(self,instance,owner): """ Return current value for the property with range of values. """ if instance is None: - return self + return self return self._current_value def __set__(self,instance,val): - """ set detector calibration file using various formats """ - if val in self._availible_values: - self._current_value = val - else: - raise KeyError(' Property can not have value {0}'.format(val)) + """ set detector calibration file using various formats """ + if val in self._availible_values: + self._current_value = val + else: + raise KeyError(' Property can not have value {0}'.format(val)) #----------------------------------------------------------------------------------------- class DetCalFile(PropDescriptor): @@ -580,31 +583,31 @@ def __init__(self): def __get__(self,instance,owner): if instance is None: - return self + return self return self._det_cal_file def __set__(self,instance,val): - """ set detector calibration file using various formats """ - - if val is None or isinstance(val,api.Workspace) or isinstance(val,str): + """ set detector calibration file using various formats """ + + if val is None or isinstance(val,api.Workspace) or isinstance(val,str): # nothing provided or workspace provided or filename probably provided - if str(val) in mtd: + if str(val) in mtd: # workspace name provided val = mtd[str(val)] - self._det_cal_file = val - return - + self._det_cal_file = val + return - if isinstance(val,int): + + if isinstance(val,int): #if val in instance.all_run_numbers: TODO: retrieve workspace from #run numbers - file_hint = str(val) - file_name = FileFinder.findRuns(file_hint)[0] - self._det_cal_file = file_name - return + file_hint = str(val) + file_name = FileFinder.findRuns(file_hint)[0] + self._det_cal_file = file_name + return - raise NameError('Detector calibration file name can be a workspace name present in Mantid or string describing an file name') + raise NameError('Detector calibration file name can be a workspace name present in Mantid or string describing an file name') #if Reducer.det_cal_file != None : # if isinstance(Reducer.det_cal_file,str) and not Reducer.det_cal_file # in mtd : # it is a file @@ -623,61 +626,61 @@ class MapMaskFile(PropDescriptor): def __init__(self,file_ext,doc_string=None): self._file_name = None self._file_ext = file_ext - if not(doc_string is None): + if not doc_string is None: self.__doc__ = doc_string def __get__(self,instance,type=None): if instance is None: - return self + return self return self._file_name def __set__(self,instance,value): if value != None: - fileName, fileExtension = os.path.splitext(value) - if (not fileExtension): - value = value + self._file_ext + fileName, fileExtension = os.path.splitext(value) + if not fileExtension: + value = value + self._file_ext self._file_name = value - + #end MapMaskFile #----------------------------------------------------------------------------------------- class HardMaskPlus(prop_helpers.ComplexProperty): - """ Legacy HardMaskPlus class which sets up hard_mask_file to file and use_hard_mask_only to True""" + """ Legacy HardMaskPlus class which sets up hard_mask_file to file and use_hard_mask_only to True""" def __init__(self): prop_helpers.ComplexProperty.__init__(self,['use_hard_mask_only','run_diagnostics']) def __get__(self,instance,type=None): if instance is None: - return self + return self return instance.hard_mask_file def __set__(self,instance,value): if value != None: - fileName, fileExtension = os.path.splitext(value) - if (not fileExtension): - value = value + '.msk' - instance.hard_mask_file = value - prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[False,True]) + fileName, fileExtension = os.path.splitext(value) + if not fileExtension: + value = value + '.msk' + instance.hard_mask_file = value + prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[False,True]) else: - prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[True,False]) + prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[True,False]) try: - del instance.__changed_properties['hardmaskOnly'] + del instance.__changed_properties['hardmaskOnly'] except: - pass - + pass + #----------------------------------------------------------------------------------------- class HardMaskOnly(prop_helpers.ComplexProperty): """ Sets diagnostics algorithm to use hard mask file provided and to disable all other diagnostics routines It controls two options, where the first one is use_hard_mask_only=True/False, controls diagnostics algorithm - and another one: hard_mask_file provides file for masking. + and another one: hard_mask_file provides file for masking. """ def __init__(self): prop_helpers.ComplexProperty.__init__(self,['use_hard_mask_only','run_diagnostics']) def __get__(self,instance,type=None): if instance is None: - return self + return self return prop_helpers.gen_getter(instance.__dict__,'use_hard_mask_only') def __set__(self,instance,value): @@ -694,7 +697,7 @@ def __set__(self,instance,value): elif value.lower() in ['false','no']: use_hard_mask_only = False else: # it is probably a hard mask file provided: - instance.hard_mask_file = value + instance.hard_mask_file = value use_hard_mask_only = True hard_mask_file = instance.hard_mask_file #end @@ -707,9 +710,9 @@ def __set__(self,instance,value): run_diagnostics = True prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[use_hard_mask_only,run_diagnostics]) try: - del instance.__changed_properties['hardmaskPlus'] + del instance.__changed_properties['hardmaskPlus'] except: - pass + pass #end HardMaskOnly #----------------------------------------------------------------------------------------- class MonovanIntegrationRange(prop_helpers.ComplexProperty): @@ -718,28 +721,27 @@ class MonovanIntegrationRange(prop_helpers.ComplexProperty): Defined either directly or as the function of the incident energy(s) - If list of incident energies is provided, map of ranges in the form 'ei'=range is returned + If list of incident energies is provided, map of ranges in the form 'ei'=range is returned """ def __init__(self,DepType=None): if DepType: self._rel_range = False prop_helpers.ComplexProperty.__init__(self,['monovan_lo_value','monovan_hi_value']) else: - self._rel_range = True + self._rel_range = True prop_helpers.ComplexProperty.__init__(self,['monovan_lo_frac','monovan_hi_frac']) - pass def __get__(self,instance,owner): if instance is None: - return self + return self if isinstance(instance,dict): - ei = 1 - tDict = instance + ei = 1 + tDict = instance else: - ei = owner.incident_energy.get_current() - tDict = instance.__dict__ + ei = owner.incident_energy.get_current() + tDict = instance.__dict__ if self._rel_range: # relative range if ei is None: @@ -752,17 +754,17 @@ def __get__(self,instance,owner): def __set__(self,instance,value): if isinstance(instance,dict): - dDict = instance + dDict = instance else: - tDict = instance.__dict__ + tDict = instance.__dict__ if value is None: - if (not self._rel_range): + if not self._rel_range: self._rel_range = True self._other_prop = ['monovan_lo_frac','monovan_hi_frac'] else: if self._rel_range: - self._rel_range = False - self._other_prop = ['monovan_lo_value','monovan_hi_value'] + self._rel_range = False + self._other_prop = ['monovan_lo_value','monovan_hi_value'] if isinstance(value,str): values = value.split(',') @@ -778,33 +780,33 @@ def __set__(self,instance,value): #----------------------------------------------------------------------------------------- class SpectraToMonitorsList(PropDescriptor): - """ property describes list of spectra, used as monitors to estimate incident energy - in a direct scattering experiment. + """ property describes list of spectra, used as monitors to estimate incident energy + in a direct scattering experiment. - Necessary when a detector working in event mode is used as monitor. Specifying this number would copy + Necessary when a detector working in event mode is used as monitor. Specifying this number would copy correspondent spectra to monitor workspace and rebin it according to monitors binning Written to work with old IDF too, where this property is absent. - """ - def __init__(self): - self._spectra_to_monitors_list = None + """ + def __init__(self): + self._spectra_to_monitors_list = None - def __get__(self,instance,type=None): - if instance is None: - return self - return self._spectra_to_monitors_list + def __get__(self,instance,type=None): + if instance is None: + return self + return self._spectra_to_monitors_list - def __set__(self,instance,spectra_list): + def __set__(self,instance,spectra_list): """ Sets copy spectra to monitors variable as a list of monitors using different forms of input """ self._spectra_to_monitors_list = self._convert_to_list(spectra_list) - def _convert_to_list(self,spectra_list): - """ convert any spectra_list representation into a list """ - if spectra_list is None: + def _convert_to_list(self,spectra_list): + """ convert any spectra_list representation into a list """ + if spectra_list is None: return None - if isinstance(spectra_list,str): + if isinstance(spectra_list,str): if spectra_list.lower() is 'none': result = None else: @@ -813,7 +815,7 @@ def _convert_to_list(self,spectra_list): for spectum in spectra : result.append(int(spectum)) - else: + else: if isinstance(spectra_list,list): if len(spectra_list) == 0: result = None @@ -823,23 +825,23 @@ def _convert_to_list(self,spectra_list): result.append(int(spectra_list[i])) else: result = [int(spectra_list)] - return result + return result #end SpectraToMonitorsList #----------------------------------------------------------------------------------------- class SaveFormat(PropDescriptor): # formats available for saving the data - save_formats = ['spe','nxspe','nxs'] - def __init__(self): - self._save_format = set() + save_formats = ['spe','nxspe','nxs'] + def __init__(self): + self._save_format = set() - def __get__(self,instance,type=None): + def __get__(self,instance,type=None): if instance is None: - return self + return self return self._save_format - def __set__(self,instance,value): + def __set__(self,instance,value): """ user can clear save formats by setting save_format=None or save_format = [] or save_format='' if empty string or empty list is provided as part of the list, all save_format-s set up earlier are cleared""" @@ -856,19 +858,19 @@ def __set__(self,instance,value): self.__set__(instance,subformats) return else: - value = subformats[0] + value = subformats[0] - if not(value in SaveFormat.save_formats): + if not value in SaveFormat.save_formats: instance.log("Trying to set saving in unknown format: \"" + str(value) + "\" No saving will occur for this format") return - else: + else: try: # set single default save format recursively - for val in value: + for val in value: self.__set__(instance,val) - return - except: - raise KeyError(' Attempting to set unknown saving format {0} of type {1}. Allowed values can be spe, nxspe or nxs'\ + return + except: + raise KeyError(' Attempting to set unknown saving format {0} of type {1}. Allowed values can be spe, nxspe or nxs'\ .format(value,type(value))) #end if different types self._save_format.add(value) @@ -876,9 +878,9 @@ def __set__(self,instance,value): #----------------------------------------------------------------------------------------- class DiagSpectra(PropDescriptor): - """ class describes spectra list which should be used in diagnostics + """ class describes spectra list which should be used in diagnostics - consist of tuples list where each tuple are the numbers + consist of tuples list where each tuple are the numbers indicating first-last spectra in the group. if None, all spectra are used in diagnostics @@ -888,7 +890,7 @@ def __init__(self): def __get__(self,instance,type=None): if instance is None: - return self + return self return self._diag_spectra @@ -919,27 +921,27 @@ def _process_spectra_list(self,specta_sring): #----------------------------------------------------------------------------------------- class BackbgroundTestRange(PropDescriptor): - """ The TOF range used in diagnostics to reject high background spectra. + """ The TOF range used in diagnostics to reject high background spectra. - Usually it is the same range as the TOF range used to remove - background (usually in powders) though it may be set up separately. + Usually it is the same range as the TOF range used to remove + background (usually in powders) though it may be set up separately. """ def __init__(self): self._background_test_range = None def __get__(self,instance,type=None): - if instance is None: - return self + if instance is None: + return self - if self._background_test_range: - return self._background_test_range - else: + if self._background_test_range: + return self._background_test_range + else: return instance.bkgd_range def __set__(self,instance,value): if value is None: - self._background_test_range = None - return + self._background_test_range = None + return if isinstance(value,str): value = str.split(value,',') if len(value) != 2: @@ -949,52 +951,52 @@ def __set__(self,instance,value): #----------------------------------------------------------------------------------------- class MultirepTOFSpectraList(PropDescriptor): - """ property describes list of spectra numbers, used to identify - TOF range corresponding to the particular energy range + """ property describes list of spectra numbers, used to identify + TOF range corresponding to the particular energy range - Usually it is list of two numbers, specifying monitors which are - closest and furthest from the sample + Usually it is list of two numbers, specifying monitors which are + closest and furthest from the sample """ def __init__(self): self._spectra_list = None def __get__(self,instance,type=None): - if instance is None: - return self + if instance is None: + return self - return self._spectra_list + return self._spectra_list def __set__(self,instance,value): if value is None: - self._spectra_list = None - return + self._spectra_list = None + return if isinstance(value,str): value = str.split(value,',') self.__set__(instance,value) return if isinstance(value, list): - rez =[] - for val in value: - rez.append(int(val)) + rez =[] + for val in value: + rez.append(int(val)) else: rez = [int(value)] self._spectra_list=rez #end MultirepTOFSpectraList class MonoCorrectionFactor(PropDescriptor): - """ property contains correction factor, used to convert - experimental scattering cross-section into absolute - units ( mb/str/mev/fu) + """ property contains correction factor, used to convert + experimental scattering cross-section into absolute + units ( mb/str/mev/fu) - There are independent two sources for this factor: - 1) if user explicitly specifies correction value. - This value then will be applied to all subsequent runs + There are independent two sources for this factor: + 1) if user explicitly specifies correction value. + This value then will be applied to all subsequent runs without any checks if the correction is appropriate - 2) set/get cashed value correspondent to current monovan + 2) set/get cashed value correspondent to current monovan run number, incident energy and integration range. - This value is cashed at first run and reapplied if + This value is cashed at first run and reapplied if no changes to the values it depends on were identified - """ + """ def __init__(self,ei_prop): self._cor_factor = None self._mono_run_number=None @@ -1002,21 +1004,21 @@ def __init__(self,ei_prop): self.cashed_values={} def __get__(self,instance,type=None): - if instance is None: - return self + if instance is None: + return self - return self._cor_factor + return self._cor_factor def __set__(self,instance,value): - self._cor_factor = value - # + self._cor_factor = value + # def set_val_to_cash(self,instance,value): - """ """ + """ """ mono_int_range = instance.monovan_integr_range cash_id = self._build_cash_val_id(mono_int_range) self.cashed_values[cash_id] = value # tell property manager that mono_correction_factor has been modified - # to avoid automatic resetting this property from any workspace + # to avoid automatic resetting this property from any workspace cp = getattr(instance,'_PropertyManager__changed_properties') cp.add('mono_correction_factor') @@ -1024,24 +1026,24 @@ def get_val_from_cash(self,instance): mono_int_range = instance.monovan_integr_range cash_id = self._build_cash_val_id(mono_int_range) if cash_id in self.cashed_values: - return self.cashed_values[cash_id] + return self.cashed_values[cash_id] else: - return None - + return None + def set_cash_mono_run_number(self,new_value): if new_value is None: - self.cashed_values={} - self._mono_run_number = None - return + self.cashed_values={} + self._mono_run_number = None + return if self._mono_run_number != int(new_value): - self.cashed_values={} - self._mono_run_number = int(new_value) + self.cashed_values={} + self._mono_run_number = int(new_value) def _build_cash_val_id(self,mono_int_range): - ei = self._ei_prop.get_current() - cash_id = "Ei={0:0>9.4e}:Int({1:0>9.4e}:{2:0>9.5e}):Run{3}".\ + ei = self._ei_prop.get_current() + cash_id = "Ei={0:0>9.4e}:Int({1:0>9.4e}:{2:0>9.5e}):Run{3}".\ format(ei,mono_int_range[0],mono_int_range[1],self._mono_run_number) - return cash_id + return cash_id #----------------------------------------------------------------------------------------- diff --git a/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py b/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py index 987c33499bb5..33c518c10e4c 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py +++ b/Code/Mantid/scripts/Inelastic/Direct/PropertyManager.py @@ -1,33 +1,34 @@ -from NonIDF_Properties import * +#pylint: disable=invalid-name +from Direct.NonIDF_Properties import * from collections import OrderedDict class PropertyManager(NonIDF_Properties): - """ Class defines the interface for Direct inelastic reduction with properties + """ Class defines the interface for Direct inelastic reduction with properties present in Instrument_Properties.xml file These properties are responsible for fine turning up of the reduction - Supported properties in IDF can be simple (prop[name]=value e.g. - prop['vanadium_mass']=30.5 - - or complex + Supported properties in IDF can be simple (prop[name]=value e.g. + prop['vanadium_mass']=30.5 + + or complex where prop[name_complex_prop] value is equal [prop[name_1],prop[name_2]] e.g. time interval used in normalization on monitor 1: prop[norm_mon_integration_range] = [prop['norm-mon1-min'],prop['norm-mon1-max']] prop['norm-mon1-min']=1000,prop['norm-mon1-max']=2000 - There are properties which provide even more complex functionality. These defined using Descriptors. + There are properties which provide even more complex functionality. These defined using Descriptors. + - - The class is written to provide the following functionality. + The class is written to provide the following functionality. - 1) Properties are initiated from Instrument_Properties.xml file as defaults. - 2) Attempt to access property, not present in this file throws. - 3) Attempt to create property not present in this file throws. - 4) A standard behavior is defined for the most of the properties (get/set appropriate value) when there is number of - overloaded properties, which support more complex behavior using specially written Descriptors + 1) Properties are initiated from Instrument_Properties.xml file as defaults. + 2) Attempt to access property, not present in this file throws. + 3) Attempt to create property not present in this file throws. + 4) A standard behavior is defined for the most of the properties (get/set appropriate value) when there is number of + overloaded properties, which support more complex behavior using specially written Descriptors 5) Changes to the properties are recorded and the list of changed properties is available on request ######## @@ -41,9 +42,9 @@ class PropertyManager(NonIDF_Properties): __getattr__ and __setattr__ are overloaded to understand such calls. The property_name itself is naturally not placed into system dictionary. - 3) Descriptors with the name present in IDF do not store their values and names in __dict__ + 3) Descriptors with the name present in IDF do not store their values and names in __dict__ (the name is removed during IDF parsing) but keep their information in the descriptor. - This is not considered a problem as only one instance of property manager is expected. If this need to be changed, + This is not considered a problem as only one instance of property manager is expected. If this need to be changed, adding property values to the __dict__ as values of _property_name keys should be safe. 4) __getattr__ (and __setattr__ ) method are overloaded to provide call to a descriptor before the search in the system dictionary. @@ -51,10 +52,10 @@ class PropertyManager(NonIDF_Properties): e.g. in case when an descriptor is called through one of its synonym name. A problem will occur if a key with name equal to descriptor name is also present in __dict__. This name would override descriptor. - This is why any new descriptor should never place a key with its name in __dict__. Current design automatically remove IDF name + This is why any new descriptor should never place a key with its name in __dict__. Current design automatically remove IDF name from __dict__ if a descriptor with such name exist, so further development should support this behavior. - 5) In many places (descriptors, RunDescriptor itself), PropertyManager assumed to be a singleton, so most Descriptors are defined on a + 5) In many places (descriptors, RunDescriptor itself), PropertyManager assumed to be a singleton, so most Descriptors are defined on a class level. If this changes, careful refactoring will be necessary @@ -76,10 +77,10 @@ def __init__(self,Instrument,instr_run=None): 'file_properties':[],'abs_norm_file_properties':[]} # place these properties to __dict__ with proper decoration self._init_private_properties(private_properties) - # + # class_dec = '_'+type(self).__name__+'__' # --------------------------------------------------------------------------------------------- - # overloaded descriptors. These properties have their personal descriptors, different from default. + # overloaded descriptors. These properties have their personal descriptors, different from default. all_methods = dir(self) object.__setattr__(self,class_dec+'descriptors',prop_helpers.extract_non_system_names(all_methods)) # --------------------------------------------------------------------------------------------- @@ -99,11 +100,11 @@ def __init__(self,Instrument,instr_run=None): object.__setattr__(self,class_dec+'abs_norm_file_properties',['monovan_mapfile']) # properties with allowed values - + def _convert_params_to_properties(self,param_list,detine_subst_dict=True,descr_list=[]): """ method processes parameters obtained from IDF and modifies the IDF properties - to the form allowing them be assigned as python class properties. - """ + to the form allowing them be assigned as python class properties. + """ subst_name = '_'+type(self).__name__+'__subst_dict' # build and use substitution dictionary @@ -117,12 +118,12 @@ def _convert_params_to_properties(self,param_list,detine_subst_dict=True,descr_l #end - # build properties list and descriptors list with their initial values - param_dict,descr_dict = prop_helpers.build_properties_dict(param_list,self.__dict__[subst_name],descr_list) + # build properties list and descriptors list with their initial values + param_dict,descr_dict = prop_helpers.build_properties_dict(param_list,self.__dict__[subst_name],descr_list) return (param_dict,descr_dict) def _init_private_properties(self,prop_dict): - """ helper method used to define all private dictionaries at once + """ helper method used to define all private dictionaries at once during __init__ procedure """ @@ -133,15 +134,15 @@ def _init_private_properties(self,prop_dict): new_key = class_decor+key object.__setattr__(self,new_key,val) - + def __setattr__(self,name0,val): """ Overloaded generic set method, disallowing non-existing properties being set. - - It also provides common checks for generic properties groups + + It also provides common checks for generic properties groups and records all properties changed - """ + """ - # Let's set private properties directly. Normally, nobody should try + # Let's set private properties directly. Normally, nobody should try # to set them through PropertyManager interface #if name0[:2]=='_P': # self.__dict__[name0] = val @@ -155,47 +156,47 @@ def __setattr__(self,name0,val): # replace common substitutions for string value if type(val) is str : - val1 = val.lower() - if (val1 == 'none' or len(val1) == 0): - val = None - if val1 == 'default': - val = self.getDefaultParameterValue(name0) + val1 = val.lower() + if val1 == 'none' or len(val1) == 0: + val = None + if val1 == 'default': + val = self.getDefaultParameterValue(name0) # boolean property? - if val1 in ['true','yes']: - val = True - if val1 in ['false','no']: - val = False + if val1 in ['true','yes']: + val = True + if val1 in ['false','no']: + val = False if type(val) is list and len(val) == 0: val = None - + # set property value: if name in self.__descriptors: - super(PropertyManager,self).__setattr__(name,val) + super(PropertyManager,self).__setattr__(name,val) else: - other_prop=prop_helpers.gen_setter(self.__dict__,name,val) + other_prop=prop_helpers.gen_setter(self.__dict__,name,val) # record the fact that the property have changed self.__changed_properties.add(name) # ---------------------------- def __getattr__(self,name): - """ Overloaded get method, disallowing non-existing properties being get but allowing - a property been called with different names specified in substitution dictionary. """ + """ Overloaded get method, disallowing non-existing properties being get but allowing + a property been called with different names specified in substitution dictionary. """ - if name in self.__subst_dict: - name = self.__subst_dict[name] - return getattr(self,name) - #end + if name in self.__subst_dict: + name = self.__subst_dict[name] + return getattr(self,name) + #end - if name in self.__descriptors: - # This can only happen only if descriptor is called through synonims dictionary + if name in self.__descriptors: + # This can only happen only if descriptor is called through synonims dictionary # This to work, all descriptors should define getter to return self on Null instance. - descr=getattr(PropertyManager,name) - return descr.__get__(self,name) - else: - return prop_helpers.gen_getter(self.__dict__,name) + descr=getattr(PropertyManager,name) + return descr.__get__(self,name) + else: + return prop_helpers.gen_getter(self.__dict__,name) ##end #---------------------------------------------------------------------------------- # Overloaded setters/getters @@ -212,7 +213,7 @@ def __getattr__(self,name): monovan_integr_range = MonovanIntegrationRange() # spectra_to_monitors_list = SpectraToMonitorsList() - # + # save_format = SaveFormat() # hardmaskOnly = HardMaskOnly() @@ -226,7 +227,7 @@ def __getattr__(self,name): # Properties with allowed value normalise_method= PropertyFromRange([None,'monitor-1','monitor-2','current'],'current') deltaE_mode = PropertyFromRange(['direct'],'direct') # other modes should not be considered here - # + # multirep_tof_specta_list=MultirepTOFSpectraList() # mono_correction_factor = MonoCorrectionFactor(NonIDF_Properties.incident_energy) @@ -237,7 +238,7 @@ def getChangedProperties(self): decor_prop = '_'+type(self).__name__+'__changed_properties' return self.__dict__[decor_prop] def setChangedProperties(self,value=set([])): - """ Method to clear changed properties list""" + """ Method to clear changed properties list""" if isinstance(value,set): decor_prop = '_'+type(self).__name__+'__changed_properties' self.__dict__[decor_prop] =value @@ -250,27 +251,27 @@ def relocate_dets(self) : return True else: return False - + def set_input_parameters_ignore_nan(self,**kwargs): - """ Like similar method set_input_parameters this one is used to - set changed parameters from dictionary of parameters. + """ Like similar method set_input_parameters this one is used to + set changed parameters from dictionary of parameters. - Unlike set_input_parameters, this method does not set parameter, - with value equal to None. As such, this method is used as interface to + Unlike set_input_parameters, this method does not set parameter, + with value equal to None. As such, this method is used as interface to set data from a function with a list of given parameters (*args vrt **kwargs), with some parameters missing. - """ - # if sum is in parameters one needs to set it first - if 'sum_runs' in kwargs and not (kwargs['sum_runs'] is None): + """ + # if sum is in parameters one needs to set it first + if 'sum_runs' in kwargs and not kwargs['sum_runs'] is None: self.sum_runs = kwargs['sum_runs'] del kwargs['sum_runs'] - if 'sum' in kwargs and not (kwargs['sum'] is None): + if 'sum' in kwargs and not kwargs['sum'] is None: self.sum_runs = kwargs['sum'] del kwargs['sum'] for par_name,value in kwargs.items() : - if not(value is None): + if not value is None: setattr(self,par_name,value) @@ -280,7 +281,7 @@ def set_input_parameters(self,**kwargs): """ # if sum is in parameters one needs to set it first to interpret - # + # if 'sum_runs' in kwargs : self.sum_runs = kwargs['sum_runs'] del kwargs['sum_runs'] @@ -295,7 +296,7 @@ def set_input_parameters(self,**kwargs): return self.getChangedProperties() def get_used_monitors_list(self): - """ Method returns list of monitors ID used during reduction """ + """ Method returns list of monitors ID used during reduction """ used_mon=set() for case in common.switch(self.normalise_method): @@ -306,7 +307,7 @@ def get_used_monitors_list(self): used_mon.add(self.mon2_norm_spec) break if case(): # default, could also just omit condition or 'if True' - pass + pass used_mon.add(self.ei_mon1_spec) used_mon.add(self.ei_mon2_spec) @@ -316,9 +317,9 @@ def get_used_monitors_list(self): def get_diagnostics_parameters(self): """ Return the dictionary of the properties used in diagnostics with their values defined in IDF - + if some values are not in IDF, default values are used instead - """ + """ diag_param_list ={'tiny':1e-10, 'huge':1e10, 'samp_zero':False, 'samp_lo':0.0, 'samp_hi':2,'samp_sig':3,\ 'van_out_lo':0.01, 'van_out_hi':100., 'van_lo':0.1, 'van_hi':1.5, 'van_sig':0.0, 'variation':1.1,\ @@ -330,26 +331,26 @@ def get_diagnostics_parameters(self): for key,val in diag_param_list.iteritems(): try: result[key] = getattr(self,key) - except KeyError: + except KeyError: self.log('--- Diagnostics property {0} is not found in instrument properties. Default value: {1} is used instead \n'.format(key,value),'warning') - + return result def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): """ Method used to update default parameters from the same instrument (with different parameters). - Used if initial parameters correspond to instrument with one validity dates and - current instrument has different validity dates and different default values for + Used if initial parameters correspond to instrument with one validity dates and + current instrument has different validity dates and different default values for these dates. - List of synonims is not modified and new properties are not added assuming that + List of synonims is not modified and new properties are not added assuming that recent dictionary and properties are most comprehensive one ignore_changes==True when changes, caused by setting properties from instrument are not recorded - ignore_changes==False -- getChangedProperties properties after applied this method would return set + ignore_changes==False -- getChangedProperties properties after applied this method would return set of all properties changed when applying this method - """ + """ if self.instr_name != pInstrument.getName(): self.log("*** WARNING: Setting reduction properties of the instrument {0} from the instrument {1}.\n" "*** This only works if both instruments have the same reduction properties!"\ @@ -362,48 +363,48 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): for prop_name in old_changes_list: old_changes[prop_name] = getattr(self,prop_name) - + param_list = prop_helpers.get_default_idf_param_list(pInstrument) # remove old changes which are not related to IDF (not to reapply it again) for prop_name in old_changes: - if not (prop_name in param_list): - try: - dependencies = getattr(PropertyManager,prop_name).dependencies() - except: - dependencies = [] - modified = False - for name in dependencies: - if name in param_list: - modified = True - break - if not modified: - del old_changes[prop_name] + if not prop_name in param_list: + try: + dependencies = getattr(PropertyManager,prop_name).dependencies() + except: + dependencies = [] + modified = False + for name in dependencies: + if name in param_list: + modified = True + break + if not modified: + del old_changes[prop_name] #end param_list,descr_dict = self._convert_params_to_properties(param_list,False,self.__descriptors) # clear record about previous changes self.setChangedProperties(set()) - #sort parameters to have complex properties (with underscore _) first + #sort parameters to have complex properties (with underscore _) first sorted_param = OrderedDict(sorted(param_list.items(),key=lambda x : ord((x[0][0]).lower()))) - # Walk through descriptors list and set their values + # Walk through descriptors list and set their values # Assignment to descriptors should accept the form, descriptor is written in IDF changed_descriptors = set() for key,val in descr_dict.iteritems(): - if not (key in old_changes_list): - try: # this is reliability check, and except ideally should never be hit. May occur if old IDF contains + if not key in old_changes_list: + try: # this is reliability check, and except ideally should never be hit. May occur if old IDF contains # properties, not present in recent IDF. - cur_val = getattr(self,key) - setattr(self,key,val) - new_val = getattr(self,key) + cur_val = getattr(self,key) + setattr(self,key,val) + new_val = getattr(self,key) except: - self.log("property {0} have not been found in existing IDF. Ignoring this property"\ + self.log("property {0} have not been found in existing IDF. Ignoring this property"\ .format(key),'warning') - continue + continue if isinstance(new_val,api.Workspace) and isinstance(cur_val,api.Workspace): - # do simplified workspace comparison which is appropriate here - if new_val.name() == cur_val.name() and \ + # do simplified workspace comparison which is appropriate here + if new_val.name() == cur_val.name() and \ new_val.getNumberHistograms() == cur_val.getNumberHistograms() and \ new_val.getNEvents() == cur_val.getNEvents() and \ new_val.getAxis(0).getUnit().unitID() == cur_val.getAxis(0).getUnit().unitID(): @@ -411,16 +412,16 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): # #end if new_val != cur_val: - changed_descriptors.add(key) + changed_descriptors.add(key) # dependencies removed either properties are equal or not try: - dependencies = getattr(PropertyManager,key).dependencies() + dependencies = getattr(PropertyManager,key).dependencies() except: - dependencies = [] + dependencies = [] for dep_name in dependencies: if dep_name in sorted_param: - del sorted_param[dep_name] + del sorted_param[dep_name] else: # remove property from old changes list not to reapply it again? pass #end loop @@ -429,7 +430,7 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): # Walk through the complex properties first and then through simple properties for key,val in sorted_param.iteritems(): - if not(key in old_changes_list): + if not key in old_changes_list: # complex properties change through their dependencies so we are setting them first if isinstance(val,prop_helpers.ComplexProperty): public_name = key[1:] @@ -439,21 +440,21 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): public_name = key prop_new_val = val - try: # this is reliability check, and except ideally should never be hit. May occur if old IDF contains + try: # this is reliability check, and except ideally should never be hit. May occur if old IDF contains # properties, not present in recent IDF. - cur_val = getattr(self,public_name) + cur_val = getattr(self,public_name) except: self.log("property {0} have not been found in existing IDF. Ignoring this property"\ .format(public_name),'warning') continue if prop_new_val !=cur_val : - setattr(self,public_name,prop_new_val) + setattr(self,public_name,prop_new_val) # Dependencies removed either properties are equal or not try: - dependencies = val.dependencies() + dependencies = val.dependencies() except: - dependencies =[] + dependencies =[] for dep_name in dependencies: # delete dependent properties not to deal with them again del sorted_param[dep_name] @@ -462,11 +463,11 @@ def update_defaults_from_instrument(self,pInstrument,ignore_changes=False): new_changes_list = self.getChangedProperties() self.setChangedProperties(set()) - # set back all changes stored earlier and may be overwritten by new IDF + # set back all changes stored earlier and may be overwritten by new IDF # (this is just to be sure -- should not change anything as we do not set properties changed) for key,val in old_changes.iteritems(): setattr(self,key,val) - + # Clear changed properties list (is this wise?, may be we want to know that some defaults changed?) if ignore_changes: self.setChangedProperties(old_changes_list) @@ -505,18 +506,18 @@ def check_files_list(files_list): if not (file is None) and isinstance(file,str): file_path = self._check_file_exist(file) if len(file_path)==0: - self.log(" Can not find file ""{0}"" for property: {1} ".format(file,prop),'error') - file_missing=True + self.log(" Can not find file ""{0}"" for property: {1} ".format(file,prop),'error') + file_missing=True return file_missing base_file_missing = check_files_list(self.__file_properties) abs_file_missing=False - if not (monovan_run is None): + if not monovan_run is None: abs_file_missing = check_files_list(self.__abs_norm_file_properties) if base_file_missing or abs_file_missing: - raise RuntimeError(" Files needed for the run are missing ") + raise RuntimeError(" Files needed for the run are missing ") # def _check_monovan_par_changed(self): """ method verifies, if properties necessary for monovanadium reduction have indeed been changed from defaults """ @@ -532,62 +533,62 @@ def _check_monovan_par_changed(self): # def log_changed_values(self,log_level='notice',display_header=True,already_changed=set()): - """ inform user about changed parameters and about the parameters that should be changed but have not - + """ inform user about changed parameters and about the parameters that should be changed but have not + This method is abstract method of NonIDF_Properties but is fully defined in PropertyManager - display_header==True prints nice additional information about run. If False, only + display_header==True prints nice additional information about run. If False, only list of changed properties displayed. """ - if display_header: + if display_header: # we may want to run absolute units normalization and this function has been called with monovan run or helper procedure - if self.monovan_run != None : + if self.monovan_run != None : # check if mono-vanadium is provided as multiple files list or just put in brackets occasionally - self.log("****************************************************************",'notice') - self.log('*** Output will be in absolute units of mb/str/mev/fu','notice') - non_changed = self._check_monovan_par_changed() - if len(non_changed) > 0: - for prop in non_changed: - value = getattr(self,prop) - message = "\n***WARNING!: Abs units norm. parameter : {0} not changed from default val: {1}"\ + self.log("****************************************************************",'notice') + self.log('*** Output will be in absolute units of mb/str/mev/fu','notice') + non_changed = self._check_monovan_par_changed() + if len(non_changed) > 0: + for prop in non_changed: + value = getattr(self,prop) + message = "\n***WARNING!: Abs units norm. parameter : {0} not changed from default val: {1}"\ "\n This may need to change for correct absolute units reduction\n" - self.log(message.format(prop,value),'warning') + self.log(message.format(prop,value),'warning') # now let's report on normal run. - if PropertyManager.incident_energy.multirep_mode(): - ei = self.incident_energy - mess = "*** Provisional Incident energies: {0:>8.3f}".format(ei[0]) - for en in ei[1:]: - mess += "; {0:>8.3f}".format(en) - mess+=" mEv" - self.log(mess,log_level) - else: - self.log("*** Provisional Incident energy: {0:>12.3f} mEv".format(self.incident_energy),log_level) + if PropertyManager.incident_energy.multirep_mode(): + ei = self.incident_energy + mess = "*** Provisional Incident energies: {0:>8.3f}".format(ei[0]) + for en in ei[1:]: + mess += "; {0:>8.3f}".format(en) + mess+=" mEv" + self.log(mess,log_level) + else: + self.log("*** Provisional Incident energy: {0:>12.3f} mEv".format(self.incident_energy),log_level) #end display_header - self.log("****************************************************************",log_level) - changed_Keys= self.getChangedProperties() - for key in changed_Keys: - if key in already_changed: - continue - val = getattr(self,key) - self.log(" Value of : {0:<25} is set to : {1:<20} ".format(key,val),log_level) - - if not display_header: - return - - save_dir = config.getString('defaultsave.directory') - self.log("****************************************************************",log_level) - if self.monovan_run != None and not('van_mass' in changed_Keys): # This output is - self.log("*** Monochromatic vanadium mass used : {0} ".format(self.van_mass),log_level) # Adroja request from may 2014 + self.log("****************************************************************",log_level) + changed_Keys= self.getChangedProperties() + for key in changed_Keys: + if key in already_changed: + continue + val = getattr(self,key) + self.log(" Value of : {0:<25} is set to : {1:<20} ".format(key,val),log_level) + + if not display_header: + return + + save_dir = config.getString('defaultsave.directory') + self.log("****************************************************************",log_level) + if self.monovan_run != None and not 'van_mass' in changed_Keys: # This output is + self.log("*** Monochromatic vanadium mass used : {0} ".format(self.van_mass),log_level) # Adroja request from may 2014 # - self.log("*** By default results are saved into: {0}".format(save_dir),log_level) - self.log("*** Output will be normalized to {0}".format(self.normalise_method),log_level) - if self.map_file == None: + self.log("*** By default results are saved into: {0}".format(save_dir),log_level) + self.log("*** Output will be normalized to {0}".format(self.normalise_method),log_level) + if self.map_file == None: self.log('*** one2one map selected',log_level) - self.log("****************************************************************",log_level) + self.log("****************************************************************",log_level) #def help(self,keyword=None) : diff --git a/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py b/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py index 3aaa2f271fa9..d1943b913b8c 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py +++ b/Code/Mantid/scripts/Inelastic/Direct/ReductionHelpers.py @@ -1,14 +1,15 @@ +#pylint: disable=invalid-name from mantid import config import os """ -Set of functions to assist with processing instrument parameters relevant to reduction. +Set of functions to assist with processing instrument parameters relevant to reduction. """ class ComplexProperty(object): - """ Class describes property which depends on other properties and stores/receives values in other properties """ + """ Class describes property which depends on other properties and stores/receives values in other properties """ def __init__(self,other_prop_list): - self._other_prop = other_prop_list; - + self._other_prop = other_prop_list + def __get__(self,spec_dict,owner=None): """ return complex properties list """ if spec_dict is None: @@ -19,24 +20,24 @@ def __get__(self,spec_dict,owner=None): spec_dict = spec_dict.__dict__ rez = list() for key in self._other_prop: - rez.append(spec_dict[key]); - return rez; + rez.append(spec_dict[key]) + return rez def __set__(self,instance,value): try: lv = len(value) except: - raise KeyError("Complex property values can be assigned only by list of other values"); + raise KeyError("Complex property values can be assigned only by list of other values") if lv != len(self._other_prop): - raise KeyError("Complex property values can be set equal to the same length values list"); + raise KeyError("Complex property values can be set equal to the same length values list") if isinstance(instance,dict): spec_dict = instance else: spec_dict = instance.__dict__ - + #changed_prop=[]; for key,val in zip(self._other_prop,value): - spec_dict[key] =val; + spec_dict[key] =val #changed_prop.append(key); #return changed_prop; def dependencies(self): @@ -52,37 +53,37 @@ def len(self): def get_default_parameter(instrument, name): - """ Function gets the value of a default instrument parameter and - assign proper(the one defined in IPF ) type to this parameter - @param instrument -- - """ - - if instrument is None: - raise ValueError("Cannot initiate default parameter, instrument has not been properly defined.") - - type_name = instrument.getParameterType(name) - if type_name == "double": - val = instrument.getNumberParameter(name) - elif type_name == "bool": - val = instrument.getBoolParameter(name) - elif type_name == "string": - val = instrument.getStringParameter(name) - if val[0] == "None" : - return None - elif type_name == "int" : - val = instrument.getIntParameter(name) - else : - raise KeyError(" Instrument: {0} does not have parameter with name: {1}".format(instrument.getName(),name)) - - return val[0] + """ Function gets the value of a default instrument parameter and + assign proper(the one defined in IPF ) type to this parameter + @param instrument -- + """ + + if instrument is None: + raise ValueError("Cannot initiate default parameter, instrument has not been properly defined.") + + type_name = instrument.getParameterType(name) + if type_name == "double": + val = instrument.getNumberParameter(name) + elif type_name == "bool": + val = instrument.getBoolParameter(name) + elif type_name == "string": + val = instrument.getStringParameter(name) + if val[0] == "None" : + return None + elif type_name == "int" : + val = instrument.getIntParameter(name) + else : + raise KeyError(" Instrument: {0} does not have parameter with name: {1}".format(instrument.getName(),name)) + + return val[0] def get_default_idf_param_list(pInstrument,synonims_list=None): """ Obtain default reduction parameters list from the instrument """ - params = pInstrument.getParameterNames(); - par_list = {}; + params = pInstrument.getParameterNames() + par_list = {} for name in params: - par_list[name] = get_default_parameter(pInstrument,name); + par_list[name] = get_default_parameter(pInstrument,name) return par_list @@ -91,25 +92,25 @@ def get_default_idf_param_list(pInstrument,synonims_list=None): def build_properties_dict(param_map,synonims,descr_list=[]) : """ function builds the properties list from the properties strings obtained from Insturment_Parameters.xml file - + The properties, which have simple values are added to dictionary in the form: properties_dict[prop_name]=(False,value); - The properties, expressed trough the values of other properties - e.g. strings in a form key1 = key2:key3 + The properties, expressed trough the values of other properties + e.g. strings in a form key1 = key2:key3 are added to the dictionary in the form: in the form properties_dict[key1]=(True,['key2','key3']) - """ + """ # dictionary used for substituting composite keys. prelim_dict = dict() for name in param_map: - if name in synonims: - final_name = str(synonims[name]) - else: - final_name = str(name) - prelim_dict[final_name]=None + if name in synonims: + final_name = str(synonims[name]) + else: + final_name = str(name) + prelim_dict[final_name]=None param_keys = prelim_dict.keys() properties_dict = dict() @@ -124,46 +125,46 @@ def build_properties_dict(param_map,synonims,descr_list=[]) : if final_name in descr_list: is_descriptor = True - if isinstance(val,str): - val = val.strip() - keys_candidates = val.split(":") - n_keys = len(keys_candidates) + if isinstance(val,str): + val = val.strip() + keys_candidates = val.split(":") + n_keys = len(keys_candidates) # - if n_keys>1 : # this is the property we want to modify - result=list() - for key in keys_candidates : - if key in synonims: - rkey = str(synonims[key]) - else: - rkey = str(key) - if rkey in param_keys: - result.append(rkey) - else: - raise KeyError('Substitution key : {0} is not in the list of allowed keys'.format(rkey)) - if is_descriptor: - descr_dict[final_name] = result - else: - properties_dict['_'+final_name]=ComplexProperty(result) - else: - if is_descriptor: - descr_dict[final_name] = keys_candidates[0] - else: - properties_dict[final_name] =keys_candidates[0] + if n_keys>1 : # this is the property we want to modify + result=list() + for key in keys_candidates : + if key in synonims: + rkey = str(synonims[key]) + else: + rkey = str(key) + if rkey in param_keys: + result.append(rkey) + else: + raise KeyError('Substitution key : {0} is not in the list of allowed keys'.format(rkey)) + if is_descriptor: + descr_dict[final_name] = result + else: + properties_dict['_'+final_name]=ComplexProperty(result) + else: + if is_descriptor: + descr_dict[final_name] = keys_candidates[0] + else: + properties_dict[final_name] =keys_candidates[0] else: - if is_descriptor: + if is_descriptor: descr_dict[final_name] = val - else: + else: properties_dict[final_name]=val return (properties_dict,descr_dict) def extract_non_system_names(names_list,prefix='_'): - """ The function processes the input list and returns - the list with names which do not have the system framing (leading __) + """ The function processes the input list and returns + the list with names which do not have the system framing (leading __) """ - result = list(); - ns = len(prefix); + result = list() + ns = len(prefix) for name in names_list: pend = min(ns,len(name)) if name[:pend] != prefix: @@ -180,11 +181,11 @@ def build_subst_dictionary(synonims_list=None) : norm-mon1-spec=my_detector in the synonyms field of the IDF parameters file. """ if not synonims_list : # nothing to do - return dict(); + return dict() if type(synonims_list) == dict : # all done - return synonims_list + return synonims_list if type(synonims_list) != str : - raise AttributeError("The synonyms field of Reducer object has to be special format string or the dictionary") + raise AttributeError("The synonyms field of Reducer object has to be special format string or the dictionary") # we are in the right place and going to transform string into dictionary subst_lines = synonims_list.split(";") @@ -193,32 +194,32 @@ def build_subst_dictionary(synonims_list=None) : lin=lin.strip() keys = lin.split("=") if len(keys) < 2 : - raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present") + raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present") if len(keys[0]) == 0: - raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, but the first key is empty") + raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, but the first key is empty") for i in xrange(1,len(keys)) : - if len(keys[i]) == 0 : - raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, but the key"+str(i)+" is empty") - kkk = keys[i].strip(); - rez[kkk]=keys[0].strip() + if len(keys[i]) == 0 : + raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, but the key"+str(i)+" is empty") + kkk = keys[i].strip() + rez[kkk]=keys[0].strip() return rez def gen_getter(keyval_dict,key): - """ function returns value from dictionary with substitution - + """ function returns value from dictionary with substitution + e.g. if keyval_dict[A] = 10, keyval_dict[B] = 20 and key_val[C] = [A,B] gen_getter(keyval_dict,A) == 10; gen_getter(keyval_dict,B) == 20; and gen_getter(keyval_dict,C) == [10,20]; """ - if not(key in keyval_dict): + if not key in keyval_dict: name = '_'+key - if not(name in keyval_dict): - raise KeyError('Property with name: {0} is not among the class properties '.format(key)); + if not name in keyval_dict: + raise KeyError('Property with name: {0} is not among the class properties '.format(key)) else: name = key - a_val= keyval_dict[name]; + a_val= keyval_dict[name] if isinstance(a_val,ComplexProperty): return a_val.__get__(keyval_dict) else: @@ -229,8 +230,8 @@ def gen_getter(keyval_dict,key): def gen_setter(keyval_dict,key,val): - """ function sets value to dictionary with substitution - + """ function sets value to dictionary with substitution + e.g. if keyval_dict[A] = 10, keyval_dict[B] = 20 and key_val[C] = [A,B] gen_setter(keyval_dict,A,20) causes keyval_dict[A] == 20 @@ -238,23 +239,22 @@ def gen_setter(keyval_dict,key,val): and gen_getter(keyval_dict,C,[1,2]) causes keyval_dict[A] == 1 and keyval_dict[B] == 2 """ - if not(key in keyval_dict): + if not key in keyval_dict: name = '_'+key - if not(name in keyval_dict): + if not name in keyval_dict: raise KeyError(' Property name: {0} is not defined'.format(key)) else: name = key - test_val = keyval_dict[name]; + test_val = keyval_dict[name] if isinstance(test_val,ComplexProperty): - if not isinstance(val,list): - raise KeyError(' You can not assign non-list value to complex property {0}'.format(key)) - pass - # Assigning values for composite function to the function components - test_val.__set__(keyval_dict,val) - return None + if not isinstance(val,list): + raise KeyError(' You can not assign non-list value to complex property {0}'.format(key)) + # Assigning values for composite function to the function components + test_val.__set__(keyval_dict,val) + return None else: - keyval_dict[key] = val; + keyval_dict[key] = val return None @@ -263,13 +263,13 @@ def check_instrument_name(old_name,new_name): if new_name is None: - if not(old_name is None): + if not old_name is None: return (None,None,str(config.getFacility())) - else: + else: raise KeyError("No instrument name is defined") if old_name == new_name: - return; + return # Instrument name might be a prefix, query Mantid for the full name short_name='' @@ -283,18 +283,18 @@ def check_instrument_name(old_name,new_name): facilities = config.getFacilities() old_facility = str(config.getFacility()) for facility in facilities: - config.setString('default.facility',facility.name()) - try : - instrument = facility.instrument(new_name) - short_name = instrument.shortName() - full_name = instrument.name() - if len(short_name)>0 : - break - except: - pass + config.setString('default.facility',facility.name()) + try : + instrument = facility.instrument(new_name) + short_name = instrument.shortName() + full_name = instrument.name() + if len(short_name)>0 : + break + except: + pass if len(short_name)==0 : - config.setString('default.facility',old_facility) - raise KeyError(" Can not find/set-up the instrument: "+new_name+' in any supported facility') + config.setString('default.facility',old_facility) + raise KeyError(" Can not find/set-up the instrument: "+new_name+' in any supported facility') new_name = short_name facility = str(config.getFacility()) @@ -306,23 +306,23 @@ def parse_single_name(filename): """ Process single run name into """ filepath,fname = os.path.split(filename) if ':' in fname: - fl,fr=fname.split(':') - path1,ind1,ext1=parse_single_name(fl) - path2,ind2,ext2=parse_single_name(fr) - if ind1>ind2: - raise ValueError('Invalid file number defined using colon : left run number {0} has to be large then right {1}'.format(ind1,ind2)) - number = range(ind1[0],ind2[0]+1) - if len(filepath)>0: - filepath=[filepath]*len(number) - else: - filepath=path1*len(number) - if len(ext2[0])>0: - fext = ext2*len(number) - else: - fext = ext1*len(number) - - return (filepath,number,fext) - + fl,fr=fname.split(':') + path1,ind1,ext1=parse_single_name(fl) + path2,ind2,ext2=parse_single_name(fr) + if ind1>ind2: + raise ValueError('Invalid file number defined using colon : left run number {0} has to be large then right {1}'.format(ind1,ind2)) + number = range(ind1[0],ind2[0]+1) + if len(filepath)>0: + filepath=[filepath]*len(number) + else: + filepath=path1*len(number) + if len(ext2[0])>0: + fext = ext2*len(number) + else: + fext = ext1*len(number) + + return (filepath,number,fext) + fname,fext = os.path.splitext(fname) fnumber = filter(lambda x: x.isdigit(), fname) @@ -331,7 +331,7 @@ def parse_single_name(filename): else: number = int(fnumber) return ([filepath],[number],[fext]) - + def parse_run_file_name(run_string): """ Parses run file name to obtain run number, path if possible, and file extension if any present in the string""" @@ -363,5 +363,5 @@ def parse_run_file_name(run_string): # extensions should be either all the same or all defined return (filepath,filenum,fext) - + diff --git a/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py b/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py index f7e35393991e..e18d3e1aa7de 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py +++ b/Code/Mantid/scripts/Inelastic/Direct/ReductionWrapper.py @@ -1,8 +1,9 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * from mantid import config,api from mantid.kernel import funcreturns -from PropertyManager import PropertyManager +from Direct.PropertyManager import PropertyManager # this import is used by children from Direct.DirectEnergyConversion import DirectEnergyConversion #import inspect @@ -11,59 +12,58 @@ class ReductionWrapper(object): - """ Abstract class provides interface to direct inelastic reduction - allowing it to be run from Mantid, web services, or system tests - using the same interface and the same run file placed in different + """ Abstract class provides interface to direct inelastic reduction + allowing it to be run from Mantid, web services, or system tests + using the same interface and the same run file placed in different locations. - """ + """ class var_holder(object): """ A simple wrapper class to keep web variables""" def __init__(self): self.standard_vars = None self.advanced_vars = None - pass def __init__(self,instrumentName,web_var=None): - """ sets properties defaults for the instrument with Name + """ sets properties defaults for the instrument with Name and define if wrapper runs from web services or not """ # internal variable, indicating if we should try to wait for input files to appear - self._wait_for_file=False + self._wait_for_file=False - # The variables which are set up from web interface or to be exported to + # The variables which are set up from web interface or to be exported to # web interface - if web_var: - self._run_from_web = True - self._wvs = web_var - else: - self._run_from_web = False - self._wvs = ReductionWrapper.var_holder() + if web_var: + self._run_from_web = True + self._wvs = web_var + else: + self._run_from_web = False + self._wvs = ReductionWrapper.var_holder() # Initialize reduced for given instrument - self.reducer = DirectEnergyConversion(instrumentName) + self.reducer = DirectEnergyConversion(instrumentName) - self._validation_fname=None + self._validation_fname=None # def get_validation_file_name(self,ReferenceFile=None): - """ function provides name of the file with mantid - workspace reduced earlier and which should be validated + """ function provides name of the file with mantid + workspace reduced earlier and which should be validated against results of current reduction Should be overloaded to return real file name for particular reduction - """ - if ReferenceFile: - self._validation_fname = ReferenceFile - return self._validation_fname + """ + if ReferenceFile: + self._validation_fname = ReferenceFile + return self._validation_fname @property def wait_for_file(self): """ If this variable set to positive value, this value - is interpreted as time to wait until check for specified run file - if this file have not been find immediately. + is interpreted as time to wait until check for specified run file + if this file have not been find immediately. if this variable is 0 or false and the the file have not been found, reduction will fail - """ + """ return self._wait_for_file @wait_for_file.setter @@ -74,72 +74,72 @@ def wait_for_file(self,value): self._wait_for_file = False # def save_web_variables(self,FileName=None): - """ Method to write simple and advanced properties and help + """ Method to write simple and advanced properties and help information into dictionary, to use by web reduction interface - If no file is provided, reduce_var.py file will be written - to + If no file is provided, reduce_var.py file will be written + to """ if not FileName: FileName = 'reduce_vars.py' - + f=open(FileName,'w') f.write("standard_vars = {\n") str_wrapper = ' ' for key,val in self._wvs.standard_vars.iteritems(): - if isinstance(val,str): - row = "{0}\'{1}\':\'{2}\'".format(str_wrapper,key,val) - else: - row = "{0}\'{1}\':{2}".format(str_wrapper,key,val) - f.write(row) - str_wrapper=',\n ' + if isinstance(val,str): + row = "{0}\'{1}\':\'{2}\'".format(str_wrapper,key,val) + else: + row = "{0}\'{1}\':{2}".format(str_wrapper,key,val) + f.write(row) + str_wrapper=',\n ' f.write("\n}\nadvanced_vars={\n") str_wrapper=' ' for key,val in self._wvs.advanced_vars.iteritems(): - if isinstance(val,str): - row = "{0}\'{1}\':\'{2}\'".format(str_wrapper,key,val) - else: - row = "{0}\'{1}\':{2}".format(str_wrapper,key,val) - f.write(row) - str_wrapper=',\n ' + if isinstance(val,str): + row = "{0}\'{1}\':\'{2}\'".format(str_wrapper,key,val) + else: + row = "{0}\'{1}\':{2}".format(str_wrapper,key,val) + f.write(row) + str_wrapper=',\n ' f.write("\n}\n") f.close() # -# +# def validate_result(self,build_validation=False,Error=1.e-3,ToleranceRelErr=True): - """ Overload this using build_or_validate_result to have possibility to run or validate result """ + """ Overload this using build_or_validate_result to have possibility to run or validate result """ return True def build_or_validate_result(self,sample_run,validationFile,build_validation=False,Error=1.e-3,ToleranceRelErr=True): """ Method validates results of the reduction against reference file provided - by get_validation_file_name() method - + by get_validation_file_name() method + At the moment, get_validation_file_name method should return the name of a file, - where workspace sample reduced workspace with default properties - is stored. - CheckWorkspaceMatch method is applied to verify if current reduced workspace is - equivalent to the workspace, stored in the reference file. + where workspace sample reduced workspace with default properties + is stored. + CheckWorkspaceMatch method is applied to verify if current reduced workspace is + equivalent to the workspace, stored in the reference file. """ if not build_validation: - if validationFile: - if isinstance(validationFile,api.Workspace): - sample = validationFile - validationFile = sample.name() - else: - sample = Load(validationFile) - else: - build_validation=True + if validationFile: + if isinstance(validationFile,api.Workspace): + sample = validationFile + validationFile = sample.name() + else: + sample = Load(validationFile) + else: + build_validation=True # just in case, to be sure current_web_state = self._run_from_web current_wait_state= self.wait_for_file - # disable wait for input and + # disable wait for input and self._run_from_web = False self.wait_for_file = False # @@ -153,21 +153,21 @@ def build_or_validate_result(self,sample_run,validationFile,build_validation=Fal if build_validation: if validationFile: - result_name = os.path.splitext(validationFile)[0] + result_name = os.path.splitext(validationFile)[0] else: - result_name = self.reducer.prop_man.save_file_name + result_name = self.reducer.prop_man.save_file_name self.reducer.prop_man.log("*** Saving validation file with name: {0}.nxs".format(result_name),'notice') SaveNexus(reduced,Filename=result_name+'.nxs') return True,'Created validation file {0}.nxs'.format(result_name) else: if isinstance(reduced,list): # check only first result in multirep reduced = reduced[0] - result = CheckWorkspacesMatch(Workspace1=sample,Workspace2=reduced, - Tolerance=Error,CheckSample=False, + result = CheckWorkspacesMatch(Workspace1=sample,Workspace2=reduced,\ + Tolerance=Error,CheckSample=False,\ CheckInstrument=False,ToleranceRelErr=ToleranceRelErr) self.wait_for_file = current_wait_state - self._run_from_web = current_web_state + self._run_from_web = current_web_state if result == 'Success!': return True,'Reference file and reduced workspace are equivalent' else: @@ -176,35 +176,35 @@ def build_or_validate_result(self,sample_run,validationFile,build_validation=Fal @abstractmethod def def_main_properties(self): """ Define properties which considered to be main properties changeable by user - - Should be overwritten by special reduction and decorated with @MainProperties decorator. - Should return dictionary with key are the properties names and values -- the default + Should be overwritten by special reduction and decorated with @MainProperties decorator. + + Should return dictionary with key are the properties names and values -- the default values these properties should have. - """ + """ raise NotImplementedError('def_main_properties has to be implemented') @abstractmethod def def_advanced_properties(self): """ Define properties which considered to be advanced but still changeable by instrument scientist or advanced user - - Should be overwritten by special reduction and decorated with @AdvancedProperties decorator. - Should return dictionary with key are the properties names and values -- the default + Should be overwritten by special reduction and decorated with @AdvancedProperties decorator. + + Should return dictionary with key are the properties names and values -- the default values these properties should have. - """ + """ raise NotImplementedError('def_advanced_properties has to be implemented') def reduce(self,input_file=None,output_directory=None): - """ The method performs all main reduction operations over + """ The method performs all main reduction operations over single run file - - Wrap it into @iliad wrapper to switch input for + + Wrap it into @iliad wrapper to switch input for reduction properties between script and web variables - """ + """ if input_file: - self.reducer.sample_run = input_file + self.reducer.sample_run = input_file timeToWait = self._wait_for_file if timeToWait: @@ -227,7 +227,7 @@ def reduce(self,input_file=None,output_directory=None): def MainProperties(main_prop_definition): """ Decorator stores properties dedicated as main and sets these properties - as input to reduction parameters.""" + as input to reduction parameters.""" def main_prop_wrapper(*args): # execute decorated function prop_dict = main_prop_definition(*args) @@ -243,7 +243,7 @@ def main_prop_wrapper(*args): def AdvancedProperties(adv_prop_definition): """ Decorator stores properties decided to be advanced and sets these properties as input for reduction parameters - """ + """ def advanced_prop_wrapper(*args): prop_dict = adv_prop_definition(*args) #print "in decorator: ",properties @@ -257,7 +257,7 @@ def advanced_prop_wrapper(*args): def iliad(reduce): - """ This decorator wraps around main procedure and switch input from + """ This decorator wraps around main procedure and switch input from web variables to properties or vise versa depending on web variables presence """ @@ -282,39 +282,39 @@ def iliad_wrapper(*args): output_directory=None # add input file folder to data search directory if file has it if input_file and isinstance(input_file,str): - data_path = os.path.dirname(input_file) - if len(data_path)>0: - try: - config.appendDataSearchDir(str(data_path)) - args[1] = os.path.basename(input_file) - except: # if mantid is not available, this should ignore config - pass + data_path = os.path.dirname(input_file) + if len(data_path)>0: + try: + config.appendDataSearchDir(str(data_path)) + args[1] = os.path.basename(input_file) + except: # if mantid is not available, this should ignore config + pass if output_directory: - config['defaultsave.directory'] = output_directory + config['defaultsave.directory'] = output_directory if host._run_from_web: web_vars = dict(host._wvs.standard_vars.items()+host._wvs.advanced_vars.items()) host.reducer.prop_man.set_input_parameters(**web_vars) else: - pass # we should set already set up variables using + pass # we should set already set up variables using + - rez = reduce(*args) - # prohibit returning workspace to web services. + # prohibit returning workspace to web services. if host._run_from_web and not isinstance(rez,str): rez="" - else: - if isinstance(rez,list): + else: + if isinstance(rez,list): # multirep run, just return as it is - return rez - if out_ws_name and rez.name() != out_ws_name : - rez=RenameWorkspace(InputWorkspace=rez,OutputWorkspace=out_ws_name) - + return rez + if out_ws_name and rez.name() != out_ws_name : + rez=RenameWorkspace(InputWorkspace=rez,OutputWorkspace=out_ws_name) + return rez return iliad_wrapper - + if __name__=="__main__": - pass \ No newline at end of file + pass diff --git a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py index 9edf8e9a1d86..edddf86fb180 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py +++ b/Code/Mantid/scripts/Inelastic/Direct/RunDescriptor.py @@ -1,8 +1,9 @@ -""" File contains Descriptors used describe run for direct inelastic reduction """ +#pylint: disable=invalid-name +""" File contains Descriptors used describe run for direct inelastic reduction """ from mantid.simpleapi import * -from PropertiesDescriptors import * +from Direct.PropertiesDescriptors import * import re @@ -18,7 +19,7 @@ class RunDescriptor(PropDescriptor): # class level reference to the property manager _PropMan = None #-------------------------------------------------------------------------------------------------------------------- - def __init__(self,prop_name,DocString=None): + def __init__(self,prop_name,DocString=None): """ """ # Run number self._run_number = None @@ -40,103 +41,103 @@ def __init__(self,prop_name,DocString=None): self.__doc__ = DocString #-------------------------------------------------------------------------------------------------------------------- def __get__(self,instance,owner): - """ return current run number or workspace if it is loaded""" - if not RunDescriptor._PropMan: - RunDescriptor._PropMan = owner - if instance is None: - return self - - if self._ws_name and self._ws_name in mtd: - return mtd[self._ws_name] - else: - return self._run_number + """ return current run number or workspace if it is loaded""" + if not RunDescriptor._PropMan: + RunDescriptor._PropMan = owner + if instance is None: + return self + + if self._ws_name and self._ws_name in mtd: + return mtd[self._ws_name] + else: + return self._run_number #-------------------------------------------------------------------------------------------------------------------- def __set__(self,instance,value): - """ Set up Run number and define workspace name from any source """ + """ Set up Run number and define workspace name from any source """ # - if not RunDescriptor._PropMan: - from PropertyManager import PropertyManager - RunDescriptor._PropMan = PropertyManager + if not RunDescriptor._PropMan: + from PropertyManager import PropertyManager + RunDescriptor._PropMan = PropertyManager - old_ws_name = self._ws_name - clear_fext = True + old_ws_name = self._ws_name + clear_fext = True #end - if value == None: # clear current run number - self._run_number = None - self._ws_name = None - self._ws_cname = '' - self._ws_suffix = '' - # only one RunDescriptor can be summed under current approach. + if value == None: # clear current run number + self._run_number = None + self._ws_name = None + self._ws_cname = '' + self._ws_suffix = '' + # only one RunDescriptor can be summed under current approach. # To disentangle one run descriptor from another -- set up binding - self._bind_to_sum = False - self._clear_old_ws(old_ws_name,self._ws_name,clear_fext) - RunDescriptor._PropMan.sum_runs.clear_sum() - return - if isinstance(value, api.Workspace): + self._bind_to_sum = False + self._clear_old_ws(old_ws_name,self._ws_name,clear_fext) + RunDescriptor._PropMan.sum_runs.clear_sum() + return + if isinstance(value, api.Workspace): #if 'SumOfRuns:' in value.getRun(): # TODO: not implemented #else: - if self._ws_name != value.name(): + if self._ws_name != value.name(): self._set_ws_as_source(value) self._clear_old_ws(old_ws_name,self._ws_name,clear_fext) self._bind_to_sum = False RunDescriptor._PropMan.sum_runs.clear_sum() return - else: # it is just reassigning the same workspace to itself - return - - if isinstance(value,str): # it may be run number as string or it may be a workspace name - if value in mtd: # workspace name - ws = mtd[value] - self.__set__(instance,ws) - return - else: - file_path,run_num,fext = prop_helpers.parse_run_file_name(value) - - if isinstance(run_num,list): - RunDescriptor._PropMan.sum_runs.set_list2add(run_num,file_path,fext) - self._bind_to_sum = True - if instance.sum_runs: - last_run_ind = RunDescriptor._PropMan.sum_runs.get_last_ind2sum() - main_fext = fext[last_run_ind].lower() - self._run_file_path = file_path[last_run_ind].lower() - else: - self.__set__(instance,run_num) - self._run_file_path = file_path - main_fext = fext.lower() - + else: # it is just reassigning the same workspace to itself + return + + if isinstance(value,str): # it may be run number as string or it may be a workspace name + if value in mtd: # workspace name + ws = mtd[value] + self.__set__(instance,ws) + return + else: + file_path,run_num,fext = prop_helpers.parse_run_file_name(value) + + if isinstance(run_num,list): + RunDescriptor._PropMan.sum_runs.set_list2add(run_num,file_path,fext) + self._bind_to_sum = True + if instance.sum_runs: + last_run_ind = RunDescriptor._PropMan.sum_runs.get_last_ind2sum() + main_fext = fext[last_run_ind].lower() + self._run_file_path = file_path[last_run_ind].lower() + else: + self.__set__(instance,run_num) + self._run_file_path = file_path + main_fext = fext.lower() + # - if len(main_fext) > 0: - self._run_ext = main_fext - else: # will be default file extension - self._run_ext = None - clear_fext = False - elif isinstance(value,list): - if len(value) == 1: - self.__set__(instance,value[0]) - return - self._bind_to_sum = True - RunDescriptor._PropMan.sum_runs.set_list2add(value) - if instance.sum_runs: + if len(main_fext) > 0: + self._run_ext = main_fext + else: # will be default file extension + self._run_ext = None + clear_fext = False + elif isinstance(value,list): + if len(value) == 1: + self.__set__(instance,value[0]) + return + self._bind_to_sum = True + RunDescriptor._PropMan.sum_runs.set_list2add(value) + if instance.sum_runs: last_run_ind = RunDescriptor._PropMan.sum_runs.get_last_ind2sum() self._run_number = value[last_run_ind] - else: - self._run_number = value[0] - clear_fext = True - else: - clear_fext = True - self._run_number = int(value) - if self._bind_to_sum and instance and instance.sum_runs: - num2_sum = RunDescriptor._PropMan.sum_runs.set_last_ind2sum(self._run_number) - if num2_sum == 0: - self._bind_to_sum = False - instance.sum_runs = False + else: + self._run_number = value[0] + clear_fext = True + else: + clear_fext = True + self._run_number = int(value) + if self._bind_to_sum and instance and instance.sum_runs: + num2_sum = RunDescriptor._PropMan.sum_runs.set_last_ind2sum(self._run_number) + if num2_sum == 0: + self._bind_to_sum = False + instance.sum_runs = False - self._ws_cname = '' - self._ws_name = None - self._clear_old_ws(old_ws_name,None,clear_fext) + self._ws_cname = '' + self._ws_name = None + self._clear_old_ws(old_ws_name,None,clear_fext) #-------------------------------------------------------------------------------------------------------------------- def run_number(self): """ Return run number regardless of workspace is loaded or not""" @@ -144,7 +145,7 @@ def run_number(self): ws = mtd[self._ws_name] return ws.getRunNumber() else: - return self._run_number + return self._run_number #-------------------------------------------------------------------------------------------------------------------- def is_monws_separate(self): """ """ @@ -169,16 +170,16 @@ def get_run_list(self): else: return [current_run] else: - return [current_run] + return [current_run] #-------------------------------------------------------------------------------------------------------------------- def set_action_suffix(self,suffix=None): - """ method to set part of the workspace name, which indicate some action performed over this workspace - - e.g.: default suffix of a loaded workspace is 'RAW' but we can set it to SPE to show that conversion to + """ method to set part of the workspace name, which indicate some action performed over this workspace + + e.g.: default suffix of a loaded workspace is 'RAW' but we can set it to SPE to show that conversion to energy will be performed for this workspace. - method returns the name of the workspace is will have with this suffix. Algorithms would later - work on the initial workspace and modify it in-place or to produce workspace with new name (depending if one + method returns the name of the workspace is will have with this suffix. Algorithms would later + work on the initial workspace and modify it in-place or to produce workspace with new name (depending if one wants to keep initial workspace) synchronize_ws(ws_pointer) then should synchronize workspace and its name. @@ -193,32 +194,32 @@ def set_action_suffix(self,suffix=None): return self._build_ws_name() #-------------------------------------------------------------------------------------------------------------------- def synchronize_ws(self,workspace=None): - """ Synchronize workspace name (after workspace may have changed due to algorithm) - with internal run holder name. Accounts for the situation when + """ Synchronize workspace name (after workspace may have changed due to algorithm) + with internal run holder name. Accounts for the situation when TODO: This method should be automatically invoked by an algorithm decorator - Until implemented, one have to ensure that it is correctly used together with + Until implemented, one have to ensure that it is correctly used together with set_action_suffix to ensue one can always get expected workspace from its name - outside of a method visibility - """ + outside of a method visibility + """ if not workspace: workspace = mtd[self._ws_name] new_name = self._build_ws_name() old_name = workspace.name() if new_name != old_name: - RenameWorkspace(InputWorkspace=old_name,OutputWorkspace=new_name) + RenameWorkspace(InputWorkspace=old_name,OutputWorkspace=new_name) - old_mon_name = old_name + '_monitors' - new_mon_name = new_name + '_monitors' - if old_mon_name in mtd: - RenameWorkspace(InputWorkspace=old_mon_name,OutputWorkspace=new_mon_name) + old_mon_name = old_name + '_monitors' + new_mon_name = new_name + '_monitors' + if old_mon_name in mtd: + RenameWorkspace(InputWorkspace=old_mon_name,OutputWorkspace=new_mon_name) self._ws_name = new_name #-------------------------------------------------------------------------------------------------------------------- def get_file_ext(self): - """ Method returns current file extension for file to load workspace from + """ Method returns current file extension for file to load workspace from e.g. .raw or .nxs extension - """ + """ if self._run_ext: return self._run_ext else: # return IDF default @@ -237,23 +238,23 @@ def set_file_ext(self,val): #-------------------------------------------------------------------------------------------------------------------- @staticmethod def _check_claibration_source(): - """ if user have not specified calibration as input to the script, + """ if user have not specified calibration as input to the script, try to retrieve calibration stored in file with run properties""" - changed_prop = RunDescriptor._holder.getChangedProperties() - if 'det_cal_file' in changed_prop: - use_workspace_calibration = False - else: - use_workspace_calibration = True - return use_workspace_calibration + changed_prop = RunDescriptor._holder.getChangedProperties() + if 'det_cal_file' in changed_prop: + use_workspace_calibration = False + else: + use_workspace_calibration = True + return use_workspace_calibration #-------------------------------------------------------------------------------------------------------------------- def get_workspace(self): """ Method returns workspace correspondent to current run number(s) and loads this workspace if it has not been loaded Returns Mantid pointer to the workspace, corresponding to this run number - """ + """ if not self._ws_name: - self._ws_name = self._build_ws_name() + self._ws_name = self._build_ws_name() if self._ws_name in mtd: @@ -261,26 +262,26 @@ def get_workspace(self): if ws.run().hasProperty("calibrated"): return ws # already calibrated else: - prefer_ws_calibration = self._check_claibration_source() - self.apply_calibration(ws,RunDescriptor._holder.det_cal_file,prefer_ws_calibration) - return ws + prefer_ws_calibration = self._check_claibration_source() + self.apply_calibration(ws,RunDescriptor._holder.det_cal_file,prefer_ws_calibration) + return ws else: - if self._run_number: - prefer_ws_calibration = self._check_claibration_source() - inst_name = RunDescriptor._holder.short_inst_name - calibration = RunDescriptor._holder.det_cal_file - if self._bind_to_sum and RunDescriptor._holder.sum_runs : # Sum runs - ws = RunDescriptor._PropMan.sum_runs.load_and_sum_runs(inst_name,RunDescriptor._holder.load_monitors_with_workspace) - else: # load current workspace - ws = self.load_run(inst_name, calibration,False, RunDescriptor._holder.load_monitors_with_workspace,prefer_ws_calibration) - - - self.synchronize_ws(ws) - self.apply_calibration(ws,calibration,prefer_ws_calibration) - - return ws - else: - return None + if self._run_number: + prefer_ws_calibration = self._check_claibration_source() + inst_name = RunDescriptor._holder.short_inst_name + calibration = RunDescriptor._holder.det_cal_file + if self._bind_to_sum and RunDescriptor._holder.sum_runs : # Sum runs + ws = RunDescriptor._PropMan.sum_runs.load_and_sum_runs(inst_name,RunDescriptor._holder.load_monitors_with_workspace) + else: # load current workspace + ws = self.load_run(inst_name, calibration,False, RunDescriptor._holder.load_monitors_with_workspace,prefer_ws_calibration) + + + self.synchronize_ws(ws) + self.apply_calibration(ws,calibration,prefer_ws_calibration) + + return ws + else: + return None #-------------------------------------------------------------------------------------------------------------------- def get_ws_clone(self,clone_name='ws_clone'): """ Get unbounded clone of eisting Run workspace """ @@ -303,33 +304,33 @@ def _set_ws_as_source(self,value): #-------------------------------------------------------------------------------------------------------------------- def chop_ws_part(self,origin,tof_range,rebin,chunk_num,n_chunks): - """ chop part of the original workspace and sets it up as new original. - Return the old one """ - if not(origin): - origin = self.get_workspace() + """ chop part of the original workspace and sets it up as new original. + Return the old one """ + if not origin: + origin = self.get_workspace() origin_name = origin.name() try: - mon_ws = mtd[origin_name+'_monitors'] + mon_ws = mtd[origin_name+'_monitors'] except: - mon_ws = None + mon_ws = None target_name = '#{0}/{1}#'.format(chunk_num,n_chunks)+origin_name if chunk_num == n_chunks: - RenameWorkspace(InputWorkspace=origin_name,OutputWorkspace=target_name) - if mon_ws: - RenameWorkspace(InputWorkspace=mon_ws,OutputWorkspace=target_name+'_monitors') - origin_name = target_name - origin_invalidated=True + RenameWorkspace(InputWorkspace=origin_name,OutputWorkspace=target_name) + if mon_ws: + RenameWorkspace(InputWorkspace=mon_ws,OutputWorkspace=target_name+'_monitors') + origin_name = target_name + origin_invalidated=True else: - if mon_ws: - CloneWorkspace(InputWorkspace=mon_ws,OutputWorkspace=target_name+'_monitors') - origin_invalidated=False + if mon_ws: + CloneWorkspace(InputWorkspace=mon_ws,OutputWorkspace=target_name+'_monitors') + origin_invalidated=False if rebin: # debug and compatibility mode with old reduction - Rebin(origin_name,OutputWorkspace=target_name,Params=[tof_range[0],tof_range[1],tof_range[2]],PreserveEvents=False) + Rebin(origin_name,OutputWorkspace=target_name,Params=[tof_range[0],tof_range[1],tof_range[2]],PreserveEvents=False) else: - CropWorkspace(origin_name,OutputWorkspace=target_name,XMin=tof_range[0],XMax=tof_range[2]) + CropWorkspace(origin_name,OutputWorkspace=target_name,XMin=tof_range[0],XMax=tof_range[2]) self._set_ws_as_source(mtd[target_name]) if origin_invalidated: @@ -339,7 +340,7 @@ def chop_ws_part(self,origin,tof_range,rebin,chunk_num,n_chunks): #-------------------------------------------------------------------------------------------------------------------- def get_monitors_ws(self,monitor_ID=None): - """ get pointer to a workspace containing monitors. + """ get pointer to a workspace containing monitors. Explores different ways of finding monitor workspace in Mantid and returns the python pointer to the workspace which contains monitors. @@ -360,39 +361,39 @@ def get_monitors_ws(self,monitor_ID=None): mon_ws = self.copy_spectrum2monitors(data_ws,mon_ws,specID) if monitor_ID: - try: - ws_index = mon_ws.getIndexFromSpectrumNumber(monitor_ID) - except: # - mon_ws = None - else: + try: + ws_index = mon_ws.getIndexFromSpectrumNumber(monitor_ID) + except: # + mon_ws = None + else: mon_list = self._holder.get_used_monitors_list() for monID in mon_list: try: ws_ind = mon_ws.getIndexFromSpectrumNumber(int(monID)) except: - mon_ws = None - break + mon_ws = None + break return mon_ws #-------------------------------------------------------------------------------------------------------------------- def get_ws_name(self): """ return workspace name. If ws name is not defined, build it first and set up as the target ws name - """ + """ if self._ws_name: if self._ws_name in mtd: return self._ws_name else: - raise RuntimeError('Getting workspace name {0} for undefined workspace. Run get_workspace first'.format(self._ws_name)) + raise RuntimeError('Getting workspace name {0} for undefined workspace. Run get_workspace first'.format(self._ws_name)) self._ws_name = self._build_ws_name() return self._ws_name #-------------------------------------------------------------------------------------------------------------------- def file_hint(self,run_num_str=None,filePath=None,fileExt=None,**kwargs): """ procedure to provide run file guess name from run properties - + main purpose -- to support customized order of file extensions - """ + """ if not run_num_str: - run_num_str = str(self.run_number()) + run_num_str = str(self.run_number()) inst_name = RunDescriptor._holder.short_inst_name @@ -403,9 +404,9 @@ def file_hint(self,run_num_str=None,filePath=None,fileExt=None,**kwargs): old_ext = self.get_file_ext() else: if fileExt: - old_ext = fileExt + old_ext = fileExt else: - old_ext = self.get_file_ext() + old_ext = self.get_file_ext() hint = inst_name + run_num_str + old_ext if not filePath: @@ -443,32 +444,32 @@ def find_file(self,inst_name=None,run_num=None,filePath=None,fileExt=None,**kwar self._run_file_path = os.path.dirname(fname) return file except RuntimeError: - message = 'Cannot find file matching hint {0} on current search paths ' \ + message = 'Cannot find file matching hint {0} on current search paths ' \ 'for instrument {1}'.format(file_hint,inst_name) - if not ('be_quet' in kwargs): + if not 'be_quet' in kwargs: RunDescriptor._logger(message,'warning') - return 'ERROR:find_file: ' + message + return 'ERROR:find_file: ' + message #-------------------------------------------------------------------------------------------------------------------- def load_file(self,inst_name,ws_name,run_number=None,load_mon_with_workspace=False,filePath=None,fileExt=None,**kwargs): - """ load run for the instrument name provided. If run_numner is None, look for the current run""" - + """ load run for the instrument name provided. If run_numner is None, look for the current run""" + data_file = self.find_file(None,filePath,fileExt,**kwargs) if data_file.find('ERROR') > -1: - self._ws_name = None - raise IOError(data_file) - + self._ws_name = None + raise IOError(data_file) + if load_mon_with_workspace: - mon_load_option = 'Include' + mon_load_option = 'Include' else: - mon_load_option = 'Separate' + mon_load_option = 'Separate' # try: # Hack: LoadEventNexus does not understand Separate at the moment and throws. # And event loader always loads monitors separately - Load(Filename=data_file, OutputWorkspace=ws_name,LoadMonitors = mon_load_option) + Load(Filename=data_file, OutputWorkspace=ws_name,LoadMonitors = mon_load_option) except ValueError: #mon_load_option =str(int(load_mon_with_workspace)) - Load(Filename=data_file, OutputWorkspace=ws_name,LoadMonitors = '1',MonitorsAsEvents='0') + Load(Filename=data_file, OutputWorkspace=ws_name,LoadMonitors = '1',MonitorsAsEvents='0') RunDescriptor._logger("Loaded {0}".format(data_file),'information') @@ -495,7 +496,7 @@ def load_run(self,inst_name, calibration=None, force=False, mon_load_option=Fals self._ws_name = None ws_name = self.get_ws_name() #----------------------------------- - if ws_name in mtd and not(force): + if ws_name in mtd and not force: RunDescriptor._logger("{0} already loaded as workspace.".format(ws_name),'information') else: # If it doesn't exists as a workspace assume we have to try and @@ -506,17 +507,17 @@ def load_run(self,inst_name, calibration=None, force=False, mon_load_option=Fals return loaded_ws #-------------------------------------------------------------------------------------------------------------------- def apply_calibration(self,loaded_ws,calibration=None,use_ws_calibration=True): - """ If calibration is present, apply it to the workspace - - use_ws_calibration -- if true, retrieve workspace property, which defines + """ If calibration is present, apply it to the workspace + + use_ws_calibration -- if true, retrieve workspace property, which defines calibration option (e.g. det_cal_file used a while ago) and try to use it """ if not (calibration or use_ws_calibration): - return + return if not isinstance(loaded_ws, api.Workspace): - raise RuntimeError(' Calibration can be applied to a workspace only and got object of type {0}'.format(type(loaded_ws))) - + raise RuntimeError(' Calibration can be applied to a workspace only and got object of type {0}'.format(type(loaded_ws))) + if loaded_ws.run().hasProperty("calibrated"): return # already calibrated @@ -532,7 +533,7 @@ def apply_calibration(self,loaded_ws,calibration=None,use_ws_calibration=True): test_name = ws_calibration ws_calibration = FileFinder.getFullPath(ws_calibration) if len(ws_calibration) == 0: - raise RuntimeError('Can not find defined in run {0} calibration file {1}\n'\ + raise RuntimeError('Can not find defined in run {0} calibration file {1}\n'\ 'Define det_cal_file reduction parameter properly'.format(loaded_ws.name(),test_name)) RunDescriptor._logger('*** load_data: Calibrating data using workspace defined calibration file: {0}'.format(ws_calibration),'notice') except KeyError: # no det_cal_file defined in workspace @@ -553,42 +554,42 @@ def apply_calibration(self,loaded_ws,calibration=None,use_ws_calibration=True): #-------------------------------------------------------------------------------------------------------------------- @staticmethod def copy_spectrum2monitors(data_ws,mon_ws,spectraID): - """ + """ this routine copies a spectrum form workspace to monitor workspace and rebins it according to monitor workspace binning @param data_ws -- the event workspace which detector is considered as monitor or Mantid pointer to this workspace - @param mon_ws -- the histogram workspace with monitors where one needs to place the detector's spectra + @param mon_ws -- the histogram workspace with monitors where one needs to place the detector's spectra @param spectraID-- the ID of the spectra to copy. """ - + # ---------------------------- - try: - ws_index = mon_ws.getIndexFromSpectrumNumber(spectraID) + try: + ws_index = mon_ws.getIndexFromSpectrumNumber(spectraID) # Spectra is already in the monitor workspace - return mon_ws - except: - ws_index = data_ws.getIndexFromSpectrumNumber(spectraID) + return mon_ws + except: + ws_index = data_ws.getIndexFromSpectrumNumber(spectraID) # - x_param = mon_ws.readX(0) - bins = [x_param[0],x_param[1] - x_param[0],x_param[-1]] - ExtractSingleSpectrum(InputWorkspace=data_ws,OutputWorkspace='tmp_mon',WorkspaceIndex=ws_index) - Rebin(InputWorkspace='tmp_mon',OutputWorkspace='tmp_mon',Params=bins,PreserveEvents='0') + x_param = mon_ws.readX(0) + bins = [x_param[0],x_param[1] - x_param[0],x_param[-1]] + ExtractSingleSpectrum(InputWorkspace=data_ws,OutputWorkspace='tmp_mon',WorkspaceIndex=ws_index) + Rebin(InputWorkspace='tmp_mon',OutputWorkspace='tmp_mon',Params=bins,PreserveEvents='0') # should be vice versa but Conjoin invalidate ws pointers and hopefully # nothing could happen with workspace during conjoining #AddSampleLog(Workspace=monWS,LogName=done_log_name,LogText=str(ws_index),LogType='Number') - mon_ws_name = mon_ws.getName() - ConjoinWorkspaces(InputWorkspace1=mon_ws,InputWorkspace2='tmp_mon') - mon_ws = mtd[mon_ws_name] + mon_ws_name = mon_ws.getName() + ConjoinWorkspaces(InputWorkspace1=mon_ws,InputWorkspace2='tmp_mon') + mon_ws = mtd[mon_ws_name] - if 'tmp_mon' in mtd: - DeleteWorkspace(WorkspaceName='tmp_mon') - return mon_ws + if 'tmp_mon' in mtd: + DeleteWorkspace(WorkspaceName='tmp_mon') + return mon_ws #-------------------------------------------------------------------------------------------------------------------- def clear_monitors(self): - """ method removes monitor workspace form analysis data service if it is there - + """ method removes monitor workspace form analysis data service if it is there + (assuming it is not needed any more) """ monWS_name = self._ws_name + '_monitors' @@ -607,7 +608,7 @@ def _build_ws_name(self): else: ws_name = '{0}{1}{2}{3}'.format(self._prop_name,self._ws_cname,sum_ext,self._ws_suffix) - return ws_name + return ws_name #-------------------------------------------------------------------------------------------------------------------- @staticmethod def rremove(thestr, trailing): @@ -616,7 +617,7 @@ def rremove(thestr, trailing): return thestr[:-thelen] return thestr def _split_ws_name(self,ws_name): - """ Method to split existing workspace name + """ Method to split existing workspace name into parts, in such a way that _build_name would restore the same name """ # Remove suffix @@ -628,10 +629,10 @@ def _split_ws_name(self,ws_name): name = name.replace(self._prop_name,'',1) try: - part_ind = re.search('#(.+?)#', name).group(0) - name =name.replace(part_ind,'',1) + part_ind = re.search('#(.+?)#', name).group(0) + name =name.replace(part_ind,'',1) except AttributeError: - part_ind='' + part_ind='' if self._run_number: instr_name = self._instr_name() @@ -642,24 +643,24 @@ def _split_ws_name(self,ws_name): self._ws_cname = part_ind+name # def _instr_name(self): - if RunDescriptor._holder: + if RunDescriptor._holder: instr_name = RunDescriptor._holder.short_inst_name - else: + else: instr_name = '_test_instrument' - return instr_name + return instr_name def _clear_old_ws(self,old_ws_name,new_name,clear_fext=False): """ helper method used in __set__. When new data (run or wod) """ if old_ws_name: - if new_name != old_ws_name: + if new_name != old_ws_name: if old_ws_name in mtd: - DeleteWorkspace(old_ws_name) + DeleteWorkspace(old_ws_name) old_mon_ws = old_ws_name + '_monitors' if old_mon_ws in mtd: DeleteWorkspace(old_mon_ws) if clear_fext: - self._run_ext = None - self._run_file_path = '' + self._run_ext = None + self._run_file_path = '' #------------------------------------------------------------------------------------------------------------------------------- @@ -668,7 +669,7 @@ def _clear_old_ws(self,old_ws_name,new_name,clear_fext=False): class RunDescriptorDependent(RunDescriptor): """ Simple RunDescriptor class dependent on another RunDescriptor, providing the host descriptor if current descriptor value is not defined - or usual descriptor functionality if somebody sets current descriptor up + or usual descriptor functionality if somebody sets current descriptor up """ def __init__(self,host_run,ws_preffix,DocString=None): @@ -677,14 +678,14 @@ def __init__(self,host_run,ws_preffix,DocString=None): self._this_run_defined = False def __get__(self,instance,owner=None): - """ return dependent run number which is host run number if this one has not been set or this run number if it was""" - if self._this_run_defined: - if instance is None: - return self - else: + """ return dependent run number which is host run number if this one has not been set or this run number if it was""" + if self._this_run_defined: + if instance is None: + return self + else: return super(RunDescriptorDependent,self).__get__(instance,owner) - else: - return self._host.__get__(instance,owner) + else: + return self._host.__get__(instance,owner) def __set__(self,instance,value): if value is None: @@ -694,10 +695,10 @@ def __set__(self,instance,value): super(RunDescriptorDependent,self).__set__(instance,value) #def __del__(self): - # # destructor removes bounded workspace + # # destructor removes bounded workspace # # Probably better not to at current approach # if self._ws_name in mtd: # DeleteWorkspace(self._ws_name) # object.__del__(self) - \ No newline at end of file + diff --git a/Code/Mantid/scripts/Inelastic/Direct/__init__.py b/Code/Mantid/scripts/Inelastic/Direct/__init__.py index e798813ca1ff..26487e011f10 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/__init__.py +++ b/Code/Mantid/scripts/Inelastic/Direct/__init__.py @@ -4,8 +4,8 @@ DirectEnergyConversion -- main reduction class PropertyManager -- helper class providing access and functionality for IDF properties ReductionWrapper -- parent class for reduction, After overloading for particular insrument provides common interface for Mantid and web services -RunDescriptor -- Class descripbing a run and instantiated as property of Property manager to specify a +RunDescriptor -- Class descripbing a run and instantiated as property of Property manager to specify a particular kind of run (e.g. sample run, monovan run etc...) """ -__all__=['dgreduce','DirectEnergyConversion','PropertyManager','ReductionWrapper','RunDescriptor'] \ No newline at end of file +__all__=['dgreduce','DirectEnergyConversion','PropertyManager','ReductionWrapper','RunDescriptor'] diff --git a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py index 80b41f20c374..9b4c61b5bcc3 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py +++ b/Code/Mantid/scripts/Inelastic/Direct/dgreduce.py @@ -1,9 +1,7 @@ +#pylint: disable=invalid-name """ Empty class temporary left for compatibility with previous interfaces """ -import DirectEnergyConversion as DRC -import CommonFunctions as common -import time as time +import Direct.DirectEnergyConversion as DRC from mantid.simpleapi import * -from mantid import api from mantid.kernel import funcreturns @@ -32,11 +30,11 @@ def setup(instname=None,reload=False): instname = config['default.instrument'] - if not (Reducer is None) : + if not Reducer is None : old_name=Reducer.prop_man.instr_name if old_name.upper()[0:3] == instname.upper()[0:3] : if not reload : - return # has been already defined + return # has been already defined Reducer = DRC.setup_reducer(instname,reload) @@ -137,10 +135,10 @@ def arb_units(wb_run,sample_run,ei_guess,rebin,map_file='default',monovan_run=No if sample_run: Reducer.sample_run = sample_run try: - n,r=funcreturns.lhs_info('both') - wksp_out=r[0] + n,r=funcreturns.lhs_info('both') + wksp_out=r[0] except: - wksp_out = Reducer.prop_man.get_sample_ws_name() + wksp_out = Reducer.prop_man.get_sample_ws_name() # res = Reducer.convert_to_energy(wb_run,sample_run,ei_guess,rebin,map_file,monovan_run,second_wb,**kwargs) # diff --git a/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py b/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py index 10898f95070d..76ba5a12bb48 100644 --- a/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py +++ b/Code/Mantid/scripts/Inelastic/Direct/diagnostics.py @@ -90,9 +90,9 @@ def diagnose(white_int,**kwargs): # Second white beam test if 'second_white' in kwargs: - __second_white_masks, num_failed = do_second_white_test(white_int, parser.second_white, parser.tiny, parser.huge, - parser.van_out_lo, parser.van_out_hi, - parser.van_lo, parser.van_hi, parser.variation, + __second_white_masks, num_failed = do_second_white_test(white_int, parser.second_white, parser.tiny, parser.huge,\ + parser.van_out_lo, parser.van_out_hi,\ + parser.van_lo, parser.van_hi, parser.variation,\ parser.van_sig, start_index, end_index) test_results[2] = [str(__second_white_masks), num_failed] add_masking(white_int, __second_white_masks, start_index, end_index) @@ -103,8 +103,8 @@ def diagnose(white_int,**kwargs): zero_count_failures = 0 if kwargs.get('sample_counts',None) is not None and kwargs.get('samp_zero',False): add_masking(parser.sample_counts, white_int) - maskZero, zero_count_failures = FindDetectorsOutsideLimits(InputWorkspace=parser.sample_counts, - StartWorkspaceIndex=start_index, EndWorkspaceIndex=end_index, + maskZero, zero_count_failures = FindDetectorsOutsideLimits(InputWorkspace=parser.sample_counts,\ + StartWorkspaceIndex=start_index, EndWorkspaceIndex=end_index,\ LowThreshold=1e-10, HighThreshold=1e100) add_masking(white_int, maskZero, start_index, end_index) DeleteWorkspace(maskZero) @@ -114,7 +114,7 @@ def diagnose(white_int,**kwargs): # if hasattr(parser, 'background_int'): add_masking(parser.background_int, white_int) - __bkgd_mask, failures = do_background_test(parser.background_int, parser.samp_lo, + __bkgd_mask, failures = do_background_test(parser.background_int, parser.samp_lo,\ parser.samp_hi, parser.samp_sig, parser.samp_zero, start_index, end_index) test_results[3] = [str(__bkgd_mask), zero_count_failures + failures] add_masking(white_int, __bkgd_mask, start_index, end_index) @@ -135,18 +135,18 @@ def diagnose(white_int,**kwargs): end_index_name=" to: end" default = True if hasattr(parser, 'print_diag_results') and parser.print_diag_results: - default=True + default=True if 'start_index' in kwargs: - default = False - start_index_name = "from: "+str(kwargs['start_index']) + default = False + start_index_name = "from: "+str(kwargs['start_index']) if 'end_index' in kwargs : - default = False - end_index_name = " to: "+str(kwargs['end_index']) + default = False + end_index_name = " to: "+str(kwargs['end_index']) testName=start_index_name+end_index_name if not default : - testName = " For bank: "+start_index_name+end_index_name + testName = " For bank: "+start_index_name+end_index_name if hasattr(parser, 'print_diag_results') and parser.print_diag_results: print_test_summary(test_results,testName) @@ -185,8 +185,8 @@ def do_white_test(white_int, tiny, large, out_lo, out_hi, median_lo, median_hi, # Make sure we are a MatrixWorkspace white_int = ConvertToMatrixWorkspace(InputWorkspace=white_int,OutputWorkspace=white_int) # The output workspace will have the failed detectors masked - white_masks,num_failed = FindDetectorsOutsideLimits(white_int, StartWorkspaceIndex=start_index, - EndWorkspaceIndex=end_index, + white_masks,num_failed = FindDetectorsOutsideLimits(white_int, StartWorkspaceIndex=start_index,\ + EndWorkspaceIndex=end_index,\ HighThreshold=large, LowThreshold=tiny) MaskDetectors(Workspace=white_int, MaskedWorkspace=white_masks, @@ -271,15 +271,15 @@ def normalise_background(background_int, white_int, second_white_int=None): """ if second_white_int is None: # quetly divide background integral by white beam integral not reporting about possible 0 in wb integral (they will be removed by diag anyway) - background_int = Divide(LHSWorkspace=background_int,RHSWorkspace=white_int,WarnOnZeroDivide='0'); + background_int = Divide(LHSWorkspace=background_int,RHSWorkspace=white_int,WarnOnZeroDivide='0') else: hmean = 2.0*white_int*second_white_int/(white_int+second_white_int) #background_int /= hmean - background_int = Divide(LHSWorkspace=background_int,RHSWorkspace=hmean,WarnOnZeroDivide='0'); + background_int = Divide(LHSWorkspace=background_int,RHSWorkspace=hmean,WarnOnZeroDivide='0') DeleteWorkspace(hmean) #------------------------------------------------------------------------------ -def do_background_test(background_int, median_lo, median_hi, sigma, mask_zero, +def do_background_test(background_int, median_lo, median_hi, sigma, mask_zero,\ start_index=None, end_index=None): """ Run the background tests @@ -324,11 +324,11 @@ def do_bleed_test(sample_run, max_framerate, ignored_pixels): # Load the sample run if __Reducer__: # Try to use generic loader which would work with files or workspaces alike sample_run = __Reducer__.get_run_descriptor(sample_run) - data_ws = sample_run.get_workspace() # this will load data if necessary + data_ws = sample_run.get_workspace() # this will load data if necessary ws_name = sample_run.get_ws_name()+'_bleed' - else: + else: # may be sample run is already a run descriptor despite __Reducer__ have not been exposed - data_ws = sample_run.get_workspace() # this will load data if necessary + data_ws = sample_run.get_workspace() # this will load data if necessary ws_name = sample_run.get_ws_name()+'_bleed' if max_framerate is None: diff --git a/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py b/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py index 532cf685079a..bd2855548e4a 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py +++ b/Code/Mantid/scripts/Inelastic/IndirectAbsCor.py @@ -1,13 +1,14 @@ +#pylint: disable=invalid-name # IDA F2PY Absorption Corrections Wrapper ## Handle selection of .pyd files for absorption corrections -import platform, sys +import sys from IndirectImport import * from IndirectCommon import * from mantid.simpleapi import * from mantid import config, logger, mtd import math, os.path, numpy as np -mp = import_mantidplot() +MTD_PLOT = import_mantidplot() def WaveRange(inWS, efixed): # create a list of 10 equi-spaced wavelengths spanning the input data @@ -163,7 +164,7 @@ def AbsRun(inputWS, geom, beam, ncan, size, density, sigs, siga, avar, Save): raise ValueError('Number of steps ( ' + str(nstep) + ' ) should be >= 20') angle = det[n] - kill, A1, A2, A3, A4 = cylabs.cylabs(astep, beam, ncan, size, + kill, A1, A2, A3, A4 = cylabs.cylabs(astep, beam, ncan, size,\ density, sigs, siga, angle, wavelas, waves, n, wrk, 0) if kill == 0: @@ -231,33 +232,33 @@ def plotAbs(workspaces, plotOpt): return if plotOpt == 'Wavelength' or plotOpt == 'Both': - graph = mp.plotSpectrum(workspaces, 0) + graph = MTD_PLOT.plotSpectrum(workspaces, 0) if plotOpt == 'Angle' or plotOpt == 'Both': - graph = mp.plotTimeBin(workspaces, 0) - graph.activeLayer().setAxisTitle(mp.Layer.Bottom, 'Angle') + graph = MTD_PLOT.plotTimeBin(workspaces, 0) + graph.activeLayer().setAxisTitle(MTD_PLOT.Layer.Bottom, 'Angle') def AbsRunFeeder(input_ws, can_ws, geom, ncan, size, avar, density, beam_width=None, sample_formula=None, can_formula=None, sigs=None, siga=None, plot_opt='None', save=False): """ - Handles the feeding of input and plotting of output for the F2PY - absorption correction routine. - - @param input_ws - workspace to generate corrections for - @param geom - type of geometry used (flat plate or cylinder) - @param beam_width - width of the beam used. If None this will be taken from the IPF - @param ncan - number of cans used. - @param size - sample & can thickness - @param sample_formula - optional, chemical formula for the sample - @param cam_formula - optional, chemical formula for the can - @param density - density of the sample and cans(s) - @param sigs - scattering for sample and can(s) - @param siga - absorption for sample and can(s) - @param avar - sample angle - @param plot_opt - whether to plot output - @param save - whether to save the output to file - @return The result workspace group + Handles the feeding of input and plotting of output for the F2PY + absorption correction routine. + + @param input_ws - workspace to generate corrections for + @param geom - type of geometry used (flat plate or cylinder) + @param beam_width - width of the beam used. If None this will be taken from the IPF + @param ncan - number of cans used. + @param size - sample & can thickness + @param sample_formula - optional, chemical formula for the sample + @param cam_formula - optional, chemical formula for the can + @param density - density of the sample and cans(s) + @param sigs - scattering for sample and can(s) + @param siga - absorption for sample and can(s) + @param avar - sample angle + @param plot_opt - whether to plot output + @param save - whether to save the output to file + @return The result workspace group """ StartTime('CalculateCorrections') @@ -288,7 +289,8 @@ def AbsRunFeeder(input_ws, can_ws, geom, ncan, size, avar, density, beam_width=N #set sample material based on input or formula if sample_formula is not None: - SetSampleMaterial(InputWorkspace=input_ws, ChemicalFormula=sample_formula, SampleNumberDensity=density[0]) + SetSampleMaterial(InputWorkspace=input_ws, ChemicalFormula=sample_formula, + SampleNumberDensity=density[0]) sample = mtd[input_ws].sample() sam_mat = sample.getMaterial() @@ -300,7 +302,8 @@ def AbsRunFeeder(input_ws, can_ws, geom, ncan, size, avar, density, beam_width=N if can_formula is not None and ncan == 2: #set can material based on input or formula - SetSampleMaterial(InputWorkspace=can_ws, ChemicalFormula=can_formula, SampleNumberDensity=density[1]) + SetSampleMaterial(InputWorkspace=can_ws, ChemicalFormula=can_formula, + SampleNumberDensity=density[1]) can_sample = mtd[can_ws].sample() can_mat = can_sample.getMaterial() @@ -323,19 +326,19 @@ def AbsRunFeeder(input_ws, can_ws, geom, ncan, size, avar, density, beam_width=N def FlatAbs(ncan, thick, density, sigs, siga, angles, waves): """ - FlatAbs - calculate flat plate absorption factors - - For more information See: - - MODES User Guide: http://www.isis.stfc.ac.uk/instruments/iris/data-analysis/modes-v3-user-guide-6962.pdf - - C J Carlile, Rutherford Laboratory report, RL-74-103 (1974) - - @param sigs - list of scattering cross-sections - @param siga - list of absorption cross-sections - @param density - list of density - @param ncan - =0 no can, >1 with can - @param thick - list of thicknesses: sample thickness, can thickness1, can thickness2 - @param angles - list of angles - @param waves - list of wavelengths + FlatAbs - calculate flat plate absorption factors + + For more information See: + - MODES User Guide: http://www.isis.stfc.ac.uk/instruments/iris/data-analysis/modes-v3-user-guide-6962.pdf + - C J Carlile, Rutherford Laboratory report, RL-74-103 (1974) + + @param sigs - list of scattering cross-sections + @param siga - list of absorption cross-sections + @param density - list of density + @param ncan - =0 no can, >1 with can + @param thick - list of thicknesses: sample thickness, can thickness1, can thickness2 + @param angles - list of angles + @param waves - list of wavelengths """ PICONV = math.pi/180. @@ -355,7 +358,7 @@ def FlatAbs(ncan, thick, density, sigs, siga, angles, waves): acc = np.ones(nlam) # case where tsec is close to 90 degrees. CALCULATION IS UNRELIABLE - if (abs(abs(tsec)-90.0) < 1.0): + if abs(abs(tsec)-90.0) < 1.0: #default to 1 for everything return ass, assc, acsc, acc else: @@ -385,7 +388,8 @@ def FlatAbs(ncan, thick, density, sigs, siga, angles, waves): sampleSec1, sampleSec2 = calcThicknessAtSec(sampleXSection, samThickness, [sec1, sec2]) - if (sec2 < 0.): + + if sec2 < 0.0: ass = fs / samThickness else: ass= np.exp(-sampleSec2) * fs / samThickness @@ -394,7 +398,8 @@ def FlatAbs(ncan, thick, density, sigs, siga, angles, waves): if useCan: #calculate can cross section canXSection = (canScatt + canAbs * waves / 1.8) * canDensity - assc, acsc, acc = calcFlatAbsCan(ass, canXSection, canThickness1, canThickness2, sampleSec1, sampleSec2, [sec1, sec2]) + assc, acsc, acc = calcFlatAbsCan(ass, canXSection, canThickness1, canThickness2, + sampleSec1, sampleSec2, [sec1, sec2]) return ass, assc, acsc, acc @@ -429,9 +434,9 @@ def calcFlatAbsCan(ass, canXSection, canThickness1, canThickness2, sampleSec1, s f2 = vecFact(canXSection,canThickness2,sec1,sec2) canThick1Sec1, canThick1Sec2 = calcThicknessAtSec(canXSection, canThickness1, sec) - canThick2Sec1, canThick2Sec2 = calcThicknessAtSec(canXSection, canThickness2, sec) + canThick2Sec2 = calcThicknessAtSec(canXSection, canThickness2, sec)[1] - if (sec2 < 0.): + if sec2 < 0.0: val = np.exp(-(canThick1Sec1-canThick1Sec2)) assc = ass * val @@ -452,7 +457,7 @@ def calcFlatAbsCan(ass, canXSection, canThickness1, canThickness2, sampleSec1, s canThickness = canThickness1 + canThickness2 - if(canThickness > 0.): + if canThickness > 0.0: acc = (acc1 + acc2) / canThickness acsc = (acsc1 + acsc2) / canThickness diff --git a/Code/Mantid/scripts/Inelastic/IndirectBayes.py b/Code/Mantid/scripts/Inelastic/IndirectBayes.py index 90123e79487c..fc7b7df38f2d 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectBayes.py +++ b/Code/Mantid/scripts/Inelastic/IndirectBayes.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # Bayes routines # Fortran programs use fixed length arrays whereas Python has variable lenght lists # Input : the Python list is padded to Fortrans length using procedure PadArray @@ -17,7 +18,7 @@ from mantid import config, logger, mtd from IndirectCommon import * import sys, platform, math, os.path, numpy as np -mp = import_mantidplot() +MTD_PLOT = import_mantidplot() def readASCIIFile(file_name): workdir = config['defaultsave.directory'] @@ -55,7 +56,7 @@ def CalcErange(inWS,ns,erange,binWidth): Xin = Xin.reshape(len(Xin)/binWidth, binWidth) #sum and normalise values in bins - Xout = [sum(bin)*bnorm for bin in Xin] + Xout = [sum(bin) * bnorm for bin in Xin] #count number of bins nbins = len(Xout) @@ -97,7 +98,7 @@ def ReadNormFile(readRes,resnormWS,nsam): # get norm & scale values nrm = len(Xin) # no. points from length of x array if nrm == 0: raise ValueError('ResNorm file has no Intensity points') - Xin = mtd[resnormWS+'_Stretch'].readX(0) # no. points from length of x array + Xin = mtd[resnormWS+'_Stretch'].readX(0) # no. points from length of x array if len(Xin) == 0: raise ValueError('ResNorm file has no xscale points') if nrm != nsam: # check that no. groups are the same @@ -129,7 +130,7 @@ def ReadWidthFile(readWidth,widthFile,numSampleGroups): asc.append(line) handle.close() - except Exception, e: + except Exception: raise ValueError('Failed to read width file') numLines = len(asc) @@ -141,8 +142,8 @@ def ReadWidthFile(readWidth,widthFile,numSampleGroups): raise ValueError('Width groups (' +str(numLines) + ') not = Sample (' +str(numSampleGroups) +')') else: # no file: just use constant values - widthY = np.zeros(numSampleGroups) - widthE = np.zeros(numSampleGroups) + widthY = np.zeros(numSampleGroups) + widthE = np.zeros(numSampleGroups) # pad for Fortran call widthY = PadArray(widthY,51) @@ -271,8 +272,8 @@ def QLRun(program,samWS,resWS,resnormWS,erange,nbins,Fit,wfile,Loop,Plot,Save): message = ' Log(prob) : '+str(yprob[0])+' '+str(yprob[1])+' '+str(yprob[2])+' '+str(yprob[3]) logger.information(message) if prog == 'QSe': - nd,xout,yout,eout,yfit,yprob=Qse.qlstexp(numb,Xv,Yv,Ev,reals,fitOp, - Xdat,Xb,Yb,Wy,We,dtn,xsc, + nd,xout,yout,eout,yfit,yprob=Qse.qlstexp(numb,Xv,Yv,Ev,reals,fitOp,\ + Xdat,Xb,Yb,Wy,We,dtn,xsc,\ wrks,wrkr,lwrk) dataX = xout[:nd] dataX = np.append(dataX,2*xout[nd-1]-xout[nd-2]) @@ -315,7 +316,7 @@ def QLRun(program,samWS,resWS,resnormWS,erange,nbins,Fit,wfile,Loop,Plot,Save): fitWS = fname+'_Workspaces' fout = fname+'_Workspace_'+ str(m) - CreateWorkspace(OutputWorkspace=fout, DataX=datX, DataY=datY, DataE=datE, + CreateWorkspace(OutputWorkspace=fout, DataX=datX, DataY=datY, DataE=datE,\ Nspec=nsp, UnitX='DeltaE', VerticalAxisUnit='Text', VerticalAxisValues=names) # append workspace to list of results @@ -334,21 +335,23 @@ def QLRun(program,samWS,resWS,resnormWS,erange,nbins,Fit,wfile,Loop,Plot,Save): yProb = yPr0 yProb = np.append(yProb,yPr1) yProb = np.append(yProb,yPr2) - CreateWorkspace(OutputWorkspace=probWS, DataX=xProb, DataY=yProb, DataE=eProb, + CreateWorkspace(OutputWorkspace=probWS, DataX=xProb, DataY=yProb, DataE=eProb,\ Nspec=3, UnitX='MomentumTransfer') outWS = C2Fw(samWS[:-4],fname) - if (Plot != 'None'): + if Plot != 'None': QuasiPlot(fname,Plot,res_plot,Loop) if program == 'QSe': outWS = C2Se(fname) - if (Plot != 'None'): + if Plot != 'None': QuasiPlot(fname,Plot,res_plot,Loop) #Add some sample logs to the output workspaces CopyLogs(InputWorkspace=samWS, OutputWorkspace=outWS) - QLAddSampleLogs(outWS, resWS, prog, background, elastic, erange, (nbin, nrbin), resnormWS, wfile) + QLAddSampleLogs(outWS, resWS, prog, background, elastic, erange, + (nbin, nrbin), resnormWS, wfile) CopyLogs(InputWorkspace=samWS, OutputWorkspace=fitWS) - QLAddSampleLogs(fitWS, resWS, prog, background, elastic, erange, (nbin, nrbin), resnormWS, wfile) + QLAddSampleLogs(fitWS, resWS, prog, background, elastic, erange, + (nbin, nrbin), resnormWS, wfile) if Save: fit_path = os.path.join(workdir,fitWS+'.nxs') @@ -365,24 +368,37 @@ def QLAddSampleLogs(workspace, res_workspace, fit_program, background, elastic_p sample_binning, res_binning = binning energy_min, energy_max = e_range - AddSampleLog(Workspace=workspace, LogName="res_file", LogType="String", LogText=res_workspace) - AddSampleLog(Workspace=workspace, LogName="fit_program", LogType="String", LogText=fit_program) - AddSampleLog(Workspace=workspace, LogName="background", LogType="String", LogText=str(background)) - AddSampleLog(Workspace=workspace, LogName="elastic_peak", LogType="String", LogText=str(elastic_peak)) - AddSampleLog(Workspace=workspace, LogName="energy_min", LogType="Number", LogText=str(energy_min)) - AddSampleLog(Workspace=workspace, LogName="energy_max", LogType="Number", LogText=str(energy_max)) - AddSampleLog(Workspace=workspace, LogName="sample_binning", LogType="Number", LogText=str(sample_binning)) - AddSampleLog(Workspace=workspace, LogName="resolution_binning", LogType="Number", LogText=str(res_binning)) + AddSampleLog(Workspace=workspace, LogName="res_file", + LogType="String", LogText=res_workspace) + AddSampleLog(Workspace=workspace, LogName="fit_program", + LogType="String", LogText=fit_program) + AddSampleLog(Workspace=workspace, LogName="background", + LogType="String", LogText=str(background)) + AddSampleLog(Workspace=workspace, LogName="elastic_peak", + LogType="String", LogText=str(elastic_peak)) + AddSampleLog(Workspace=workspace, LogName="energy_min", + LogType="Number", LogText=str(energy_min)) + AddSampleLog(Workspace=workspace, LogName="energy_max", + LogType="Number", LogText=str(energy_max)) + AddSampleLog(Workspace=workspace, LogName="sample_binning", + LogType="Number", LogText=str(sample_binning)) + AddSampleLog(Workspace=workspace, LogName="resolution_binning", + LogType="Number", LogText=str(res_binning)) resnorm_used = (resnorm_workspace != '') - AddSampleLog(Workspace=workspace, LogName="resnorm", LogType="String", LogText=str(resnorm_used)) + AddSampleLog(Workspace=workspace, LogName="resnorm", + LogType="String", LogText=str(resnorm_used)) if resnorm_used: - AddSampleLog(Workspace=workspace, LogName="resnorm_file", LogType="String", LogText=resnorm_workspace) + AddSampleLog(Workspace=workspace, LogName="resnorm_file", + LogType="String", LogText=resnorm_workspace) width_file_used = (width_file != '') - AddSampleLog(Workspace=workspace, LogName="width", LogType="String", LogText=str(width_file_used)) + AddSampleLog(Workspace=workspace, LogName="width", + LogType="String", LogText=str(width_file_used)) if width_file_used: - AddSampleLog(Workspace=workspace, LogName="width_file", LogType="String", LogText=width_file) + AddSampleLog(Workspace=workspace, LogName="width_file", + LogType="String", LogText=width_file) + def yield_floats(block): #yield a list of floats from a list of lines of text @@ -390,6 +406,7 @@ def yield_floats(block): for line in block: yield ExtractFloat(line) + def read_ql_file(file_name, nl): #offet to ignore header header_offset = 8 @@ -463,6 +480,7 @@ def read_ql_file(file_name, nl): return q_data, (amp_data, FWHM_data, height_data), (amp_error, FWHM_error, height_error) + def C2Fw(prog,sname): output_workspace = sname+'_Result' num_spectra = 0 @@ -513,22 +531,23 @@ def C2Fw(prog,sname): axis_names.append('f'+str(nl)+'.f0.'+'Height') x.append(x_data) for j in range(1,nl+1): - axis_names.append('f'+str(nl)+'.f'+str(j)+'.Amplitude') - x.append(x_data) - axis_names.append('f'+str(nl)+'.f'+str(j)+'.FWHM') - x.append(x_data) - axis_names.append('f'+str(nl)+'.f'+str(j)+'.EISF') - x.append(x_data) + axis_names.append('f'+str(nl)+'.f'+str(j)+'.Amplitude') + x.append(x_data) + axis_names.append('f'+str(nl)+'.f'+str(j)+'.FWHM') + x.append(x_data) + axis_names.append('f'+str(nl)+'.f'+str(j)+'.EISF') + x.append(x_data) x = np.asarray(x).flatten() y = np.asarray(y).flatten() e = np.asarray(e).flatten() - CreateWorkspace(OutputWorkspace=output_workspace, DataX=x, DataY=y, DataE=e, Nspec=num_spectra, + CreateWorkspace(OutputWorkspace=output_workspace, DataX=x, DataY=y, DataE=e, Nspec=num_spectra,\ UnitX='MomentumTransfer', YUnitLabel='', VerticalAxisUnit='Text', VerticalAxisValues=axis_names) return output_workspace + def SeBlock(a,first): #read Ascii block of Integers line1 = a[first] first += 1 @@ -560,6 +579,7 @@ def SeBlock(a,first): #read Ascii block of Integ first += 1 return first,Q,int0,fw,int,be #values as list + def C2Se(sname): prog = 'QSe' outWS = sname+'_Result' @@ -613,26 +633,26 @@ def C2Se(sname): Vaxis.append('f1.Beta') logger.information('Vaxis=' + str(Vaxis)) - CreateWorkspace(OutputWorkspace=outWS, DataX=dataX, DataY=dataY, DataE=dataE, Nspec=nhist, + CreateWorkspace(OutputWorkspace=outWS, DataX=dataX, DataY=dataY, DataE=dataE, Nspec=nhist,\ UnitX='MomentumTransfer', VerticalAxisUnit='Text', VerticalAxisValues=Vaxis, YUnitLabel='') return outWS + def QuasiPlot(ws_stem,plot_type,res_plot,sequential): if plot_type: if sequential: ws_name = ws_stem + '_Result' - num_spectra = mtd[ws_name].getNumberHistograms() - if (plot_type == 'Prob' or plot_type == 'All'): + if plot_type == 'Prob' or plot_type == 'All': prob_ws = ws_stem+'_Prob' if prob_ws in mtd.getObjectNames(): - mp.plotSpectrum(prob_ws,[1,2],False) + MTD_PLOT.plotSpectrum(prob_ws,[1,2],False) QuasiPlotParameters(ws_name, plot_type) - if (plot_type == 'Fit' or plot_type == 'All'): + if plot_type == 'Fit' or plot_type == 'All': fWS = ws_stem+'_Workspace_0' - f_plot=mp.plotSpectrum(fWS,res_plot,False) + MTD_PLOT.plotSpectrum(fWS,res_plot,False) def QuasiPlotParameters(ws_name, plot_type): @@ -641,18 +661,20 @@ def QuasiPlotParameters(ws_name, plot_type): in the workspace @param ws_name :: name of the workspace to plot from. This function expects it has a TextAxis - @param plot_type :: the name of the parameter to plot (or All if all parameters should be plotted) + @param plot_type :: the name of the parameter to plot (or All if all parameters should + be plotted) """ num_spectra = mtd[ws_name].getNumberHistograms() param_names = ['Amplitude', 'FWHM', 'Beta'] for param_name in param_names: - if (plot_type == param_name or plot_type == 'All'): + if plot_type == param_name or plot_type == 'All': spectra_indicies = [i for i in range(num_spectra) if param_name in mtd[ws_name].getAxis(1).label(i)] - if(len(spectra_indicies) > 0): + if len(spectra_indicies) > 0: plotSpectra(ws_name, param_name, indicies=spectra_indicies[:3]) + # Quest programs def CheckBetSig(nbs): Nsig = int(nbs[1]) @@ -735,14 +757,14 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): Nb,Xb,Yb,Eb = GetXYE(resWS,0,array_len) numb = [nsam, nsp, ntc, Ndat, nbin, Imin, Imax, Nb, nrbin, Nbet, Nsig] reals = [efix, theta[m], rscl, bnorm] - xsout,ysout,xbout,ybout,zpout=Que.quest(numb,Xv,Yv,Ev,reals,fitOp, + xsout,ysout,xbout,ybout,zpout=Que.quest(numb,Xv,Yv,Ev,reals,fitOp,\ Xdat,Xb,Yb,wrks,wrkr,lwrk) dataXs = xsout[:Nsig] # reduce from fixed Fortran array dataYs = ysout[:Nsig] dataXb = xbout[:Nbet] dataYb = ybout[:Nbet] zpWS = fname + '_Zp' +str(m) - if (m > 0): + if m > 0: Qaxis += ',' Qaxis += str(Q[m]) @@ -759,7 +781,8 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): dataEz = np.append(dataEz,eBet0) CreateWorkspace(OutputWorkspace=zpWS, DataX=dataXz, DataY=dataYz, DataE=dataEz, - Nspec=Nsig, UnitX='MomentumTransfer', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=dataXs) + Nspec=Nsig, UnitX='MomentumTransfer', + VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=dataXs) unitx = mtd[zpWS].getAxis(0).setUnit("Label") unitx.setLabel('beta' , '') @@ -784,12 +807,12 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): groupZ = groupZ +','+ zpWS #create workspaces for sigma and beta - CreateWorkspace(OutputWorkspace=fname+'_Sigma', DataX=xSig, DataY=ySig, DataE=eSig, + CreateWorkspace(OutputWorkspace=fname+'_Sigma', DataX=xSig, DataY=ySig, DataE=eSig,\ Nspec=nsam, UnitX='', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) unitx = mtd[fname+'_Sigma'].getAxis(0).setUnit("Label") unitx.setLabel('sigma' , '') - CreateWorkspace(OutputWorkspace=fname+'_Beta', DataX=xBet, DataY=yBet, DataE=eBet, + CreateWorkspace(OutputWorkspace=fname+'_Beta', DataX=xBet, DataY=yBet, DataE=eBet,\ Nspec=nsam, UnitX='', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) unitx = mtd[fname+'_Beta'].getAxis(0).setUnit("Label") unitx.setLabel('beta' , '') @@ -817,28 +840,36 @@ def QuestRun(samWS,resWS,nbs,erange,nbins,Fit,Loop,Plot,Save): logger.information('Output file for Fit : ' + fpath) logger.information('Output file for Contours : ' + cpath) - if (Plot != 'None' and Loop == True): + if Plot != 'None' and Loop == True: QuestPlot(fname,Plot) EndTime('Quest') def QuestAddSampleLogs(workspace, res_workspace, background, elastic_peak, e_range, sample_binning, sigma, beta): energy_min, energy_max = e_range - AddSampleLog(Workspace=workspace, LogName="res_file", LogType="String", LogText=res_workspace) - AddSampleLog(Workspace=workspace, LogName="background", LogType="String", LogText=str(background)) - AddSampleLog(Workspace=workspace, LogName="elastic_peak", LogType="String", LogText=str(elastic_peak)) - AddSampleLog(Workspace=workspace, LogName="energy_min", LogType="Number", LogText=str(energy_min)) - AddSampleLog(Workspace=workspace, LogName="energy_max", LogType="Number", LogText=str(energy_max)) - AddSampleLog(Workspace=workspace, LogName="sample_binning", LogType="Number", LogText=str(sample_binning)) - AddSampleLog(Workspace=workspace, LogName="sigma", LogType="Number", LogText=str(sigma)) - AddSampleLog(Workspace=workspace, LogName="beta", LogType="Number", LogText=str(beta)) + AddSampleLog(Workspace=workspace, LogName="res_file", + LogType="String", LogText=res_workspace) + AddSampleLog(Workspace=workspace, LogName="background", + LogType="String", LogText=str(background)) + AddSampleLog(Workspace=workspace, LogName="elastic_peak", + LogType="String", LogText=str(elastic_peak)) + AddSampleLog(Workspace=workspace, LogName="energy_min", + LogType="Number", LogText=str(energy_min)) + AddSampleLog(Workspace=workspace, LogName="energy_max", + LogType="Number", LogText=str(energy_max)) + AddSampleLog(Workspace=workspace, LogName="sample_binning", + LogType="Number", LogText=str(sample_binning)) + AddSampleLog(Workspace=workspace, LogName="sigma", + LogType="Number", LogText=str(sigma)) + AddSampleLog(Workspace=workspace, LogName="beta", + LogType="Number", LogText=str(beta)) def QuestPlot(inputWS,Plot): - if (Plot == 'Sigma' or Plot == 'All'): - sig_plot=mp.importMatrixWorkspace(inputWS+'_Sigma').plotGraph2D() - if (Plot == 'Beta' or Plot == 'All'): - beta_plot=mp.importMatrixWorkspace(inputWS+'_Beta').plotGraph2D() + if Plot == 'Sigma' or Plot == 'All': + MTD_PLOT.importMatrixWorkspace(inputWS+'_Sigma').plotGraph2D() + if Plot == 'Beta' or Plot == 'All': + MTD_PLOT.importMatrixWorkspace(inputWS+'_Beta').plotGraph2D() # ResNorm programs def ResNormRun(vname,rname,erange,nbin,Plot='None',Save=False): @@ -879,7 +910,7 @@ def ResNormRun(vname,rname,erange,nbin,Plot='None',Save=False): nsp = m+1 numb = [nvan, nsp, ntc, Ndat, nbin, Imin, Imax, Nb] reals = [efix, theta[0], rscl, bnorm] - nd,xout,yout,eout,yfit,pfit=resnorm.resnorm(numb,Xv,Yv,Ev,reals, + nd,xout,yout,eout,yfit,pfit=resnorm.resnorm(numb,Xv,Yv,Ev,reals,\ Xdat,Xb,Yb,wrks,wrkr,lwrk) message = ' Fit paras : '+str(pfit[0])+' '+str(pfit[1]) logger.information(message) @@ -888,26 +919,29 @@ def ResNormRun(vname,rname,erange,nbin,Plot='None',Save=False): if m == 0: yPar1 = np.array([pfit[0]]) yPar2 = np.array([pfit[1]]) - CreateWorkspace(OutputWorkspace='Data', DataX=dataX, DataY=yout[:nd], DataE=eout[:nd], + CreateWorkspace(OutputWorkspace='Data', DataX=dataX, DataY=yout[:nd], DataE=eout[:nd],\ NSpec=1, UnitX='DeltaE') - CreateWorkspace(OutputWorkspace='Fit', DataX=dataX, DataY=yfit[:nd], DataE=np.zeros(nd), + CreateWorkspace(OutputWorkspace='Fit', DataX=dataX, DataY=yfit[:nd], DataE=np.zeros(nd),\ NSpec=1, UnitX='DeltaE') else: yPar1 = np.append(yPar1,pfit[0]) yPar2 = np.append(yPar2,pfit[1]) - CreateWorkspace(OutputWorkspace='__datmp', DataX=dataX, DataY=yout[:nd], DataE=eout[:nd], - NSpec=1, UnitX='DeltaE') - ConjoinWorkspaces(InputWorkspace1='Data', InputWorkspace2='__datmp', CheckOverlapping=False) - CreateWorkspace(OutputWorkspace='__f1tmp', DataX=dataX, DataY=yfit[:nd], DataE=np.zeros(nd), - NSpec=1, UnitX='DeltaE') - ConjoinWorkspaces(InputWorkspace1='Fit', InputWorkspace2='__f1tmp', CheckOverlapping=False) + + CreateWorkspace(OutputWorkspace='__datmp', DataX=dataX, DataY=yout[:nd], + DataE=eout[:nd], NSpec=1, UnitX='DeltaE') + ConjoinWorkspaces(InputWorkspace1='Data', InputWorkspace2='__datmp', + CheckOverlapping=False) + CreateWorkspace(OutputWorkspace='__f1tmp', DataX=dataX, DataY=yfit[:nd], + DataE=np.zeros(nd), NSpec=1, UnitX='DeltaE') + ConjoinWorkspaces(InputWorkspace1='Fit', InputWorkspace2='__f1tmp', + CheckOverlapping=False) resnorm_intesity = fname+'_ResNorm_Intensity' resnorm_stretch = fname+'_ResNorm_Stretch' - CreateWorkspace(OutputWorkspace=resnorm_intesity, DataX=xPar, DataY=yPar1, DataE=xPar, + CreateWorkspace(OutputWorkspace=resnorm_intesity, DataX=xPar, DataY=yPar1, DataE=xPar,\ NSpec=1, UnitX='MomentumTransfer') - CreateWorkspace(OutputWorkspace=resnorm_stretch, DataX=xPar, DataY=yPar2, DataE=xPar, + CreateWorkspace(OutputWorkspace=resnorm_stretch, DataX=xPar, DataY=yPar2, DataE=xPar,\ NSpec=1, UnitX='MomentumTransfer') group = resnorm_intesity + ','+ resnorm_stretch @@ -934,24 +968,27 @@ def ResNormRun(vname,rname,erange,nbin,Plot='None',Save=False): logger.information('Parameter file created : ' + par_path) logger.information('Fit file created : ' + fit_path) - if (Plot != 'None'): + if Plot != 'None': ResNormPlot(fname,Plot) EndTime('ResNorm') def ResNormAddSampleLogs(workspace, e_range, v_binning): energy_min, energy_max = e_range - AddSampleLog(Workspace=workspace, LogName="energy_min", LogType="Number", LogText=str(energy_min)) - AddSampleLog(Workspace=workspace, LogName="energy_max", LogType="Number", LogText=str(energy_max)) - AddSampleLog(Workspace=workspace, LogName="van_binning", LogType="Number", LogText=str(v_binning)) + AddSampleLog(Workspace=workspace, LogName="energy_min", + LogType="Number", LogText=str(energy_min)) + AddSampleLog(Workspace=workspace, LogName="energy_max", + LogType="Number", LogText=str(energy_max)) + AddSampleLog(Workspace=workspace, LogName="van_binning", + LogType="Number", LogText=str(v_binning)) def ResNormPlot(inputWS,Plot): - if (Plot == 'Intensity' or Plot == 'All'): + if Plot == 'Intensity' or Plot == 'All': iWS = inputWS + '_ResNorm_Intensity' - i_plot=mp.plotSpectrum(iWS,0,False) - if (Plot == 'Stretch' or Plot == 'All'): + MTD_PLOT.plotSpectrum(iWS,0,False) + if Plot == 'Stretch' or Plot == 'All': sWS = inputWS + '_ResNorm_Stretch' - s_plot=mp.plotSpectrum(sWS,0,False) - if (Plot == 'Fit' or Plot == 'All'): + MTD_PLOT.plotSpectrum(sWS,0,False) + if Plot == 'Fit' or Plot == 'All': fWS = inputWS + '_ResNorm_Fit' - f_plot=mp.plotSpectrum(fWS,0,False) + MTD_PLOT.plotSpectrum(fWS,0,False) diff --git a/Code/Mantid/scripts/Inelastic/IndirectCommon.py b/Code/Mantid/scripts/Inelastic/IndirectCommon.py index 043c2717866c..7804beeac9c0 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectCommon.py +++ b/Code/Mantid/scripts/Inelastic/IndirectCommon.py @@ -1,88 +1,79 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * from mantid.api import TextAxis from mantid import config, logger from IndirectImport import import_mantidplot -import sys, platform, os.path, math, datetime, re +import os.path +import math +import datetime +import re import numpy as np import itertools + def StartTime(prog): logger.notice('----------') - message = 'Program ' + prog +' started @ ' + str(datetime.datetime.now()) + message = 'Program ' + prog + ' started @ ' + str(datetime.datetime.now()) logger.notice(message) + def EndTime(prog): - message = 'Program ' + prog +' ended @ ' + str(datetime.datetime.now()) + message = 'Program ' + prog + ' ended @ ' + str(datetime.datetime.now()) logger.notice(message) logger.notice('----------') -def loadInst(instrument): - ws = '__empty_' + instrument - if not mtd.doesExist(ws): - idf_dir = config['instrumentDefinition.directory'] - idf = idf_dir + instrument + '_Definition.xml' - LoadEmptyInstrument(Filename=idf, OutputWorkspace=ws) - -def loadNexus(filename): - ''' - Loads a Nexus file into a workspace with the name based on the - filename. Convenience function for not having to play around with paths - in every function. - ''' - name = os.path.splitext( os.path.split(filename)[1] )[0] - LoadNexus(Filename=filename, OutputWorkspace=name) - return name def getInstrRun(ws_name): - ''' + """ Get the instrument name and run number from a workspace. @param ws_name - name of the workspace @return tuple of form (instrument, run number) - ''' - ws = mtd[ws_name] - run_number = str(ws.getRunNumber()) + """ + workspace = mtd[ws_name] + run_number = str(workspace.getRunNumber()) if run_number == '0': - #attempt to parse run number off of name + # Attempt to parse run number off of name match = re.match(r'([a-zA-Z]+)([0-9]+)', ws_name) if match: run_number = match.group(2) else: raise RuntimeError("Could not find run number associated with workspace.") - instrument = ws.getInstrument().getName() + instrument = workspace.getInstrument().getName() facility = config.getFacility() instrument = facility.instrument(instrument).filePrefix(int(run_number)) instrument = instrument.lower() return instrument, run_number + def getWSprefix(wsname): - ''' + """ Returns a string of the form '__' on which all of our other naming conventions are built. The workspace is used to get the instrument parameters. - ''' + """ if wsname == '': return '' - ws = mtd[wsname] + workspace = mtd[wsname] facility = config['default.facility'] - ws_run = ws.getRun() + ws_run = workspace.getRun() if 'facility' in ws_run: facility = ws_run.getLogData('facility').value (instrument, run_number) = getInstrRun(wsname) if facility == 'ILL': - run_name = instrument + '_'+ run_number + run_name = instrument + '_' + run_number else: run_name = instrument + run_number try: - analyser = ws.getInstrument().getStringParameter('analyser')[0] - reflection = ws.getInstrument().getStringParameter('reflection')[0] + analyser = workspace.getInstrument().getStringParameter('analyser')[0] + reflection = workspace.getInstrument().getStringParameter('reflection')[0] except IndexError: analyser = '' reflection = '' @@ -94,10 +85,12 @@ def getWSprefix(wsname): return prefix + def getEfixed(workspace, detIndex=0): inst = mtd[workspace].getInstrument() return inst.getNumberParameter("efixed-val")[0] + def checkUnitIs(ws, unit_id, axis_index=0): """ Check that the workspace has the correct units by comparing @@ -105,10 +98,12 @@ def checkUnitIs(ws, unit_id, axis_index=0): """ axis = mtd[ws].getAxis(axis_index) unit = axis.getUnit() - return (unit.unitID() == unit_id) + return unit.unitID() == unit_id -# Get the default save directory and check it's valid def getDefaultWorkingDirectory(): + """ + Get the default save directory and check it's valid. + """ workdir = config['defaultsave.directory'] if not os.path.isdir(workdir): @@ -116,46 +111,49 @@ def getDefaultWorkingDirectory(): return workdir + def createQaxis(inputWS): result = [] - ws = mtd[inputWS] - nHist = ws.getNumberHistograms() - if ws.getAxis(1).isSpectra(): - inst = ws.getInstrument() - samplePos = inst.getSample().getPos() - beamPos = samplePos - inst.getSource().getPos() - for i in range(0,nHist): + workspace = mtd[inputWS] + num_hist = workspace.getNumberHistograms() + if workspace.getAxis(1).isSpectra(): + inst = workspace.getInstrument() + sample_pos = inst.getSample().getPos() + beam_pos = sample_pos - inst.getSource().getPos() + for i in range(0, num_hist): efixed = getEfixed(inputWS, i) - detector = ws.getDetector(i) - theta = detector.getTwoTheta(samplePos, beamPos) / 2 - lamda = math.sqrt(81.787/efixed) + detector = workspace.getDetector(i) + theta = detector.getTwoTheta(sample_pos, beam_pos) / 2 + lamda = math.sqrt(81.787 / efixed) q = 4 * math.pi * math.sin(theta) / lamda result.append(q) else: - axis = ws.getAxis(1) + axis = workspace.getAxis(1) msg = 'Creating Axis based on Detector Q value: ' if not axis.isNumeric(): msg += 'Input workspace must have either spectra or numeric axis.' raise ValueError(msg) - if ( axis.getUnit().unitID() != 'MomentumTransfer' ): + if axis.getUnit().unitID() != 'MomentumTransfer': msg += 'Input must have axis values of Q' raise ValueError(msg) - for i in range(0, nHist): + for i in range(0, num_hist): result.append(float(axis.label(i))) return result + def GetWSangles(inWS): - nhist = mtd[inWS].getNumberHistograms() # get no. of histograms/groups - sourcePos = mtd[inWS].getInstrument().getSource().getPos() - samplePos = mtd[inWS].getInstrument().getSample().getPos() - beamPos = samplePos - sourcePos + num_hist = mtd[inWS].getNumberHistograms() # get no. of histograms/groups + source_pos = mtd[inWS].getInstrument().getSource().getPos() + sample_pos = mtd[inWS].getInstrument().getSample().getPos() + beam_pos = sample_pos - source_pos angles = [] # will be list of angles - for index in range(0, nhist): + for index in range(0, num_hist): detector = mtd[inWS].getDetector(index) # get index - twoTheta = detector.getTwoTheta(samplePos, beamPos)*180.0/math.pi # calc angle - angles.append(twoTheta) # add angle + two_theta = detector.getTwoTheta(sample_pos, beam_pos) * 180.0 / math.pi # calc angle + angles.append(two_theta) # add angle return angles + def GetThetaQ(ws): """ Returns the theta and elastic Q for each spectrum in a given workspace. @@ -164,8 +162,8 @@ def GetThetaQ(ws): @returns A tuple containing a list of theta values and a list of Q values """ - eFixed = getEfixed(ws) - wavelas = math.sqrt(81.787 / eFixed) # Elastic wavelength + e_fixed = getEfixed(ws) + wavelas = math.sqrt(81.787 / e_fixed) # Elastic wavelength k0 = 4.0 * math.pi / wavelas axis = mtd[ws].getAxis(1) @@ -191,28 +189,40 @@ def GetThetaQ(ws): return theta, q + def ExtractFloat(data_string): - """ Extract float values from an ASCII string""" + """ + Extract float values from an ASCII string + """ values = data_string.split() values = map(float, values) return values + def ExtractInt(data_string): - """ Extract int values from an ASCII string""" + """ + Extract int values from an ASCII string + """ values = data_string.split() values = map(int, values) return values -def PadArray(inarray,nfixed): #pad a list to specified size - npt=len(inarray) - padding = nfixed-npt - outarray=[] + +def PadArray(inarray, nfixed): + """ + Pad a list to specified size. + """ + npt = len(inarray) + padding = nfixed - npt + outarray = [] outarray.extend(inarray) - outarray +=[0]*padding + outarray += [0] * padding return outarray -def CheckAnalysers(in1WS,in2WS): - '''Check workspaces have identical analysers and reflections + +def CheckAnalysers(in1WS, in2WS): + """ + Check workspaces have identical analysers and reflections Args: @param in1WS - first 2D workspace @@ -224,22 +234,24 @@ def CheckAnalysers(in1WS,in2WS): Raises: @exception Valuerror - workspaces have different analysers @exception Valuerror - workspaces have different reflections - ''' + """ ws1 = mtd[in1WS] - a1 = ws1.getInstrument().getStringParameter('analyser')[0] - r1 = ws1.getInstrument().getStringParameter('reflection')[0] + analyser_1 = ws1.getInstrument().getStringParameter('analyser')[0] + reflection_1 = ws1.getInstrument().getStringParameter('reflection')[0] ws2 = mtd[in2WS] - a2 = ws2.getInstrument().getStringParameter('analyser')[0] - r2 = ws2.getInstrument().getStringParameter('reflection')[0] - if a1 != a2: - raise ValueError('Workspace '+in1WS+' and '+in2WS+' have different analysers') - elif r1 != r2: - raise ValueError('Workspace '+in1WS+' and '+in2WS+' have different reflections') + analyser_2 = ws2.getInstrument().getStringParameter('analyser')[0] + reflection_2 = ws2.getInstrument().getStringParameter('reflection')[0] + if analyser_1 != analyser_2: + raise ValueError('Workspace %s and %s have different analysers' % (ws1, ws2)) + elif reflection_1 != reflection_2: + raise ValueError('Workspace %s and %s have different reflections' % (ws1, ws2)) else: - logger.information('Analyser is '+a1+r1) + logger.information('Analyser is %s, reflection %s' % (analyser_1, reflection_1)) + def CheckHistZero(inWS): - '''Retrieves basic info on a worskspace + """ + Retrieves basic info on a worskspace Checks the workspace is not empty, then returns the number of histogram and the number of X-points, which is the number of bin boundaries minus one @@ -248,25 +260,27 @@ def CheckHistZero(inWS): @param inWS 2D workspace Returns: - @return nhist - number of histograms in the workspace + @return num_hist - number of histograms in the workspace @return ntc - number of X-points in the first histogram, which is the number of bin boundaries minus one. It is assumed all histograms have the same number of X-points. Raises: @exception ValueError - Worskpace has no histograms - ''' - nhist = mtd[inWS].getNumberHistograms() # no. of hist/groups in WS - if nhist == 0: - raise ValueError('Workspace '+inWS+' has NO histograms') - Xin = mtd[inWS].readX(0) - ntc = len(Xin)-1 # no. points from length of x array + """ + num_hist = mtd[inWS].getNumberHistograms() # no. of hist/groups in WS + if num_hist == 0: + raise ValueError('Workspace ' + inWS + ' has NO histograms') + x_in = mtd[inWS].readX(0) + ntc = len(x_in) - 1 # no. points from length of x array if ntc == 0: - raise ValueError('Workspace '+inWS+' has NO points') - return nhist,ntc + raise ValueError('Workspace ' + inWS + ' has NO points') + return num_hist, ntc -def CheckHistSame(in1WS,name1,in2WS,name2): - '''Check workspaces have same number of histograms and bin boundaries + +def CheckHistSame(in1WS, name1, in2WS, name2): + """ + Check workspaces have same number of histograms and bin boundaries Args: @param in1WS - first 2D workspace @@ -280,49 +294,52 @@ def CheckHistSame(in1WS,name1,in2WS,name2): Raises: Valuerror: number of histograms is different Valuerror: number of bin boundaries in the histograms is different - ''' - nhist1 = mtd[in1WS].getNumberHistograms() # no. of hist/groups in WS1 - X1 = mtd[in1WS].readX(0) - xlen1 = len(X1) - nhist2 = mtd[in2WS].getNumberHistograms() # no. of hist/groups in WS2 - X2 = mtd[in2WS].readX(0) - xlen2 = len(X2) - if nhist1 != nhist2: # check that no. groups are the same - e1 = name1+' ('+in1WS+') histograms (' +str(nhist1) + ')' - e2 = name2+' ('+in2WS+') histograms (' +str(nhist2) + ')' - error = e1 + ' not = ' + e2 + """ + num_hist_1 = mtd[in1WS].getNumberHistograms() # no. of hist/groups in WS1 + x_1 = mtd[in1WS].readX(0) + x_len_1 = len(x_1) + num_hist_2 = mtd[in2WS].getNumberHistograms() # no. of hist/groups in WS2 + x_2 = mtd[in2WS].readX(0) + x_len_2 = len(x_2) + if num_hist_1 != num_hist_2: # Check that no. groups are the same + error_1 = '%s (%s) histograms (%d)' % (name1, in1WS, num_hist_1) + error_2 = '%s (%s) histograms (%d)' % (name2, in2WS, num_hist_2) + error = error_1 + ' not = ' + error_2 raise ValueError(error) - elif xlen1 != xlen2: - e1 = name1+' ('+in1WS+') array length (' +str(xlen1) + ')' - e2 = name2+' ('+in2WS+') array length (' +str(xlen2) + ')' - error = e1 + ' not = ' + e2 + elif x_len_1 != x_len_2: + error_1 = '%s (%s) array length (%d)' % (name1, in1WS, x_len_1) + error_2 = '%s (%s) array length (%d)' % (name2, in2WS, x_len_2) + error = error_1 + ' not = ' + error_2 raise ValueError(error) -def CheckXrange(x_range,type): - if not ( ( len(x_range) == 2 ) or ( len(x_range) == 4 ) ): + +def CheckXrange(x_range, type): + if not ((len(x_range) == 2) or (len(x_range) == 4)): raise ValueError(type + ' - Range must contain either 2 or 4 numbers') for lower, upper in zip(x_range[::2], x_range[1::2]): if math.fabs(lower) < 1e-5: - raise ValueError(type + ' - input minimum ('+str(lower)+') is Zero') + raise ValueError('%s - input minimum (%f) is zero' % (type, lower)) if math.fabs(upper) < 1e-5: - raise ValueError(type + ' - input maximum ('+str(upper)+') is Zero') + raise ValueError('%s - input maximum (%f) is zero' % (type, upper)) if upper < lower: - raise ValueError(type + ' - input max ('+str(upper)+') < min ('+str(lower)+')') + raise ValueError('%s - input maximum (%f) < minimum (%f)' % (type, upper, lower)) + -def CheckElimits(erange,Xin): - nx = len(Xin)-1 +def CheckElimits(erange, Xin): + len_x = len(Xin) - 1 if math.fabs(erange[0]) < 1e-5: - raise ValueError('Elimits - input emin ( '+str(erange[0])+' ) is Zero') + raise ValueError('Elimits - input emin (%f) is Zero' % (erange[0])) if erange[0] < Xin[0]: - raise ValueError('Elimits - input emin ( '+str(erange[0])+' ) < data emin ( '+str(Xin[0])+' )') + raise ValueError('Elimits - input emin (%f) < data emin (%f)' % (erange[0], Xin[0])) if math.fabs(erange[1]) < 1e-5: - raise ValueError('Elimits - input emax ( '+str(erange[1])+' ) is Zero') - if erange[1] > Xin[nx]: - raise ValueError('Elimits - input emax ( '+str(erange[1])+' ) > data emax ( '+str(Xin[nx])+' )') + raise ValueError('Elimits - input emax (%f) is Zero' % (erange[1])) + if erange[1] > Xin[len_x]: + raise ValueError('Elimits - input emax (%f) > data emax (%f)' % (erange[1], Xin[len_x])) if erange[1] < erange[0]: - raise ValueError('Elimits - input emax ( '+str(erange[1])+' ) < emin ( '+str(erange[0])+' )') + raise ValueError('Elimits - input emax (%f) < emin (%f)' % (erange[1], erange[0])) + def getInstrumentParameter(ws, param_name): """Get an named instrument parameter from a workspace. @@ -333,8 +350,8 @@ def getInstrumentParameter(ws, param_name): """ inst = mtd[ws].getInstrument() - #create a map of type parameters to functions. This is so we avoid writing lots of - #if statements becuase there's no way to dynamically get the type. + # Create a map of type parameters to functions. This is so we avoid writing lots of + # if statements becuase there's no way to dynamically get the type. func_map = {'double': inst.getNumberParameter, 'string': inst.getStringParameter, 'int': inst.getIntParameter, 'bool': inst.getBoolParameter} @@ -349,6 +366,7 @@ def getInstrumentParameter(ws, param_name): return param + def plotSpectra(ws, y_axis_title, indicies=[]): """ Plot a selection of spectra given a list of indicies @@ -362,14 +380,15 @@ def plotSpectra(ws, y_axis_title, indicies=[]): indicies = range(num_spectra) try: - mp = import_mantidplot() - plot = mp.plotSpectrum(ws, indicies, True) + mtd_plot = import_mantidplot() + plot = mtd_plot.plotSpectrum(ws, indicies, True) layer = plot.activeLayer() - layer.setAxisTitle(mp.Layer.Left, y_axis_title) + layer.setAxisTitle(mtd_plot.Layer.Left, y_axis_title) except RuntimeError: - #User clicked cancel on plot so don't do anything + # User clicked cancel on plot so don't do anything return + def plotParameters(ws, *param_names): """ Plot a number of spectra given a list of parameter names @@ -387,78 +406,81 @@ def plotParameters(ws, *param_names): if len(indicies) > 0: plotSpectra(ws, name, indicies) + def convertToElasticQ(input_ws, output_ws=None): - """ + """ Helper function to convert the spectrum axis of a sample to ElasticQ. @param input_ws - the name of the workspace to convert from @param output_ws - the name to call the converted workspace - """ + """ - if output_ws is None: - output_ws = input_ws + if output_ws is None: + output_ws = input_ws - axis = mtd[input_ws].getAxis(1) - if axis.isSpectra(): - e_fixed = getEfixed(input_ws) - ConvertSpectrumAxis(input_ws,Target='ElasticQ',EMode='Indirect',EFixed=e_fixed,OutputWorkspace=output_ws) + axis = mtd[input_ws].getAxis(1) + if axis.isSpectra(): + e_fixed = getEfixed(input_ws) + ConvertSpectrumAxis(input_ws, Target='ElasticQ', EMode='Indirect', EFixed=e_fixed, + OutputWorkspace=output_ws) - elif axis.isNumeric(): - #check that units are Momentum Transfer - if axis.getUnit().unitID() != 'MomentumTransfer': - raise RuntimeError('Input must have axis values of Q') + elif axis.isNumeric(): + # Check that units are Momentum Transfer + if axis.getUnit().unitID() != 'MomentumTransfer': + raise RuntimeError('Input must have axis values of Q') + + CloneWorkspace(input_ws, OutputWorkspace=output_ws) + else: + raise RuntimeError('Input workspace must have either spectra or numeric axis.') - CloneWorkspace(input_ws, OutputWorkspace=output_ws) - else: - raise RuntimeError('Input workspace must have either spectra or numeric axis.') def transposeFitParametersTable(params_table, output_table=None): - """ + """ Transpose the parameter table created from a multi domain Fit. This function will make the output consistent with PlotPeakByLogValue. @param params_table - the parameter table output from Fit. @param output_table - name to call the transposed table. If omitted, the output_table will be the same as the params_table - """ - params_table = mtd[params_table] - - table_ws = '__tmp_table_ws' - table_ws = CreateEmptyTableWorkspace(OutputWorkspace=table_ws) - - param_names = params_table.column(0)[:-1] #-1 to remove cost function - param_values = params_table.column(1)[:-1] - param_errors = params_table.column(2)[:-1] - - #find the number of parameters per function - func_index = param_names[0].split('.')[0] - num_params = 0 - for i, name in enumerate(param_names): - if name.split('.')[0] != func_index: - num_params = i - break - - #create columns with parameter names for headers - column_names = ['.'.join(name.split('.')[1:]) for name in param_names[:num_params]] - column_error_names = [name + '_Err' for name in column_names] - column_names = zip(column_names, column_error_names) - table_ws.addColumn('double', 'axis-1') - for name, error_name in column_names: - table_ws.addColumn('double', name) - table_ws.addColumn('double', error_name) - - #output parameter values to table row - for i in xrange(0, params_table.rowCount()-1, num_params): - row_values = param_values[i:i+num_params] - row_errors = param_errors[i:i+num_params] - row = [value for pair in zip(row_values, row_errors) for value in pair] - row = [i/num_params] + row - table_ws.addRow(row) - - if output_table is None: - output_table = params_table.name() - - RenameWorkspace(table_ws.name(), OutputWorkspace=output_table) + """ + params_table = mtd[params_table] + + table_ws = '__tmp_table_ws' + table_ws = CreateEmptyTableWorkspace(OutputWorkspace=table_ws) + + param_names = params_table.column(0)[:-1] # -1 to remove cost function + param_values = params_table.column(1)[:-1] + param_errors = params_table.column(2)[:-1] + + # Find the number of parameters per function + func_index = param_names[0].split('.')[0] + num_params = 0 + for i, name in enumerate(param_names): + if name.split('.')[0] != func_index: + num_params = i + break + + # Create columns with parameter names for headers + column_names = ['.'.join(name.split('.')[1:]) for name in param_names[:num_params]] + column_error_names = [name + '_Err' for name in column_names] + column_names = zip(column_names, column_error_names) + table_ws.addColumn('double', 'axis-1') + for name, error_name in column_names: + table_ws.addColumn('double', name) + table_ws.addColumn('double', error_name) + + # Output parameter values to table row + for i in xrange(0, params_table.rowCount() - 1, num_params): + row_values = param_values[i:i + num_params] + row_errors = param_errors[i:i + num_params] + row = [value for pair in zip(row_values, row_errors) for value in pair] + row = [i / num_params] + row + table_ws.addRow(row) + + if output_table is None: + output_table = params_table.name() + + RenameWorkspace(table_ws.name(), OutputWorkspace=output_table) def search_for_fit_params(suffix, table_ws): @@ -472,7 +494,7 @@ def search_for_fit_params(suffix, table_ws): def convertParametersToWorkspace(params_table, x_column, param_names, output_name): - """ + """ Convert a parameter table output by PlotPeakByLogValue to a MatrixWorkspace. This will make a spectrum for each parameter name using the x_column vairable as the @@ -482,60 +504,64 @@ def convertParametersToWorkspace(params_table, x_column, param_names, output_nam @param x_column - the column in the table to use for the x values. @param parameter_names - list of parameter names to add to the workspace @param output_name - name to call the output workspace. - """ - #search for any parameters in the table with the given parameter names, - #ignoring their function index and output them to a workspace - workspace_names = [] - for param_name in param_names: - column_names = search_for_fit_params(param_name, params_table) - column_error_names = search_for_fit_params(param_name+'_Err', params_table) - param_workspaces = [] - for name, error_name in zip(column_names, column_error_names): - ConvertTableToMatrixWorkspace(params_table, x_column, name, error_name, OutputWorkspace=name) - param_workspaces.append(name) - workspace_names.append(param_workspaces) - - #transpose list of workspaces, ignoring unequal length of lists - #this handles the case where a parameter occurs only once in the whole workspace - workspace_names = map(list, itertools.izip_longest(*workspace_names)) - workspace_names = [filter(None, sublist) for sublist in workspace_names] - - #join all the parameters for each peak into a single workspace per peak - temp_workspaces = [] - for peak_params in workspace_names: - temp_peak_ws = peak_params[0] - for param_ws in peak_params[1:]: - ConjoinWorkspaces(temp_peak_ws, param_ws, False) - temp_workspaces.append(temp_peak_ws) - - #join all peaks into a single workspace - temp_workspace = temp_workspaces[0] - for temp_ws in temp_workspaces[1:]: - ConjoinWorkspaces(temp_workspace, temp_peak_ws, False) - - RenameWorkspace(temp_workspace, OutputWorkspace=output_name) - - #replace axis on workspaces with text axis - axis = TextAxis.create(mtd[output_name].getNumberHistograms()) - workspace_names = [name for sublist in workspace_names for name in sublist] - for i, name in enumerate(workspace_names): - axis.setLabel(i, name) - mtd[output_name].replaceAxis(1, axis) + """ + # Search for any parameters in the table with the given parameter names, + # ignoring their function index and output them to a workspace + workspace_names = [] + for param_name in param_names: + column_names = search_for_fit_params(param_name, params_table) + column_error_names = search_for_fit_params(param_name + '_Err', params_table) + param_workspaces = [] + for name, error_name in zip(column_names, column_error_names): + ConvertTableToMatrixWorkspace(params_table, x_column, name, error_name, + OutputWorkspace=name) + param_workspaces.append(name) + workspace_names.append(param_workspaces) + + # Transpose list of workspaces, ignoring unequal length of lists + # this handles the case where a parameter occurs only once in the whole workspace + workspace_names = map(list, itertools.izip_longest(*workspace_names)) + workspace_names = [filter(None, sublist) for sublist in workspace_names] + + # Join all the parameters for each peak into a single workspace per peak + temp_workspaces = [] + for peak_params in workspace_names: + temp_peak_ws = peak_params[0] + for param_ws in peak_params[1:]: + ConjoinWorkspaces(temp_peak_ws, param_ws, False) + temp_workspaces.append(temp_peak_ws) + + # Join all peaks into a single workspace + temp_workspace = temp_workspaces[0] + for temp_ws in temp_workspaces[1:]: # TODO: fairly certain something is wrong here + ConjoinWorkspaces(temp_workspace, temp_peak_ws, False) + + RenameWorkspace(temp_workspace, OutputWorkspace=output_name) + + # Replace axis on workspaces with text axis + axis = TextAxis.create(mtd[output_name].getNumberHistograms()) + workspace_names = [name for sublist in workspace_names for name in sublist] + for i, name in enumerate(workspace_names): + axis.setLabel(i, name) + mtd[output_name].replaceAxis(1, axis) + def addSampleLogs(ws, sample_logs): - """ + """ Add a dictionary of logs to a workspace. The type of the log is inferred by the type of the value passed to the log. + @param ws - workspace to add logs too. @param sample_logs - dictionary of logs to append to the workspace. - """ - for key, value in sample_logs.iteritems(): - if isinstance(value, bool): - log_type = 'String' - elif isinstance(value, (int, long, float)): - log_type = 'Number' - else: - log_type = 'String' + """ + + for key, value in sample_logs.iteritems(): + if isinstance(value, bool): + log_type = 'String' + elif isinstance(value, (int, long, float)): + log_type = 'Number' + else: + log_type = 'String' - AddSampleLog(Workspace=ws, LogName=key, LogType=log_type, LogText=str(value)) + AddSampleLog(Workspace=ws, LogName=key, LogType=log_type, LogText=str(value)) diff --git a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py index ca7a18289489..a6a3af0d3dc3 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py +++ b/Code/Mantid/scripts/Inelastic/IndirectDataAnalysis.py @@ -1,5 +1,6 @@ +#pylint: disable=invalid-name from IndirectImport import import_mantidplot -mp = import_mantidplot() +MTD_PLOT = import_mantidplot() from IndirectCommon import * import math, re, os.path, numpy as np @@ -8,32 +9,6 @@ from mantid import * -############################################################################## -# Misc. Helper Functions -############################################################################## - -def split(l, n): - #Yield successive n-sized chunks from l. - for i in xrange(0, len(l), n): - yield l[i:i+n] - -def segment(l, fromIndex, toIndex): - for i in xrange(fromIndex, toIndex + 1): - yield l[i] - -def trimData(nSpec, vals, min, max): - result = [] - chunkSize = len(vals) / nSpec - assert min >= 0, 'trimData: min is less then zero' - assert max <= chunkSize - 1, 'trimData: max is greater than the number of spectra' - assert min <= max, 'trimData: min is greater than max' - chunks = split(vals,chunkSize) - for chunk in chunks: - seg = segment(chunk,min,max) - for val in seg: - result.append(val) - return result - ############################################################################## # ConvFit ############################################################################## @@ -87,11 +62,13 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin using_delta_func = ftype[:5] == 'Delta' lorentzians = ftype[5:6] if using_delta_func else ftype[:1] - logger.information('Input files : '+str(inputWS)) - logger.information('Fit type : Delta = ' + str(using_delta_func) + ' ; Lorentzians = ' + str(lorentzians)) - logger.information('Background type : ' + bgd) + logger.information('Input files: ' + str(inputWS)) + logger.information('Fit type: Delta=%s; Lorentzians=%s' % ( + str(using_delta_func), str(lorentzians))) + logger.information('Background type: ' + bgd) - output_workspace = getWSprefix(inputWS) + 'conv_' + ftype + bgd + '_s' + str(specMin) + "_to_" + str(specMax) + output_workspace = '%sconv_%s%s_s%d_to_%d' % ( + getWSprefix(inputWS), ftype, bgd, specMin, specMax) #convert input workspace to get Q axis temp_fit_workspace = "__convfit_fit_ws" @@ -122,23 +99,32 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin axis.setUnit("MomentumTransfer") CopyLogs(InputWorkspace=inputWS, OutputWorkspace=wsname) - AddSampleLog(Workspace=wsname, LogName='convolve_members', LogType='String', LogText=str(convolve)) - AddSampleLog(Workspace=wsname, LogName="fit_program", LogType="String", LogText='ConvFit') - AddSampleLog(Workspace=wsname, LogName='background', LogType='String', LogText=str(bgd)) - AddSampleLog(Workspace=wsname, LogName='delta_function', LogType='String', LogText=str(using_delta_func)) - AddSampleLog(Workspace=wsname, LogName='lorentzians', LogType='String', LogText=str(lorentzians)) + AddSampleLog(Workspace=wsname, LogName='convolve_members', + LogType='String', LogText=str(convolve)) + AddSampleLog(Workspace=wsname, LogName="fit_program", + LogType="String", LogText='ConvFit') + AddSampleLog(Workspace=wsname, LogName='background', + LogType='String', LogText=str(bgd)) + AddSampleLog(Workspace=wsname, LogName='delta_function', + LogType='String', LogText=str(using_delta_func)) + AddSampleLog(Workspace=wsname, LogName='lorentzians', + LogType='String', LogText=str(lorentzians)) CopyLogs(InputWorkspace=wsname, OutputWorkspace=output_workspace + "_Workspaces") temp_correction = temperature is not None - AddSampleLog(Workspace=wsname, LogName='temperature_correction', LogType='String', LogText=str(temp_correction)) + AddSampleLog(Workspace=wsname, LogName='temperature_correction', + LogType='String', LogText=str(temp_correction)) if temp_correction: - AddSampleLog(Workspace=wsname, LogName='temperature_value', LogType='String', LogText=str(temperature)) + AddSampleLog(Workspace=wsname, LogName='temperature_value', + LogType='String', LogText=str(temperature)) - RenameWorkspace(InputWorkspace=output_workspace, OutputWorkspace=output_workspace + "_Parameters") + RenameWorkspace(InputWorkspace=output_workspace, + OutputWorkspace=output_workspace + "_Parameters") fit_workspaces = mtd[output_workspace + '_Workspaces'].getNames() - for i, ws in enumerate(fit_workspaces): - RenameWorkspace(ws, OutputWorkspace=output_workspace + '_' + str(i+specMin) + '_Workspace') + for i, workspace in enumerate(fit_workspaces): + RenameWorkspace(workspace, + OutputWorkspace='%s_%d_Workspace' % (output_workspace, i + specMin)) if Save: # path name for nxs file @@ -159,178 +145,178 @@ def confitSeq(inputWS, func, startX, endX, ftype, bgd, temperature=None, specMin ############################################################################## def furyfitSeq(inputWS, func, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None'): + StartTime('FuryFit') - StartTime('FuryFit') - - fit_type = ftype[:-2] - logger.information('Option: ' + fit_type) - logger.information(func) + fit_type = ftype[:-2] + logger.information('Option: ' + fit_type) + logger.information(func) - tmp_fit_workspace = "__furyfit_fit_ws" - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx) + tmp_fit_workspace = "__furyfit_fit_ws" + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx) - num_hist = mtd[inputWS].getNumberHistograms() - if spec_max is None: - spec_max = num_hist - 1 + num_hist = mtd[inputWS].getNumberHistograms() + if spec_max is None: + spec_max = num_hist - 1 - # name stem for generated workspace - output_workspace = getWSprefix(inputWS) + 'fury_' + ftype + str(spec_min) + "_to_" + str(spec_max) + # Name stem for generated workspace + output_workspace = '%sfury_%s%d_to_%d' % (getWSprefix(inputWS), ftype, spec_min, spec_max) - ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) - convertToElasticQ(tmp_fit_workspace) + ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) + convertToElasticQ(tmp_fit_workspace) - #build input string for PlotPeakByLogValue - input_str = [tmp_fit_workspace + ',i%d' % i for i in range(spec_min, spec_max + 1)] - input_str = ';'.join(input_str) + # Build input string for PlotPeakByLogValue + input_str = [tmp_fit_workspace + ',i%d' % i for i in range(spec_min, spec_max + 1)] + input_str = ';'.join(input_str) - PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func, - StartX=startx, EndX=endx, FitType='Sequential', CreateOutput=True) + PlotPeakByLogValue(Input=input_str, OutputWorkspace=output_workspace, Function=func, + StartX=startx, EndX=endx, FitType='Sequential', CreateOutput=True) - #remove unsused workspaces - DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices') - DeleteWorkspace(output_workspace + '_Parameters') + # Remove unsused workspaces + DeleteWorkspace(output_workspace + '_NormalisedCovarianceMatrices') + DeleteWorkspace(output_workspace + '_Parameters') - fit_group = output_workspace + '_Workspaces' - params_table = output_workspace + '_Parameters' - RenameWorkspace(output_workspace, OutputWorkspace=params_table) + fit_group = output_workspace + '_Workspaces' + params_table = output_workspace + '_Parameters' + RenameWorkspace(output_workspace, OutputWorkspace=params_table) - #create *_Result workspace - result_workspace = output_workspace + "_Result" - parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] - convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) + # Create *_Result workspace + result_workspace = output_workspace + "_Result" + parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] + convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) - #set x units to be momentum transfer - axis = mtd[result_workspace].getAxis(0) - axis.setUnit("MomentumTransfer") + # Set x units to be momentum transfer + axis = mtd[result_workspace].getAxis(0) + axis.setUnit("MomentumTransfer") - #process generated workspaces - wsnames = mtd[fit_group].getNames() - params = [startx, endx, fit_type] - for i, ws in enumerate(wsnames): - output_ws = output_workspace + '_%d_Workspace' % i - RenameWorkspace(ws, OutputWorkspace=output_ws) + # Process generated workspaces + wsnames = mtd[fit_group].getNames() + for i, workspace in enumerate(wsnames): + output_ws = output_workspace + '_%d_Workspace' % i + RenameWorkspace(workspace, OutputWorkspace=output_ws) - sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type, - 'intensities_constrained': intensities_constrained, 'beta_constrained': False} + sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': fit_type, + 'intensities_constrained': intensities_constrained, 'beta_constrained': False} - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) - addSampleLogs(fit_group, sample_logs) - addSampleLogs(result_workspace, sample_logs) + addSampleLogs(fit_group, sample_logs) + addSampleLogs(result_workspace, sample_logs) - if Save: - save_workspaces = [result_workspace, fit_group] - furyFitSaveWorkspaces(save_workspaces) + if Save: + save_workspaces = [result_workspace, fit_group] + furyFitSaveWorkspaces(save_workspaces) - if Plot != 'None' : - furyfitPlotSeq(result_workspace, Plot) + if Plot != 'None' : + furyfitPlotSeq(result_workspace, Plot) - EndTime('FuryFit') - return result_workspace + EndTime('FuryFit') + return result_workspace def furyfitMult(inputWS, function, ftype, startx, endx, spec_min=0, spec_max=None, intensities_constrained=False, Save=False, Plot='None'): - StartTime('FuryFit Multi') + StartTime('FuryFit Multi') - nHist = mtd[inputWS].getNumberHistograms() - output_workspace = getWSprefix(inputWS) + 'fury_1Smult_s0_to_' + str(nHist-1) + nHist = mtd[inputWS].getNumberHistograms() + output_workspace = getWSprefix(inputWS) + 'fury_1Smult_s0_to_' + str(nHist-1) - option = ftype[:-2] - logger.information('Option: '+option) - logger.information('Function: '+function) + option = ftype[:-2] + logger.information('Option: '+option) + logger.information('Function: '+function) - #prepare input workspace for fitting - tmp_fit_workspace = "__furyfit_fit_ws" - if spec_max is None: - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, - StartWorkspaceIndex=spec_min) - else: - CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, XMin=startx, XMax=endx, - StartWorkspaceIndex=spec_min, EndWorkspaceIndex=spec_max) + #prepare input workspace for fitting + tmp_fit_workspace = "__furyfit_fit_ws" + if spec_max is None: + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, + XMin=startx, XMax=endx, + StartWorkspaceIndex=spec_min) + else: + CropWorkspace(InputWorkspace=inputWS, OutputWorkspace=tmp_fit_workspace, + XMin=startx, XMax=endx, + StartWorkspaceIndex=spec_min, EndWorkspaceIndex=spec_max) - ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) - convertToElasticQ(tmp_fit_workspace) + ConvertToHistogram(tmp_fit_workspace, OutputWorkspace=tmp_fit_workspace) + convertToElasticQ(tmp_fit_workspace) - #fit multi-domian functino to workspace - multi_domain_func, kwargs = createFuryMultiDomainFunction(function, tmp_fit_workspace) - Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0, - Output=output_workspace, CreateOutput=True, **kwargs) + #fit multi-domian functino to workspace + multi_domain_func, kwargs = createFuryMultiDomainFunction(function, tmp_fit_workspace) + Fit(Function=multi_domain_func, InputWorkspace=tmp_fit_workspace, WorkspaceIndex=0, + Output=output_workspace, CreateOutput=True, **kwargs) - params_table = output_workspace + '_Parameters' - transposeFitParametersTable(params_table) + params_table = output_workspace + '_Parameters' + transposeFitParametersTable(params_table) - #set first column of parameter table to be axis values - ax = mtd[tmp_fit_workspace].getAxis(1) - axis_values = ax.extractValues() - for i, value in enumerate(axis_values): - mtd[params_table].setCell('axis-1', i, value) + #set first column of parameter table to be axis values + x_axis = mtd[tmp_fit_workspace].getAxis(1) + axis_values = x_axis.extractValues() + for i, value in enumerate(axis_values): + mtd[params_table].setCell('axis-1', i, value) - #convert parameters to matrix workspace - result_workspace = output_workspace + "_Result" - parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] - convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) + #convert parameters to matrix workspace + result_workspace = output_workspace + "_Result" + parameter_names = ['A0', 'Intensity', 'Tau', 'Beta'] + convertParametersToWorkspace(params_table, "axis-1", parameter_names, result_workspace) - #set x units to be momentum transfer - axis = mtd[result_workspace].getAxis(0) - axis.setUnit("MomentumTransfer") + #set x units to be momentum transfer + axis = mtd[result_workspace].getAxis(0) + axis.setUnit("MomentumTransfer") - result_workspace = output_workspace + '_Result' - fit_group = output_workspace + '_Workspaces' + result_workspace = output_workspace + '_Result' + fit_group = output_workspace + '_Workspaces' - sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': ftype, - 'intensities_constrained': intensities_constrained, 'beta_constrained': True} + sample_logs = {'start_x': startx, 'end_x': endx, 'fit_type': ftype, + 'intensities_constrained': intensities_constrained, 'beta_constrained': True} - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) - CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=result_workspace) + CopyLogs(InputWorkspace=inputWS, OutputWorkspace=fit_group) - addSampleLogs(result_workspace, sample_logs) - addSampleLogs(fit_group, sample_logs) + addSampleLogs(result_workspace, sample_logs) + addSampleLogs(fit_group, sample_logs) - DeleteWorkspace(tmp_fit_workspace) + DeleteWorkspace(tmp_fit_workspace) - if Save: - save_workspaces = [result_workspace] - furyFitSaveWorkspaces(save_workspaces) + if Save: + save_workspaces = [result_workspace] + furyFitSaveWorkspaces(save_workspaces) - if Plot != 'None': - furyfitPlotSeq(result_workspace, Plot) + if Plot != 'None': + furyfitPlotSeq(result_workspace, Plot) - EndTime('FuryFit Multi') - return result_workspace + EndTime('FuryFit Multi') + return result_workspace def createFuryMultiDomainFunction(function, input_ws): - multi= 'composite=MultiDomainFunction,NumDeriv=1;' - comp = '(composite=CompositeFunction,$domains=i;' + function + ');' + multi= 'composite=MultiDomainFunction,NumDeriv=true;' + comp = '(composite=CompositeFunction,NumDeriv=true,$domains=i;' + function + ');' - ties = [] - kwargs = {} - num_spectra = mtd[input_ws].getNumberHistograms() - for i in range(0, num_spectra): - multi += comp - kwargs['WorkspaceIndex_' + str(i)] = i + ties = [] + kwargs = {} + num_spectra = mtd[input_ws].getNumberHistograms() + for i in range(0, num_spectra): + multi += comp + kwargs['WorkspaceIndex_' + str(i)] = i - if i > 0: - kwargs['InputWorkspace_' + str(i)] = input_ws + if i > 0: + kwargs['InputWorkspace_' + str(i)] = input_ws - #tie beta for every spectrum - tie = 'f%d.f1.Beta=f0.f1.Beta' % i - ties.append(tie) + #tie beta for every spectrum + tie = 'f%d.f1.Beta=f0.f1.Beta' % i + ties.append(tie) - ties = ','.join(ties) - multi += 'ties=(' + ties + ')' + ties = ','.join(ties) + multi += 'ties=(' + ties + ')' - return multi, kwargs + return multi, kwargs def furyFitSaveWorkspaces(save_workspaces): - workdir = getDefaultWorkingDirectory() - for ws in save_workspaces: - #save workspace to default directory - fpath = os.path.join(workdir, ws+'.nxs') - SaveNexusProcessed(InputWorkspace=ws, Filename=fpath) - logger.information(ws + ' output to file : '+fpath) + workdir = getDefaultWorkingDirectory() + for workspace in save_workspaces: + #save workspace to default directory + fpath = os.path.join(workdir, workspace+'.nxs') + SaveNexusProcessed(InputWorkspace=workspace, Filename=fpath) + logger.information(workspace + ' output to file : '+fpath) def furyfitPlotSeq(ws, plot): @@ -347,12 +333,12 @@ def furyfitPlotSeq(ws, plot): ############################################################################## def msdfitPlotSeq(inputWS, xlabel): - ws = mtd[inputWS+'_A1'] - if len(ws.readX(0)) > 1: - msd_plot = mp.plotSpectrum(inputWS+'_A1',0,True) + workspace = mtd[inputWS + '_A1'] + if len(workspace.readX(0)) > 1: + msd_plot = MTD_PLOT.plotSpectrum(inputWS+'_A1',0,True) msd_layer = msd_plot.activeLayer() - msd_layer.setAxisTitle(mp.Layer.Bottom,xlabel) - msd_layer.setAxisTitle(mp.Layer.Left,'') + msd_layer.setAxisTitle(MTD_PLOT.Layer.Bottom,xlabel) + msd_layer.setAxisTitle(MTD_PLOT.Layer.Left,'') def msdfit(ws, startX, endX, spec_min=0, spec_max=None, Save=False, Plot=True): StartTime('msdFit') @@ -438,13 +424,13 @@ def plotInput(inputfiles,spectra=[]): spectra = [spectra[0], spectra[0]] OneSpectra = True workspaces = [] - for file in inputfiles: - root = LoadNexus(Filename=file) + for in_file in inputfiles: + root = LoadNexus(Filename=in_file) if not OneSpectra: GroupDetectors(root, root, DetectorList=range(spectra[0],spectra[1]+1) ) workspaces.append(root) if len(workspaces) > 0: - graph = mp.plotSpectrum(workspaces,0) + graph = MTD_PLOT.plotSpectrum(workspaces,0) graph.activeLayer().setTitle(", ".join(workspaces)) ############################################################################## @@ -461,9 +447,9 @@ def CubicFit(inputWS, spec): fit = Fit(Function=function, InputWorkspace=inputWS, WorkspaceIndex=spec, CreateOutput=True, Output='Fit') table = mtd['Fit_Parameters'] - A0 = table.cell(0,1) - A1 = table.cell(1,1) - A2 = table.cell(2,1) + A0 = table.cell(0, 1) + A1 = table.cell(1, 1) + A2 = table.cell(2, 1) Abs = [A0, A1, A2] logger.information('Group '+str(spec)+' of '+inputWS+' ; fit coefficients are : '+str(Abs)) return Abs @@ -504,15 +490,14 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): ConvertUnits(InputWorkspace=inputWS, OutputWorkspace=inputWS, Target='Wavelength') else: efixed = getEfixed(inputWS) # Get efixed - theta, Q = GetThetaQ(inputWS) + Q = GetThetaQ(inputWS)[1] ConvertUnits(InputWorkspace=inputWS, OutputWorkspace=inputWS, Target='Wavelength', EMode='Indirect', EFixed=efixed) sam_name = getWSprefix(inputWS) - nameStem = corr[:-4] corrections = mtd[corr].getNames() if mtd.doesExist(canWS): - (instr, can_run) = getInstrRun(canWS) + can_run = getInstrRun(canWS)[1] CorrectedWS = sam_name +'Correct_'+ can_run if diffraction_run: @@ -525,9 +510,9 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): nHist = mtd[inputWS].getNumberHistograms() # Check that number of histograms in each corrections workspace matches # that of the input (sample) workspace - for ws in corrections: - if ( mtd[ws].getNumberHistograms() != nHist ): - raise ValueError('Mismatch: num of spectra in '+ws+' and inputWS') + for workspace in corrections: + if mtd[workspace].getNumberHistograms() != nHist: + raise ValueError('Mismatch: num of spectra in '+workspace+' and inputWS') # Workspaces that hold intermediate results CorrectedSampleWS = '__csam' CorrectedCanWS = '__ccan' @@ -537,7 +522,8 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): logger.information(str(i) + str(mtd[CorrectedSampleWS].readX(0))) if len(corrections) == 1: Ass = CubicFit(corrections[0], i) - PolynomialCorrection(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedSampleWS, + PolynomialCorrection(InputWorkspace=CorrectedSampleWS, + OutputWorkspace=CorrectedSampleWS, Coefficients=Ass, Operation='Divide') if i == 0: CloneWorkspace(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedWS) @@ -554,11 +540,13 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): PolynomialCorrection(InputWorkspace=CorrectedCanWS, OutputWorkspace=CorrectedCanWS, Coefficients=Acsc, Operation='Multiply') - subractCanWorkspace(CorrectedSampleWS, CorrectedCanWS, CorrectedSampleWS, rebin_can=rebin_can) + subractCanWorkspace(CorrectedSampleWS, CorrectedCanWS, + CorrectedSampleWS, rebin_can=rebin_can) Assc = CubicFit(corrections[1], i) - PolynomialCorrection(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedSampleWS, - Coefficients=Assc, Operation='Divide') + PolynomialCorrection(InputWorkspace=CorrectedSampleWS, + OutputWorkspace=CorrectedSampleWS, + Coefficients=Assc, Operation='Divide') if i == 0: CloneWorkspace(InputWorkspace=CorrectedSampleWS, OutputWorkspace=CorrectedWS) else: @@ -604,7 +592,7 @@ def applyCorrections(inputWS, canWS, corr, rebin_can=False): return CorrectedWS -def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, ScaleOrNotToScale=False, factor=1, Save=False, +def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, ScaleOrNotToScale=False, factor=1, Save=False,\ PlotResult='None', PlotContrib=False): ''' Load up the necessary files and then passes them into the main @@ -613,7 +601,7 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S StartTime('ApplyCorrections') workdir = config['defaultsave.directory'] - s_hist,sxlen = CheckHistZero(sample) + s_hist = CheckHistZero(sample)[0] CloneWorkspace(sample, OutputWorkspace='__apply_corr_cloned_sample') sample = '__apply_corr_cloned_sample' @@ -635,11 +623,12 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S if diffraction_run and not checkUnitIs(container, 'dSpacing'): raise ValueError("Sample and Can must both have the same units.") - (instr, can_run) = getInstrRun(container) + can_run = getInstrRun(container)[1] if ScaleOrNotToScale: - #use temp workspace so we don't modify original data - Scale(InputWorkspace=container, OutputWorkspace=scaled_container, Factor=factor, Operation='Multiply') + # Use temp workspace so we don't modify original data + Scale(InputWorkspace=container, OutputWorkspace=scaled_container, + Factor=factor, Operation='Multiply') logger.information('Container scaled by %f' % factor) else: @@ -659,7 +648,6 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S cred_path = os.path.join(workdir,cor_result + ext + '.nxs') SaveNexusProcessed(InputWorkspace=cor_result + ext, Filename=cred_path) logger.information('Output file created : '+cred_path) - calc_plot = [cor_result + ext, sample] if not diffraction_run: res_plot = cor_result + '_rqw' @@ -676,7 +664,7 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S subractCanWorkspace(sample, scaled_container, sub_result, rebin_can=RebinCan) if not diffraction_run: - ConvertSpectrumAxis(InputWorkspace=sub_result, OutputWorkspace=sub_result+'_rqw', + ConvertSpectrumAxis(InputWorkspace=sub_result, OutputWorkspace=sub_result+'_rqw',\ Target='ElasticQ', EMode='Indirect', EFixed=efixed) red_ws_name = sub_result + '_red' @@ -721,7 +709,8 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S fout = outNm + str(i) CreateWorkspace(OutputWorkspace=fout, DataX=dataX, DataY=dataY, DataE=dataE, - Nspec=3, UnitX=x_unit, VerticalAxisUnit='Text', VerticalAxisValues=names) + Nspec=3, UnitX=x_unit, VerticalAxisUnit='Text', + VerticalAxisValues=names) if i == 0: group = fout @@ -735,7 +724,7 @@ def abscorFeeder(sample, container, geom, useCor, corrections, RebinCan=False, S if Save: res_path = os.path.join(workdir,outNm[:-1] + '.nxs') SaveNexusProcessed(InputWorkspace=outNm[:-1], Filename=res_path) - logger.information('Output file created : '+res_path) + logger.information('Output file created : ' + res_path) DeleteWorkspace(cws) @@ -751,11 +740,11 @@ def plotCorrResult(inWS, PlotResult): plot_list = [] for i in range(0, nHist): plot_list.append(i) - res_plot=mp.plotSpectrum(inWS, plot_list) + MTD_PLOT.plotSpectrum(inWS, plot_list) if PlotResult == 'Contour' or PlotResult == 'Both': if nHist >= 5: #needs at least 5 hists for a contour - mp.importMatrixWorkspace(inWS).plotGraph2D() + MTD_PLOT.importMatrixWorkspace(inWS).plotGraph2D() def plotCorrContrib(plot_list, n): - con_plot = mp.plotSpectrum(plot_list, n) + MTD_PLOT.plotSpectrum(plot_list, n) diff --git a/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py b/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py index f41533106ec1..af6f9f98bd8b 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py +++ b/Code/Mantid/scripts/Inelastic/IndirectDiffractionReduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import mantid from msg_reducer import MSGReducer import inelastic_indirect_reduction_steps as steps @@ -68,5 +69,6 @@ def getStringProperty(workspace, property): inst = mantid.AnalysisDataService[workspace].getInstrument() try: prop = inst.getStringParameter(property)[0] - except IndexError: return "" + except IndexError: + return "" return prop diff --git a/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py b/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py index c295b1c277de..efee01eca620 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py +++ b/Code/Mantid/scripts/Inelastic/IndirectEnergyConversion.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * from IndirectCommon import * from IndirectImport import import_mantidplot @@ -6,7 +7,7 @@ import inelastic_indirect_reducer import sys, os.path, numpy as np -def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1, +def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1,\ Suffix=''): workspaces = [] for file in rawfiles: @@ -16,7 +17,7 @@ def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1, if ( SpecMin == -1 ) and ( SpecMax == -1 ): Load(Filename=file, OutputWorkspace=name+Suffix, LoadLogFiles=False) else: - Load(Filename=file, OutputWorkspace=name+Suffix, SpectrumMin=SpecMin, + Load(Filename=file, OutputWorkspace=name+Suffix, SpectrumMin=SpecMin,\ SpectrumMax=SpecMax, LoadLogFiles=False) workspaces.append(name+Suffix) except ValueError, message: @@ -33,8 +34,10 @@ def loadData(rawfiles, outWS='RawFile', Sum=False, SpecMin=-1, SpecMax=-1, return workspaces def createMappingFile(groupFile, ngroup, nspec, first): - if ( ngroup == 1 ): return 'All' - if ( nspec == 1 ): return 'Individual' + if ngroup == 1: + return 'All' + if nspec == 1: + return 'Individual' filename = config['defaultsave.directory'] filename = os.path.join(filename, groupFile) handle = open(filename, 'w') @@ -85,7 +88,7 @@ def getInstrumentDetails(instrument): if j < ( len(reflections[i][1]) -1 ): message += ',' result += message - if ( i < ( len(reflections) - 1) ): + if i < ( len(reflections) - 1) : result += '\n' return result diff --git a/Code/Mantid/scripts/Inelastic/IndirectImport.py b/Code/Mantid/scripts/Inelastic/IndirectImport.py index 34cf8d8e99f4..e88d525831ce 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectImport.py +++ b/Code/Mantid/scripts/Inelastic/IndirectImport.py @@ -1,16 +1,19 @@ -''' Temporary solutions to the messy problem of importing F2Py libraries into +""" +Temporary solutions to the messy problem of importing F2Py libraries into the Indirect scripts depending on platform and numpy package version. We also deal with importing the mantidplot module outside of MantidPlot here. -''' +""" import numpy import platform import sys from mantid import logger + def import_mantidplot(): - ''' Currently, all scripts in the PythonAlgorithms directory are imported + """ + Currently, all scripts in the PythonAlgorithms directory are imported during system tests. Unfortunately, these tests are run outside of MantidPlot and so are incompatible with scripts that import the "mantidplot" module. As a result, an error message is dumped to the @@ -20,7 +23,7 @@ def import_mantidplot(): Here, we silently catch all ImportErrors so that this does not occur. @returns the mantidplot module. - ''' + """ try: import mantidplot return mantidplot @@ -29,9 +32,11 @@ def import_mantidplot(): # scripts are not needed there. return None + def _os_env(): return platform.system() + platform.architecture()[0] + def _lib_suffix(): if platform.system() == "Windows": suffix = "win" @@ -41,37 +46,37 @@ def _lib_suffix(): return "" return "_" + suffix + platform.architecture()[0][0:2] + def _numpy_ver(): - return numpy.version.short_version + """ + Gets the version of Numpy installed on the host system. -def _linux_distro_name(): - return platform.linux_distribution()[0] + @return Version number + """ + return numpy.version.short_version -def _linux_distro_version(): - return platform.linux_distribution()[1] def unsupported_message(): logger.error('F2Py functionality not currently available on your platform.') sys.exit() + def is_supported_f2py_platform(): - ''' We check for numpy version, as if Linux we check its distro and version + """ + We check for numpy version, as if Linux we check its distro and version as well. @returns True if we are currently on a platform that supports the F2Py libraries, else False. - ''' + """ if _os_env().startswith("Windows") and _numpy_ver() == "1.6.2": return True - #if _os_env() == "Linux64bit" and \ - # _linux_distro_name()[0:24] == "Red Hat Enterprise Linux" and \ - # _linux_distro_version() == "6.2" and \ - # _numpy_ver() == "1.3.0": - # return True return False + def import_f2py(lib_base_name): - ''' Until we can include the compilation process of Indirect F2Py modules + """ + Until we can include the compilation process of Indirect F2Py modules into the automated build of Mantid, we are forced to compile the libraries separately on every platform we wish to support. @@ -83,7 +88,7 @@ def import_f2py(lib_base_name): of "QLres". @returns the imported module. - ''' + """ # Only proceed if we are indeed on one of the supported platforms. assert is_supported_f2py_platform() @@ -91,9 +96,11 @@ def import_f2py(lib_base_name): return __import__(lib_name) + def run_f2py_compatibility_test(): - ''' Convenience method that raises an exception should a user try to run + """ + Convenience method that raises an exception should a user try to run the F2Py libraries on an incompatible platform. - ''' + """ if not is_supported_f2py_platform(): raise RuntimeError("F2Py programs NOT available on this platform.") diff --git a/Code/Mantid/scripts/Inelastic/IndirectMuscat.py b/Code/Mantid/scripts/Inelastic/IndirectMuscat.py index e20601e39e48..99cd2f969532 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectMuscat.py +++ b/Code/Mantid/scripts/Inelastic/IndirectMuscat.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # MUSIC : Version of Minus for MIDAS from IndirectImport import * @@ -18,19 +19,19 @@ def CalcW0(nq,dq,disp,coeff): w0 = [] e0 = [] for n in range(0,nq): - q0 = (n+1)*dq - Q.append(q0) - q02 = q0*q0 - Q2.append(q02) - if (disp == 'Poly'): - w = coeff[0]+coeff[1]*q0+coeff[2]*q02+coeff[3]*q0*q02+coeff[4]*q02*q02 - if (disp == 'CE'): - qk = coeff[1]*q0 - w = coeff[0]*(1.0-math.sin(qk)/qk) - if (disp == 'SS'): - w0 = coeff[0]*(1.0-math.exp(coeff[1]*q02)) - w0.append(w*0.001) #convert from mmeV to meV - e0.append(0.0) + q0 = (n+1)*dq + Q.append(q0) + q02 = q0*q0 + Q2.append(q02) + if disp == 'Poly': + w = coeff[0]+coeff[1]*q0+coeff[2]*q02+coeff[3]*q0*q02+coeff[4]*q02*q02 + if disp == 'CE': + qk = coeff[1]*q0 + w = coeff[0]*(1.0-math.sin(qk)/qk) + if disp == 'SS': + w0 = coeff[0]*(1.0-math.exp(coeff[1]*q02)) + w0.append(w*0.001) #convert from mmeV to meV + e0.append(0.0) return Q,w0,e0 def CalcSqw(q0,nw2,nel,dw,w0): @@ -41,69 +42,69 @@ def CalcSqw(q0,nw2,nel,dw,w0): nq = len(q0) Qaxis = '' for i in range(0,nq): - ww0 = w0[i] - for j in range(0,nw2): + ww0 = w0[i] + for j in range(0,nw2): # S(I,J)=S(I,J)+PKHT*W0(I)/(W0(I)**2+W**2) !Lorentzian S(Q,w) - ww = (j-nel)*dw - xSqw.append(ww) #convert to microeV - ss = PKHT*ww0/(ww0**2+ww**2) - ySqw.append(ss) - eSqw.append(0.0) - if i == 0: - Qaxis += str(q0[i]) - else: - Qaxis += ','+str(q0[i]) - CreateWorkspace(OutputWorkspace='S(Q,w)', DataX=xSqw, DataY=ySqw, DataE=eSqw, + ww = (j-nel)*dw + xSqw.append(ww) #convert to microeV + ss = PKHT*ww0/(ww0**2+ww**2) + ySqw.append(ss) + eSqw.append(0.0) + if i == 0: + Qaxis += str(q0[i]) + else: + Qaxis += ','+str(q0[i]) + CreateWorkspace(OutputWorkspace='S(Q,w)', DataX=xSqw, DataY=ySqw, DataE=eSqw,\ Nspec=nq, UnitX='DeltaE', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) def CheckCoeff(disp,coeff): if (disp == 'CE') or (disp == 'SS'): - if coeff[0] < 1e-8: - error = disp + ' coeff 1 is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) - if coeff[1] < 1e-8: - error = disp + ' coeff 2 is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) - if (disp == 'Poly'): - cc = coeff[0]+coeff[1]+coeff[2]+coeff[3]+coeff[4] - if cc < 1e-8: - error = 'Poly coeffs all zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + if coeff[0] < 1e-8: + error = disp + ' coeff 1 is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) + if coeff[1] < 1e-8: + error = disp + ' coeff 2 is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) + if disp == 'Poly': + cc = coeff[0]+coeff[1]+coeff[2]+coeff[3]+coeff[4] + if cc < 1e-8: + error = 'Poly coeffs all zero' + logger.notice('ERROR *** '+error) + sys.exit(error) def CheckQw(grid): nq = grid[0] if nq == 0: - error = 'Grid : Number of Q values is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Grid : Number of Q values is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) nw = grid[2] if nw == 0: - error = 'Grid : Number of w values is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Grid : Number of w values is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) dq = grid[1] if dq < 1e-5: - error = 'Grid : Q increment is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Grid : Q increment is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) dw = grid[3]*0.001 if dw < 1e-8: - error = 'Grid : w increment is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Grid : w increment is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) return nq,dq,nw,dw def CreateSqw(disp,coeff,grid,Verbose): CheckCoeff(disp,coeff) if Verbose: - logger.notice('Dispersion is '+disp) - logger.notice('Coefficients : '+str(coeff)) + logger.notice('Dispersion is '+disp) + logger.notice('Coefficients : '+str(coeff)) nq,dq,nw,dw = CheckQw(grid) q0,w0,e0 = CalcW0(nq,dq,disp,coeff) - CreateWorkspace(OutputWorkspace=disp, DataX=q0, DataY=w0, DataE=e0, + CreateWorkspace(OutputWorkspace=disp, DataX=q0, DataY=w0, DataE=e0,\ Nspec=1, UnitX='MomentumTransfer') nw2 = 2*nw+1 nel= nw+1 @@ -115,77 +116,77 @@ def ReadSqw(sqw,Verbose): axis = mtd[sqw].getAxis(1) Q = [] for i in range(0,nq): - Q.append(float(axis.label(i))) + Q.append(float(axis.label(i))) Q_in = PadArray(Q,500) Sqw_in = [] for n in range(0,nq): - Xw = mtd[sqw].readX(n) # energy array - Ys = mtd[sqw].readY(n) # S(q,w) values - Ys = PadArray(Ys,1000) # pad to Fortran energy size 1000 - Sqw_in.append(Ys) + Xw = mtd[sqw].readX(n) # energy array + Ys = mtd[sqw].readY(n) # S(q,w) values + Ys = PadArray(Ys,1000) # pad to Fortran energy size 1000 + Sqw_in.append(Ys) dw = Xw[2]-Xw[1] if dw < 1e-8: - error = 'Sqw : w increment is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Sqw : w increment is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) nel= nw+1 for n in range(0,nw): - if (Xw[n] < dw): - nel = n + if Xw[n] < dw: + nel = n dq = Q[1]-Q[0] if dq < 1e-5: - error = 'Sqw : Q increment is zero' - logger.notice('ERROR *** '+error) - sys.exit(error) + error = 'Sqw : Q increment is zero' + logger.notice('ERROR *** '+error) + sys.exit(error) if Verbose: - logger.notice('Q : '+str(nq)+' points from '+str(Q[0])+' to '+str(Q[nq-1])+' at '+str(dq)) - logger.notice('w : '+str(nw)+' points from '+str(Xw[0])+' to '+str(Xw[nw])+' at '+str(dw) + logger.notice('Q : '+str(nq)+' points from '+str(Q[0])+' to '+str(Q[nq-1])+' at '+str(dq)) + logger.notice('w : '+str(nw)+' points from '+str(Xw[0])+' to '+str(Xw[nw])+' at '+str(dw)\ +' ; Elastic energy at : '+str(nel)) X0 = [] X0 = PadArray(X0,1000) # zeroes for n in range(nq,500): # pad to Fortran Q size 500 - Sqw_in.append(X0) + Sqw_in.append(X0) return nq,dq,Q_in,nw,dw,nel,Xw,Sqw_in def CheckNeut(neut): # neut = [NRUN1, NRUN2, JRAND, MRAND, NMST] if neut[0] == 0: - error = 'NRUN1 is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'NRUN1 is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) if neut[1] == 0: - error = 'NRUN2 is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'NRUN2 is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) if neut[4] == 0: - error = 'Number scatterings is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Number scatterings is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) def CheckBeam(beam): # beam = [THICK, WIDTH, HEIGHT, alfa] if beam[0] <1e-5: - error = 'Beam thickness is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Beam thickness is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) if beam[1] <1e-5: - error = 'Beam width is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Beam width is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) if beam[2] <1e-5: - error = 'Beam height is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Beam height is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) def CheckSam(sam): if sam[1] <1e-8: - error = 'Sample density is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Sample density is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) if (sam[2]+sam[3]) <1e-8: - error = 'Sample total scattering cross-section (scat+abs) is Zero' - logger.notice('ERROR *** ' + error) - sys.exit(error) + error = 'Sample total scattering cross-section (scat+abs) is Zero' + logger.notice('ERROR *** ' + error) + sys.exit(error) def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): # neut = [NRUN1, NRUN2, JRAND, MRAND, NMST] @@ -203,23 +204,23 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): # ijeom = [jeom, Jann] Jann = 1 if geom == 'Flat': - ijeom = [2, Jann] + ijeom = [2, Jann] if geom == 'Cyl': - ijeom = [3, Jann] + ijeom = [3, Jann] # rgeom = [thick, width, height] rgeom = [beam[0], beam[1], beam[2]] nran = [neut[0], neut[1], neut[2], neut[3]] lpt = os.path.join(workdir, sname[:-3]+geom+'_ms.lpt') # path name for lpt file if Verbose: - logger.notice('Detectors/angles : '+str(mang)) - logger.notice('Sample geometry : '+geom) - logger.notice('Sample parameters') - logger.notice(' sigs = '+str(sam[3])+' ; siga = '+str(sam[1])+' ; rho = '+str(sam[0])) - if geom == 'Cyl': - logger.notice(' inner radius = '+str(beam[0])+' ; outer radius = '+str(beam[1])) - if geom == 'Flat': - logger.notice(' thickness = '+str(beam[0])) - logger.notice('Output lptfile : ' + lpt) + logger.notice('Detectors/angles : '+str(mang)) + logger.notice('Sample geometry : '+geom) + logger.notice('Sample parameters') + logger.notice(' sigs = '+str(sam[3])+' ; siga = '+str(sam[1])+' ; rho = '+str(sam[0])) + if geom == 'Cyl': + logger.notice(' inner radius = '+str(beam[0])+' ; outer radius = '+str(beam[1])) + if geom == 'Flat': + logger.notice(' thickness = '+str(beam[0])) + logger.notice('Output lptfile : ' + lpt) llpt = len(lpt) lpt.ljust(140,' ') lsqw = len(sqw) @@ -235,49 +236,49 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): Qaxis = '' for m in range(0,mang): # rinstr = [efixed, theta, alfa] - rinstr = [efixed, angle[m], beam[3]] - logger.notice('Detector ' +str(m+1)+ ' at angle ' +str(angle[m])+ ' and Q = ' +str(QQ[m])) + rinstr = [efixed, angle[m], beam[3]] + logger.notice('Detector ' +str(m+1)+ ' at angle ' +str(angle[m])+ ' and Q = ' +str(QQ[m])) # SUBROUTINE MUSCAT_data(IDET,sfile,l_sf,rfile,l_rf,rinstr,nran, # 1 ijeom,rgeom,sam,ims,dqw,Q_in,S_in, # 2 totals,iw,energy,scat1,scatm,RR,S_out) - idet = m+1 - kill,totals,iw,energy,scat1,scatm,RR,Sqw=muscat.muscat_data(idet,lpt,llpt,sqw,lsqw,rinstr,nran, + idet = m+1 + kill,totals,iw,energy,scat1,scatm,RR,Sqw=muscat.muscat_data(idet,lpt,llpt,sqw,lsqw,rinstr,nran,\ ijeom,rgeom,sam,ims,dqw,Q_in,Sqw_in) - if (kill != 0): - error = 'Muscat error code : '+str(kill) - logger.notice(error) - sys.exit(error) - else: - xEn = energy[:iw] - xEn = np.append(xEn,2*energy[iw-1]-energy[iw-2]) - ySc1 = scat1[:iw] # single scattering energy distribution - yScM = scatm[:iw] # total scattering energy distribution - yRr = RR[:iw] # R-factor energy distribution - if m == 0: - tot1 = np.array(totals[1]) # total single scattering - tot2 = np.array(totals[2]) # total second scattering - tot3 = np.array(totals[3]) # total third scattering - total = np.array(totals[4]) # total all scattering - xMs = xEn - yMsc1 = ySc1 - yMscM = yScM - yMr = yRr - else: - tot1 = np.append(tot1,totals[1]) - tot2 = np.append(tot2,totals[2]) - tot3 = np.append(tot3,totals[3]) - total = np.append(total,totals[4]) - xMs = np.append(xMs,xEn) - yMsc1 = np.append(yMsc1,ySc1) - yMscM = np.append(yMscM,yScM) - yMr = np.append(yMr,yRr) - Qaxis += ',' - Qaxis += str(QQ[m]) + if kill != 0: + error = 'Muscat error code : '+str(kill) + logger.notice(error) + sys.exit(error) + else: + xEn = energy[:iw] + xEn = np.append(xEn,2*energy[iw-1]-energy[iw-2]) + ySc1 = scat1[:iw] # single scattering energy distribution + yScM = scatm[:iw] # total scattering energy distribution + yRr = RR[:iw] # R-factor energy distribution + if m == 0: + tot1 = np.array(totals[1]) # total single scattering + tot2 = np.array(totals[2]) # total second scattering + tot3 = np.array(totals[3]) # total third scattering + total = np.array(totals[4]) # total all scattering + xMs = xEn + yMsc1 = ySc1 + yMscM = yScM + yMr = yRr + else: + tot1 = np.append(tot1,totals[1]) + tot2 = np.append(tot2,totals[2]) + tot3 = np.append(tot3,totals[3]) + total = np.append(total,totals[4]) + xMs = np.append(xMs,xEn) + yMsc1 = np.append(yMsc1,ySc1) + yMscM = np.append(yMscM,yScM) + yMr = np.append(yMr,yRr) + Qaxis += ',' + Qaxis += str(QQ[m]) # start output of Totals totx = [angle[0]] tote = np.zeros(mang) for m in range(1,mang): - totx = np.append(totx,angle[m]) + totx = np.append(totx,angle[m]) nt = 1 Taxis = 'Scat1' xTot = totx @@ -285,19 +286,19 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): eTot = tote spec_list = [nt-1] if nmst > 1: - nt += 1 - spec_list.append(nt-1) - Taxis += ',Scat2' - xTot = np.append(xTot,totx) - yTot = np.append(yTot,tot2) - eTot = np.append(eTot,tote) - if nmst > 2: - nt += 1 - spec_list.append(nt-1) - Taxis += ',Scat3' - xTot = np.append(xTot,totx) - yTot = np.append(yTot,tot3) - eTot = np.append(eTot,tote) + nt += 1 + spec_list.append(nt-1) + Taxis += ',Scat2' + xTot = np.append(xTot,totx) + yTot = np.append(yTot,tot2) + eTot = np.append(eTot,tote) + if nmst > 2: + nt += 1 + spec_list.append(nt-1) + Taxis += ',Scat3' + xTot = np.append(xTot,totx) + yTot = np.append(yTot,tot3) + eTot = np.append(eTot,tote) xTot = np.append(xTot,totx) yTot = np.append(yTot,total) eTot = np.append(eTot,tote) @@ -310,30 +311,30 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): logger.notice('yTot : ' + str(len(yTot))) logger.notice('eTot : ' + str(len(eTot))) msname = sname+'_MS' - CreateWorkspace(OutputWorkspace=msname+'_Totals', DataX=xTot, DataY=yTot, DataE=eTot, + CreateWorkspace(OutputWorkspace=msname+'_Totals', DataX=xTot, DataY=yTot, DataE=eTot,\ Nspec=nt, UnitX='MomentumTransfer') # Nspec=nt, UnitX='MomentumTransfer', VerticalAxisUnit='Text', VerticalAxisValues='Taxis') # start output of MultScat eMs = np.zeros(iw*mang) - CreateWorkspace(OutputWorkspace=msname+'_1', DataX=xMs, DataY=yMsc1, DataE=eMs, + CreateWorkspace(OutputWorkspace=msname+'_1', DataX=xMs, DataY=yMsc1, DataE=eMs,\ Nspec=mang, UnitX='DeltaE', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) - CreateWorkspace(OutputWorkspace=msname+'_M', DataX=xMs, DataY=yMscM, DataE=eMs, + CreateWorkspace(OutputWorkspace=msname+'_M', DataX=xMs, DataY=yMscM, DataE=eMs,\ Nspec=mang, UnitX='DeltaE', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) - CreateWorkspace(OutputWorkspace=msname+'_R', DataX=xMs, DataY=yMr, DataE=eMs, + CreateWorkspace(OutputWorkspace=msname+'_R', DataX=xMs, DataY=yMr, DataE=eMs,\ Nspec=mang, UnitX='DeltaE', VerticalAxisUnit='MomentumTransfer', VerticalAxisValues=Qaxis) group = msname+'_1,'+ msname+'_M,'+ msname+'_R' GroupWorkspaces(InputWorkspaces=group,OutputWorkspace=msname+'_Scat') # start output if Save: - tot_path = os.path.join(workdir,msname+'_Totals.nxs') - SaveNexusProcessed(InputWorkspace=msname+'_Totals', Filename=tot_path) - scat_path = os.path.join(workdir,msname+'_Scat.nxs') - SaveNexusProcessed(InputWorkspace=msname+'_Scat', Filename=scat_path) - if Verbose: - logger.notice('Output total scattering file : ' + tot_path) - logger.notice('Output MS scattering file : ' + scat_path) + tot_path = os.path.join(workdir,msname+'_Totals.nxs') + SaveNexusProcessed(InputWorkspace=msname+'_Totals', Filename=tot_path) + scat_path = os.path.join(workdir,msname+'_Scat.nxs') + SaveNexusProcessed(InputWorkspace=msname+'_Scat', Filename=scat_path) + if Verbose: + logger.notice('Output total scattering file : ' + tot_path) + logger.notice('Output MS scattering file : ' + scat_path) if Plot: - plotMuscat(msname,spec_list,Plot) + plotMuscat(msname,spec_list,Plot) def MuscatFuncStart(sname,geom,neut,beam,sam,grid,disp,coeff,kr1,Verbose,Plot,Save): StartTime('Muscat Function') @@ -344,8 +345,8 @@ def MuscatFuncStart(sname,geom,neut,beam,sam,grid,disp,coeff,kr1,Verbose,Plot,Sa sqw = 'S(Q,w)' CreateSqw(disp,coeff,grid,Verbose) if Verbose: - logger.notice('Sample run : '+spath) - logger.notice('S(Q,w) from : '+disp) + logger.notice('Sample run : '+spath) + logger.notice('S(Q,w) from : '+disp) MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save) EndTime('Muscat Function') @@ -359,13 +360,13 @@ def MuscatDataStart(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): qpath = os.path.join(workdir, sqw+'.nxs') # path name for S(Q,w) nxs file LoadNexusProcessed(FileName=qpath, OutputWorkspace=sqw) if Verbose: - logger.notice('Sample run : '+spath) - logger.notice('S(Q,w) file : '+qpath) + logger.notice('Sample run : '+spath) + logger.notice('S(Q,w) file : '+qpath) MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save) EndTime('Muscat Data') def plotMuscat(inWS,spec_list,Plot): - if (Plot == 'Totals' or Plot == 'All'): - tot_plot=mp.plotSpectrum(inWS+'_Totals',spec_list) - if (Plot == 'Scat1' or Plot == 'All'): - mp.importMatrixWorkspace(inWS+'_1').plotGraph2D() + if Plot == 'Totals' or Plot == 'All': + tot_plot=mp.plotSpectrum(inWS+'_Totals',spec_list) + if Plot == 'Scat1' or Plot == 'All': + mp.importMatrixWorkspace(inWS+'_1').plotGraph2D() diff --git a/Code/Mantid/scripts/Inelastic/IndirectNeutron.py b/Code/Mantid/scripts/Inelastic/IndirectNeutron.py index ca8becb04006..3ff569b788e9 100644 --- a/Code/Mantid/scripts/Inelastic/IndirectNeutron.py +++ b/Code/Mantid/scripts/Inelastic/IndirectNeutron.py @@ -1,12 +1,12 @@ +#pylint: disable=invalid-name #Force for ILL backscattering raw # from IndirectImport import * from mantid.simpleapi import * from mantid import config, logger, mtd, FileFinder -from mantid.kernel import V3D import sys, math, os.path, numpy as np from IndirectCommon import StartTime, EndTime, ExtractFloat, ExtractInt -mp = import_mantidplot() +MTD_PLOT = import_mantidplot() # Routines for Ascii file of raw data @@ -94,7 +94,7 @@ def ReadIbackGroup(a,first): #read Ascii block of spec def getFilePath(run,ext,instr): path = None fname = None - if(os.path.isfile(run)): + if os.path.isfile(run): #using full file path path = run #base name less extension @@ -212,7 +212,7 @@ def IbackStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): #Ascii s eOut.append(em[mm]/10.0) xMon.append(2*xMon[new-1]-xMon[new-2]) monWS = '__Mon' - CreateWorkspace(OutputWorkspace=monWS, DataX=xMon, DataY=yOut, DataE=eOut, + CreateWorkspace(OutputWorkspace=monWS, DataX=xMon, DataY=yOut, DataE=eOut,\ Nspec=1, UnitX='DeltaE') # Qaxis = '' @@ -223,7 +223,7 @@ def IbackStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): #Ascii s for n in range(0, nsp): next,xd,yd,ed = ReadIbackGroup(asc,next) tot.append(sum(yd)) - logger.information('Spectrum ' + str(n+1) +' at angle '+ str(theta[n])+ + logger.information('Spectrum ' + str(n+1) +' at angle '+ str(theta[n])+\ ' ; Total counts = '+str(sum(yd))) for m in range(0, new+1): mm = m+imin @@ -236,9 +236,9 @@ def IbackStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): #Ascii s Qaxis += str(theta[n]) ascWS = fname +'_' +ana+refl +'_asc' outWS = fname +'_' +ana+refl +'_red' - CreateWorkspace(OutputWorkspace=ascWS, DataX=xDat, DataY=yDat, DataE=eDat, + CreateWorkspace(OutputWorkspace=ascWS, DataX=xDat, DataY=yDat, DataE=eDat,\ Nspec=nsp, UnitX='DeltaE') - Divide(LHSWorkspace=ascWS, RHSWorkspace=monWS, OutputWorkspace=ascWS, + Divide(LHSWorkspace=ascWS, RHSWorkspace=monWS, OutputWorkspace=ascWS,\ AllowDifferentNumberSpectra=True) DeleteWorkspace(monWS) # delete monitor WS InstrParas(ascWS,instr,ana,refl) @@ -255,7 +255,7 @@ def IbackStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): #Ascii s opath = os.path.join(workdir,outWS+'.nxs') SaveNexusProcessed(InputWorkspace=outWS, Filename=opath) logger.information('Output file : ' + opath) - if (Plot): + if Plot: plotForce(outWS,Plot) EndTime('Iback') @@ -324,7 +324,7 @@ def InxStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): ns += 1 ascWS = fname +'_' +ana+refl +'_inx' outWS = fname +'_' +ana+refl +'_red' - CreateWorkspace(OutputWorkspace=ascWS, DataX=xDat, DataY=yDat, DataE=eDat, + CreateWorkspace(OutputWorkspace=ascWS, DataX=xDat, DataY=yDat, DataE=eDat,\ Nspec=ns, UnitX='DeltaE') InstrParas(ascWS,instr,ana,refl) efixed = RunParas(ascWS,instr,0,title) @@ -347,7 +347,7 @@ def InxStart(instr,run,ana,refl,rejectZ,useM,mapPath,Plot,Save): opath = os.path.join(workdir,outWS+'.nxs') SaveNexusProcessed(InputWorkspace=outWS, Filename=opath) logger.information('Output file : ' + opath) - if (Plot): + if Plot: plotForce(outWS,Plot) EndTime('Inx') @@ -359,12 +359,13 @@ def RejectZero(inWS,tot): outWS = inWS[:-3]+'red' for n in range(0, nin): if tot[n] > 0: - ExtractSingleSpectrum(InputWorkspace=inWS, OutputWorkspace='__tmp', + ExtractSingleSpectrum(InputWorkspace=inWS, OutputWorkspace='__tmp',\ WorkspaceIndex=n) if nout == 0: RenameWorkspace(InputWorkspace='__tmp', OutputWorkspace=outWS) else: - ConjoinWorkspaces(InputWorkspace1=outWS, InputWorkspace2='__tmp',CheckOverlapping=False) + ConjoinWorkspaces(InputWorkspace1=outWS, InputWorkspace2='__tmp', + CheckOverlapping=False) nout += 1 else: logger.information('** spectrum '+str(n+1)+' rejected') @@ -378,7 +379,7 @@ def ReadMap(path): logger.information('Map file : ' + path +' ; spectra = ' +str(lasc-1)) val = ExtractInt(asc[0]) numb = val[0] - if (numb != (lasc-1)): + if numb != (lasc-1): error = 'Number of lines not equal to number of spectra' logger.error(error) sys.exit(error) @@ -388,39 +389,40 @@ def ReadMap(path): map.append(val[1]) return map -def UseMap(inWS,map): +def UseMap(inWS, map): nin = mtd[inWS].getNumberHistograms() # no. of hist/groups in sam nout = 0 outWS = inWS[:-3]+'red' for n in range(0, nin): if map[n] == 1: - ExtractSingleSpectrum(InputWorkspace=inWS, OutputWorkspace='__tmp', + ExtractSingleSpectrum(InputWorkspace=inWS, OutputWorkspace='__tmp',\ WorkspaceIndex=n) if nout == 0: RenameWorkspace(InputWorkspace='__tmp', OutputWorkspace=outWS) else: - ConjoinWorkspaces(InputWorkspace1=outWS, InputWorkspace2='__tmp',CheckOverlapping=False) + ConjoinWorkspaces(InputWorkspace1=outWS, InputWorkspace2='__tmp', + CheckOverlapping=False) nout += 1 logger.information('** spectrum '+str(n+1)+' mapped') else: logger.information('** spectrum '+str(n+1)+' skipped') def plotForce(inWS,Plot): - if (Plot == 'Spectrum' or Plot == 'Both'): + if Plot == 'Spectrum' or Plot == 'Both': nHist = mtd[inWS].getNumberHistograms() if nHist > 10 : nHist = 10 plot_list = [] for i in range(0, nHist): plot_list.append(i) - res_plot=mp.plotSpectrum(inWS,plot_list) - if (Plot == 'Contour' or Plot == 'Both'): - cont_plot=mp.importMatrixWorkspace(inWS).plotGraph2D() + MTD_PLOT.plotSpectrum(inWS,plot_list) + if Plot == 'Contour' or Plot == 'Both': + MTD_PLOT.importMatrixWorkspace(inWS).plotGraph2D() def ChangeAngles(inWS,instr,theta): workdir = config['defaultsave.directory'] - file = instr+'_angles.txt' - path = os.path.join(workdir, file) + filename = instr+'_angles.txt' + path = os.path.join(workdir, filename) logger.information('Creating angles file : ' + path) handle = open(path, 'w') head = 'spectrum,theta' @@ -429,7 +431,7 @@ def ChangeAngles(inWS,instr,theta): handle.write(str(n+1) +' '+ str(theta[n]) +"\n" ) logger.information('Spectrum ' +str(n+1)+ ' = '+str(theta[n])) handle.close() - UpdateInstrumentFromFile(Workspace=inWS, Filename=path, MoveMonitors=False, IgnorePhi=False, + UpdateInstrumentFromFile(Workspace=inWS, Filename=path, MoveMonitors=False, IgnorePhi=False,\ AsciiHeader=head) def InstrParas(ws,instr,ana,refl): @@ -500,9 +502,9 @@ def IN13Read(instr,run,ana,refl,Plot,Save): #Ascii start routine logger.information('No. sub-spectra : ' + str(nsubsp)) logger.information('No. spectra : ' + str(nspec)) - logger.information('Scan type : ' + str(int(Fval[8]))+ + logger.information('Scan type : ' + str(int(Fval[8]))+\ ' ; Average energy : ' + str(Fval[9])) - logger.information('CaF2 lattice : ' + str(Fval[81])+ + logger.information('CaF2 lattice : ' + str(Fval[81])+\ ' ; Graphite lattice : ' + str(Fval[82])) logger.information('Wavelength : ' + str(wave)) logger.information('No. temperatures : ' + str(ntemp)) @@ -584,17 +586,17 @@ def IN13Read(instr,run,ana,refl,Plot,Save): #Ascii start routine xDq = np.append(xDq,sorted_Q) yDq = np.append(yDq,y1Dq) eDq = np.append(eDq,e1Dq) - CreateWorkspace(OutputWorkspace=ascWS, DataX=xData, DataY=yData, DataE=eData, + CreateWorkspace(OutputWorkspace=ascWS, DataX=xData, DataY=yData, DataE=eData,\ Nspec=3, UnitX='MomentumTransfer') IN13Paras(ascWS,run,title,wave) - CreateWorkspace(OutputWorkspace=outWS, DataX=xDq, DataY=yDq, DataE=eDq, + CreateWorkspace(OutputWorkspace=outWS, DataX=xDq, DataY=yDq, DataE=eDq,\ Nspec=3, UnitX='MomentumTransfer') IN13Paras(outWS,run,title,wave) if Save: opath = os.path.join(workdir,outWS+'.nxs') SaveNexusProcessed(InputWorkspace=outWS, Filename=opath) logger.information('Output file : ' + opath) - if (Plot != 'None'): + if Plot != 'None': plotForce(outWS,Plot) return outWS diff --git a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reducer.py b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reducer.py index 09561f344fc5..26702c6cd4bf 100644 --- a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reducer.py +++ b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reducer.py @@ -109,7 +109,7 @@ def _setup_steps(self): self.append_step(step) # The "SaveItem" step saves the files in the requested formats. - if (len(self._save_formats) > 0): + if len(self._save_formats) > 0: step = steps.SaveItem() step.set_formats(self._save_formats) step.set_save_to_cm_1(self._save_to_cm_1) diff --git a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py index 40e79d977176..70bec0c356c9 100644 --- a/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py +++ b/Code/Mantid/scripts/Inelastic/inelastic_indirect_reduction_steps.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name,no-init from reduction.reducer import ReductionStep import mantid @@ -34,6 +35,7 @@ class LoadData(ReductionStep): _data_files = {} _extra_load_opts = {} _contains_event_data = False + _reducer = None def __init__(self): """Initialise the ReductionStep. Constructor should set the initial @@ -67,7 +69,7 @@ def execute(self, reducer, file_ws): if ( self._sum ) and ( len(self._data_files) > 1 ): ## Sum files merges = [] - if ( self._multiple_frames ): + if self._multiple_frames : self._sum_chopped(wsname) else: self._sum_regular(wsname) @@ -116,14 +118,14 @@ def _load_single_file(self, filename, output_ws): # Quick hack for older BASIS files that only have one side #if (mtd[file].getRun()['run_number'] < 16693): # basis_mask = "BASIS_Mask_before_16693.xml" - basis_mask_filename = os.path.join(config.getString('maskFiles.directory') + basis_mask_filename = os.path.join(config.getString('maskFiles.directory')\ , basis_mask) if os.path.isfile(basis_mask_filename): - LoadMask(Instrument="BASIS", OutputWorkspace="__basis_mask", + LoadMask(Instrument="BASIS", OutputWorkspace="__basis_mask",\ InputFile=basis_mask_filename) - MaskDetectors(Workspace=output_ws, MaskedWorkspace="__basis_mask") + MaskDetectors(Workspace=output_ws, MaskedWorkspace="__basis_mask") else: - logger.notice("Couldn't find specified mask file : " + str(basis_mask_filename)) + logger.notice("Couldn't find specified mask file : " + str(basis_mask_filename)) if self._parameter_file != None: LoadParameterFile(Workspace=output_ws,Filename= self._parameter_file) @@ -131,14 +133,14 @@ def _load_single_file(self, filename, output_ws): self._monitor_index = self._reducer._get_monitor_index(mtd[output_ws]) if self._require_chop_data(output_ws): - ChopData(InputWorkspace=output_ws,OutputWorkspace= output_ws,Step= 20000.0,NChops= 5, IntegrationRangeLower=5000.0, - IntegrationRangeUpper=10000.0, + ChopData(InputWorkspace=output_ws,OutputWorkspace= output_ws,Step= 20000.0,NChops= 5, IntegrationRangeLower=5000.0,\ + IntegrationRangeUpper=10000.0,\ MonitorWorkspaceIndex=self._monitor_index) self._multiple_frames = True else: self._multiple_frames = False - if ( self._multiple_frames ): + if self._multiple_frames : workspaces = mtd[output_ws].getNames() else: workspaces = [output_ws] @@ -157,8 +159,8 @@ def _load_single_file(self, filename, output_ws): raise ValueError("Range %d - %d is not a valid detector range." % (self._detector_range_start, self._detector_range_end)) ## Crop the workspace to remove uninteresting detectors - CropWorkspace(InputWorkspace=ws,OutputWorkspace= ws, - StartWorkspaceIndex=self._detector_range_start, + CropWorkspace(InputWorkspace=ws,OutputWorkspace= ws,\ + StartWorkspaceIndex=self._detector_range_start,\ EndWorkspaceIndex=self._detector_range_end) def _load_data(self, filename, output_ws): @@ -225,7 +227,7 @@ def _require_chop_data(self, ws): 'Workflow.ChopDataIfGreaterThan')[0] except IndexError: return False - if ( mtd[ws].readX(0)[mtd[ws].blocksize()] > cdigt ): + if mtd[ws].readX(0)[mtd[ws].blocksize()] > cdigt : return True else: return False @@ -256,7 +258,7 @@ def __init__(self, MultipleFrames=False): def execute(self, reducer, file_ws): - if (self._multiple_frames): + if self._multiple_frames: try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -269,7 +271,7 @@ def execute(self, reducer, file_ws): except IndexError: msk = 'None' - if (msk != 'IdentifyNoisyDetectors'): + if msk != 'IdentifyNoisyDetectors': return temp_ws_mask = '__temp_ws_mask' @@ -278,7 +280,7 @@ def execute(self, reducer, file_ws): nhist = ws.getNumberHistograms() for i in range(0, nhist): - if (ws.readY(i)[0] == 0.0): + if ws.readY(i)[0] == 0.0: self._masking_detectors.append(i) DeleteWorkspace(Workspace=temp_ws_mask) @@ -306,7 +308,7 @@ def __init__(self, MultipleFrames=False): self._background_end = None def execute(self, reducer, file_ws): - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -316,7 +318,7 @@ def execute(self, reducer, file_ws): for ws in workspaces: ConvertToDistribution(Workspace=ws) - CalculateFlatBackground(InputWorkspace=ws,OutputWorkspace= ws,StartX= self._background_start, + CalculateFlatBackground(InputWorkspace=ws,OutputWorkspace= ws,StartX= self._background_start,\ EndX=self._background_end, Mode='Mean') ConvertFromDistribution(Workspace=ws) @@ -339,7 +341,7 @@ def __init__(self): def execute(self, reducer, file_ws): if self._calib_workspace is None: # No calibration workspace set return - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -376,7 +378,7 @@ def __init__(self, MultipleFrames=False): def execute(self, reducer, file_ws): """Does everything we want to with the Monitor. """ - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -413,14 +415,14 @@ def _need_to_unwrap(self, ws): 'Workflow.UnwrapMonitor')[0] except IndexError: return False # Default it to not unwrap - if ( unwrap == 'Never' ): + if unwrap == 'Never' : return False - elif ( unwrap == 'Always' ): + elif unwrap == 'Always' : return True - elif ( unwrap == 'BaseOnTimeRegime' ): + elif unwrap == 'BaseOnTimeRegime' : SpecMon = mtd[ws+'_mon'].readX(0)[0] SpecDet = mtd[ws].readX(0)[0] - if ( SpecMon == SpecDet ): + if SpecMon == SpecDet : return True else: return False @@ -431,7 +433,7 @@ def _unwrap_monitor(self, ws): l_ref = self._get_reference_length(ws, 0) monitor = ws+'_mon' unwrapped_ws, join = UnwrapMonitor(InputWorkspace=monitor, OutputWorkspace=monitor, LRef=l_ref) - RemoveBins(InputWorkspace=monitor,OutputWorkspace= monitor,XMin= join-0.001,XMax= join+0.001, + RemoveBins(InputWorkspace=monitor,OutputWorkspace= monitor,XMin= join-0.001,XMax= join+0.001,\ Interpolation='Linear') try: FFTSmooth(InputWorkspace=monitor,OutputWorkspace=monitor,WorkspaceIndex=0) @@ -458,10 +460,10 @@ def _monitor_efficiency(self, monitor): thickness = inst.getNumberParameter(montiorStr+'-Thickness')[0] attenuation= inst.getNumberParameter(montiorStr+'-Attenuation')[0] except IndexError: - raise ValueError('Unable to retrieve monitor thickness, area and ' + raise ValueError('Unable to retrieve monitor thickness, area and '\ 'attenuation from Instrument Parameter file.') else: - if ( area == -1 or thickness == -1 or attenuation == -1): + if area == -1 or thickness == -1 or attenuation == -1: return OneMinusExponentialCor(InputWorkspace=monitor,OutputWorkspace= monitor,C= (attenuation * thickness),C1= area) @@ -493,7 +495,7 @@ def __init__(self, MultipleFrames=False, EMode="Indirect"): self._emode = EMode def execute(self, reducer, file_ws): - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -544,7 +546,7 @@ def _create_scaling_workspace(self, wsgroup, merged): lowest = 0 highest = 0 for ws in wsgroup: - if ( unit == '' ): + if unit == '' : unit = mtd[ws].getAxis(0).getUnit().unitID() low = mtd[ws].dataX(0)[0] high = mtd[ws].dataX(0)[mtd[ws].blocksize()-1] @@ -563,7 +565,7 @@ def _create_scaling_workspace(self, wsgroup, merged): def _ws_in_range(self, ranges, xval): result = 0 for range in ranges: - if ( xval >= range[0] and xval <= range[1] ): result += 1 + if xval >= range[0] and xval <= range[1] : result += 1 return result class ConvertToCm1(ReductionStep): @@ -583,7 +585,7 @@ def execute(self, reducer, file_ws): if self._save_to_cm_1 == False: return - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaceNames = mtd[file_ws].getNames() except AttributeError: @@ -613,7 +615,7 @@ def __init__(self, MultipleFrames=False): self._multiple_frames = MultipleFrames def execute(self, reducer, file_ws): - if ( self._multiple_frames ): + if self._multiple_frames : try: workspaces = mtd[file_ws].getNames() except AttributeError: @@ -653,7 +655,7 @@ def _rebin_mf(self, workspaces): nbins = mtd[ws].blocksize() if nbins > nbin: nbin = nbins for ws in workspaces: - if (mtd[ws].blocksize() == nbin): + if mtd[ws].blocksize() == nbin: Rebin(InputWorkspace=ws,OutputWorkspace= ws,Params= self._rebin_string) else: Rebin(InputWorkspace=ws,OutputWorkspace= ws,Params= rstwo) @@ -715,7 +717,7 @@ def execute(self, reducer, file_ws): correction = 11.606 / ( 2 * self._temp ) - if ( self._multiple_frames ): + if self._multiple_frames : workspaces = mtd[file_ws].getNames() else: workspaces = [file_ws] @@ -741,7 +743,7 @@ def execute(self, reducer, file_ws): if self._scale_factor is None: # Scale factor is the default value, 1.0 return - if ( self._multiple_frames ): + if self._multiple_frames : workspaces = mtd[file_ws].getNames() else: workspaces = [file_ws] @@ -824,7 +826,7 @@ def _group_data(self, workspace): for i in range(0, nhist): if i not in self._masking_detectors: wslist.append(i) - GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, + GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, WorkspaceIndexList=wslist, Behaviour='Average') else: # We may have either a workspace name or a mapping file name here @@ -852,10 +854,10 @@ def _group_data(self, workspace): # Run GroupDetectors with a workspace if we have one # Otherwise try to run it with a mapping file if grouping_workspace is not None: - GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, CopyGroupingFromWorkspace=grouping_workspace, + GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, CopyGroupingFromWorkspace=grouping_workspace,\ Behaviour='Average') elif os.path.isfile(grouping_filename): - GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, MapFile=grouping_filename, + GroupDetectors(InputWorkspace=workspace, OutputWorkspace=workspace, MapFile=grouping_filename,\ Behaviour='Average') return workspace @@ -960,7 +962,7 @@ def _get_ws_name(self, workspace): elif type == 'RunTitle': return self._run_title(workspace) else: - raise NotImplementedError('Unknown \'Workflow.NamingConvention\'' + raise NotImplementedError('Unknown \'Workflow.NamingConvention\''\ ' parameter encountered on workspace: ' + workspace) def _run_title(self, workspace): diff --git a/Code/Mantid/scripts/Inelastic/msg_reducer.py b/Code/Mantid/scripts/Inelastic/msg_reducer.py index 2f06d44cee44..fe8a132e8758 100644 --- a/Code/Mantid/scripts/Inelastic/msg_reducer.py +++ b/Code/Mantid/scripts/Inelastic/msg_reducer.py @@ -26,6 +26,8 @@ class MSGReducer(reducer.Reducer): _save_formats = [] _info_table_props = None _extra_load_opts = {} + _reduction_steps = None + _data_files = None def __init__(self): super(MSGReducer, self).__init__() @@ -37,18 +39,18 @@ def pre_process(self): loadData.set_ws_list(self._data_files) loadData.set_sum(self._sum) loadData.set_load_logs(self._load_logs) - loadData.set_detector_range(self._detector_range[0], + loadData.set_detector_range(self._detector_range[0],\ self._detector_range[1]) loadData.set_parameter_file(self._parameter_file) loadData.set_extra_load_opts(self._extra_load_opts) loadData.execute(self, None) - + if loadData.contains_event_data and (self._rebin_string is None or self._rebin_string is ''): logger.warning('Reductins of event data without rebinning may give bad data!') self._multiple_frames = loadData.is_multiple_frames() - if( self._info_table_props is not None ): + if self._info_table_props is not None : wsNames = loadData.get_ws_list().keys() wsNameList = ", ".join(wsNames) propsList = ", ".join(self._info_table_props) @@ -58,7 +60,7 @@ def pre_process(self): LogPropertyNames=propsList, GroupPolicy="First") - if ( self._sum ): + if self._sum : self._data_files = loadData.get_ws_list() self._setup_steps() @@ -111,7 +113,7 @@ def set_parameter_file(self, file_name): for directory in config.getInstrumentDirectories(): if os.path.isfile(os.path.join(directory, file_name)): self._parameter_file = os.path.join(directory, file_name) - return + return def set_rebin_string(self, rebin): """Sets the rebin string to be used with the Rebin algorithm. @@ -178,7 +180,7 @@ def get_result_workspaces(self): except AttributeError: pass except IndexError: - raise RuntimeError("None of the reduction steps implement " + raise RuntimeError("None of the reduction steps implement "\ "the get_result_workspaces() method.") def _get_monitor_index(self, workspace): diff --git a/Code/Mantid/scripts/Interface/compile_refm_ui.py b/Code/Mantid/scripts/Interface/compile_refm_ui.py index f73ec768ea6f..6d730cffcce1 100755 --- a/Code/Mantid/scripts/Interface/compile_refm_ui.py +++ b/Code/Mantid/scripts/Interface/compile_refm_ui.py @@ -15,4 +15,4 @@ compile_ui("ui/reflectometer/refl_stitching.ui") except: - print "Could not compile resource file" \ No newline at end of file + print "Could not compile resource file" diff --git a/Code/Mantid/scripts/Interface/compile_sans_ui.py b/Code/Mantid/scripts/Interface/compile_sans_ui.py index 1a7b3f1b7367..d7a8e65a946f 100644 --- a/Code/Mantid/scripts/Interface/compile_sans_ui.py +++ b/Code/Mantid/scripts/Interface/compile_sans_ui.py @@ -29,4 +29,4 @@ os.system("pyuic4 -o ui/ui_data_catalog.py ui/data_catalog.ui") os.system("pyuic4 -o ui/ui_stitcher.py ui/stitcher.ui") except: - print "Could not compile resource file" \ No newline at end of file + print "Could not compile resource file" diff --git a/Code/Mantid/scripts/Interface/reduction_application.py b/Code/Mantid/scripts/Interface/reduction_application.py index 79bb187d52a0..a5c5fdfcfd0c 100644 --- a/Code/Mantid/scripts/Interface/reduction_application.py +++ b/Code/Mantid/scripts/Interface/reduction_application.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Main window for reduction UIs """ @@ -16,7 +17,6 @@ import sip sip.setapi('QString',2) sip.setapi('QVariant',2) - pass from PyQt4 import QtGui, QtCore @@ -91,7 +91,7 @@ def __init__(self, instrument=None, instrument_list=None): self._compute_resources = ['Fermi'] if IS_IN_MANTIDPLOT \ and hasattr(ConfigService.Instance().getFacility(), "computeResources"): - self._compute_resources = ConfigService.Instance().getFacility().computeResources() + self._compute_resources = ConfigService.Instance().getFacility().computeResources() # Internal flag for clearing all settings and restarting the application self._clear_and_restart = False @@ -392,7 +392,7 @@ def closeEvent(self, event): Executed when the application closes """ if False: - reply = QtGui.QMessageBox.question(self, 'Message', + reply = QtGui.QMessageBox.question(self, 'Message',\ "Are you sure you want to quit this application?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: diff --git a/Code/Mantid/scripts/Interface/reduction_gui/instruments/interface.py b/Code/Mantid/scripts/Interface/reduction_gui/instruments/interface.py index 5d4c44518e9e..a71fab7ed1a4 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/instruments/interface.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/instruments/interface.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Base class for instrument-specific user interface """ diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_adv_setup_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_adv_setup_script.py index ab1f5dad562d..0c202970df84 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_adv_setup_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_adv_setup_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -15,7 +16,7 @@ def getBooleanElement(instrument_dom, keyname, default): (1) True/False (2) 1/0 """ - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ keyname, default=default) if tempbool == "True": @@ -30,7 +31,7 @@ def getFloatElement(instrument_dom, keyname, default): return the default value. """ try: - return BaseScriptElement.getFloatElement(instrument_dom, + return BaseScriptElement.getFloatElement(instrument_dom,\ keyname, default=default) except ValueError: return default @@ -182,22 +183,22 @@ def from_xml(self, xml_str): AdvancedSetupScript.removepropmppulsewidth) try: - self.maxchunksize = BaseScriptElement.getIntElement(instrument_dom, + self.maxchunksize = BaseScriptElement.getIntElement(instrument_dom,\ "maxchunksize", default=AdvancedSetupScript.maxchunksize) except ValueError: self.maxchunksize = AdvancedSetupScript.maxchunksize - self.filterbadpulses = getFloatElement(instrument_dom, + self.filterbadpulses = getFloatElement(instrument_dom,\ "filterbadpulses", AdvancedSetupScript.filterbadpulses) - self.bkgdsmoothpars = BaseScriptElement.getStringElement(instrument_dom, + self.bkgdsmoothpars = BaseScriptElement.getStringElement(instrument_dom,\ "bkgdsmoothpars", default=AdvancedSetupScript.bkgdsmoothpars) - self.pushdatapositive = BaseScriptElement.getStringElement(instrument_dom, + self.pushdatapositive = BaseScriptElement.getStringElement(instrument_dom,\ "pushdatapositive", default=AdvancedSetupScript.pushdatapositive) - self.stripvanadiumpeaks = getBooleanElement(instrument_dom, + self.stripvanadiumpeaks = getBooleanElement(instrument_dom,\ "stripvanadiumpeaks", AdvancedSetupScript.stripvanadiumpeaks) self.vanadiumfwhm = getFloatElement(instrument_dom, "vanadiumfwhm", @@ -206,16 +207,16 @@ def from_xml(self, xml_str): self.vanadiumpeaktol = getFloatElement(instrument_dom, "vanadiumpeaktol", AdvancedSetupScript.vanadiumpeaktol) - self.vanadiumsmoothparams = BaseScriptElement.getStringElement(instrument_dom, + self.vanadiumsmoothparams = BaseScriptElement.getStringElement(instrument_dom,\ "vanadiumsmoothparams", default=AdvancedSetupScript.vanadiumsmoothparams) - self.extension = BaseScriptElement.getStringElement(instrument_dom, + self.extension = BaseScriptElement.getStringElement(instrument_dom,\ "extension", default=AdvancedSetupScript.extension) self.preserveevents = getBooleanElement(instrument_dom, "preserveevents", default=AdvancedSetupScript.preserveevents) - self.outputfileprefix = BaseScriptElement.getStringElement(instrument_dom, + self.outputfileprefix = BaseScriptElement.getStringElement(instrument_dom,\ "outputfileprefix", default = AdvancedSetupScript.outputfileprefix) self.scaledata = getFloatElement(instrument_dom, "scaledata", diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py index b65ebe31f07c..d31ee3d5a9bd 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -172,7 +173,7 @@ def from_xml(self, xml_str): self.minimumlogvalue = self.getFloatElement(instrument_dom, "minimumlogvalue", FilterSetupScript.minimumlogvalue) self.maximumlogvalue = self.getFloatElement(instrument_dom, "maximumlogvalue", FilterSetupScript.maximumlogvalue) self.logvalueinterval = self.getFloatElement(instrument_dom, "logvalueinterval", FilterSetupScript.logvalueinterval) - self.filterlogvaluebychangingdirection = self.getStringElement(instrument_dom, "filterlogvaluebychangingdirection", + self.filterlogvaluebychangingdirection = self.getStringElement(instrument_dom, "filterlogvaluebychangingdirection",\ FilterSetupScript.filterlogvaluebychangingdirection) self.timetolerance = self.getFloatElement(instrument_dom, "timetolerance", FilterSetupScript.timetolerance) self.logboundary = self.getStringElement(instrument_dom, "logboundary", FilterSetupScript.logboundary) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py index cd18ffcf104d..f2dffcfc13e4 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_reduction_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -27,7 +28,7 @@ def __init__(self, name="VULCAN", facility="SNS"): """ Initialization """ super(DiffractionReductionScripter, self).__init__(name=name, facility=facility) - + print "[diffraction_reduction_script] Facility = %s, Instrument = %s" % (self.facility_name, self.instrument_name) return @@ -160,7 +161,7 @@ def constructPythonScript(self, paramdict): script += "%sMinimumLogValue = '%s',\n" % (DiffractionReductionScripter.WIDTH, filterdict["MinimumLogValue"]) if filterdict["MaximumLogValue"] != "": script += "%sMaximumLogValue = '%s',\n" % (DiffractionReductionScripter.WIDTH, filterdict["MaximumLogValue"]) - script += "%sFilterLogValueByChangingDirection = '%s',\n" % (DiffractionReductionScripter.WIDTH, + script += "%sFilterLogValueByChangingDirection = '%s',\n" % (DiffractionReductionScripter.WIDTH,\ filterdict["FilterLogValueByChangingDirection"]) if filterdict["LogValueInterval"] != "": # Filter by log value interval @@ -353,7 +354,7 @@ def buildPowderDataReductionScript(self, runsetupdict, advsetupdict, runnumber=N if splitwsname is not None and splitwsname != "": script += "%sSplittersWorkspace = '%s',\n" % (DiffractionReductionScripter.WIDTH, str(splitwsname)) if splitinfowsname is not None and splitinfowsname != "": - script += "%sSplitInformationWorkspace='%s',\n" % (DiffractionReductionScripter.WIDTH, + script += "%sSplitInformationWorkspace='%s',\n" % (DiffractionReductionScripter.WIDTH,\ str(splitinfowsname)) script += "%s)\n" % (DiffractionReductionScripter.WIDTH) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_run_setup_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_run_setup_script.py index dfb474340bf0..91c46724fb6c 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_run_setup_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_run_setup_script.py @@ -160,66 +160,66 @@ def from_xml(self, xml_str): instrument_dom = element_list[0] # - self.runnumbers = BaseScriptElement.getStringElement(instrument_dom, + self.runnumbers = BaseScriptElement.getStringElement(instrument_dom,\ "runnumber", default=RunSetupScript.runnumbers) - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ "sum", default=str(int(RunSetupScript.dosum))) self.dosum = bool(int(tempbool)) - self.calibfilename = BaseScriptElement.getStringElement(instrument_dom, + self.calibfilename = BaseScriptElement.getStringElement(instrument_dom,\ "calibrationfile", default=RunSetupScript.calibfilename) - self.charfilename = BaseScriptElement.getStringElement(instrument_dom, + self.charfilename = BaseScriptElement.getStringElement(instrument_dom,\ "characterizationrunsfile", default=RunSetupScript.charfilename) - self.binning = BaseScriptElement.getFloatElement(instrument_dom, + self.binning = BaseScriptElement.getFloatElement(instrument_dom,\ "binning", default=RunSetupScript.binning) - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ "binindspace", default=str(int(RunSetupScript.binindspace))) self.binindspace = bool(int(tempbool)) - self.resamplex = BaseScriptElement.getIntElement(instrument_dom, + self.resamplex = BaseScriptElement.getIntElement(instrument_dom,\ "resamplex", default=RunSetupScript.resamplex) - self.saveas = BaseScriptElement.getStringElement(instrument_dom, + self.saveas = BaseScriptElement.getStringElement(instrument_dom,\ "saveas", default=RunSetupScript.saveas) - self.outputdir = BaseScriptElement.getStringElement(instrument_dom, + self.outputdir = BaseScriptElement.getStringElement(instrument_dom,\ "outputdirectory", default=RunSetupScript.outputdir) - self.finalunits = BaseScriptElement.getStringElement(instrument_dom, + self.finalunits = BaseScriptElement.getStringElement(instrument_dom,\ "finaldataunits", default=RunSetupScript.finalunits) - tempint = BaseScriptElement.getStringElement(instrument_dom, + tempint = BaseScriptElement.getStringElement(instrument_dom,\ "backgroundnumber", default=RunSetupScript.bkgdrunnumber) try: self.bkgdrunnumber = int(tempint) except ValueError: self.bkgdrunnumber = None - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ "disablebackgroundcorrection", default=str(int(RunSetupScript.disablebkgdcorrection))) self.disablebkgdcorrection = bool(int(tempbool)) - tempint = BaseScriptElement.getStringElement(instrument_dom, + tempint = BaseScriptElement.getStringElement(instrument_dom,\ "vanadiumnumber", default=RunSetupScript.vanrunnumber) try: self.vanrunnumber = int(tempint) except ValueError: self.vanrunnumber = "" - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ "disablevanadiumcorrection", default=str(int(RunSetupScript.disablevancorrection))) self.disablevancorrection = bool(int(tempbool)) - tempint = BaseScriptElement.getStringElement(instrument_dom, + tempint = BaseScriptElement.getStringElement(instrument_dom,\ "vanadiumbackgroundnumber", default=RunSetupScript.vanbkgdrunnumber) try: self.vanbkgdrunnumber = int(tempint) except ValueError: self.vanbkgdrunnumber = None - tempbool = BaseScriptElement.getStringElement(instrument_dom, + tempbool = BaseScriptElement.getStringElement(instrument_dom,\ "disablevanadiumbackgroundcorrection", default=str(int(RunSetupScript.disablevanbkgdcorrection))) self.disablevanbkgdcorrection = bool(int(tempbool)) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/eqsans_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/eqsans_reduction.py index 899c6b35d6ff..6d2552cdf3b0 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/eqsans_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/eqsans_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This class holds all the necessary information to create a reduction script. This is a fake version of the Reducer for testing purposes. diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/hfir_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/hfir_reduction.py index f787756416c7..9b6c63891afb 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/hfir_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/hfir_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This class holds all the necessary information to create a reduction script. This is a fake version of the Reducer for testing purposes. diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py index 2ecd16e8c1ad..9e89b2a27269 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py index d9772dcbfb68..63bae3d9f3e0 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -121,20 +122,20 @@ def from_xml(self, xml_str): self.incident_beam_norm = BaseScriptElement.getStringElement(instrument_dom, "incident_beam_norm", default=DataCorrectionsScript.incident_beam_norm) - self.monitor_int_low = BaseScriptElement.getIntElement(instrument_dom, - "monint_range_low", + self.monitor_int_low = BaseScriptElement.getIntElement(instrument_dom,\ + "monint_range_low",\ default=DataCorrectionsScript.monitor_int_low) - self.monitor_int_high = BaseScriptElement.getIntElement(instrument_dom, - "monint_range_high", + self.monitor_int_high = BaseScriptElement.getIntElement(instrument_dom,\ + "monint_range_high",\ default=DataCorrectionsScript.monitor_int_high) self.tib_subtraction = BaseScriptElement.getBoolElement(instrument_dom, "timeindepbkg_sub", default=DataCorrectionsScript.tib_subtraction) - self.tib_tof_start = BaseScriptElement.getIntElement(instrument_dom, - "tib_tof_range_start", + self.tib_tof_start = BaseScriptElement.getIntElement(instrument_dom,\ + "tib_tof_range_start",\ default=DataCorrectionsScript.tib_tof_start) - self.tib_tof_end = BaseScriptElement.getIntElement(instrument_dom, - "tib_tof_range_end", + self.tib_tof_end = BaseScriptElement.getIntElement(instrument_dom,\ + "tib_tof_range_end",\ default=DataCorrectionsScript.tib_tof_end) self.correct_kikf = BaseScriptElement.getBoolElement(instrument_dom, "correct_kikf", @@ -142,26 +143,26 @@ def from_xml(self, xml_str): self.detector_vanadium = BaseScriptElement.getStringElement(instrument_dom, "detector_vanadium", default=DataCorrectionsScript.detector_vanadium) - self.detvan_integration = BaseScriptElement.getBoolElement(instrument_dom, - "use_bounds_detvan", + self.detvan_integration = BaseScriptElement.getBoolElement(instrument_dom,\ + "use_bounds_detvan",\ default=DataCorrectionsScript.detvan_integration) - self.detvan_int_range_low = BaseScriptElement.getStringElement(instrument_dom, - "detvan_range_low", + self.detvan_int_range_low = BaseScriptElement.getStringElement(instrument_dom,\ + "detvan_range_low",\ default=DataCorrectionsScript.detvan_int_range_low) - self.detvan_int_range_high = BaseScriptElement.getStringElement(instrument_dom, - "detvan_range_high", + self.detvan_int_range_high = BaseScriptElement.getStringElement(instrument_dom,\ + "detvan_range_high",\ default=DataCorrectionsScript.detvan_int_range_high) - self.detvan_int_range_units = BaseScriptElement.getStringElement(instrument_dom, - "detvan_range_units", + self.detvan_int_range_units = BaseScriptElement.getStringElement(instrument_dom,\ + "detvan_range_units",\ default=DataCorrectionsScript.detvan_int_range_units) - self.save_proc_detvan = BaseScriptElement.getBoolElement(instrument_dom, - "save_proc_detvan", + self.save_proc_detvan = BaseScriptElement.getBoolElement(instrument_dom,\ + "save_proc_detvan",\ default=DataCorrectionsScript.save_proc_detvan) - self.save_proc_detvan_file = BaseScriptElement.getStringElement(instrument_dom, - "save_proc_detvan_filename", + self.save_proc_detvan_file = BaseScriptElement.getStringElement(instrument_dom,\ + "save_proc_detvan_filename",\ default=DataCorrectionsScript.save_proc_detvan_file) - self.use_proc_detvan = BaseScriptElement.getBoolElement(instrument_dom, - "use_proc_detvan", + self.use_proc_detvan = BaseScriptElement.getBoolElement(instrument_dom,\ + "use_proc_detvan",\ default=DataCorrectionsScript.use_proc_detvan) def reset(self): diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py index 6960fca539c5..05cf070afb81 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -175,8 +176,8 @@ def from_xml(self, xml_str): self.sambkg_errorbar_criterion = BaseScriptElement.getFloatElement(instrument_dom, "sambkg_errorbar_criterion", default=DiagnoseDetectorsScript.sambkg_errorbar_criterion) - self.tof_start = BaseScriptElement.getIntElement(instrument_dom, - "background_tof_start", + self.tof_start = BaseScriptElement.getIntElement(instrument_dom,\ + "background_tof_start",\ default=DiagnoseDetectorsScript.tof_start) self.tof_end = BaseScriptElement.getIntElement(instrument_dom, "background_tof_end", diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py index cc1ff2e316dd..4f358fd8caad 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py index 4218d65ea0ae..2390fc5ccbf5 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the DgsReduction class could @@ -128,8 +129,8 @@ def from_xml(self, xml_str): self.sample_file = BaseScriptElement.getStringElement(instrument_dom, "sample_input_file", default=SampleSetupScript.sample_file) - self.live_button = BaseScriptElement.getBoolElement(instrument_dom, - "live_button", + self.live_button = BaseScriptElement.getBoolElement(instrument_dom,\ + "live_button",\ default=SampleSetupScript.live_button) self.output_wsname = BaseScriptElement.getStringElement(instrument_dom, "output_wsname", @@ -176,8 +177,8 @@ def from_xml(self, xml_str): self.show_workspaces = BaseScriptElement.getBoolElement(instrument_dom, "show_workspaces", default=SampleSetupScript.show_workspaces) - self.savedir = BaseScriptElement.getStringElement(instrument_dom, - "savedir", + self.savedir = BaseScriptElement.getStringElement(instrument_dom,\ + "savedir",\ default=SampleSetupScript.savedir) def reset(self): diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py index 360c9ad69c72..c74a606fe121 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py @@ -53,7 +53,7 @@ def get_parameter(self, name): if val[0] == "None" : return None elif type_name == "int" : - val = self._instrument.getIntParameter(name) + val = self._instrument.getIntParameter(name) else : return default try: diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/output_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/output_script.py index d5dc1c054f53..761bb0d46dd4 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/output_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/output_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from scripter import BaseScriptElement # Check whether we are running in MantidPlot diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_script.py index 357266aa9e57..5a8fefbf9452 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_script.py @@ -112,7 +112,7 @@ def to_script(self, for_automated_reduction=False): # sf configuration file # if self.scaling_factor_file != '': - if (self.scaling_factor_file_flag): + if self.scaling_factor_file_flag: script += "ScalingFactorFile='%s',\n" % str(self.scaling_factor_file) else: script += "ScalingFactorFile='',\n" @@ -227,12 +227,12 @@ def from_xml_element(self, instrument_dom): #data metadata _tthd_value = BaseScriptElement.getStringElement(instrument_dom, "tthd_value") - if (_tthd_value == ''): + if _tthd_value == '': _tthd_value = 'N/A' self.tthd_value = _tthd_value _ths_value = BaseScriptElement.getStringElement(instrument_dom, "ths_value") - if (_ths_value == ''): + if _ths_value == '': _ths_value = 'N/A' self.ths_value = _ths_value diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py index 7980023fbb2d..c35820136313 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This class holds all the necessary information to create a reduction script. """ diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py index fa68ff9c5923..80b78fe6cff0 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This class holds all the necessary information to create a reduction script. This is a fake version of the Reducer for testing purposes. diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py index 387831efd38d..5647e64be5f2 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/data_cat.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Simple local data catalog for Mantid Gets main information from data files in a directory and stores @@ -175,7 +176,7 @@ def __init__(self, replace_db=True): self.db = None try: - self._create_db(db_path, replace_db) + self._create_db(db_path, replace_db) except: print "DataCatalog: Could not access local data catalog\n%s" % sys.exc_value diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py index 9311c309a351..8330391948dc 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Data catalog for EQSANS """ @@ -113,4 +114,4 @@ class DataCatalog(BaseCatalog): data_set_cls = EQSANSDataSet def __init__(self, replace_db=False): - super(DataCatalog, self).__init__(replace_db) \ No newline at end of file + super(DataCatalog, self).__init__(replace_db) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py index 1371b7028761..0354545a3284 100755 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py @@ -55,4 +55,4 @@ def from_setup_info(self, xml_str): """ self.reset() super(DataSets, self).from_setup_info(xml_str) - self.background.from_setup_info(xml_str) \ No newline at end of file + self.background.from_setup_info(xml_str) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py index 2eaf8c2d5191..edaac8e15d58 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/eqsans_options_script.py @@ -31,10 +31,10 @@ class ReductionOptions(BaseOptions): # Perform EQSANS TOF correction perform_TOF_correction = True - + # Turn off the wedges n_wedges = 0 - + # Turn off log binning alignment with decades align_log_with_decades = False @@ -216,7 +216,7 @@ def from_xml(self, xml_str): # Resolution self.compute_resolution = BaseScriptElement.getBoolElement(dom, "ComputeResolution", default = ReductionOptions.compute_resolution) - self.sample_aperture_diameter = BaseScriptElement.getFloatElement(dom, "SampleApertureDiameter", + self.sample_aperture_diameter = BaseScriptElement.getFloatElement(dom, "SampleApertureDiameter",\ default = ReductionOptions.sample_aperture_diameter) # TOF correction diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py index ef059d34bc04..545af6a13e5e 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the HFIRReduction class could @@ -203,20 +204,20 @@ def from_xml(self, xml_str): default = Background.dark_current_corr) self.dark_current_file = BaseScriptElement.getStringElement(instrument_dom, "dark_current_file") - self.background_corr = BaseScriptElement.getBoolElement(instrument_dom, "background_corr", + self.background_corr = BaseScriptElement.getBoolElement(instrument_dom, "background_corr",\ default = Background.background_corr) self.background_file = BaseScriptElement.getStringElement(instrument_dom, "background_file") - self.bck_transmission_enabled = BaseScriptElement.getBoolElement(instrument_dom, "bck_trans_enabled", + self.bck_transmission_enabled = BaseScriptElement.getBoolElement(instrument_dom, "bck_trans_enabled",\ default = Background.bck_transmission_enabled) - self.bck_transmission = BaseScriptElement.getFloatElement(instrument_dom, "bck_trans", + self.bck_transmission = BaseScriptElement.getFloatElement(instrument_dom, "bck_trans",\ default=Background.bck_transmission) - self.bck_transmission_spread = BaseScriptElement.getFloatElement(instrument_dom, "bck_trans_spread", + self.bck_transmission_spread = BaseScriptElement.getFloatElement(instrument_dom, "bck_trans_spread",\ default=Background.bck_transmission_spread) self.calculate_transmission = BaseScriptElement.getBoolElement(instrument_dom, "calculate_trans", default = Background.calculate_transmission) - self.theta_dependent = BaseScriptElement.getBoolElement(instrument_dom, "theta_dependent", + self.theta_dependent = BaseScriptElement.getBoolElement(instrument_dom, "theta_dependent",\ default = Background.theta_dependent) self.trans_dark_current = BaseScriptElement.getStringElement(instrument_dom, "trans_dark_current") diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py index 216e9ec3c250..c768f92cad3a 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_catalog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Data catalog for HFIR SANS """ @@ -94,4 +95,4 @@ class DataCatalog(BaseCatalog): data_set_cls = HFIRDataSet def __init__(self, replace_db=False): - super(DataCatalog, self).__init__(replace_db) \ No newline at end of file + super(DataCatalog, self).__init__(replace_db) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_data_proxy.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_data_proxy.py index 799a7d325159..4ad3e41978bd 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_data_proxy.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_data_proxy.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import sys # Check whether Mantid is available try: diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py index 286e077301f3..6f0c65f526d0 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py @@ -181,28 +181,28 @@ def from_xml(self, xml_str): default = Detector.sensitivity_corr) self.sensitivity_data = BaseScriptElement.getStringElement(instrument_dom, "sensitivity_data") self.sensitivity_dark = BaseScriptElement.getStringElement(instrument_dom, "sensitivity_dark") - self.use_sample_dark = BaseScriptElement.getBoolElement(instrument_dom, "use_sample_dark", + self.use_sample_dark = BaseScriptElement.getBoolElement(instrument_dom, "use_sample_dark",\ default = Detector.use_sample_dark) - self.min_sensitivity = BaseScriptElement.getFloatElement(instrument_dom, "sensitivity_min", + self.min_sensitivity = BaseScriptElement.getFloatElement(instrument_dom, "sensitivity_min",\ default=Detector.min_sensitivity) - self.max_sensitivity = BaseScriptElement.getFloatElement(instrument_dom, "sensitivity_max", + self.max_sensitivity = BaseScriptElement.getFloatElement(instrument_dom, "sensitivity_max",\ default=Detector.max_sensitivity) - self.use_sample_beam_center = BaseScriptElement.getBoolElement(instrument_dom, "use_sample_beam_center", + self.use_sample_beam_center = BaseScriptElement.getBoolElement(instrument_dom, "use_sample_beam_center",\ default = Detector.use_sample_beam_center) beam_center_list = instrument_dom.getElementsByTagName("FloodBeamFinder") if len(beam_center_list)>0: beam_finder_dom = beam_center_list[0] - self.flood_x_position = BaseScriptElement.getFloatElement(beam_finder_dom, "x", + self.flood_x_position = BaseScriptElement.getFloatElement(beam_finder_dom, "x",\ default=Detector.flood_x_position) - self.flood_y_position = BaseScriptElement.getFloatElement(beam_finder_dom, "y", + self.flood_y_position = BaseScriptElement.getFloatElement(beam_finder_dom, "y",\ default=Detector.flood_y_position) - self.flood_use_finder = BaseScriptElement.getBoolElement(beam_finder_dom, "use_finder", + self.flood_use_finder = BaseScriptElement.getBoolElement(beam_finder_dom, "use_finder",\ default = Detector.flood_use_finder) self.flood_beam_file = BaseScriptElement.getStringElement(beam_finder_dom, "beam_file") - self.flood_beam_radius = BaseScriptElement.getFloatElement(beam_finder_dom, "beam_radius", + self.flood_beam_radius = BaseScriptElement.getFloatElement(beam_finder_dom, "beam_radius",\ default=Detector.flood_beam_radius) - self.flood_use_direct_beam = BaseScriptElement.getBoolElement(beam_finder_dom, "use_direct_beam", + self.flood_use_direct_beam = BaseScriptElement.getBoolElement(beam_finder_dom, "use_direct_beam",\ default = Detector.flood_use_direct_beam) element_list = dom.getElementsByTagName("BeamFinder") @@ -215,9 +215,9 @@ def from_xml(self, xml_str): self.use_finder = BaseScriptElement.getBoolElement(beam_finder_dom, "use_finder", default = Detector.use_finder) self.beam_file = BaseScriptElement.getStringElement(beam_finder_dom, "beam_file") - self.beam_radius = BaseScriptElement.getFloatElement(beam_finder_dom, "beam_radius", + self.beam_radius = BaseScriptElement.getFloatElement(beam_finder_dom, "beam_radius",\ default=Detector.beam_radius) - self.use_direct_beam = BaseScriptElement.getBoolElement(beam_finder_dom, "use_direct_beam", + self.use_direct_beam = BaseScriptElement.getBoolElement(beam_finder_dom, "use_direct_beam",\ default = Detector.use_direct_beam) def from_setup_info(self, xml_str): @@ -255,19 +255,19 @@ def from_setup_info(self, xml_str): self.flood_y_position = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterY", default=Detector.flood_y_position) self.flood_beam_file = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterFile", default='') - self.flood_beam_radius = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterRadius", + self.flood_beam_radius = BaseScriptElement.getPropertyValue(alg, "SensitivityBeamCenterRadius",\ default=Detector.flood_beam_radius) # Beam center center_method = BaseScriptElement.getPropertyValue(alg, "BeamCenterMethod", default='None') self.use_finder = center_method in ['DirectBeam', 'Scattering'] self.use_direct_beam = center_method=='DirectBeam' - self.x_position = BaseScriptElement.getPropertyValue(alg, "BeamCenterX", + self.x_position = BaseScriptElement.getPropertyValue(alg, "BeamCenterX",\ default=Detector.x_position) - self.y_position = BaseScriptElement.getPropertyValue(alg, "BeamCenterY", + self.y_position = BaseScriptElement.getPropertyValue(alg, "BeamCenterY",\ default=Detector.y_position) self.beam_file = BaseScriptElement.getPropertyValue(alg, "BeamCenterFile", default='') - self.beam_radius = BaseScriptElement.getPropertyValue(alg, "BeamRadius", + self.beam_radius = BaseScriptElement.getPropertyValue(alg, "BeamRadius",\ default=Detector.beam_radius) def reset(self): diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py index 76ef9527bc49..40663e98f6bc 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_options_script.py @@ -40,12 +40,12 @@ class ReductionOptions(BaseScriptElement): log_binning = False align_log_with_decades = True error_weighting = False - + # Wedges n_wedges = 2 wedge_angle = 30.0 wedge_offset = 0.0 - + # Mask side masked_side = None @@ -126,13 +126,13 @@ def to_script(self): if self.align_log_with_decades: script += ", align_log_with_decades=%s" % str(self.align_log_with_decades) if self.error_weighting: script += ", error_weighting=%s" % str(self.error_weighting) script += ")\n" - + # If we align we decades, use more points for I(qx,qy) n_xy_bins = self.n_q_bins if self.log_binning and self.align_log_with_decades: n_xy_bins = int(3*self.n_q_bins) script += "IQxQy(nbins=%g)\n" % n_xy_bins - + if self.n_wedges>0: script += "SetWedges(number_of_wedges=%g, wedge_angle=%g, wedge_offset=%g)\n" % (self.n_wedges, self.wedge_angle, self.wedge_offset) @@ -141,7 +141,7 @@ def to_script(self): if self.masked_side is not None: script += "MaskDetectorSide('%s')\n" % str(self.masked_side) # Edges - if (self.top != 0 or self.bottom != 0 or self.left != 0 or self.right != 0): + if self.top != 0 or self.bottom != 0 or self.left != 0 or self.right != 0: script += "Mask(nx_low=%d, nx_high=%d, ny_low=%d, ny_high=%d)\n" % (self.left, self.right, self.bottom, self.top) # Rectangles for item in self.shapes: @@ -198,7 +198,7 @@ def to_xml(self): xml += " %g\n" % self.n_wedges xml += " %g\n" % self.wedge_angle xml += " %g\n" % self.wedge_offset - + xml += " %d\n" % self.normalization # Output directory @@ -212,7 +212,7 @@ def to_xml(self): xml += " %g\n" % self.bottom xml += " %g\n" % self.left xml += " %g\n" % self.right - + xml += " %s\n" % str(self.masked_side) xml += " \n" @@ -261,7 +261,7 @@ def from_xml(self, xml_str): default=ReductionOptions.detector_offset) self.wavelength = BaseScriptElement.getFloatElement(instrument_dom, "wavelength", default=ReductionOptions.wavelength) - self.wavelength_spread = BaseScriptElement.getFloatElement(instrument_dom, "wavelength_spread", + self.wavelength_spread = BaseScriptElement.getFloatElement(instrument_dom, "wavelength_spread",\ default=ReductionOptions.wavelength_spread) self.solid_angle_corr = BaseScriptElement.getBoolElement(instrument_dom, "solid_angle_corr", @@ -278,11 +278,11 @@ def from_xml(self, xml_str): default = ReductionOptions.dark_current_corr) self.dark_current_data = BaseScriptElement.getStringElement(instrument_dom, "dark_current_data") - self.n_q_bins = BaseScriptElement.getIntElement(instrument_dom, "n_q_bins", + self.n_q_bins = BaseScriptElement.getIntElement(instrument_dom, "n_q_bins",\ default=ReductionOptions.n_q_bins) - self.n_sub_pix = BaseScriptElement.getIntElement(instrument_dom, "n_sub_pix", + self.n_sub_pix = BaseScriptElement.getIntElement(instrument_dom, "n_sub_pix",\ default=ReductionOptions.n_sub_pix) - self.log_binning = BaseScriptElement.getBoolElement(instrument_dom, "log_binning", + self.log_binning = BaseScriptElement.getBoolElement(instrument_dom, "log_binning",\ default = ReductionOptions.log_binning) self.align_log_with_decades = BaseScriptElement.getBoolElement(instrument_dom, "align_log_with_decades", default = ReductionOptions.align_log_with_decades) @@ -452,7 +452,7 @@ def reset(self): self.log_binning = ReductionOptions.log_binning self.align_log_with_decades = ReductionOptions.align_log_with_decades self.error_weighting = ReductionOptions.error_weighting - + self.n_wedges = ReductionOptions.n_wedges self.wedge_angle = ReductionOptions.wedge_angle self.wedge_offset = ReductionOptions.wedge_offset diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py index 10bce2ea2a88..737f9582d26c 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Classes for each reduction step. Those are kept separately from the the interface class so that the HFIRReduction class could @@ -145,9 +146,9 @@ def from_xml(self, dom): self.sample_spreader = BaseScriptElement.getStringElement(instrument_dom, "sample_spreader") self.direct_scatt = BaseScriptElement.getStringElement(instrument_dom, "direct_scatt") self.direct_spreader = BaseScriptElement.getStringElement(instrument_dom, "direct_spreader") - self.spreader_trans = BaseScriptElement.getFloatElement(instrument_dom, "spreader_trans", + self.spreader_trans = BaseScriptElement.getFloatElement(instrument_dom, "spreader_trans",\ default=SampleData.BeamSpreader.spreader_trans) - self.spreader_trans_spread = BaseScriptElement.getFloatElement(instrument_dom, "spreader_trans_spread", + self.spreader_trans_spread = BaseScriptElement.getFloatElement(instrument_dom, "spreader_trans_spread",\ default=SampleData.BeamSpreader.spreader_trans_spread) def from_setup_info(self, xml_str): @@ -304,11 +305,11 @@ def from_xml(self, xml_str): instrument_dom = element_list[0] self.transmission = BaseScriptElement.getFloatElement(instrument_dom, "trans", default=SampleData.transmission) - self.transmission_spread = BaseScriptElement.getFloatElement(instrument_dom, "trans_spread", + self.transmission_spread = BaseScriptElement.getFloatElement(instrument_dom, "trans_spread",\ default=SampleData.transmission_spread) self.calculate_transmission = BaseScriptElement.getBoolElement(instrument_dom, "calculate_trans", default = SampleData.calculate_transmission) - self.theta_dependent = BaseScriptElement.getBoolElement(instrument_dom, "theta_dependent", + self.theta_dependent = BaseScriptElement.getBoolElement(instrument_dom, "theta_dependent",\ default = SampleData.theta_dependent) self.dark_current = BaseScriptElement.getStringElement(instrument_dom, "dark_current") diff --git a/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py b/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py index 9aa957df9d16..daab5c3f4279 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/reduction/scripter.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Reduction scripter used to take reduction parameters end produce a Mantid reduction script diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/base_widget.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/base_widget.py index f07c5fc5efe4..3b0f1d46bf4d 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/base_widget.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/base_widget.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import os import types @@ -128,8 +129,8 @@ def data_browse_dialog(self, data_type=None, title=None, multi=False): if title is None: title = "Data file - Choose a data file" if multi: - qflist = QtGui.QFileDialog.getOpenFileNames(self, title, - self._settings.data_path, + qflist = QtGui.QFileDialog.getOpenFileNames(self, title,\ + self._settings.data_path,\ data_type) if len(qflist)>0: flist = [] @@ -141,8 +142,8 @@ def data_browse_dialog(self, data_type=None, title=None, multi=False): else: return None else: - fname = QtCore.QFileInfo(QtGui.QFileDialog.getOpenFileName(self, title, - self._settings.data_path, + fname = QtCore.QFileInfo(QtGui.QFileDialog.getOpenFileName(self, title,\ + self._settings.data_path,\ data_type)).filePath() if fname: # Store the location of the loaded file diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py index f6397ea6c560..099d45abb1a8 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/cluster_status.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import os import sys diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_adv_setup.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_adv_setup.py index 8c8315a76363..dfbeb129de7c 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_adv_setup.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_adv_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ################################################################################ # Advanced Setup Widget ################################################################################ @@ -92,10 +93,10 @@ def initialize_content(self): self._content.filterbadpulses_edit.setText("95.") # Connections from action/event to function to handle - self.connect(self._content.stripvanpeaks_chkbox, QtCore.SIGNAL("clicked()"), + self.connect(self._content.stripvanpeaks_chkbox, QtCore.SIGNAL("clicked()"),\ self._stripvanpeaks_clicked) - self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"),\ self._show_help) # Hanlder for events # FIXME - Need to add an event hanlder for the change of instrument and facility diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py index 49e6a2bd8bff..6d4731dea439 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ################################################################################ # Event Filtering (and advanced) Setup Widget ################################################################################ @@ -111,25 +112,25 @@ def initialize_content(self): # Default states # Connections from action/event to function to handle - self.connect(self._content.timefilter_checkBox, QtCore.SIGNAL("stateChanged(int)"), + self.connect(self._content.timefilter_checkBox, QtCore.SIGNAL("stateChanged(int)"),\ self._filterbytime_statechanged) - self.connect(self._content.logvaluefilter_checkBox, QtCore.SIGNAL("stateChanged(int)"), + self.connect(self._content.logvaluefilter_checkBox, QtCore.SIGNAL("stateChanged(int)"),\ self._filterbylogvalue_statechanged) - self.connect(self._content.load_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.load_button, QtCore.SIGNAL("clicked()"),\ self._run_number_changed) # self.connect(self._content.run_number_edit, QtCore.SIGNAL("textChanged(QString)"), self._run_number_changed) self.connect(self._content.run_number_edit, QtCore.SIGNAL("returnPressed()"), self._run_number_changed) - self.connect(self._content.plot_log_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.plot_log_button, QtCore.SIGNAL("clicked()"),\ self._plot_log_clicked) - self.connect(self._content.syn_logname_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.syn_logname_button, QtCore.SIGNAL("clicked()"),\ self._sync_logname_clicked) - self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"),\ self._show_help) # Validated widgets @@ -277,7 +278,7 @@ def _run_number_changed(self): # 3. Update the log name combo box if metaws is None: - self._content.info_text_browser.setText( + self._content.info_text_browser.setText(\ str("Error! Failed to load data file %s. Current working directory is %s. " % (eventnxsname, os.getcwd()))) else: self._metaws = metaws @@ -334,15 +335,15 @@ def _plot_log_clicked(self): logproperty = run.getProperty(str(logname)) except RuntimeError: # Unable to plot - msg3 = str("Error! Workspace %s does not contain log %s. " % (str(self._metaws), + msg3 = str("Error! Workspace %s does not contain log %s. " % (str(self._metaws),\ logname)) self._content.info_text_browser.setText(str(msg1+msg3)) return # Construct workspace - output = api.ExportTimeSeriesLog(InputWorkspace = str(self._metaws), - OutputWorkspace = str(logname), - LogName = str(logname), + output = api.ExportTimeSeriesLog(InputWorkspace = str(self._metaws),\ + OutputWorkspace = str(logname),\ + LogName = str(logname),\ IsEventWorkspace = False) #api.DeleteWorkspace(Workspace="PercentStat") @@ -439,7 +440,7 @@ def call_back(xmin, xmax): maxwidget.setText("%-f" % float(xmax)) return - self.logvalue_vs_time_distribution(workspace=ws, + self.logvalue_vs_time_distribution(workspace=ws,\ callback=call_back) return @@ -451,7 +452,7 @@ def logvalue_vs_time_distribution(self, workspace, callback): xmax = workspace.dataX(0)[-1] if callback is not None: from LargeScaleStructures import data_stitching - data_stitching.RangeSelector.connect([workspace], callback, + data_stitching.RangeSelector.connect([workspace], callback,\ xmin=xmin, xmax=xmax) return diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py index 21e78699c4d2..ebf5f2629f44 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ################################################################################ # This is my first attempt to make a tab from quasi-scratch ################################################################################ @@ -111,15 +112,15 @@ def initialize_content(self): # self._handle_tzero_guess(self._content.use_ei_guess_chkbox.isChecked()) # Connections from action/event to function to handle - self.connect(self._content.calfile_browse, QtCore.SIGNAL("clicked()"), + self.connect(self._content.calfile_browse, QtCore.SIGNAL("clicked()"),\ self._calfile_browse) - self.connect(self._content.charfile_browse, QtCore.SIGNAL("clicked()"), + self.connect(self._content.charfile_browse, QtCore.SIGNAL("clicked()"),\ self._charfile_browse) - self.connect(self._content.outputdir_browse, QtCore.SIGNAL("clicked()"), + self.connect(self._content.outputdir_browse, QtCore.SIGNAL("clicked()"),\ self._outputdir_browse) - self.connect(self._content.binning_edit, QtCore.SIGNAL("valueChanged"), + self.connect(self._content.binning_edit, QtCore.SIGNAL("valueChanged"),\ self._binvalue_edit) - self.connect(self._content.bintype_combo, QtCore.SIGNAL("currentIndexChanged(QString)"), + self.connect(self._content.bintype_combo, QtCore.SIGNAL("currentIndexChanged(QString)"),\ self._bintype_process) #self.connect(self._content.override_emptyrun_checkBox, QtCore.SIGNAL("clicked()"), @@ -129,19 +130,19 @@ def initialize_content(self): #self.connect(self._content.override_vanbkgdrun_checkBox, QtCore.SIGNAL("clicked()"), # self._overridevanbkgdrun_clicked) - self.connect(self._content.disablebkgdcorr_chkbox, QtCore.SIGNAL("clicked()"), + self.connect(self._content.disablebkgdcorr_chkbox, QtCore.SIGNAL("clicked()"),\ self._disablebkgdcorr_clicked) - self.connect(self._content.disablevancorr_chkbox, QtCore.SIGNAL("clicked()"), + self.connect(self._content.disablevancorr_chkbox, QtCore.SIGNAL("clicked()"),\ self._disablevancorr_clicked) - self.connect(self._content.disablevanbkgdcorr_chkbox, QtCore.SIGNAL("clicked()"), + self.connect(self._content.disablevanbkgdcorr_chkbox, QtCore.SIGNAL("clicked()"),\ self._disablevanbkgdcorr_clicked) - self.connect(self._content.usebin_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.usebin_button, QtCore.SIGNAL("clicked()"),\ self._usebin_clicked) - self.connect(self._content.resamplex_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.resamplex_button, QtCore.SIGNAL("clicked()"),\ self._resamplex_clicked) - self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"), + self.connect(self._content.help_button, QtCore.SIGNAL("clicked()"),\ self._show_help) # Validated widgets diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py index bf773a667399..6a87cf213116 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_absolute_units.py @@ -1,5 +1,5 @@ -from PyQt4 import QtGui, uic, QtCore -from functools import partial +#pylint: disable=invalid-name +from PyQt4 import QtGui, QtCore from reduction_gui.widgets.base_widget import BaseWidget from reduction_gui.reduction.inelastic.dgs_absolute_units_script import AbsoluteUnitsScript import reduction_gui.widgets.util as util @@ -32,16 +32,16 @@ def __init__(self, parent=None): def initialize_content(self): # Constraints - for widget in [ - self._content.ei_edit, - self._content.van_mass_edit, - self._content.sample_mass_edit, - self._content.sample_rmm_edit, - self._content.median_test_high_edit, - self._content.median_test_low_edit, - self._content.median_test_out_high_edit, - self._content.median_test_out_low_edit, - self._content.errorbar_crit_edit, + for widget in [\ + self._content.ei_edit,\ + self._content.van_mass_edit,\ + self._content.sample_mass_edit,\ + self._content.sample_rmm_edit,\ + self._content.median_test_high_edit,\ + self._content.median_test_low_edit,\ + self._content.median_test_out_high_edit,\ + self._content.median_test_out_low_edit,\ + self._content.errorbar_crit_edit,\ ]: dvp = QtGui.QDoubleValidator(widget) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py index bcad89d2c524..97fd1f0bf314 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore from functools import partial from reduction_gui.widgets.base_widget import BaseWidget diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py index bb32beeca1d3..a8ed11691da5 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_diagnose_detectors.py @@ -1,5 +1,5 @@ -from PyQt4 import QtGui, uic, QtCore -from functools import partial +#pylint: disable=invalid-name +from PyQt4 import QtGui, QtCore from reduction_gui.widgets.base_widget import BaseWidget from reduction_gui.reduction.inelastic.dgs_diagnose_detectors_script import DiagnoseDetectorsScript import reduction_gui.widgets.util as util @@ -32,16 +32,16 @@ def __init__(self, parent=None): def initialize_content(self): # Constraints - for widget in [ - self._content.median_test_high_edit, - self._content.median_test_low_edit, - self._content.median_test_out_high_edit, - self._content.median_test_out_low_edit, - self._content.errorbar_crit_edit, - self._content.ratio_var_crit_edit, - self._content.sambkg_median_test_high_edit, - self._content.sambkg_median_test_low_edit, - self._content.sambkg_errorbar_crit_edit + for widget in [\ + self._content.median_test_high_edit,\ + self._content.median_test_low_edit,\ + self._content.median_test_out_high_edit,\ + self._content.median_test_out_low_edit,\ + self._content.errorbar_crit_edit,\ + self._content.ratio_var_crit_edit,\ + self._content.sambkg_median_test_high_edit,\ + self._content.sambkg_median_test_low_edit,\ + self._content.sambkg_errorbar_crit_edit\ ]: dvp = QtGui.QDoubleValidator(widget) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py index 40b9a26ba370..3db7b584dadd 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore from functools import partial from reduction_gui.widgets.base_widget import BaseWidget diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py index 8ec1f100358c..25786527e771 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore from functools import partial from reduction_gui.widgets.base_widget import BaseWidget @@ -147,9 +148,9 @@ def _grouping_browse(self): self._content.grouping_edit.setText(fname) def _savedir_browse(self): - save_dir = QtGui.QFileDialog.getExistingDirectory(self, "Output Directory - Choose a directory", - os.path.expanduser('~'), - QtGui.QFileDialog.ShowDirsOnly + save_dir = QtGui.QFileDialog.getExistingDirectory(self, "Output Directory - Choose a directory",\ + os.path.expanduser('~'),\ + QtGui.QFileDialog.ShowDirsOnly\ | QtGui.QFileDialog.DontResolveSymlinks) if save_dir: self._content.savedir_edit.setText(save_dir) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py index f2f4319cf527..cf30672d6521 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import sys """ @@ -63,7 +64,7 @@ def getPixelRange(self): def calculatePixelRange(self): nbr_x = len(self.x_list) - if ((nbr_x % 304) == 0): + if (nbr_x % 304) == 0: _list = self.y_list #REF_L else: _list = self.x_list #REF_M diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py index f8105395e8d8..d1a8c68ff43d 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py @@ -1,4 +1,5 @@ -from PyQt4 import QtGui, uic, QtCore +#pylint: disable=invalid-name,unused-import +from PyQt4 import QtGui, QtCore import reduction_gui.widgets.util as util import math import os @@ -211,9 +212,7 @@ def getMetadata(self,file): This retrieve the metadata from the data event NeXus file """ _full_file_name = file - tmpWks = LoadEventNexus(Filename=_full_file_name, -# OutputWorkspace='tmpWks', - MetaDataOnly='1') + tmpWks = LoadEventNexus(Filename=_full_file_name,MetaDataOnly='1') #mt1 = mtd['tmpWks'] #mt_run = mt1.getRun() @@ -319,19 +318,19 @@ def _smooth_x_axis(self, x_axis, y_axis, e_axis): sz = len(x_axis) i=0 - while (i < sz-1): + while i < sz-1: _left_x = x_axis[i] _right_x = x_axis[i+1] bCalAverage = False - if (_left_x == _right_x): + if _left_x == _right_x: bCalAverage = True else: _left_x = math.fabs(_left_x) _right_x = math.fabs(_right_x) _relative_diff = (_left_x - _right_x) / (_left_x + _right_x) - if (math.fabs(_relative_diff <= _precision)): + if math.fabs(_relative_diff <= _precision): bCalAverage = True _left_e = e_axis[i] @@ -345,7 +344,7 @@ def _smooth_x_axis(self, x_axis, y_axis, e_axis): _right_e2 = _right_e * _right_e _right_y = y_axis[i+1] - if (_left_e2 == 0. or _right_e2 == 0.): + if _left_e2 == 0. or _right_e2 == 0.: _y = 0. _e = 0. else: @@ -383,16 +382,16 @@ def weightedMean(self, data_array, error_array): sz = len(data_array) # calculate the numerator of mean - dataNum = 0; + dataNum = 0 for i in range(sz): - if not (data_array[i] == 0): + if not data_array[i] == 0: tmpFactor = float(data_array[i]) / float((pow(error_array[i],2))) dataNum += tmpFactor # calculate denominator - dataDen = 0; + dataDen = 0 for i in range(sz): - if not (error_array[i] == 0): + if not error_array[i] == 0: tmpFactor = 1./float((pow(error_array[i],2))) dataDen += tmpFactor @@ -444,7 +443,7 @@ def _average_y_of_same_x_(self): for j in range(len(data_y_i)): if data_y[j]>0 and data_y_i[j]>0: - [data_y[j], data_e[j]] = self.weightedMean([data_y[j], data_y_i[j]], [data_e[j], data_e_i[j]]); + [data_y[j], data_e[j]] = self.weightedMean([data_y[j], data_y_i[j]], [data_e[j], data_e_i[j]]) elif (data_y[j] == 0) and (data_y_i[j]>0): data_y[j] = data_y_i[j] data_e[j] = data_e_i[j] @@ -541,7 +540,7 @@ def _produce_y_of_same_x_(self, isUsingLessErrorValue): if data_y[j]>0 and data_y_i[j]>0: if isUsingLessErrorValue: - if (data_e[j] > data_e_i[j]): + if data_e[j] > data_e_i[j]: data_y[j] = data_y_i[j] data_e[j] = data_e_i[j] else: @@ -570,7 +569,7 @@ def _create_ascii_clicked(self): #retrieve name of the output file file_name = QtGui.QFileDialog.getSaveFileName(self, "Select or define a ASCII file name", default_file_name, "(*.txt)") - if (str(file_name).strip() == ''): + if str(file_name).strip() == '': return #check the status of the 4th column switch @@ -618,7 +617,7 @@ def _create_ascii_clicked(self): sz = len(x_axis)-1 for i in range(sz): # do not display data where R=0 - if (y_axis[i] > 1e-15): + if y_axis[i] > 1e-15: _line = str(x_axis[i]) _line += ' ' + str(y_axis[i]) _line += ' ' + str(e_axis[i]) @@ -638,7 +637,7 @@ def browse_config_file_name(self): ''' try: file_name = QtGui.QFileDialog.getOpenFileName(self, "Select a SF configuration file", "", "(*.cfg)") - if (str(file_name).strip() != ''): + if str(file_name).strip() != '': if os.path.isfile(file_name): self._summary.cfg_scaling_factor_file_name.setText(file_name) self.retrieve_list_of_incident_medium(file_name) @@ -816,7 +815,7 @@ def _report_error(error=None): f = open(file_path,'w') f.write(content) f.close() - QtGui.QMessageBox.information(self, "Automated reduction script saved", + QtGui.QMessageBox.information(self, "Automated reduction script saved",\ "The automated reduction script has been updated") except: _report_error() @@ -918,14 +917,14 @@ def _norm_clicked(self, is_checked): self._summary.norm_peak_to_pixel.setEnabled(is_checked) self._summary.norm_background_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_background_clicked(False) else: NormBackFlag = self._summary.norm_background_switch.isChecked() self._norm_background_clicked(NormBackFlag) self._summary.norm_low_res_range_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_low_res_clicked(False) else: LowResFlag = self._summary.norm_low_res_range_switch.isChecked() @@ -973,7 +972,7 @@ def _plot_count_vs_y(self, is_peak=True): For REFM, this is X For REFL, this is Y """ - + # run_number = self._summary.data_run_number_edit.text() # f = FileFinder.findRuns("%s%s" % (self.instrument_name, str(run_number)))[0] # @@ -1023,10 +1022,10 @@ def _plot_count_vs_y_bck(self): For REFL, this is Y """ - min, max = self._integrated_plot(True, - self._summary.data_run_number_edit, - self._summary.data_background_from_pixel1, - self._summary.data_background_to_pixel1, + min, max = self._integrated_plot(True,\ + self._summary.data_run_number_edit,\ + self._summary.data_background_from_pixel1,\ + self._summary.data_background_to_pixel1,\ False) def _plot_count_vs_x(self): @@ -1060,7 +1059,7 @@ def _plot_data_count_vs_tof_2d(self): basename = os.path.basename(file_path) ws_base = "__%s" % basename - if (self.instrument_name == 'REF_L'): + if self.instrument_name == 'REF_L': ws_output_base = "Pixel Y vs TOF" + " - " + basename else: ws_output_base = "Pixel X vs TOF" + " - " + basename @@ -1122,12 +1121,12 @@ def _plot_data_count_vs_tof_2d(self): #mantidplot.app.connect(mantidplot.app.mantidUI, QtCore.SIGNAL("python_peak_back_tof_range_update(double,double,double,double,double,double)"), call_back) #mantidplot.app.connect(mantidplot.app.RefDetectorViewer, QtCore.SIGNAL("python_peak_back_tof_range_update(double,double,double,double,double,double)"), call_back) - peak_min = int(self._summary.data_peak_from_pixel.text()); - peak_max = int(self._summary.data_peak_to_pixel.text()); - back_min = int(self._summary.data_background_from_pixel1.text()); - back_max = int(self._summary.data_background_to_pixel1.text()); - tof_min = int(self._summary.data_from_tof.text()); - tof_max = int(self._summary.data_to_tof.text()); + peak_min = int(self._summary.data_peak_from_pixel.text()) + peak_max = int(self._summary.data_peak_to_pixel.text()) + back_min = int(self._summary.data_background_from_pixel1.text()) + back_max = int(self._summary.data_background_to_pixel1.text()) + tof_min = int(self._summary.data_from_tof.text()) + tof_max = int(self._summary.data_to_tof.text()) import mantidqtpython self.ref_det_view = mantidqtpython.MantidQt.RefDetectorViewer.RefMatrixWSImageView(ws_output_base, peak_min, peak_max, back_min, back_max, tof_min, tof_max) @@ -1136,12 +1135,12 @@ def _plot_data_count_vs_tof_2d(self): def call_back(self, peakmin, peakmax, backmin, backmax, tofmin, tofmax): - self._summary.data_peak_from_pixel.setText("%-d" % int(peakmin)) - self._summary.data_peak_to_pixel.setText("%-d" % int(peakmax)) - self._summary.data_background_from_pixel1.setText("%-d" % int(backmin)) - self._summary.data_background_to_pixel1.setText("%-d" % int(backmax)) - self._summary.data_from_tof.setText("%-d" % int(tofmin)) - self._summary.data_to_tof.setText("%-d" % int(tofmax)) + self._summary.data_peak_from_pixel.setText("%-d" % int(peakmin)) + self._summary.data_peak_to_pixel.setText("%-d" % int(peakmax)) + self._summary.data_background_from_pixel1.setText("%-d" % int(backmin)) + self._summary.data_background_to_pixel1.setText("%-d" % int(backmax)) + self._summary.data_from_tof.setText("%-d" % int(tofmin)) + self._summary.data_to_tof.setText("%-d" % int(tofmax)) def _norm_count_vs_y(self): @@ -1310,7 +1309,7 @@ def _add_data(self): state.q_step = float(_q_step) state.scaling_factor_file = self._summary.cfg_scaling_factor_file_name.text() - if (self._summary.use_sf_config_switch.isChecked()): + if self._summary.use_sf_config_switch.isChecked(): state.scaling_factor_file_flag = True else: state.scaling_factor_file_flag = False @@ -1320,7 +1319,7 @@ def _add_data(self): state.geometry_correction_switch = self._summary.geometry_correction_switch.isChecked() #incident medium - _incident_medium_list = [str(self._summary.incident_medium_combobox.itemText(j)) + _incident_medium_list = [str(self._summary.incident_medium_combobox.itemText(j))\ for j in range(self._summary.incident_medium_combobox.count())] _incident_medium_index_selected = self._summary.incident_medium_combobox.currentIndex() @@ -1344,7 +1343,7 @@ def _add_data(self): item_widget = QtGui.QListWidgetItem(run_numbers, self._summary.angle_list) state.scaling_factor_file = self._summary.cfg_scaling_factor_file_name.text() - if (self._summary.use_sf_config_switch.isChecked()): + if self._summary.use_sf_config_switch.isChecked(): state.scaling_factor_file_flag = True else: state.scaling_factor_file_flag = False diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py index 8d7a5d7e4a11..db89665db9b7 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # used to parse files more easily from __future__ import with_statement @@ -60,7 +61,7 @@ def __init__(self, wk1=None, wk2=None, parent=None, type='data'): self.y2 = mt2.readY(0)[:] self.dataType = type - if (type == 'data'): + if type == 'data': self._peakFromValue=float(parent._summary.data_peak_from_pixel.text()) self._peakToValue=float(parent._summary.data_peak_to_pixel.text()) self._backFromValue=float(parent._summary.data_background_from_pixel1.text()) @@ -252,7 +253,7 @@ def peak_input_changed(self): def update_peak_back_selection_mode(self, bPeak): """Make sure that only 1 peak/back selection is activated at the same time""" self.peakSwitch.setChecked(bPeak) - self.backSwitch.setChecked(not(bPeak)) + self.backSwitch.setChecked(not bPeak) if bPeak: # class_name = self.from_peak_input.__class__.__name__ @@ -275,7 +276,7 @@ def update_back_selection_mode(self): def update_linear_log_selection_mode(self, bLinear): """Make sure that only linear or log are selected at the same time""" self.linear.setChecked(bLinear) - self.log.setChecked(not(bLinear)) + self.log.setChecked(not bLinear) def update_linear_selection_mode(self): self.update_linear_log_selection_mode(True) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py index f888acdcd1d3..b20f3a35624f 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math @@ -492,7 +493,7 @@ def _report_error(error=None): f = open(file_path,'w') f.write(content) f.close() - QtGui.QMessageBox.information(self, "Automated reduction script saved", + QtGui.QMessageBox.information(self, "Automated reduction script saved",\ "The automated reduction script has been updated") except: _report_error() @@ -595,14 +596,14 @@ def _norm_clicked(self, is_checked): self._summary.norm_peak_to_pixel.setEnabled(is_checked) self._summary.norm_background_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_background_clicked(False) else: NormBackFlag = self._summary.norm_background_switch.isChecked() self._norm_background_clicked(NormBackFlag) self._summary.norm_low_res_range_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_low_res_clicked(False) else: LowResFlag = self._summary.norm_low_res_range_switch.isChecked() @@ -1033,7 +1034,7 @@ def get_editing_state(self): m.DataPeakPixels = [int(self._summary.data_peak_from_pixel.text()), int(self._summary.data_peak_to_pixel.text())] - m.data_x_range = [int(self._summary.x_min_edit.text()), + m.data_x_range = [int(self._summary.x_min_edit.text()),\ int(self._summary.x_max_edit.text())] m.data_x_range_flag = self._summary.data_low_res_range_switch.isChecked() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py index 4fb464fa0057..decb4f87cd10 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math @@ -148,7 +149,7 @@ def get_editing_state(self): m.incident_medium_index_selected = self._summary.incident_medium_combobox.currentIndex() - m.data_x_range = [int(self._summary.x_min_edit.text()), + m.data_x_range = [int(self._summary.x_min_edit.text()),\ int(self._summary.x_max_edit.text())] m.data_x_range_flag = self._summary.data_low_res_range_switch.isChecked() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py index d845ccd96107..7d7fa32c1abc 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math @@ -134,7 +135,7 @@ def browse_config_file_name(self): Define configuration file name ''' file_name = QtGui.QFileDialog.getOpenFileName(self, "Select config file name", "", "(*.cfg)") - if (str(file_name).strip() != ''): + if str(file_name).strip() != '': self._summary.cfg_scaling_factor_file_name.setText(file_name) self.display_preview_config_file() @@ -288,7 +289,7 @@ def _add_data(self): in_list = False # Check whether it's already in the list run_numbers = self._summary.data_run_number_edit.text() - if (run_numbers == ''): + if run_numbers == '': return list_items = self._summary.angle_list.findItems(run_numbers, QtCore.Qt.MatchFixedString) @@ -314,7 +315,7 @@ def _add_data(self): state.scaling_factor_file = self._summary.cfg_scaling_factor_file_name.text() #incident medium - _incident_medium_list = [str(self._summary.incident_medium_combobox.itemText(j)) + _incident_medium_list = [str(self._summary.incident_medium_combobox.itemText(j))\ for j in range(self._summary.incident_medium_combobox.count())] _incident_medium_index_selected = self._summary.incident_medium_combobox.currentIndex() @@ -403,7 +404,7 @@ def set_editing_state(self, state): self._summary.tof_max.setText(str(state.tof_max)) self._summary.cfg_scaling_factor_file_name.setText(str(state.scaling_factor_file)) - if (state.scaling_factor_file != ''): + if state.scaling_factor_file != '': self.display_preview_config_file() self._summary.data_run_number_edit.setText(str(state.data_file)) @@ -429,7 +430,7 @@ def get_state(self): state_list = [] #common incident medium - m.incident_medium_list = [self._summary.incident_medium_combobox.itemText(i) + m.incident_medium_list = [self._summary.incident_medium_combobox.itemText(i)\ for i in range(self._summary.incident_medium_combobox.count())] m.incident_medium_index_selected = self._summary.incident_medium_combobox.currentIndex() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py index 062c0497128a..a6b69395b762 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math @@ -359,7 +360,7 @@ def _report_error(error=None): f = open(file_path,'w') f.write(content) f.close() - QtGui.QMessageBox.information(self, "Automated reduction script saved", + QtGui.QMessageBox.information(self, "Automated reduction script saved",\ "The automated reduction script has been updated") except: _report_error() @@ -461,14 +462,14 @@ def _norm_clicked(self, is_checked): self._summary.norm_peak_to_pixel.setEnabled(is_checked) self._summary.norm_background_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_background_clicked(False) else: NormBackFlag = self._summary.norm_background_switch.isChecked() self._norm_background_clicked(NormBackFlag) self._summary.norm_low_res_range_switch.setEnabled(is_checked) - if (not(is_checked)): + if not is_checked: self._norm_low_res_clicked(False) else: LowResFlag = self._summary.norm_low_res_range_switch.isChecked() @@ -846,7 +847,7 @@ def get_editing_state(self): m.DataPeakPixels = [int(self._summary.data_peak_from_pixel.text()), int(self._summary.data_peak_to_pixel.text())] - m.data_x_range = [int(self._summary.x_min_edit.text()), + m.data_x_range = [int(self._summary.x_min_edit.text()),\ int(self._summary.x_max_edit.text())] m.data_x_range_flag = self._summary.data_low_res_range_switch.isChecked() @@ -964,12 +965,12 @@ def _plot_data_count_vs_tof_2d(self): #mantidplot.app.connect(mantidplot.app.mantidUI, QtCore.SIGNAL("python_peak_back_tof_range_update(double,double,double,double,double,double)"), call_back) #mantidplot.app.connect(mantidplot.app.RefDetectorViewer, QtCore.SIGNAL("python_peak_back_tof_range_update(double,double,double,double,double,double)"), call_back) - peak_min = int(self._summary.data_peak_from_pixel.text()); - peak_max = int(self._summary.data_peak_to_pixel.text()); - back_min = int(self._summary.data_background_from_pixel1.text()); - back_max = int(self._summary.data_background_to_pixel1.text()); - tof_min = int(self._summary.data_from_tof.text()); - tof_max = int(self._summary.data_to_tof.text()); + peak_min = int(self._summary.data_peak_from_pixel.text()) + peak_max = int(self._summary.data_peak_to_pixel.text()) + back_min = int(self._summary.data_background_from_pixel1.text()) + back_max = int(self._summary.data_background_to_pixel1.text()) + tof_min = int(self._summary.data_from_tof.text()) + tof_max = int(self._summary.data_to_tof.text()) import mantidqtpython self.ref_det_view = mantidqtpython.MantidQt.RefDetectorViewer.RefMatrixWSImageView(ws_output_base_ff+'_2D', peak_min, peak_max, back_min, back_max, tof_min, tof_max) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py index 4ba451ee7e3e..5486443fe023 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import sip import os @@ -320,8 +321,8 @@ def _apply(self): message = "Could not scale data\n %s" % sys.exc_value if self._content.scale_to_one_chk.isChecked(): message += "\n\nCheck your Q range near the critical edge" - QtGui.QMessageBox.warning(self, - "Error scaling data", + QtGui.QMessageBox.warning(self,\ + "Error scaling data",\ message) def _pick_specular_ridge(self): @@ -382,8 +383,8 @@ def _scale_data_sets(self): ref_data = item.get_user_data(ref_pol) if ref_data is None: - QtGui.QMessageBox.warning(self, - "Invalid choice of reference cross-section", + QtGui.QMessageBox.warning(self,\ + "Invalid choice of reference cross-section",\ "The selected cross-section is empty, please select another one") return s.append(ref_data) @@ -466,7 +467,7 @@ def _save_result(self, send_email=False): self._stitcher.save_combined(fname, as_canSAS=False) file_list.append(fname) else: - pol_list = ["Off_Off", "On_Off", + pol_list = ["Off_Off", "On_Off",\ "Off_On", "On_On"] for pol in pol_list: try: diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py index e7ad2b6040b0..bff21bffae1c 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import os diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py index 7871cb0b37e8..34738beaa8a5 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py index 2944e837ece2..c5a77deeb62d 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import os diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py index b1151785c73a..42e017168515 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import os @@ -134,7 +135,7 @@ def _patch_checked(self): def _draw_patch(self): if IS_IN_MANTIDPLOT: - self.show_instrument(self._content.sensitivity_file_edit.text, + self.show_instrument(self._content.sensitivity_file_edit.text,\ workspace=self.patch_ws, tab=2, reload=True, data_proxy=None) def _create_sensitivity(self): diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py index 1a8ef047e21c..5c2c1e8879ac 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import math @@ -120,7 +121,7 @@ def initialize_content(self): self.connect(self._summary.log_binning_radio, QtCore.SIGNAL("clicked(bool)"), self._summary.align_check.setEnabled) self._summary.scale_edit.setText("1") - + self._summary.n_wedges_edit.setText("2") self._summary.wedge_angle_edit.setText("30") self._summary.wedge_offset_edit.setText("0") @@ -150,7 +151,7 @@ def initialize_content(self): self._summary.mask_side_none_radio.hide() self._summary.mask_side_front_radio.hide() self._summary.mask_side_back_radio.hide() - + if not self._in_mantidplot: self._summary.dark_plot_button.hide() self._summary.scale_data_plot_button.hide() @@ -349,18 +350,18 @@ def set_state(self, state): self._summary.align_check.setEnabled(state.log_binning) self._summary.align_check.setChecked(state.align_log_with_decades) self._summary.error_weighting_check.setChecked(state.error_weighting) - + self._summary.n_wedges_edit.setText(str(state.n_wedges)) self._summary.wedge_angle_edit.setText(str(state.wedge_angle)) self._summary.wedge_offset_edit.setText(str(state.wedge_offset)) - + # Mask self._summary.mask_edit.setText(str(state.mask_file)) self._summary.mask_check.setChecked(state.use_mask_file) self._mask_checked(state.use_mask_file) self._masked_detectors = state.detector_ids self.mask_reload = True - + if state.masked_side == 'Front': self._summary.mask_side_front_radio.setChecked(True) elif state.masked_side == 'Back': @@ -440,7 +441,7 @@ def get_state(self): m.masked_side = 'Back' else: m.masked_side = None - + # Mask detector IDs m.use_mask_file = self._summary.mask_check.isChecked() m.mask_file = unicode(self._summary.mask_edit.text()) diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py index ff890705a4e9..af57ad1391ad 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/hfir_sample_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import reduction_gui.widgets.util as util import os @@ -172,7 +173,7 @@ def get_state(self): return m def _sample_scatt_plot(self): - self.show_instrument(unicode(self._content.sample_scatt_edit.text())) + self.show_instrument(unicode(self._content.sample_scatt_edit.text())) def _sample_scatt_browse(self): fname = self.data_browse_dialog() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py index 9ec8166fc03d..d02ae0d78f49 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import os from reduction_gui.settings.application_settings import GeneralSettings @@ -162,13 +163,13 @@ def _get_catalog(self): self._content.data_set_table.resizeColumnsToContents() def _browse_directory(self): - dir = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory", + dir = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory",\ self._settings.data_path) - if dir: + if dir: # Store the location of the loaded file - self._settings.data_path = str(dir) - self._content.directory_edit.setText(dir) - self._update_content() + self._settings.data_path = str(dir) + self._content.directory_edit.setText(dir) + self._update_content() def set_state(self, state): """ @@ -180,4 +181,4 @@ def set_state(self, state): self._update_content(False) def get_state(self): - return Catalog() \ No newline at end of file + return Catalog() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py index ff8927473391..322e7bad78da 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/sans/stitcher.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtGui, uic, QtCore import os from reduction_gui.settings.application_settings import GeneralSettings @@ -512,4 +513,4 @@ def get_state(self): """ Return dummy state """ - return StitcherState() \ No newline at end of file + return StitcherState() diff --git a/Code/Mantid/scripts/Interface/reduction_gui/widgets/util.py b/Code/Mantid/scripts/Interface/reduction_gui/widgets/util.py index 862e7528df74..0ec9cb1e3cd8 100644 --- a/Code/Mantid/scripts/Interface/reduction_gui/widgets/util.py +++ b/Code/Mantid/scripts/Interface/reduction_gui/widgets/util.py @@ -38,7 +38,7 @@ def _check_and_get_float_line_edit(line_edit, min=None): value = 0.0 try: value = float(line_edit.text()) - if (min is None or value>min): + if min is None or value>min: line_edit.setStyleSheet(CSS_DEFAULT) else: line_edit.setStyleSheet(CSS_INVALID) diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py index b7ce069e2c6e..034e3994dcb1 100644 --- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py +++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_diffraction_adv_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'diffraction_adv_setup.ui' @@ -376,7 +377,7 @@ def retranslateUi(self, Frame): self.preserveevents_checkbox.setStatusTip(_translate("Frame", "Check to calculate the absolute scale factor using the direct beam method.", None)) self.preserveevents_checkbox.setText(_translate("Frame", "Preserve Events", None)) self.vanadium_correction_groupbox.setTitle(_translate("Frame", "Strip Vanadium Peaks", None)) - self.mask_help_label.setText(_translate("Frame", "The following input parameters are used to control the algorithm to strip vanadium peaks.\n" + self.mask_help_label.setText(_translate("Frame", "The following input parameters are used to control the algorithm to strip vanadium peaks.\n"\ "", None)) self.stripvanpeaks_chkbox.setToolTip(_translate("Frame", "

Check to subtract fitted vanadium peaks from the known positions.

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

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

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

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

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

Disable emptry/background correction.

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

Enter vanadium background run number.

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

User specified maximum TOF of the data.

", None)) diff --git a/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py b/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py index 460bdfcbe610..9a448ee278d4 100644 --- a/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py +++ b/Code/Mantid/scripts/Interface/ui/diffraction/ui_filter_info.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'filter_info.ui' @@ -51,7 +52,7 @@ def setupUi(self, Dialog): def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Filter help", None, QtGui.QApplication.UnicodeUTF8)) - self.plainTextEdit.setPlainText(QtGui.QApplication.translate("Dialog", "To use this application, you will need:\n" + self.plainTextEdit.setPlainText(QtGui.QApplication.translate("Dialog", "To use this application, you will need:\n"\ "\n" "- Your Nexus event files ( _event.nxs)\n" "- The Nexus event file used in this filter setup page must be same to the data reduction page.\n" diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py index e019a1e190d9..4a326237468b 100644 --- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py +++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_absolute_units.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/inelastic/dgs_absolute_units.ui' diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py index 7f53416ea85e..6ad6b96db96e 100644 --- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py +++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_data_corrections.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/inelastic/dgs_data_corrections.ui' diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py index c9154b2a56c3..dfbb26eecbe1 100644 --- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py +++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_diagnose_detectors.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/inelastic/dgs_diagnose_detectors.ui' diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py index 816d5f5d01f0..9cd9be763606 100644 --- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py +++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_pd_sc_conversion.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/inelastic/dgs_pd_sc_conversion.ui' diff --git a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py index ff07c13ee698..88f73ac39881 100644 --- a/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py +++ b/Code/Mantid/scripts/Interface/ui/inelastic/ui_dgs_sample_setup.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file './dgs_sample_setup.ui' diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py index 7a027ee6777e..f231c63e780c 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_choose_col.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name #This is an extension of refl_columns.py as that is a auto-generated script form pyqt and shouldn't be edited #so this file provides any extra GUI tweaks not easily doable in the designer #for the time being this also includes non-GUI behaviour @@ -37,4 +38,4 @@ def on_listColumns_itemChanged(self, item): def on_buttonsColumns_Clicked(self, button): if self.buttonsColumns.button(QtGui.QDialogButtonBox.RestoreDefaults) == button: for i in range(self.listColumns.count()): - self.listColumns.item(i).setCheckState(2) \ No newline at end of file + self.listColumns.item(i).setCheckState(2) diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py index 9535885c8cc8..d1fd9c668295 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_columns.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'D:\mantid\windows\Code\Mantid\scripts\Interface\ui\reflectometer/refl_columns.ui' diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py index 99b3c7da943e..0789e8d3c743 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import refl_window import refl_save import refl_choose_col @@ -82,28 +83,28 @@ def __init__(self): self.live_method = settings.value(self.__live_data_method_key, "", type=str) self.live_freq = settings.value(self.__live_data_frequency_key, 0, type=float) - if not (self.live_freq): + if not self.live_freq: logger.information("No settings were found for Update frequency of loading live data, Loading default of 60 seconds") self.live_freq = float(60) settings.setValue(self.__live_data_frequency_key, self.live_freq) - if not (self.live_method): + if not self.live_method: logger.information("No settings were found for Accumulation Method of loading live data, Loading default of \"Add\"") self.live_method = "Add" settings.setValue(self.__live_data_method_key, self.live_method) settings.endGroup() settings.beginGroup(self.__generic_settings) - + self.__alg_migrate = settings.value(self.__alg_migration_key, True, type=bool) if self.__alg_migrate: self.__alg_use = True # We will use the algorithms by default rather than the quick scripts self.__alg_migrate = False # Never do this again. We only want to reset once. else: self.__alg_use = settings.value(self.__ads_use_key, True, type=bool) - + self.__icat_download = settings.value(self.__icat_download_key, False, type=bool) self.__group_tof_workspaces = settings.value(self.__group_tof_workspaces_key, True, type=bool) - + settings.setValue(self.__ads_use_key, self.__alg_use) settings.setValue(self.__icat_download_key, self.__icat_download) settings.setValue(self.__group_tof_workspaces_key, self.__group_tof_workspaces) @@ -127,15 +128,15 @@ def _save_check(self): """ msgBox = QtGui.QMessageBox() msgBox.setText("The table has been modified. Do you want to save your changes?") - + accept_btn = QtGui.QPushButton('Accept') cancel_btn = QtGui.QPushButton('Cancel') discard_btn = QtGui.QPushButton('Discard') - + msgBox.addButton(accept_btn, QtGui.QMessageBox.AcceptRole) msgBox.addButton(cancel_btn, QtGui.QMessageBox.RejectRole) msgBox.addButton(discard_btn, QtGui.QMessageBox.NoRole) - + msgBox.setIcon(QtGui.QMessageBox.Question) msgBox.setDefaultButton(accept_btn) msgBox.setEscapeButton(cancel_btn) @@ -149,7 +150,7 @@ def _save_check(self): ret = QtGui.QMessageBox.RejectRole else: ret = QtGui.QMessageBox.NoRole - + return ret, saved def closeEvent(self, event): @@ -166,7 +167,7 @@ def closeEvent(self, event): elif ret == QtGui.QMessageBox.NoRole: self.mod_flag = False event.accept() - + def _instrument_selected(self, instrument): """ Change the default instrument to the selected one @@ -279,12 +280,12 @@ def _initialise_table(self): for column in range(self.tableMain.columnCount()): for row in range(self.tableMain.rowCount()): - if (column in self.run_cols): + if column in self.run_cols: item = QtGui.QTableWidgetItem() item.setText('') item.setToolTip('Runs can be colon delimited to coadd them') self.tableMain.setItem(row, column, item) - elif (column in self.angle_cols): + elif column in self.angle_cols: item = QtGui.QTableWidgetItem() item.setText('') item.setToolTip('Angles are in degrees') @@ -438,15 +439,15 @@ def _autofill(self): howMany = len(self.tableMain.selectedItems()) for cell in self.tableMain.selectedItems(): sum = sum + self.tableMain.row(cell) - if (howMany): + if howMany: selectedrow = self.tableMain.row(self.tableMain.selectedItems()[0]) - if (sum / howMany == selectedrow): + if sum / howMany == selectedrow: startrow = selectedrow + 1 filled = 0 for cell in self.tableMain.selectedItems(): row = startrow txt = cell.text() - while (self.tableMain.item(row, 0).text() != ''): + while self.tableMain.item(row, 0).text() != '': item = QtGui.QTableWidgetItem() item.setText(txt) self.tableMain.setItem(row, self.tableMain.column(cell), item) @@ -685,22 +686,22 @@ def _process(self): overlapLow = [] overlapHigh = [] theta = [0, 0, 0] - if (self.tableMain.item(row, 0).text() != ''): + if self.tableMain.item(row, 0).text() != '': self.statusMain.showMessage("Processing row: " + str(row + 1)) logger.debug("Processing row: " + str(row + 1)) for i in range(3): run_entry = str(self.tableMain.item(row, i * 5).text()) - if (run_entry != ''): + if run_entry != '': runno.append(run_entry) ovLow = str(self.tableMain.item(row, (i * 5) + 3).text()) - if (ovLow != ''): + if ovLow != '': overlapLow.append(float(ovLow)) ovHigh = str(self.tableMain.item(row, (i * 5) + 4).text()) - if (ovHigh != ''): + if ovHigh != '': overlapHigh.append(float(ovHigh)) # Determine resolution - if (self.tableMain.item(row, 15).text() == ''): + if self.tableMain.item(row, 15).text() == '': loadedRun = None if load_live_runs.is_live_run(runno[0]): loadedRun = load_live_runs.get_live_data(config['default.instrument'], frequency = self.live_freq, accumulation = self.live_method) @@ -717,7 +718,7 @@ def _process(self): #If we're given a group workspace, we can just run it on the first member of the group instead thetaRun = loadedRun if isinstance(thetaRun, WorkspaceGroup): - thetaRun = thetaRun[0] + thetaRun = thetaRun[0] dqq, two_theta = CalculateResolution(Workspace = thetaRun, TwoTheta = two_theta) #Put the calculated resolution into the table @@ -760,16 +761,16 @@ def _process(self): qmin = round(qmin, 3) qmax = round(qmax, 3) wksp.append(wq.name()) - if (self.tableMain.item(row, i * 5 + 1).text() == ''): + if self.tableMain.item(row, i * 5 + 1).text() == '': item = QtGui.QTableWidgetItem() item.setText(str(theta)) self.tableMain.setItem(row, i * 5 + 1, item) - if (self.tableMain.item(row, i * 5 + 3).text() == ''): + if self.tableMain.item(row, i * 5 + 3).text() == '': item = QtGui.QTableWidgetItem() item.setText(str(qmin)) self.tableMain.setItem(row, i * 5 + 3, item) overlapLow.append(qmin) - if (self.tableMain.item(row, i * 5 + 4).text() == ''): + if self.tableMain.item(row, i * 5 + 4).text() == '': item = QtGui.QTableWidgetItem() if i == len(runno) - 1: # allow full high q-range for last angle @@ -783,28 +784,28 @@ def _process(self): #Scale each run if self.tableMain.item(row, self.scale_col).text(): Scale(InputWorkspace=wksp[i], OutputWorkspace=wksp[i], Factor=1 / float(self.tableMain.item(row, self.scale_col).text())) - + if self.__checked_row_stiched(row): - if (len(runno) == 1): + if len(runno) == 1: logger.notice("Nothing to combine for processing row : " + str(row)) else: w1 = getWorkspace(wksp[0]) w2 = getWorkspace(wksp[-1]) - if (len(runno) == 2): + if len(runno) == 2: outputwksp = runno[0] + '_' + runno[1][3:5] else: outputwksp = runno[0] + '_' + runno[-1][3:5] begoverlap = w2.readX(0)[0] # get Qmax - if (self.tableMain.item(row, i * 5 + 4).text() == ''): + if self.tableMain.item(row, i * 5 + 4).text() == '': overlapHigh = 0.3 * max(w1.readX(0)) Qmin = min(w1.readX(0)) Qmax = max(w2.readX(0)) wcomb = combineDataMulti(wksp, outputwksp, overlapLow, overlapHigh, Qmin, Qmax, -dqq, 1, keep=True) - - + + # Enable the plot button plotbutton = self.tableMain.cellWidget(row, self.plot_col).children()[1] plotbutton.setProperty('runno',runno) @@ -880,7 +881,7 @@ def _plot(self, plotbutton): self.__graphs[wksp[i]] = base_graph titl = groupGet(ws_name_binned, 'samp', 'run_title') - if (type(titl) == str): + if type(titl) == str: base_graph.activeLayer().setTitle(titl) base_graph.activeLayer().setAxisScale(Layer.Left, Imin * 0.1, Imax * 10, Layer.Log10) base_graph.activeLayer().setAxisScale(Layer.Bottom, Qmin * 0.9, Qmax * 1.1, Layer.Log10) @@ -889,14 +890,14 @@ def _plot(self, plotbutton): # Create and plot stitched outputs if self.__checked_row_stiched(row): - if (len(runno) == 2): + if len(runno) == 2: outputwksp = runno[0] + '_' + runno[1][3:5] else: outputwksp = runno[0] + '_' + runno[2][3:5] if not getWorkspace(outputwksp, report_error=False): # Stitching has not been done as part of processing, so we need to do it here. wcomb = combineDataMulti(wkspBinned, outputwksp, overlapLow, overlapHigh, Qmin, Qmax, -dqq, 1, keep=True) - + Qmin = min(getWorkspace(outputwksp).readX(0)) Qmax = max(getWorkspace(outputwksp).readX(0)) if canMantidPlot: @@ -1043,7 +1044,7 @@ def _save_table_contents(self, filename): rowtext = [] for column in range(self.tableMain.columnCount() - 2): rowtext.append(self.tableMain.item(row, column).text()) - if (len(rowtext) > 0): + if len(rowtext) > 0: writer.writerow(rowtext) self.current_table = filename logger.notice("Saved file to " + filename) @@ -1132,7 +1133,7 @@ def _load_table(self): reader = csv.reader(open(filename, "rb")) row = 0 for line in reader: - if (row < 100): + if row < 100: for column in range(self.tableMain.columnCount() - 2): item = QtGui.QTableWidgetItem() item.setText(line[column]) @@ -1167,7 +1168,7 @@ def _reload_table(self): reader = csv.reader(open(filename, "rb")) row = 0 for line in reader: - if (row < 100): + if row < 100: for column in range(self.tableMain.columnCount() - 2): item = QtGui.QTableWidgetItem() item.setText(line[column]) @@ -1198,8 +1199,8 @@ def _options_dialog(self): Shows the dialog for setting options regarding live data """ try: - - dialog_controller = refl_options.ReflOptions(def_method = self.live_method, def_freq = self.live_freq, + + dialog_controller = refl_options.ReflOptions(def_method = self.live_method, def_freq = self.live_freq, def_alg_use = self.__alg_use, def_icat_download=self.__icat_download, def_group_tof_workspaces = self.__group_tof_workspaces) if dialog_controller.exec_(): diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py index 484e52c3dfab..459c1018ebb7 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_gui_run.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import refl_gui from PyQt4 import QtCore, QtGui @@ -8,4 +9,4 @@ ui = refl_gui.ReflGui() ui.setupUi(MainWindow) MainWindow.show() - sys.exit(app.exec_()) \ No newline at end of file + sys.exit(app.exec_()) diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py index da837f4513dd..536297b780ae 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import refl_options_window from PyQt4 import QtCore, QtGui @@ -69,14 +70,14 @@ def __update_groupTOF_method(self, checked): self.__group_tof_workspaces = checked def icatDownload(self): - return (self.__icat_download) + return self.__icat_download def groupTOFWorkspaces(self): return self.__group_tof_workspaces def frequency(self): return self.__frequency - + def useAlg(self): return self.__alg_use diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options_window.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options_window.py index 0d4bf0e8273f..a2ab5338fd87 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options_window.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_options_window.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'refl_options_window.ui' diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py index f7d4a857e09f..6dabce7fe2a5 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_save.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtCore, QtGui import os from mantid.simpleapi import * @@ -17,7 +18,7 @@ class Ui_SaveWindow(object): def __init__(self): - self.__has_mount_point = True; + self.__has_mount_point = True self.__instrument = config['default.instrument'].strip().upper() @@ -26,7 +27,7 @@ def __init__(self): self.__mountpoint = usersettings.get_named_setting("DataMountPoint") except KeyError: print "DataMountPoint is missing from the config.xml file." - self.__has_mount_point = False; + self.__has_mount_point = False def setupUi(self, SaveWindow): self.SavePath="" @@ -276,7 +277,7 @@ def populateList(self): self.listWidget.setCurrentItem(self.listWidget.item(0)) # try to get correct user directory currentInstrument=config['default.instrument'] - if (self.SavePath!=''): + if self.SavePath!='': self.lineEdit.setText(self.SavePath) else: if self.__has_mount_point: @@ -317,23 +318,23 @@ def buttonClickHandler1(self): for idx in self.listWidget.selectedItems(): runlist=parseRunList(str(self.spectraEdit.text())) fname=os.path.join(self.lineEdit.text(),prefix + idx.text()) - if (self.comboBox.currentIndex() == 0): + if self.comboBox.currentIndex() == 0: print "Custom Ascii format" - if (self.radio1.isChecked()): + if self.radio1.isChecked(): sep=',' - elif (self.radio2.isChecked()): + elif self.radio2.isChecked(): sep=' ' - elif (self.radio3.isChecked()): + elif self.radio3.isChecked(): sep='\t' else: sep=' ' saveCustom(idx,fname,sep,self.listWidget2.selectedItems(),self.titleCheckBox.isChecked(),self.xErrorCheckBox.isChecked()) - elif (self.comboBox.currentIndex() == 1): + elif self.comboBox.currentIndex() == 1: print "Not yet implemented!" - elif (self.comboBox.currentIndex() == 2): + elif self.comboBox.currentIndex() == 2: print "ANSTO format" saveANSTO(idx,fname) - elif (self.comboBox.currentIndex() == 3): + elif self.comboBox.currentIndex() == 3: print "ILL MFT format" saveMFT(idx,fname,self.listWidget2.selectedItems()) # for idx in self.listWidget.selectedItems(): @@ -377,16 +378,16 @@ def groupGet(wksp, whattoget, field=''): returns information about instrument or sample details for a given workspace wksp, also if the workspace is a group (info from first group element) ''' - if (whattoget == 'inst'): + if whattoget == 'inst': if isinstance(mtd[wksp], WorkspaceGroup): return mtd[wksp + '_1'].getInstrument() else: return mtd[wksp].getInstrument() - elif (whattoget == 'samp' and field != ''): + elif whattoget == 'samp' and field != '': if isinstance(mtd[wksp], WorkspaceGroup): try: log = mtd[wksp + '_1'].getRun().getLogData(field).value - if (type(log) is int or type(log) is str): + if type(log) is int or type(log) is str: res = log else: res = log[len(log) - 1] @@ -396,7 +397,7 @@ def groupGet(wksp, whattoget, field=''): else: try: log = mtd[wksp].getRun().getLogData(field).value - if (type(log) is int or type(log) is str): + if type(log) is int or type(log) is str: res = log else: res = log[len(log) - 1] @@ -404,7 +405,7 @@ def groupGet(wksp, whattoget, field=''): res = 0 print "Block " + field + " not found." return res - elif (whattoget == 'wksp'): + elif whattoget == 'wksp': if isinstance(mtd[wksp], WorkspaceGroup): return mtd[wksp + '_1'].getNumberHistograms() else: diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py index 689e5e4647f9..c4ab20582203 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/refl_window.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'refl_window.ui' diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py index a4b1339ff18f..4af2bc635311 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_data_refl_simple.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'data_refl_simple.ui' @@ -1579,7 +1580,7 @@ def retranslateUi(self, Frame): Frame.setWindowTitle(QtGui.QApplication.translate("Frame", "Frame", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_3.setTitle(QtGui.QApplication.translate("Frame", "Angle List", None, QtGui.QApplication.UnicodeUTF8)) self.label_10.setText(QtGui.QApplication.translate("Frame", "List of runs to be stitched together.", None, QtGui.QApplication.UnicodeUTF8)) - self.waiting_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.waiting_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -1685,7 +1686,7 @@ def retranslateUi(self, Frame): self.q_bins_label.setText(QtGui.QApplication.translate("Frame", "Number of bins ", None, QtGui.QApplication.UnicodeUTF8)) self.q_step_label.setText(QtGui.QApplication.translate("Frame", "Q steps ", None, QtGui.QApplication.UnicodeUTF8)) self.q_step_edit.setText(QtGui.QApplication.translate("Frame", "0.02", None, QtGui.QApplication.UnicodeUTF8)) - self.q_step_unit_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.q_step_unit_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -1703,7 +1704,7 @@ def retranslateUi(self, Frame): self.overlapValueLowestErrorRadioButton.setText(QtGui.QApplication.translate("Frame", "use lowest error value", None, QtGui.QApplication.UnicodeUTF8)) self.overlapValueMeanRadioButton.setText(QtGui.QApplication.translate("Frame", "use mean value ", None, QtGui.QApplication.UnicodeUTF8)) self.fourth_column_switch.setText(QtGui.QApplication.translate("Frame", "4th column (precision)", None, QtGui.QApplication.UnicodeUTF8)) - self.dq0_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.dq0_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -1713,14 +1714,14 @@ def retranslateUi(self, Frame): self.dq_over_q_label.setText(QtGui.QApplication.translate("Frame", "dQ/Q", None, QtGui.QApplication.UnicodeUTF8)) self.dq_over_q.setText(QtGui.QApplication.translate("Frame", "0.02", None, QtGui.QApplication.UnicodeUTF8)) self.create_ascii_button.setText(QtGui.QApplication.translate("Frame", "Create ASCII...", None, QtGui.QApplication.UnicodeUTF8)) - self.edited_warning_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.edited_warning_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" "

Click Save To List to apply your changes →

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

\n" "

", None, QtGui.QApplication.UnicodeUTF8)) self.label_2.setText(QtGui.QApplication.translate("Frame", "Run", None, QtGui.QApplication.UnicodeUTF8)) - self.label_4.setText(QtGui.QApplication.translate("Frame", "Scaling\n" + self.label_4.setText(QtGui.QApplication.translate("Frame", "Scaling\n"\ "factor", None, QtGui.QApplication.UnicodeUTF8)) - self.label_3.setText(QtGui.QApplication.translate("Frame", "Low-end\n" + self.label_3.setText(QtGui.QApplication.translate("Frame", "Low-end\n"\ "points to\n" "skip", None, QtGui.QApplication.UnicodeUTF8)) - self.label_5.setText(QtGui.QApplication.translate("Frame", "High-end\n" + self.label_5.setText(QtGui.QApplication.translate("Frame", "High-end\n"\ "points to\n" "skip", None, QtGui.QApplication.UnicodeUTF8)) self.scale_to_one_chk.setText(QtGui.QApplication.translate("Frame", "Scale to unity", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py index 2d64b50dd307..267934bda984 100644 --- a/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py +++ b/Code/Mantid/scripts/Interface/ui/reflectometer/ui_refm_reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'refm_reduction.ui' @@ -1233,9 +1234,9 @@ def setupUi(self, Frame): def retranslateUi(self, Frame): Frame.setWindowTitle(QtGui.QApplication.translate("Frame", "Frame", None, QtGui.QApplication.UnicodeUTF8)) self.groupBox_3.setTitle(QtGui.QApplication.translate("Frame", "Angle List", None, QtGui.QApplication.UnicodeUTF8)) - self.label_10.setText(QtGui.QApplication.translate("Frame", "List of runs to be \n" + self.label_10.setText(QtGui.QApplication.translate("Frame", "List of runs to be \n"\ "stitched together.", None, QtGui.QApplication.UnicodeUTF8)) - self.waiting_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.waiting_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -1319,7 +1320,7 @@ def retranslateUi(self, Frame): self.tof_max_label2.setText(QtGui.QApplication.translate("Frame", " µs", None, QtGui.QApplication.UnicodeUTF8)) self.plot_tof_btn.setToolTip(QtGui.QApplication.translate("Frame", "Plot TOF distribution", None, QtGui.QApplication.UnicodeUTF8)) self.plot_tof_btn.setText(QtGui.QApplication.translate("Frame", "TOF distribution", None, QtGui.QApplication.UnicodeUTF8)) - self.edited_warning_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.edited_warning_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -1342,7 +1343,7 @@ def retranslateUi(self, Frame): self.angle_offset_unit_label.setText(QtGui.QApplication.translate("Frame", " degrees", None, QtGui.QApplication.UnicodeUTF8)) self.outdir_label.setText(QtGui.QApplication.translate("Frame", "Output directory", None, QtGui.QApplication.UnicodeUTF8)) self.outdir_browse_button.setText(QtGui.QApplication.translate("Frame", "Browse", None, QtGui.QApplication.UnicodeUTF8)) - self.auto_reduce_help_label.setText(QtGui.QApplication.translate("Frame", "\n" + self.auto_reduce_help_label.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py index 721d18f94ac9..49e5bff30d84 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_info.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/eqsans_info.ui' @@ -46,7 +47,7 @@ def setupUi(self, Dialog): def retranslateUi(self, Dialog): Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "EQSANS help", None, QtGui.QApplication.UnicodeUTF8)) - self.plainTextEdit.setPlainText(QtGui.QApplication.translate("Dialog", "To use this application, you will need:\n" + self.plainTextEdit.setPlainText(QtGui.QApplication.translate("Dialog", "To use this application, you will need:\n"\ "\n" "- Your Nexus event files (.nxs)\n" "- The corresponding eqsans_configuration.xxxx files [optional]\n" diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py index e591d6a37ced..870b7a7d93c5 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/eqsans_instrument.ui' @@ -576,7 +577,7 @@ def retranslateUi(self, Frame): self.output_dir_edit.setStatusTip(QtGui.QApplication.translate("Frame", "Output directory for reduced data.", None, QtGui.QApplication.UnicodeUTF8)) self.output_dir_browse_button.setText(QtGui.QApplication.translate("Frame", "Browse", None, QtGui.QApplication.UnicodeUTF8)) self.geometry_options_groupbox.setTitle(QtGui.QApplication.translate("Frame", "Experiment Parameters", None, QtGui.QApplication.UnicodeUTF8)) - self.experiment_parameter_help.setText(QtGui.QApplication.translate("Frame", "The sample-detector distance is updated automatically when a sample data file is selected.\n" + self.experiment_parameter_help.setText(QtGui.QApplication.translate("Frame", "The sample-detector distance is updated automatically when a sample data file is selected.\n"\ "Values can be selected by hand by checking the boxes below.", None, QtGui.QApplication.UnicodeUTF8)) self.detector_offset_chk.setToolTip(QtGui.QApplication.translate("Frame", "Select to set the detector distance offset.", None, QtGui.QApplication.UnicodeUTF8)) self.detector_offset_chk.setStatusTip(QtGui.QApplication.translate("Frame", "Select to set the detector distance offset.", None, QtGui.QApplication.UnicodeUTF8)) @@ -592,7 +593,7 @@ def retranslateUi(self, Frame): self.config_mask_chk.setToolTip(QtGui.QApplication.translate("Frame", "Select to mask detectors as specified in the configuration file, as applicable.", None, QtGui.QApplication.UnicodeUTF8)) self.config_mask_chk.setStatusTip(QtGui.QApplication.translate("Frame", "Select to mask detectors as specified in the configuration file, as applicable.", None, QtGui.QApplication.UnicodeUTF8)) self.config_mask_chk.setText(QtGui.QApplication.translate("Frame", "Use mask from configuration file as applicable", None, QtGui.QApplication.UnicodeUTF8)) - self.mask_help_label.setText(QtGui.QApplication.translate("Frame", "Choose a file to set your mask. Note that only the mask information, not the data, will be used in the reduction.\n" + self.mask_help_label.setText(QtGui.QApplication.translate("Frame", "Choose a file to set your mask. Note that only the mask information, not the data, will be used in the reduction.\n"\ "The data is only used to help you setting the mask.\n" "The mask information is saved separately so that your data file will NOT be modified.", None, QtGui.QApplication.UnicodeUTF8)) self.mask_check.setToolTip(QtGui.QApplication.translate("Frame", "Select to apply the mask built from the specified data file.", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py index 1e899ec825c2..c2e42a69e670 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_eqsans_sample_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/eqsans_sample_data.ui' diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py index 4f12a693d2f8..4ab3d4e4e9d5 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_background.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/hfir_background.ui' diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py index b3733d77fd4b..cf5fc9336376 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_detector.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/hfir_detector.ui' diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py index 7080dd0f3fe3..2224f3ec82bd 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/hfir_instrument.ui' @@ -536,7 +537,7 @@ def retranslateUi(self, Frame): Frame.setWindowTitle(QtGui.QApplication.translate("Frame", "Frame", None, QtGui.QApplication.UnicodeUTF8)) self.instr_name_label.setText(QtGui.QApplication.translate("Frame", "BIOSANS", None, QtGui.QApplication.UnicodeUTF8)) self.reduction_options_group.setTitle(QtGui.QApplication.translate("Frame", "Reduction Options", None, QtGui.QApplication.UnicodeUTF8)) - self.label_6.setText(QtGui.QApplication.translate("Frame", "\n" + self.label_6.setText(QtGui.QApplication.translate("Frame", "\n"\ "\n" @@ -572,7 +573,7 @@ def retranslateUi(self, Frame): self.label.setText(QtGui.QApplication.translate("Frame", "Number of Q bins ", None, QtGui.QApplication.UnicodeUTF8)) self.n_q_bins_edit.setToolTip(QtGui.QApplication.translate("Frame", "Enter the number of Q bins for the output I(Q) distribution.", None, QtGui.QApplication.UnicodeUTF8)) self.label_3.setText(QtGui.QApplication.translate("Frame", "Number of sub-pixels", None, QtGui.QApplication.UnicodeUTF8)) - self.n_sub_pix_edit.setToolTip(QtGui.QApplication.translate("Frame", "Enter the number of sub-pixels in each direction of a detector pixel to use for the\n" + self.n_sub_pix_edit.setToolTip(QtGui.QApplication.translate("Frame", "Enter the number of sub-pixels in each direction of a detector pixel to use for the\n"\ "radial averaging. For instance, entering 3 will sub-divide each detector pixel by 3\n" "in each direction and will create 9 sub-pixels.", None, QtGui.QApplication.UnicodeUTF8)) self.error_weighting_check.setText(QtGui.QApplication.translate("Frame", "Error weighting", None, QtGui.QApplication.UnicodeUTF8)) @@ -587,7 +588,7 @@ def retranslateUi(self, Frame): self.label_11.setText(QtGui.QApplication.translate("Frame", "Wedge offset [deg]", None, QtGui.QApplication.UnicodeUTF8)) self.wedge_offset_edit.setToolTip(QtGui.QApplication.translate("Frame", "Enter an angular offset for the wedges, in degrees.", None, QtGui.QApplication.UnicodeUTF8)) self.geometry_options_groupbox.setTitle(QtGui.QApplication.translate("Frame", "Experiment Parameters", None, QtGui.QApplication.UnicodeUTF8)) - self.experiment_parameter_help.setText(QtGui.QApplication.translate("Frame", "The sample-detector distance and wavelength are updated automatically when a sample data file is selected.\n" + self.experiment_parameter_help.setText(QtGui.QApplication.translate("Frame", "The sample-detector distance and wavelength are updated automatically when a sample data file is selected.\n"\ "Values can be selected by hand by checking the boxes below.", None, QtGui.QApplication.UnicodeUTF8)) self.detector_offset_chk.setToolTip(QtGui.QApplication.translate("Frame", "Select to set the detector distance offset.", None, QtGui.QApplication.UnicodeUTF8)) self.detector_offset_chk.setText(QtGui.QApplication.translate("Frame", "Detector distance offset [mm]", None, QtGui.QApplication.UnicodeUTF8)) @@ -608,7 +609,7 @@ def retranslateUi(self, Frame): self.mask_side_front_radio.setText(QtGui.QApplication.translate("Frame", "Front", None, QtGui.QApplication.UnicodeUTF8)) self.mask_side_back_radio.setToolTip(QtGui.QApplication.translate("Frame", "Select to mask the back panel of the detector.", None, QtGui.QApplication.UnicodeUTF8)) self.mask_side_back_radio.setText(QtGui.QApplication.translate("Frame", "Back", None, QtGui.QApplication.UnicodeUTF8)) - self.label_5.setText(QtGui.QApplication.translate("Frame", "Choose a file to set your mask. Note that only the mask information, not the data, will be used in the reduction.\n" + self.label_5.setText(QtGui.QApplication.translate("Frame", "Choose a file to set your mask. Note that only the mask information, not the data, will be used in the reduction.\n"\ "The data is only used to help you setting the mask.\n" "The mask information is saved separately so that your data file will NOT be modified.", None, QtGui.QApplication.UnicodeUTF8)) self.mask_check.setToolTip(QtGui.QApplication.translate("Frame", "Select to apply the mask built from the specified data file.", None, QtGui.QApplication.UnicodeUTF8)) diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py index 9f61e3268220..834aa6ef746c 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_hfir_sample_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/hfir_sample_data.ui' diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py index 2d0f5b0d4cd4..423ff87ff5f5 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_direct_beam.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/trans_direct_beam.ui' diff --git a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py index bf6726a520d5..566620ef1ad0 100644 --- a/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py +++ b/Code/Mantid/scripts/Interface/ui/sans/ui_trans_spreader.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/sans/trans_spreader.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py b/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py index 5a7723885a96..d29d1c852590 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py +++ b/Code/Mantid/scripts/Interface/ui/ui_cluster_details_dialog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/cluster_details_dialog.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py b/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py index 09839356ba28..edb55cc71116 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py +++ b/Code/Mantid/scripts/Interface/ui/ui_cluster_status.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/cluster_status.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py b/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py index 04b37cdfe961..9893c53b9a45 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py +++ b/Code/Mantid/scripts/Interface/ui/ui_data_catalog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/data_catalog.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py b/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py index 9f0603eb5ead..b779a4dc13d7 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py +++ b/Code/Mantid/scripts/Interface/ui/ui_hfir_output.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/hfir_output.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py b/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py index 5baa1882f8e9..67b3ab66b280 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py +++ b/Code/Mantid/scripts/Interface/ui/ui_instrument_dialog.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/instrument_dialog.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py b/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py index 5352477c0e49..f3fecebf0c6e 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py +++ b/Code/Mantid/scripts/Interface/ui/ui_reduction_main.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'reduction_main.ui' @@ -114,7 +115,7 @@ def setupUi(self, SANSReduction): def retranslateUi(self, SANSReduction): SANSReduction.setWindowTitle(_translate("SANSReduction", "SANS Reduction", None)) - self.label.setText(_translate("SANSReduction", "\n" + self.label.setText(_translate("SANSReduction", "\n"\ "\n" diff --git a/Code/Mantid/scripts/Interface/ui/ui_stitcher.py b/Code/Mantid/scripts/Interface/ui/ui_stitcher.py index a06ea1446f35..9ca6c11a4af1 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_stitcher.py +++ b/Code/Mantid/scripts/Interface/ui/ui_stitcher.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/stitcher.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py b/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py index 77d34dbd9a69..d7a996b26006 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py +++ b/Code/Mantid/scripts/Interface/ui/ui_trans_direct_beam.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/trans_direct_beam.ui' diff --git a/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py b/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py index 6a2072489a60..d5d5119dbcc1 100644 --- a/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py +++ b/Code/Mantid/scripts/Interface/ui/ui_trans_spreader.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ui/trans_spreader.ui' diff --git a/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py b/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py index ad61eeed9c47..501f59eb7ebf 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py +++ b/Code/Mantid/scripts/LargeScaleStructures/EQSANS_geometry.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from geometry_writer import MantidGeom import math @@ -54,8 +55,8 @@ def create_geometry(file_name=None, tube_width=TUBE_WIDTH, tube_length=TUBE_SIZE det.addComponent(id_str, id_str) doc_handle = det.makeTypeElement(id_str) - det.addCylinderPixel("pixel", (0.0, 0.0, 0.0), (0.0, 1.0, 0.0), - (tube_width/2.0), + det.addCylinderPixel("pixel", (0.0, 0.0, 0.0), (0.0, 1.0, 0.0),\ + (tube_width/2.0),\ (tube_length/NUM_PIXELS_PER_TUBE)) for i in range(0, NUM_BANKS/2): @@ -94,4 +95,4 @@ def create_geometry(file_name=None, tube_width=TUBE_WIDTH, tube_length=TUBE_SIZE det.writeGeom(xml_outfile) if __name__ == "__main__": - create_geometry() \ No newline at end of file + create_geometry() diff --git a/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py b/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py index 45b8018c8691..8dff73421bb4 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py +++ b/Code/Mantid/scripts/LargeScaleStructures/REF_L_geometry.py @@ -1,5 +1,5 @@ +#pylint: disable=invalid-name from geometry_writer import MantidGeom -import math NUM_PIXELS_PER_TUBE = 304 NUM_TUBES = 256 @@ -100,4 +100,4 @@ def create_geometry(file_name=None, pixel_width=None, pixel_height=None): if __name__ == "__main__": create_geometry() - #create_grouping() \ No newline at end of file + #create_grouping() diff --git a/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py b/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py index f81bdb8f1c58..7e5311c04ec7 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py +++ b/Code/Mantid/scripts/LargeScaleStructures/ReflectometerCors.py @@ -1,65 +1,66 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * def heliumDetectorEff(workspace): - ''' Calculate the corrected Helium detector values. ''' + ''' Calculate the corrected Helium detector values. ''' - ac= 6.022169e23 # Avogadro's constant mol-1 - vm= 2.24136e4 # Molar volume of gas cm3 mol-1 - gp= 10.0 # Gas pressure (atms) - gsig0= 5333.0e-24 # Gas cross section at LAM0 cm2 - gt= 2.5 # Gas path length cm - lam0= 1.8 # Characteristic wavelength + ac= 6.022169e23 # Avogadro's constant mol-1 + vm= 2.24136e4 # Molar volume of gas cm3 mol-1 + gp= 10.0 # Gas pressure (atms) + gsig0= 5333.0e-24 # Gas cross section at LAM0 cm2 + gt= 2.5 # Gas path length cm + lam0= 1.8 # Characteristic wavelength - gn= ac*gp/vm # Number density of gas - sgn= gn*gsig0*gt/lam0 # Exponential term for gas + gn= ac*gp/vm # Number density of gas + sgn= gn*gsig0*gt/lam0 # Exponential term for gas - OneMinusExponentialCor(InputWorkspace=workspace,OutputWorkspace=workspace,C=str(sgn),Operation="Divide") + OneMinusExponentialCor(InputWorkspace=workspace,OutputWorkspace=workspace,C=str(sgn),Operation="Divide") - wt= 60.014 # Molecular weight Ni-Cu g mol-1 - rho= 8.00 # Density Ni-Cu g cm-3 - ct= 0.05 # Monel (Ni-Cu) wall thickness cm - wsig0= 4.522e-24 # Wall cross section at LAM0 cm2 + wt= 60.014 # Molecular weight Ni-Cu g mol-1 + rho= 8.00 # Density Ni-Cu g cm-3 + ct= 0.05 # Monel (Ni-Cu) wall thickness cm + wsig0= 4.522e-24 # Wall cross section at LAM0 cm2 - wn= ac*rho/wt # Number density of wall - swn= wn*wsig0*ct/lam0 # Exponential term for wall + wn= ac*rho/wt # Number density of wall + swn= wn*wsig0*ct/lam0 # Exponential term for wall - ExponentialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,C1=str(swn),Operation="Divide") + ExponentialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,C1=str(swn),Operation="Divide") # simple polynomial correction based on a D2O spectrum taken at 1.5 deg - PolynomialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,Coefficients="-1.3697,0.8602,-0.7839,0.2866,-0.0447,0.0025") - return + PolynomialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,Coefficients="-1.3697,0.8602,-0.7839,0.2866,-0.0447,0.0025") + return def monitor2Eff(workspace): - ''' Calculate the corrected monitor2 values. ''' + ''' Calculate the corrected monitor2 values. ''' # expon= unt*(1-exp(-8.3047 * zz * x_mean )) # yout[i]= yin[i]*(1.0-expon) / expon # eout[i]= ein[i]*(1.0-expon) / expon # The above correction is equivalent to: (1/unt - 1) + e^(-8.3047*zz*x) # ------------------------------ # ( 1 - e^(-8.3047*zz*x) ) - unt=0.24 # 0.05 # ratio of scintillator to total area - zz = 0.6 #0.03 # thickness(cm) of scintillator - c1 = 0.7112*zz #8.3047*zz + unt=0.24 # 0.05 # ratio of scintillator to total area + zz = 0.6 #0.03 # thickness(cm) of scintillator + c1 = 0.7112*zz #8.3047*zz - ExponentialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,C1=str(c1),Operation="Multiply") - shift = (1.0/unt)-1.0 - CreateSingleValuedWorkspace(OutputWorkspace="shift",DataValue=str(shift),ErrorValue="0.0") - Plus(LHSWorkspace=workspace,RHSWorkspace="shift",OutputWorkspace=workspace) - mtd.remove("shift") - OneMinusExponentialCor(InputWorkspace=workspace,OutputWorkspace=workspace,C=str(c1)) + ExponentialCorrection(InputWorkspace=workspace,OutputWorkspace=workspace,C1=str(c1),Operation="Multiply") + shift = (1.0/unt)-1.0 + CreateSingleValuedWorkspace(OutputWorkspace="shift",DataValue=str(shift),ErrorValue="0.0") + Plus(LHSWorkspace=workspace,RHSWorkspace="shift",OutputWorkspace=workspace) + mtd.remove("shift") + OneMinusExponentialCor(InputWorkspace=workspace,OutputWorkspace=workspace,C=str(c1)) - return + return def main(): - '''This main routine. It is executed on if the script is run directly, not if it is imported.''' - LoadRawDialog(OutputWorkspace="ws",SpectrumMin="1",SpectrumMax="1") - ConvertUnits(InputWorkspace="ws",OutputWorkspace="ws",Target="Wavelength",AlignBins="1") - heliumDetectorEff("ws") - monitor2Eff("ws") - print "Done!" + '''This main routine. It is executed on if the script is run directly, not if it is imported.''' + LoadRawDialog(OutputWorkspace="ws",SpectrumMin="1",SpectrumMax="1") + ConvertUnits(InputWorkspace="ws",OutputWorkspace="ws",Target="Wavelength",AlignBins="1") + heliumDetectorEff("ws") + monitor2Eff("ws") + print "Done!" if __name__ == '__main__': - main() + main() diff --git a/Code/Mantid/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py b/Code/Mantid/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py index 8fc284bffaec..03baa7e92672 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py +++ b/Code/Mantid/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py @@ -149,7 +149,7 @@ def _calculateFinalYAxis(self, bNumerator=True): ws_event_data = LoadEventNexus(Filename=nexus_file_numerator, OutputWorkspace='EventDataWks') mt1 = mtd['EventDataWks'] - + is_nexus_detector_rotated_flag = wks_utility.isNexusTakeAfterRefDate(ws_event_data.getRun().getProperty('run_start').value) if is_nexus_detector_rotated_flag: self.alpha_pixel_nbr = 304 @@ -376,7 +376,7 @@ def plotObject(instance): linestyle='', label='Exp. data') - if (instance.a is not None): + if instance.a is not None: x = linspace(10000, 22000, 100) _label = "%.3f + x*%.2e" % (instance.a, instance.b) plot(x, instance.a + instance.b * x, label=_label) diff --git a/Code/Mantid/scripts/LargeScaleStructures/data_stitching.py b/Code/Mantid/scripts/LargeScaleStructures/data_stitching.py index 43eb1c295419..976d7f45a2ca 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/data_stitching.py +++ b/Code/Mantid/scripts/LargeScaleStructures/data_stitching.py @@ -1,13 +1,12 @@ +#pylint: disable=invalid-name import os -import copy -import math from mantid.simpleapi import * from mantid.kernel import Logger IS_IN_MANTIDPLOT = True try: import mantidplot - from PyQt4 import QtGui, QtCore + from PyQt4 import QtCore except: IS_IN_MANTIDPLOT = False @@ -26,8 +25,8 @@ def __init__(self): def disconnect(self): if IS_IN_MANTIDPLOT: - mantidplot.app.disconnect(mantidplot.app.mantidUI, - QtCore.SIGNAL("x_range_update(double,double)"), + mantidplot.app.disconnect(mantidplot.app.mantidUI,\ + QtCore.SIGNAL("x_range_update(double,double)"),\ self._call_back) def connect(self, ws, call_back, xmin=None, xmax=None, @@ -41,8 +40,8 @@ def connect(self, ws, call_back, xmin=None, xmax=None, self._call_back = call_back self._ws_output_base = ws_output_base - mantidplot.app.connect(mantidplot.app.mantidUI, - QtCore.SIGNAL("x_range_update(double,double)"), + mantidplot.app.connect(mantidplot.app.mantidUI,\ + QtCore.SIGNAL("x_range_update(double,double)"),\ self._call_back) g = mantidplot.graph(self._graph) @@ -226,9 +225,9 @@ def apply_scale(self, xmin=None, xmax=None): y_trim.append(y[i]) e_trim.append(e[i]) - CreateWorkspace(DataX=x_trim, DataY=y_trim, DataE=e_trim, - OutputWorkspace=self._ws_scaled, - UnitX="MomentumTransfer", + CreateWorkspace(DataX=x_trim, DataY=y_trim, DataE=e_trim,\ + OutputWorkspace=self._ws_scaled,\ + UnitX="MomentumTransfer",\ ParentWorkspace=self._ws_name) dq_scaled = mtd[self._ws_scaled].dataDx(0) @@ -525,9 +524,9 @@ def cmp(p1,p2): combined = sorted(zipped, cmp) x,y,e,dx = zip(*combined) - CreateWorkspace(DataX=x, DataY=y, DataE=e, - OutputWorkspace=ws_combined, - UnitX="MomentumTransfer", + CreateWorkspace(DataX=x, DataY=y, DataE=e,\ + OutputWorkspace=ws_combined,\ + UnitX="MomentumTransfer",\ ParentWorkspace=first_ws) dxtmp = mtd[ws_combined].dataDx(0) diff --git a/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py b/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py index df87ed791fa8..d22a91ab2e2d 100644 --- a/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py +++ b/Code/Mantid/scripts/LargeScaleStructures/geometry_writer.py @@ -1,8 +1,9 @@ +#pylint: disable=invalid-name from xml.dom.minidom import getDOMImplementation from datetime import datetime -from string import split,join import re -class MantidGeom: + +class MantidGeom(object): def __init__(self, instname, valid_from=None): if valid_from is None: @@ -76,10 +77,10 @@ def addModerator(self, distance): """ source = self._append_child("component", self._root, type="moderator") try: - distance = float(distance) - if distance > 0: - distance *= -1.0 - self._append_child("location", source, z=distance) + distance = float(distance) + if distance > 0: + distance *= -1.0 + self._append_child("location", source, z=distance) except: print "PROBLEM with addModerator" @@ -115,9 +116,9 @@ def addDetectorPixels(self, name, r=[], theta=[], phi=[], names=[], energy=[]): for i in range(len(r)): for j in range(len(r[i])): - if (str(r[i][j]) != "nan"): + if str(r[i][j]) != "nan": basecomponent = self._append_child("component", type_element, type="pixel") - location_element = self._append_child("location", basecomponent,r=str(r[i][j]), + location_element = self._append_child("location", basecomponent,r=str(r[i][j]),\ t=str(theta[i][j]), p=str(phi[i][j]), name=str(names[i][j])) self._append_child("facing", location_element, x="0.0", y="0.0", z="0.0") @@ -128,7 +129,7 @@ def addDetectorPixelsIdList(self, name, r=[], names=[]): component = self._append_child("idlist", self._root, idname=name) for i in range(len(r)): for j in range(len(r[i])): - if (str(r[i][j]) != "nan"): + if str(r[i][j]) != "nan": self._append_child("id", component, val=str(names[i][j])) def addMonitors(self, distance=[], names=[]): @@ -198,7 +199,7 @@ def addDetector(self, x, y, z, rot_x, rot_y, rot_z, name, comp_type, usepolar=No if usepolar is not None: self.addLocationPolar(comp_element, x, y, z) else: - self.addLocation(comp_element, x, y, z, rot_x, rot_y, rot_z) + self.addLocation(comp_element, x, y, z, rot_x, rot_y, rot_z) def addSingleDetector(self, root, x, y, z, rot_x, rot_y, rot_z, name=None, id=None, usepolar=None): @@ -332,7 +333,7 @@ def addCylinderPixel(self, name, center_bottom_base, axis, pixel_radius, self._append_child("height", cylinder, val=str(pixel_height)) self._append_child("algebra", type_element, val="cyl-approx") - def addCuboidPixel(self, name, lfb_pt, lft_pt, lbb_pt, rfb_pt, + def addCuboidPixel(self, name, lfb_pt, lft_pt, lbb_pt, rfb_pt,\ is_type="detector"): """ Add a cuboid pixel. The origin of the cuboid is assumed to be the @@ -341,13 +342,13 @@ def addCuboidPixel(self, name, lfb_pt, lft_pt, lbb_pt, rfb_pt, """ type_element = self._append_child("type", self._root, **{"name":name, "is":is_type}) cuboid = self._append_child("cuboid", type_element, id="shape") - self._append_child("left-front-bottom-point", cuboid, x=str(lfb_pt[0]), + self._append_child("left-front-bottom-point", cuboid, x=str(lfb_pt[0]),\ y=str(lfb_pt[1]), z=str(lfb_pt[2])) - self._append_child("left-front-top-point", cuboid, x=str(lft_pt[0]), + self._append_child("left-front-top-point", cuboid, x=str(lft_pt[0]),\ y=str(lft_pt[1]), z=str(lft_pt[2])) - self._append_child("left-back-bottom-point", cuboid, x=str(lbb_pt[0]), + self._append_child("left-back-bottom-point", cuboid, x=str(lbb_pt[0]),\ y=str(lbb_pt[1]), z=str(lbb_pt[2])) - self._append_child("right-front-bottom-point", cuboid, x=str(rfb_pt[0]), + self._append_child("right-front-bottom-point", cuboid, x=str(rfb_pt[0]),\ y=str(rfb_pt[1]), z=str(rfb_pt[2])) self._append_child("algebra", type_element, val="shape") @@ -389,11 +390,11 @@ def addDetectorIds(self, idname, idlist): id_element = self._append_child("idlist", self._root, idname=idname) for i in range(num_ids): if idlist[(i*3)+2] is None: - self._append_child("id", id_element, start=str(idlist[(i*3)]), + self._append_child("id", id_element, start=str(idlist[(i*3)]),\ end=str(idlist[(i*3)+1])) else: - self._append_child("id", id_element, start=str(idlist[(i*3)]), - step=str(idlist[(i*3)+2]), + self._append_child("id", id_element, start=str(idlist[(i*3)]),\ + step=str(idlist[(i*3)+2]),\ end=str(idlist[(i*3)+1])) def addMonitorIds(self, ids=[]): diff --git a/Code/Mantid/scripts/ORNL_SANS.py b/Code/Mantid/scripts/ORNL_SANS.py index 885aadc6e708..c0cb689df6f5 100644 --- a/Code/Mantid/scripts/ORNL_SANS.py +++ b/Code/Mantid/scripts/ORNL_SANS.py @@ -1,9 +1,9 @@ +#pylint: disable=invalid-name """ Script used to start the HFIR SANS reduction gui from Mantidplot """ from reduction_application import ReductionGUI -from PyQt4 import QtCore, uic reducer = ReductionGUI(instrument_list=["BIOSANS", "GPSANS", "EQSANS"]) if reducer.setup_layout(load_last=True): - reducer.show() \ No newline at end of file + reducer.show() diff --git a/Code/Mantid/scripts/Powder_Diffraction_Reduction.py b/Code/Mantid/scripts/Powder_Diffraction_Reduction.py index dd74e42e4e07..e803a5898f5e 100644 --- a/Code/Mantid/scripts/Powder_Diffraction_Reduction.py +++ b/Code/Mantid/scripts/Powder_Diffraction_Reduction.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Script used to start the DGS reduction GUI from MantidPlot """ diff --git a/Code/Mantid/scripts/PyChop.py b/Code/Mantid/scripts/PyChop.py index d98e547ebd8c..650936bba2ea 100644 --- a/Code/Mantid/scripts/PyChop.py +++ b/Code/Mantid/scripts/PyChop.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid import config from PyChop import fluxGUI from PyChop import PyChopGUI @@ -7,10 +8,10 @@ def qapp(): if QtGui.QApplication.instance(): - app = QtGui.QApplication.instance() + _app = QtGui.QApplication.instance() else: - app = QtGui.QApplication(sys.argv) - return app + _app = QtGui.QApplication(sys.argv) + return _app app = qapp() instr_name = config['default.instrument'] @@ -19,4 +20,4 @@ def qapp(): else: Resolution = PyChopGUI.MainWindow() Resolution.show() -app.exec_() \ No newline at end of file +app.exec_() diff --git a/Code/Mantid/scripts/PyChop/PyChop.py b/Code/Mantid/scripts/PyChop/PyChop.py index f01b80fe0f8f..a869bbdaefb0 100644 --- a/Code/Mantid/scripts/PyChop/PyChop.py +++ b/Code/Mantid/scripts/PyChop/PyChop.py @@ -1,11 +1,12 @@ +#pylint: disable=invalid-name import time as time import math import numpy from mantid.simpleapi import * try: - from mantidplot import * + from mantidplot import * except ImportError: - pass + pass ''' chop(inst,ei,chop_type,frequency): python implementation of CHOP ver 1.0 @@ -193,39 +194,39 @@ def calculate(ei,frequency,**kwargs): if instname=='maps' or instname=='map' or instname=='MAP'or instname=='MAPS': #For MAPS - x0 = 10.1000 - xa = 8.1100 - x1 = 1.9000 - x2 = 6.0000 - wa_mm = 70.130 - ha_mm = 70.130 - wa = ha_mm / 1000.00 - ha = ha_mm / 1000.00 + x0 = 10.1000 + xa = 8.1100 + x1 = 1.9000 + x2 = 6.0000 + wa_mm = 70.130 + ha_mm = 70.130 + wa = ha_mm / 1000.00 + ha = ha_mm / 1000.00 # chopper details # now some moderator details # for 300K H2O - s=numpy.zeros(6) - s[1] = 38.60 - s[2] = 0.52260 - s[3] = 0.00 - s[4] = 0.00 - s[5] = 0.00 - th_deg = 32.00 - imod = 2 - mod_type = 'AP' + s=numpy.zeros(6) + s[1] = 38.60 + s[2] = 0.52260 + s[3] = 0.00 + s[4] = 0.00 + s[5] = 0.00 + th_deg = 32.00 + imod = 2 + mod_type = 'AP' # sample details - sx_mm = 2.00 - sy_mm = 50.00 - sz_mm = 50.00 - isam = 0 - gam_deg = 0.00 - ia = 0 - ix = 0 + sx_mm = 2.00 + sy_mm = 50.00 + sz_mm = 50.00 + isam = 0 + gam_deg = 0.00 + ia = 0 + ix = 0 # detector details - idet = 1 - dd_mm = 250 - tbin_us = 0.00 + idet = 1 + dd_mm = 250 + tbin_us = 0.00 #chop_par,titledata=setchoptype(instname,chop_type) # end of maps parameters @@ -432,7 +433,7 @@ def van_var(*args): #! chopper: tsqchp,ifail=tchop(omega, ei) ifail - if (ifail <> 0): + if ifail <> 0: tsqchp = 0.0 @@ -467,7 +468,7 @@ def tikeda(S1,S2,B1,B2,EMOD,ei): SIG=math.sqrt( (S1*S1) + ((S2*S2*81.8048)/ei) ) A = 4.37392e-4 * SIG * math.sqrt(ei) for j in range(len(ei)): - if (ei[j] > 130.0): + if ei[j] > 130.0: B[j]=B2 else: B[j]=B1 @@ -508,7 +509,7 @@ def tchop(omega,ei): w=omega ei=ei - if (p == 0.00 and R == 0.00 and rho == 0.00): + if p == 0.00 and R == 0.00 and rho == 0.00: ierr=1 tausqr = 0.00 @@ -522,12 +523,12 @@ def tchop(omega,ei): #! ------------------------------------- #for j in range(len(ei)): groot=0 - if (gammm >= 4.00): + if gammm >= 4.00: ierr=1 tausqr=0.00 else: ierr=0 - if (gammm <= 1.00): + if gammm <= 1.00: gsqr=(1.00-(gammm**2)**2 /10.00) / (1.00-(gammm**2)/6.00) else: groot=math.sqrt(gammm) @@ -771,7 +772,7 @@ def achop(ei,omega): #for j in range(numpy.size(ei)): groot=0 - if (gamm >= 4.00): + if gamm >= 4.00: f1=0 print 'no transmission at ', ei, 'meV at ',omega/(2*math.pi), 'Hz' else: @@ -788,7 +789,7 @@ def achop(ei,omega): return area def frange(limit1, limit2 = None, increment = 1.): - """ + """ Range function that accepts floats (and integers). Usage: @@ -799,10 +800,10 @@ def frange(limit1, limit2 = None, increment = 1.): The returned value is an iterator. Use list(frange) for a list. """ - if limit2 is None: - limit2, limit1 = limit1, 0. - else: - limit1 = float(limit1) + if limit2 is None: + limit2, limit1 = limit1, 0. + else: + limit1 = float(limit1) - count = int(math.ceil(limit2 - limit1)/increment) - return (limit1 + n*increment for n in range(count)) + count = int(math.ceil(limit2 - limit1)/increment) + return (limit1 + n*increment for n in range(count)) diff --git a/Code/Mantid/scripts/PyChop/PyChopGUI.py b/Code/Mantid/scripts/PyChop/PyChopGUI.py index 463e066e20b3..73140bc45410 100644 --- a/Code/Mantid/scripts/PyChop/PyChopGUI.py +++ b/Code/Mantid/scripts/PyChop/PyChopGUI.py @@ -1,16 +1,10 @@ +#pylint: disable=invalid-name -import sys from PyChopUI import Ui_MainWindow -from PyQt4 import QtCore, uic,QtGui -#from DirectEnergyConversion import * -import time as time +from PyQt4 import QtCore, QtGui from mantidplot import * -import dgreduce -import inspect -import numpy from mantid import * from mantid.simpleapi import * -import math import PyChop class MainWindow(QtGui.QMainWindow): @@ -40,9 +34,9 @@ def set_inst(self,name): self.inst=name config['default.instrument']=name if len(self.chop)>0: - message,err = PyChop.setchoptype(self.inst,self.chop) - if err>0: - self.chop='' + message,err = PyChop.setchoptype(self.inst,self.chop) + if err>0: + self.chop='' def set_chop(self,chop_type): message,err = PyChop.setchoptype(self.inst,chop_type) diff --git a/Code/Mantid/scripts/PyChop/PyChopUI.py b/Code/Mantid/scripts/PyChop/PyChopUI.py index 4c56ae2ec080..a36624b4cf51 100644 --- a/Code/Mantid/scripts/PyChop/PyChopUI.py +++ b/Code/Mantid/scripts/PyChop/PyChopUI.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file '/Users/jon/QtSDK/pychopui.ui' diff --git a/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py b/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py index 2470ecff8724..b25f6b025567 100644 --- a/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py +++ b/Code/Mantid/scripts/PyChop/PyChop_LET_UI.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Mantid\Code\Mantid\scripts\PyChop\PyChop_LET_UI.ui' diff --git a/Code/Mantid/scripts/PyChop/fluxGUI.py b/Code/Mantid/scripts/PyChop/fluxGUI.py index c2e6dc39c391..7f6444bff60c 100644 --- a/Code/Mantid/scripts/PyChop/fluxGUI.py +++ b/Code/Mantid/scripts/PyChop/fluxGUI.py @@ -1,7 +1,6 @@ -import sys +#pylint: disable=invalid-name from PyChop_LET_UI import Ui_MainWindow #import line for the UI python class from PyQt4 import QtCore, QtGui #import others if needed -import math from mantidplot import * from mantid import * @@ -14,6 +13,16 @@ class MainWindow(QtGui.QMainWindow): + flux_matrix = None + flux_energies = None + res_matrix = None + res_energies = None + frequencies = None + ei = None + ei_min = None + ei_max = None + interpolation = None + def __init__(self, parent=None): QtGui.QMainWindow.__init__(self,parent) self.ui = Ui_MainWindow() @@ -29,7 +38,7 @@ def __init__(self, parent=None): QtCore.QObject.connect(self.ui.actionMAPS,QtCore.SIGNAL("triggered()"), lambda : self.otherInstrumentSelected('MAP')) - self.graph=None; + self.graph=None self.loadData() @@ -56,7 +65,7 @@ def loadData(self): self.res_energies = array.array( 'f', [0.2, 0.4, 0.6, 0.8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40] ) self.frequencies = np.arange(30,310,10) - self.ei=""; + self.ei="" self.ei_min = 0.2 # max(min(self.flux_energies),min(self.res_energies)) self.ei_max = 40. #min(max(self.flux_energies),max(self.res_energies)) @@ -108,10 +117,10 @@ def interpolate_data(self,data_matrix,energies): return result def letSelected(self): - QtGui.QMessageBox.warning(self, "Currently You have to switch gui to select another instrument") - self.ui.actionLET.setChecked(True) + QtGui.QMessageBox.warning(self, "Currently You have to switch gui to select another instrument") + self.ui.actionLET.setChecked(True) def otherInstrumentSelected(self,INAME): - reply = QtGui.QMessageBox.question(self, 'Selecting : '+INAME, + reply = QtGui.QMessageBox.question(self, 'Selecting : '+INAME,\ "Do you want to switch GUI?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: config['default.instrument'] = INAME @@ -133,7 +142,7 @@ def calculate(self): self.ei = float (self.ei) if self.ei< self.ei_min or self.ei > self.ei_max: - self.ei=""; + self.ei="" QtGui.QMessageBox.warning(self, "LETFlux", "Energy out of range.\n Please, Provide value between "+str(self.ei_min)+" and "+str(self.ei_max)+" meV \n") else: self.setUpTable() @@ -142,7 +151,7 @@ def calculate(self): self.ui.list.insertItem(0,string) string_title = 'Frequency(Hz) Flux(n/s/cm^2) Resolution[ueV]' self.ui.list.insertItem(1,string_title) - t=self.t; + t=self.t for i in xrange(0, len(self.frequencies)): string1 = str(self.frequencies[i])+' '+ "%e" % t.cell(2,i+1)+' '+ "%e"% t.cell(3,i+1) self.ui.list.insertItem(2+i,string1) @@ -171,7 +180,7 @@ def plotData(self): self.graph = newGraph("Flux and Resolution",2,1,2) - l1 = self.graph.layer(1); + l1 = self.graph.layer(1) l1.setAntialiasing() l1.setTitle("Flux") l1.setAxisTitle(Layer.Bottom, "Frequency [Hz]") @@ -179,7 +188,7 @@ def plotData(self): l1.showGrid() # self.graphFlux.insertCurve(self.t, "Flux/Frequency_2", Layer.Scatter) # legend = self.graphFlux.newLegend(str(self.ei)) - l2 = self.graph.layer(2); + l2 = self.graph.layer(2) l2.setAntialiasing() l2.setTitle("Resolution") l2.setAxisTitle(Layer.Bottom, "Frequency [Hz]") @@ -188,9 +197,9 @@ def plotData(self): # self.graphRes.insertCurve(self.t, "Resolution/Frequency_2", Layer.Scatter) l2.showGrid() - self.addPlot(); + self.addPlot() - self.raise_(); + self.raise_() self.show() return self @@ -199,7 +208,7 @@ def addPlot(self): """ Adds plot to an existing graph """ if self.graph==None: - self.plotData(); + self.plotData() else: self.calculate() if self.ei == "": diff --git a/Code/Mantid/scripts/REFL_Reduction.py b/Code/Mantid/scripts/REFL_Reduction.py index b811a3f8f53e..8038e3f00867 100644 --- a/Code/Mantid/scripts/REFL_Reduction.py +++ b/Code/Mantid/scripts/REFL_Reduction.py @@ -1,9 +1,9 @@ +#pylint: disable=invalid-name """ Script used to start the REFL reduction gui from Mantidplot """ from reduction_application import ReductionGUI -from PyQt4 import QtCore, uic reducer = ReductionGUI(instrument="REFL", instrument_list=["REFL"]) if reducer.setup_layout(load_last=True): - reducer.show() \ No newline at end of file + reducer.show() diff --git a/Code/Mantid/scripts/REFL_SF_Calculator.py b/Code/Mantid/scripts/REFL_SF_Calculator.py index 839f8d3b21b9..eabf63819a2d 100644 --- a/Code/Mantid/scripts/REFL_SF_Calculator.py +++ b/Code/Mantid/scripts/REFL_SF_Calculator.py @@ -1,9 +1,9 @@ +#pylint: disable=invalid-name """ Script used to start the REFL SF calculator gui from Mantidplot """ from reduction_application import ReductionGUI -from PyQt4 import QtCore, uic reducer = ReductionGUI(instrument="REFLSF", instrument_list=["REFLSF"]) if reducer.setup_layout(load_last=True): - reducer.show() \ No newline at end of file + reducer.show() diff --git a/Code/Mantid/scripts/REFM_Reduction.py b/Code/Mantid/scripts/REFM_Reduction.py index 42aa147ac080..d589aa0b2c13 100644 --- a/Code/Mantid/scripts/REFM_Reduction.py +++ b/Code/Mantid/scripts/REFM_Reduction.py @@ -1,9 +1,9 @@ +#pylint: disable=invalid-name """ Script used to start the REFL reduction gui from Mantidplot """ from reduction_application import ReductionGUI -from PyQt4 import QtCore, uic reducer = ReductionGUI(instrument="REFM", instrument_list=["REFM"]) if reducer.setup_layout(load_last=True): - reducer.show() \ No newline at end of file + reducer.show() diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py index 037f88995b45..39c88637742e 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/combineMulti.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from l2q import * from mantid.simpleapi import * import math @@ -20,37 +21,37 @@ def combineDataMulti(wksp_list,output_wksp,beg_overlap,end_overlap,Qmin,Qmax,bin # check if overlaps have correct number of entries defaultoverlaps = False if type(beg_overlap) != list: - beg_overlap = [beg_overlap] + beg_overlap = [beg_overlap] if type(end_overlap) != list: - end_overlap = [end_overlap] + end_overlap = [end_overlap] if len(wksp_list) != len(beg_overlap): - print "Using default values!" - defaultoverlaps = True + print "Using default values!" + defaultoverlaps = True #copy first workspace into temporary wksp 'currentSum' currentSum = CloneWorkspace(InputWorkspace=wksp_list[0]) print "Length: ",len(wksp_list), wksp_list for i in range(0,len(wksp_list)-1): - w1=currentSum - w2=getWorkspace(wksp_list[i+1]) # TODO: distinguishing between a group and a individual workspace is unnecessary for an algorithm. But custom group behavior WILL be required. - if defaultoverlaps: - overlapLow = w2.readX(0)[0] - overlapHigh = 0.5*max(w1.readX(0)) - else: - overlapLow = beg_overlap[i+1] - overlapHigh = end_overlap[i] - print "Iteration",i - currentSum, scale_factor = stitch2(currentSum, mtd[wksp_list[i+1]], currentSum.name(), overlapLow, overlapHigh, Qmin, Qmax, binning, scale_high) + w1=currentSum + w2=getWorkspace(wksp_list[i+1]) # TODO: distinguishing between a group and a individual workspace is unnecessary for an algorithm. But custom group behavior WILL be required. + if defaultoverlaps: + overlapLow = w2.readX(0)[0] + overlapHigh = 0.5*max(w1.readX(0)) + else: + overlapLow = beg_overlap[i+1] + overlapHigh = end_overlap[i] + print "Iteration",i + currentSum, scale_factor = stitch2(currentSum, mtd[wksp_list[i+1]], currentSum.name(), overlapLow, overlapHigh, Qmin, Qmax, binning, scale_high) RenameWorkspace(InputWorkspace=currentSum.name(),OutputWorkspace=output_wksp) # Remove any existing workspaces from the workspace list. if not keep: - names = mtd.getObjectNames() - for ws in wksp_list: - candidate = ws - if candidate in names: - DeleteWorkspace(candidate) + names = mtd.getObjectNames() + for ws in wksp_list: + candidate = ws + if candidate in names: + DeleteWorkspace(candidate) return mtd[output_wksp] @@ -70,14 +71,14 @@ def stitch2(ws1, ws2, output_ws_name, begoverlap,endoverlap,Qmin,Qmax,binning,sc scalefactor: Use the manual scaling factor provided if > 0 """ if scalefactor > 0.0: - manual_scalefactor = True + manual_scalefactor = True else: - manual_scalefactor = False - scalefactor = 1.0 + manual_scalefactor = False + scalefactor = 1.0 # Interally use the Stitch1D algorithm. - outputs = Stitch1D(LHSWorkspace=ws1, RHSWorkspace=ws2, - OutputWorkspace=output_ws_name, StartOverlap=begoverlap, EndOverlap=endoverlap, - UseManualScaleFactor=manual_scalefactor, + outputs = Stitch1D(LHSWorkspace=ws1, RHSWorkspace=ws2,\ + OutputWorkspace=output_ws_name, StartOverlap=begoverlap, EndOverlap=endoverlap,\ + UseManualScaleFactor=manual_scalefactor,\ ManualScaleFactor=scalefactor, Params="%f,%f,%f" % (Qmin, binning, Qmax)) return outputs @@ -99,14 +100,14 @@ def combine2(wksp1,wksp2,outputwksp,begoverlap,endoverlap,Qmin,Qmax,binning,scal scalefactor: Use the manual scaling factor provided if > 0 """ if scalefactor > 0.0: - manual_scalefactor = True + manual_scalefactor = True else: - manual_scalefactor = False - scalefactor = 1.0 + manual_scalefactor = False + scalefactor = 1.0 # Interally use the Stitch1D algorithm. - outputs = Stitch1D(LHSWorkspace=mtd[wksp1], RHSWorkspace=mtd[wksp2], - OutputWorkspace=outputwksp, StartOverlap=begoverlap, EndOverlap=endoverlap, - UseManualScaleFactor=manual_scalefactor, + outputs = Stitch1D(LHSWorkspace=mtd[wksp1], RHSWorkspace=mtd[wksp2],\ + OutputWorkspace=outputwksp, StartOverlap=begoverlap, EndOverlap=endoverlap,\ + UseManualScaleFactor=manual_scalefactor,\ ManualScaleFactor=scalefactor, Params="%f,%f,%f" % (Qmin, binning, Qmax)) outscalefactor = outputs[1] @@ -118,9 +119,9 @@ def getWorkspace(wksp): Get the workspace if it is not a group workspace. If it is a group workspace, get the first period. """ if isinstance(mtd[wksp], WorkspaceGroup): - wout = mtd[wksp][0] + wout = mtd[wksp][0] else: - wout = mtd[wksp] + wout = mtd[wksp] return wout diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py index 2f724574dee3..f92a97e05040 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import mantid.simpleapi as msi import mantid.api from mantid.kernel import logger @@ -51,7 +52,7 @@ def to_workspace(cls, candidate, ws_prefix="_"): msi.Load(Filename=candidate, OutputWorkspace=ws_name) _workspace = mantid.api.AnalysisDataService.retrieve(ws_name) else: - raise ValueError("Unknown source item %s" % candidate) + raise ValueError("Unknown source item %s" % candidate) return _workspace def get_workspace_from_list(self, index): @@ -136,7 +137,7 @@ def convert(self, wavelength_min, wavelength_max, detector_workspace_indexes, mo _monitor_ws: A workspace of monitors """ # Sanity check inputs. - if(wavelength_min >= wavelength_max): + if wavelength_min >= wavelength_max: raise ValueError("Wavelength_min must be < wavelength_max min: %s, max: %s" % (wavelength_min, wavelength_max)) if correct_monitor and not all((bg_min, bg_max)): diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/l2q.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/l2q.py index a05e5ae10332..f5954ab46c0b 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/l2q.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/l2q.py @@ -1,7 +1,7 @@ +#pylint: disable=invalid-name import math from mantid.simpleapi import * # New API -from mantid.geometry import ReferenceFrame def l2q(ws,whichDet,theta, sample_component_name): ''' diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py index 8627309e7403..2be3a6c4cb1b 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/load_live_runs.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from mantid.simpleapi import * def get_live_data(instrument_name, frequency = 60, accumulation = "Add", output_name = "live"): StartLiveData(Instrument=str(instrument_name), UpdateEvery = frequency, Outputworkspace=str(output_name), AccumulationMethod = accumulation) @@ -5,6 +6,6 @@ def get_live_data(instrument_name, frequency = 60, accumulation = "Add", output_ return ws def is_live_run(run): try: - return (int(run) is 0) + return int(run) is 0 except: return False diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py index c3b43430dd0d..999dd0a65df4 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/procedures.py @@ -1,16 +1,17 @@ +#pylint: disable=invalid-name from math import * try: - from mantid.simpleapi import * # New API + from mantid.simpleapi import * # New API except ImportError: - pass + pass #import qti as qti import numpy as n def addRuns(runlist,wname): - mtd.deleteWorkspace(str(wname)) - output=str(wname) - if runlist[0] != "0": + mtd.deleteWorkspace(str(wname)) + output=str(wname) + if runlist[0] != "0": #nzeros=8-len(str(runlist[0])) #fpad="" #for i in range(nzeros): @@ -24,20 +25,20 @@ def addRuns(runlist,wname): #fname=fname.lower() ##fname=str.replace(fname,'.nxs','.raw') #Load(fname,output) - Load(str(runlist[0]),output) - else: - #dae="ndx"+mtd.settings['default.instrument'].lower() - dae="ndxoffspec" - LoadDAE(DAEname=dae,OutputWorkspace=output,SpectrumMin="1") - if(mtd[output].isGroup()): - for k in mtd[output].getNames(): - mtd[k].setYUnit('Counts') + Load(str(runlist[0]),output) else: - mtd[output].setYUnit('Counts') + #dae="ndx"+mtd.settings['default.instrument'].lower() + dae="ndxoffspec" + LoadDAE(DAEname=dae,OutputWorkspace=output,SpectrumMin="1") + if mtd[output].isGroup(): + for k in mtd[output].getNames(): + mtd[k].setYUnit('Counts') + else: + mtd[output].setYUnit('Counts') - if len(runlist) > 1: - for i in range(1,len(runlist)): - if runlist[i] != "0": + if len(runlist) > 1: + for i in range(1,len(runlist)): + if runlist[i] != "0": #nzeros=8-len(str(runlist[i])) #fpad="" #for j in range(nzeros): @@ -51,20 +52,20 @@ def addRuns(runlist,wname): #fname=fname.lower() ##fname=str.replace(fname,'.nxs','.raw') #Load(fname,"wtemp") - Load(str(runlist[i]),"wtemp") - else: + Load(str(runlist[i]),"wtemp") + else: #dae="ndx"+mtd.settings['default.instrument'].lower() - dae="ndxoffspec" - LoadDAE(DAEname=dae,OutputWorkspace="wtemp",SpectrumMin="1") - if(mtd['wtemp'].isGroup()): - for k in mtd['wtemp'].getNames(): - mtd[k].setYUnit('Counts') - else: - mtd[output].setYUnit('Counts') - Plus(output,"wtemp",output) - mtd.deleteWorkspace("wtemp") + dae="ndxoffspec" + LoadDAE(DAEname=dae,OutputWorkspace="wtemp",SpectrumMin="1") + if mtd['wtemp'].isGroup(): + for k in mtd['wtemp'].getNames(): + mtd[k].setYUnit('Counts') + else: + mtd[output].setYUnit('Counts') + Plus(output,"wtemp",output) + mtd.deleteWorkspace("wtemp") - mtd.sendLogMessage("addRuns Completed") + mtd.sendLogMessage("addRuns Completed") ''' parse a text string of the format "1-6:2+8+9,10+11+12+13-19:3,20-24" @@ -132,15 +133,15 @@ def floodnorm(wkspName,floodfile): # # pixel by pixel efficiency correction for the linear detector # - floodloaded=0 - a1=mtd.getWorkspaceNames() - for i in range(len(a1)): - if a1[i] == "ld240flood": - floodloaded=1 - if floodloaded == 0: - LoadNexusProcessed(Filename=floodfile,OutputWorkspace="ld240flood") - - Divide(wkspName,"ld240flood",wkspName) + floodloaded=0 + a1=mtd.getWorkspaceNames() + for i in range(len(a1)): + if a1[i] == "ld240flood": + floodloaded=1 + if floodloaded == 0: + LoadNexusProcessed(Filename=floodfile,OutputWorkspace="ld240flood") + + Divide(wkspName,"ld240flood",wkspName) # # Plot a bunch of workspaces as 2D maps # using the supplied limits and log scale settings @@ -263,9 +264,9 @@ def removeoutlayer(wksp): for i in range(nspec): for j in range(len(x)-1): y=a1.readY(i)[j] - if (y<2): - a1.dataY(i)[j]=0.0; - a1.dataE(i)[j]=0.0; + if y<2: + a1.dataY(i)[j]=0.0 + a1.dataE(i)[j]=0.0 def nrSESANSFn(runList,nameList,P0runList,P0nameList,minSpec,maxSpec,upPeriod,downPeriod,existingP0,SEConstants,gparams,convertToSEL,lnPOverLam,diagnostics="0",removeoutlayer="0",floodfile="none",): nlist=parseNameList(nameList) @@ -297,13 +298,13 @@ def nrSESANSFn(runList,nameList,P0runList,P0nameList,minSpec,maxSpec,upPeriod,do GroupDetectors(InputWorkspace=i,OutputWorkspace=i,MapFile=mapfile) ConvertUnits(i,i,"Wavelength",AlignBins=1) Rebin(i,i,reb) - if (removeoutlayer != "0"): + if removeoutlayer != "0": removeoutlayer(i+"_1") removeoutlayer(i+"_2") CropWorkspace(i,i+"mon",StartWorkspaceIndex=mon_spec,EndWorkspaceIndex=mon_spec) if nspec == 245: CropWorkspace(i,i+"2ddet",StartWorkspaceIndex=4,EndWorkspaceIndex=243) - if (floodfile != "none"): + if floodfile != "none": floodnorm(i+"2ddet",floodfile) if nspec == 1030: CropWorkspace(i,i+"2ddet",StartWorkspaceIndex=3,EndWorkspaceIndex=124) @@ -316,7 +317,7 @@ def nrSESANSFn(runList,nameList,P0runList,P0nameList,minSpec,maxSpec,upPeriod,do if nspec > 4 and minSp != 3: Divide(i+"2ddet",i+"mon",i+"2dnorm") DeleteWorkspace(i+"mon") - if (diagnostics == "0"): + if diagnostics == "0": DeleteWorkspace(i+"det") DeleteWorkspace(i) Minus(i+"norm_"+upPeriod,i+"norm_"+downPeriod,"num") @@ -424,9 +425,9 @@ def nrSESANSFn(runList,nameList,P0runList,P0nameList,minSpec,maxSpec,upPeriod,do k=k+1 def nrCalcSEConst(RFFrequency,poleShoeAngle): - if (RFFrequency=="0.5"): + if RFFrequency=="0.5": B=0.53*34.288 - elif (RFFrequency=="1.0"): + elif RFFrequency=="1.0": B=34.288 else: B=2.0*34.288 @@ -474,7 +475,7 @@ def nrSESANSP0Fn(P0runList,P0nameList,minSpec,maxSpec,upPeriod,downPeriod,gparam else: CropWorkspace(i,i+"det",StartWorkspaceIndex=minSp,EndWorkspaceIndex=maxSp) Divide(i+"det",i+"mon",i+"norm") - if (diagnostics=="0"): + if diagnostics=="0": DeleteWorkspace(i+"mon") DeleteWorkspace(i+"det") DeleteWorkspace(i) @@ -482,7 +483,7 @@ def nrSESANSP0Fn(P0runList,P0nameList,minSpec,maxSpec,upPeriod,downPeriod,gparam Plus(i+"norm_2",i+"norm_1","den") Divide("num","den",i+"pol") ReplaceSpecialValues(i+"pol",i+"pol",0.0,0.0,0.0,0.0) - if (diagnostics=="0"): + if diagnostics=="0": DeleteWorkspace(i+"norm_2") DeleteWorkspace(i+"norm_1") DeleteWorkspace("num") @@ -624,7 +625,7 @@ def nrNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpara k=0 for i in nlist: - if(mtd[i].isGroup()): + if mtd[i].isGroup(): #RenameWorkspace(i+"_1",i) snames=mtd[i].getNames() Plus(i+"_1",i+"_2","wtemp") @@ -700,7 +701,7 @@ def nrNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpara k=k+1 DeleteWorkspace(i) - if(diagnostics==0): + if diagnostics==0: DeleteWorkspace(i+"mon") DeleteWorkspace(i+"det") @@ -734,7 +735,7 @@ def nrDBFn(runListShort,nameListShort,runListLong,nameListLong,nameListComb,minS ConvertUnits(InputWorkspace=i,OutputWorkspace=i,Target="Wavelength",AlignBins="1") Rebin(InputWorkspace=i,OutputWorkspace=i,Params=reb) CropWorkspace(InputWorkspace=i,OutputWorkspace=i+"mon",StartWorkspaceIndex=mon_spec,EndWorkspaceIndex=mon_spec) - if(mtd[i].isGroup()): + if mtd[i].isGroup(): snames=mtd[i].getNames() a1=mtd[snames[0]] else: @@ -757,7 +758,7 @@ def nrDBFn(runListShort,nameListShort,runListLong,nameListLong,nameListComb,minS ConvertUnits(InputWorkspace=i,OutputWorkspace=i,Target="Wavelength",AlignBins="1") Rebin(InputWorkspace=i,OutputWorkspace=i,Params=reb) CropWorkspace(InputWorkspace=i,OutputWorkspace=i+"mon",StartWorkspaceIndex=mon_spec,EndWorkspaceIndex=mon_spec) - if(mtd[i].isGroup()): + if mtd[i].isGroup(): lnames=mtd[i].getNames() a1=mtd[lnames[0]] else: @@ -777,7 +778,7 @@ def nrDBFn(runListShort,nameListShort,runListLong,nameListLong,nameListComb,minS ReplaceSpecialValues(i+"norm",i+"norm","0.0","0.0","0.0","0.0") for i in range(len(nlistS)): - if(mtd[nlistS[i]+"norm"].isGroup()): + if mtd[nlistS[i]+"norm"].isGroup(): snames=mtd[nlistS[i]+"norm"].getNames() lnames=mtd[nlistL[i]+"norm"].getNames() for k in range(len(snames)): @@ -788,7 +789,7 @@ def nrDBFn(runListShort,nameListShort,runListLong,nameListLong,nameListComb,minS a1=findbin(lnames[k],float(minWavelength)) MultiplyRange(lnames[k],lnames[k],"0",str(a1),"0.0") WeightedMean(snames[k],lnames[k],nlistComb[i]+"_"+str(k+1)) - if (diagnostics=="0"): + if diagnostics=="0": DeleteWorkspace(snames[k]+"int") DeleteWorkspace(lnames[k]+"int") else: @@ -799,11 +800,11 @@ def nrDBFn(runListShort,nameListShort,runListLong,nameListLong,nameListComb,minS a1=findbin(nlistL[i]+"norm",float(minWavelength)) MultiplyRange(nlistL[i]+"norm",nlistL[i]+"norm","0",str(a1),"0.0") WeightedMean(nlistS[i]+"norm",nlistL[i]+"norm",nlistComb[i]) - if (diagnostics=="0"): + if diagnostics=="0": DeleteWorkspace(nlistS[i]+"int") DeleteWorkspace(nlistL[i]+"int") - if (diagnostics=="0"): + if diagnostics=="0": DeleteWorkspace(nlistS[i]+"mon") DeleteWorkspace(nlistS[i]+"det") if nspec != 4: @@ -915,7 +916,7 @@ def NRCombineDatafn(RunsNameList,CombNameList,applySFs,SFList,SFError,scaleOptio RenameWorkspace('currentSum',CombNameList) for i in range(len(rlist)-1): mtd.deleteWorkspace("sf"+str(i)) - if (diagnostics==0): + if diagnostics==0: for i in range(len(rlist)): mtd.deleteWorkspace(rlist[i]+"reb") return [arr2list(sfs),arr2list(sferrs)] @@ -1108,7 +1109,7 @@ def nrPNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpar for i in nlist: a1=mtd[i+"_1"] nspec=a1.getNumberHistograms() - if (subbgd==1 and nspec!=4): + if subbgd==1 and nspec!=4: # If a background subtraction is required sum the bgd outside the # area of the detector that is visible through the analyser over all periods and average CloneWorkspace(i,"bgdtemp") @@ -1116,7 +1117,7 @@ def nrPNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpar Rebin(InputWorkspace="bgdtemp",OutputWorkspace="bgdtemp",Params=reb) CropWorkspace(InputWorkspace="bgdtemp",OutputWorkspace="bgdtemp",StartWorkspaceIndex=4,EndWorkspaceIndex=243) Plus("bgdtemp"+"_"+pnums[0],"bgdtemp"+"_"+pnums[1],OutputWorkspace="wbgdsum") - if (nper>2): + if nper>2: for j in range(2,nper): Plus("wbgdsum","bgdtemp"+"_"+pnums[j],OutputWorkspace="wbgdsum") GroupDetectors("wbgdsum","bgd2",WorkspaceIndexList=range(0,50),KeepUngroupedSpectra="0") @@ -1150,7 +1151,7 @@ def nrPNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpar #print str(2.0*float(incAngles[k]))+" "+str(atan((float(minSpec)-float(specChan))*1.2e-3/3.63)*180.0/pi)+" "+str(a1) RotateInstrumentComponent(wksp+"det","DetectorBench",X="-1.0",Angle=str(a1)) floodnorm(wksp+"det",floodfile) - if (subbgd==1): + if subbgd==1: # Subract a per spectrum background Minus(wksp+"det",wbgdtemp,OutputWorkspace=wksp+"det") ResetNegatives(InputWorkspace=wksp+"det",OutputWorkspace=wksp+"det",AddMinimum='0',ResetValue="0.0") @@ -1178,7 +1179,7 @@ def nrPNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpar RenameWorkspace(InputWorkspace=i+"norm"+"_"+pnums[j]+"corr",OutputWorkspace=i+"normcorr"+"_"+pnums[j]) GroupWorkspaces(InputWorkspaces=i+"normcorr_"+pnums[0]+","+i+"normcorr_"+pnums[1],OutputWorkspace=i+"normcorr") ConvertUnits(InputWorkspace=i+"normcorr",OutputWorkspace=i+"normcorrRvQ",Target="MomentumTransfer") - if (nspec > 4 and doLDCorrs != "0"): + if nspec > 4 and doLDCorrs != "0": nrPNRCorrection(i+"detnorm_"+pnums[0],i+"detnorm_"+pnums[1]) for j in range(4): RenameWorkspace(InputWorkspace=i+"detnorm"+"_"+pnums[j]+"corr",OutputWorkspace=i+"detnormcorr"+"_"+pnums[j]) @@ -1189,19 +1190,19 @@ def nrPNRFn(runList,nameList,incidentAngles,DBList,specChan,minSpec,maxSpec,gpar RenameWorkspace(InputWorkspace=i+"norm"+"_"+pnums[j]+"corr",OutputWorkspace=i+"normcorr"+"_"+pnums[j]) GroupWorkspaces(InputWorkspaces=i+"normcorr_"+pnums[0]+","+i+"normcorr_"+pnums[1]+","+i+"normcorr_"+pnums[2]+","+i+"normcorr_"+pnums[3]+"",OutputWorkspace=i+"normcorr") ConvertUnits(InputWorkspace=i+"normcorr",OutputWorkspace=i+"normcorrRvQ",Target="MomentumTransfer") - if (nspec > 4 and doLDCorrs != "0"): + if nspec > 4 and doLDCorrs != "0": nrPACorrection(i+"detnorm_"+pnums[0],i+"detnorm_"+pnums[1],i+"detnorm_"+pnums[2],i+"detnorm_"+pnums[3]) for j in range(4): RenameWorkspace(InputWorkspace=i+"detnorm"+"_"+pnums[j]+"corr",OutputWorkspace=i+"detnormcorr"+"_"+pnums[j]) GroupWorkspaces(InputWorkspaces=i+"detnormcorr_"+pnums[0]+","+i+"detnormcorr_"+pnums[1]+","+i+"detnormcorr_"+pnums[2]+","+i+"detnormcorr_"+pnums[3]+"",OutputWorkspace=i+"detnormcorr") - if (diagnostics == 0 and doCorrs != "0"): + if diagnostics == 0 and doCorrs != "0": DeleteWorkspace(i+"norm") DeleteWorkspace(i+"RvQ") - if (diagnostics == 0 and doLDCorrs != "0"): + if diagnostics == 0 and doLDCorrs != "0": DeleteWorkspace(i+"detnorm") k=k+1 DeleteWorkspace(i) - if (subbgd==1): + if subbgd==1: DeleteWorkspace("wbgdtemp") def tl(wksp,th0,schan): diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py index 7034bf842664..fa0c74c731df 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/quick.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ''' SVN Info: The variables below will only get subsituted at svn checkout if the repository is configured for variable subsitution. @@ -91,12 +92,12 @@ def quick(run, theta=None, pointdet=True,roi=[0,0], db=[0,0], trans='', polcorr= cPp = idf_defaults['cPp'] - return quick_explicit(run=run, i0_monitor_index = i0_monitor_index, lambda_min = lambda_min, lambda_max = lambda_max, - point_detector_start = point_detector_start, point_detector_stop = point_detector_stop, - multi_detector_start = multi_detector_start, background_min = background_min, background_max = background_max, - int_min = int_min, int_max = int_max, theta = theta, pointdet = pointdet, roi = roi, db = db, trans = trans, - debug = debug, correction_strategy = correction_strategy, stitch_start_overlap=stitch_start_overlap, - stitch_end_overlap=stitch_end_overlap, stitch_params=stitch_params, polcorr=polcorr, crho=crho, calpha=calpha, cAp=cAp, cPp=cPp, + return quick_explicit(run=run, i0_monitor_index = i0_monitor_index, lambda_min = lambda_min, lambda_max = lambda_max,\ + point_detector_start = point_detector_start, point_detector_stop = point_detector_stop,\ + multi_detector_start = multi_detector_start, background_min = background_min, background_max = background_max,\ + int_min = int_min, int_max = int_max, theta = theta, pointdet = pointdet, roi = roi, db = db, trans = trans,\ + debug = debug, correction_strategy = correction_strategy, stitch_start_overlap=stitch_start_overlap,\ + stitch_end_overlap=stitch_end_overlap, stitch_params=stitch_params, polcorr=polcorr, crho=crho, calpha=calpha, cAp=cAp, cPp=cPp,\ detector_component_name=detector_component_name, sample_component_name=sample_component_name, correct_positions=correct_positions) @@ -129,7 +130,7 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max, background_mi print i0_monitor_index print nHist - if (run=='0'): + if run=='0': RunNumber = '0' else: RunNumber = groupGet(_sample_ws.getName(),'samp','run_number') @@ -147,7 +148,7 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max, background_mi DirectBeam = SumSpectra(InputWorkspace=_detector_ws, StartWorkspaceIndex=db[0], EndWorkspaceIndex=db[1]) ReflectedBeam = ReflectedBeam / DirectBeam polCorr(polcorr, IvsLam, crho, calpha, cAp, cPp) - if (theta and correct_positions): + if theta and correct_positions: IvsQ = l2q(ReflectedBeam, detector_component_name, theta, sample_component_name) else: IvsQ = ConvertUnits(InputWorkspace=ReflectedBeam, Target="MomentumTransfer") @@ -181,7 +182,7 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max, background_mi # Convert to I vs Q # check if detector in direct beam - if (theta == None or theta == 0 or theta == ''): + if theta == None or theta == 0 or theta == '': inst = groupGet('IvsLam','inst') detLocation=inst.getComponentByName(detector_component_name).getPos() sampleLocation=inst.getComponentByName(sample_component_name).getPos() @@ -290,7 +291,7 @@ def make_trans_corr(transrun, stitch_start_overlap, stitch_end_overlap, stitch_p _detector_ws_llam = Divide(LHSWorkspace=_detector_ws_llam, RHSWorkspace=_mon_int_trans) print stitch_start_overlap, stitch_end_overlap, stitch_params - transWS, outputScaling = Stitch1D(LHSWorkspace=_detector_ws_slam, RHSWorkspace=_detector_ws_llam, StartOverlap=stitch_start_overlap, + transWS, outputScaling = Stitch1D(LHSWorkspace=_detector_ws_slam, RHSWorkspace=_detector_ws_llam, StartOverlap=stitch_start_overlap,\ EndOverlap=stitch_end_overlap, Params=stitch_params) transWS = RenameWorkspace(InputWorkspace=transWS, OutputWorkspace="TRANS_" + slam + "_" + llam) @@ -319,8 +320,8 @@ def transCorr(transrun, i_vs_lam, lambda_min, lambda_max, background_min, backgr else: logger.debug("Creating new transmission correction workspace.") # Make the transmission correction workspace. - _transWS = make_trans_corr(transrun, stitch_start_overlap, stitch_end_overlap, stitch_params, - lambda_min, lambda_max, background_min, background_max, + _transWS = make_trans_corr(transrun, stitch_start_overlap, stitch_end_overlap, stitch_params,\ + lambda_min, lambda_max, background_min, background_max,\ int_min, int_max, detector_index_ranges, i0_monitor_index,) #got sometimes very slight binning diferences, so do this again: @@ -410,7 +411,7 @@ def nrPNRCorrection(Wksp,crho,calpha,cAp,cPp): logger.notice(message) print message CloneWorkspace(Wksp,OutputWorkspace='_'+Wksp+'_uncorrected') - if ( (not isinstance(mtd[Wksp], WorkspaceGroup)) or (not mtd[Wksp].size()==2) ): + if (not isinstance(mtd[Wksp], WorkspaceGroup)) or (not mtd[Wksp].size()==2) : print "PNR correction works only with exactly 2 periods!" return mtd[Wksp] else: @@ -559,17 +560,17 @@ def groupGet(wksp,whattoget,field=''): returns information about instrument or sample details for a given workspace wksp, also if the workspace is a group (info from first group element) ''' - if (whattoget == 'inst'): + if whattoget == 'inst': if isinstance(mtd[wksp], WorkspaceGroup): return mtd[wksp+'_1'].getInstrument() else: return mtd[wksp].getInstrument() - elif (whattoget == 'samp' and field != ''): + elif whattoget == 'samp' and field != '': if isinstance(mtd[wksp], WorkspaceGroup): try: log = mtd[wksp + '_1'].getRun().getLogData(field).value - if (type(log) is int or type(log) is str): + if type(log) is int or type(log) is str: res=log else: res = log[len(log)-1] @@ -579,7 +580,7 @@ def groupGet(wksp,whattoget,field=''): else: try: log = mtd[wksp].getRun().getLogData(field).value - if (type(log) is int or type(log) is str): + if type(log) is int or type(log) is str: res=log else: res = log[len(log)-1] @@ -587,7 +588,7 @@ def groupGet(wksp,whattoget,field=''): res = 0 print "Block "+field+" not found." return res - elif (whattoget == 'wksp'): + elif whattoget == 'wksp': if isinstance(mtd[wksp], WorkspaceGroup): return mtd[wksp+'_1'].getNumberHistograms() else: diff --git a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/saveModule.py b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/saveModule.py index 2aba6a0cad54..46b5f7866b8b 100644 --- a/Code/Mantid/scripts/Reflectometry/isis_reflectometry/saveModule.py +++ b/Code/Mantid/scripts/Reflectometry/isis_reflectometry/saveModule.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name from PyQt4 import QtCore from mantid.simpleapi import * import numpy as n diff --git a/Code/Mantid/scripts/SANS/ISISCommandInterface.py b/Code/Mantid/scripts/SANS/ISISCommandInterface.py index f3cd45cac67a..b453bb6065b2 100644 --- a/Code/Mantid/scripts/SANS/ISISCommandInterface.py +++ b/Code/Mantid/scripts/SANS/ISISCommandInterface.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Enables the SANS commands (listed at http://www.mantidproject.org/SANS) to be run @@ -265,7 +266,7 @@ def TransmissionSample(sample, direct, reload = True, period_t = -1, period_d = """ _printMessage('TransmissionSample("' + str(sample) + '","' + str(direct) + '")') ReductionSingleton().set_trans_sample(sample, direct, reload, period_t, period_d) - return ReductionSingleton().samp_trans_load.execute( + return ReductionSingleton().samp_trans_load.execute(\ ReductionSingleton(), None) def TransmissionCan(can, direct, reload = True, period_t = -1, period_d = -1): @@ -279,7 +280,7 @@ def TransmissionCan(can, direct, reload = True, period_t = -1, period_d = -1): """ _printMessage('TransmissionCan("' + str(can) + '","' + str(direct) + '")') ReductionSingleton().set_trans_can(can, direct, reload, period_t, period_d) - return ReductionSingleton().can_trans_load.execute( + return ReductionSingleton().can_trans_load.execute(\ ReductionSingleton(), None) def AssignSample(sample_run, reload = True, period = isis_reduction_steps.LoadRun.UNSET_PERIOD): @@ -316,7 +317,7 @@ def SetCentre(xcoord, ycoord, bank = 'rear'): """ _printMessage('SetCentre(' + str(xcoord) + ', ' + str(ycoord) + ')') - ReductionSingleton().set_beam_finder(isis_reduction_steps.BaseBeamFinder( + ReductionSingleton().set_beam_finder(isis_reduction_steps.BaseBeamFinder(\ float(xcoord)/1000.0, float(ycoord)/1000.0), bank) def GetMismatchedDetList(): @@ -379,9 +380,9 @@ def WavRangeReduction(wav_start=None, wav_end=None, full_trans_wav=None, name_su # if the user chose to reduce front and does not require fit if not (com_det_option == 'front' and not fitRequired): reduce_rear_flag = True - if (com_det_option != 'rear'): + if com_det_option != 'rear': reduce_front_flag = True - if (com_det_option == 'merged'): + if com_det_option == 'merged': merge_flag = True #The shift and scale is always on the front detector. @@ -407,7 +408,7 @@ def WavRangeReduction(wav_start=None, wav_end=None, full_trans_wav=None, name_su # do reduce front bank if reduce_front_flag: # it is necessary to replace the Singleton if a reduction was done before - if (reduce_rear_flag): + if reduce_rear_flag: # In this case, it is necessary to reload the files, in order to move the components to the # correct position defined by its get_beam_center. (ticket #5942) @@ -415,8 +416,8 @@ def WavRangeReduction(wav_start=None, wav_end=None, full_trans_wav=None, name_su ReductionSingleton.replace(ReductionSingleton().cur_settings()) # for the LOQ instrument, if the beam centers are different, we have to reload the data. - if (ReductionSingleton().instrument._NAME == 'LOQ' and - (ReductionSingleton().get_beam_center('rear') != ReductionSingleton().get_beam_center('front'))): + if ReductionSingleton().instrument._NAME == 'LOQ' and\ + ReductionSingleton().get_beam_center('rear') != ReductionSingleton().get_beam_center('front'): # It is necessary to reload sample, transmission and can files. #reload sample @@ -452,9 +453,9 @@ def WavRangeReduction(wav_start=None, wav_end=None, full_trans_wav=None, name_su if merge_flag: retWSname_merged = retWSname_rear if retWSname_merged.count('rear') == 1: - retWSname_merged = retWSname_merged.replace('rear', 'merged') + retWSname_merged = retWSname_merged.replace('rear', 'merged') else: - retWSname_merged = retWSname_merged + "_merged" + retWSname_merged = retWSname_merged + "_merged" Nf = mtd[retWSname_front+"_sumOfNormFactors"] Nr = mtd[retWSname_rear+"_sumOfNormFactors"] @@ -574,26 +575,26 @@ def _fitRescaleAndShift(rAnds, frontData, rearData): if rAnds.qRangeUserSelected: Fit(InputWorkspace=rearData, Function='name=TabulatedFunction, Workspace="'+str(frontData)+'"' - +";name=FlatBackground", + +";name=FlatBackground", Ties='f0.Scaling='+str(rAnds.scale)+',f0.Shift=0.0', Output="__fitRescaleAndShift", StartX=rAnds.qMin, EndX=rAnds.qMax) else: Fit(InputWorkspace=rearData, Function='name=TabulatedFunction, Workspace="'+str(frontData)+'"' - +";name=FlatBackground", + +";name=FlatBackground", Ties='f0.Scaling='+str(rAnds.scale)+',f0.Shift=0.0', Output="__fitRescaleAndShift") elif rAnds.fitShift==False: if rAnds.qRangeUserSelected: Fit(InputWorkspace=rearData, Function='name=TabulatedFunction, Workspace="'+str(frontData)+'"' - +";name=FlatBackground", + +";name=FlatBackground", Ties='f1.A0='+str(rAnds.shift*rAnds.scale)+',f0.Shift=0.0', Output="__fitRescaleAndShift", StartX=rAnds.qMin, EndX=rAnds.qMax) else: Fit(InputWorkspace=rearData, Function='name=TabulatedFunction, Workspace="'+str(frontData)+'"' - +";name=FlatBackground", + +";name=FlatBackground", Ties='f1.A0='+str(rAnds.shift*rAnds.scale)+',f0.Shift=0.0', Output="__fitRescaleAndShift") else: @@ -635,7 +636,7 @@ def _WavRangeReduction(name_suffix=None): Run a reduction that has been set up, from loading the raw data to calculating Q """ def _setUpPeriod(period): - assert(ReductionSingleton().get_sample().loader.move2ws(period)) + assert ReductionSingleton().get_sample().loader.move2ws(period) can = ReductionSingleton().get_can() if can and can.loader.periods_in_file > 1: can.loader.move2ws(period) @@ -867,8 +868,8 @@ def LimitsR(rmin, rmax, quiet=False, reducer=None): def LimitsWav(lmin, lmax, step, bin_type): _printMessage('LimitsWav(' + str(lmin) + ', ' + str(lmax) + ', ' + str(step) + ', ' + bin_type + ')') - if ( bin_type.upper().strip() == 'LINEAR'): bin_type = 'LIN' - if ( bin_type.upper().strip() == 'LOGARITHMIC'): bin_type = 'LOG' + if bin_type.upper().strip() == 'LINEAR': bin_type = 'LIN' + if bin_type.upper().strip() == 'LOGARITHMIC': bin_type = 'LOG' if bin_type == 'LOG': bin_sym = '-' else: @@ -1048,7 +1049,7 @@ def FindBeamCentre(rlow, rupp, MaxIter = 10, xstart = None, ystart = None, toler if xstart or ystart: ReductionSingleton().set_beam_finder( - isis_reduction_steps.BaseBeamFinder( + isis_reduction_steps.BaseBeamFinder(\ float(xstart), float(ystart)),det_bank) beamcoords = ReductionSingleton().get_beam_center() @@ -1093,7 +1094,7 @@ def FindBeamCentre(rlow, rupp, MaxIter = 10, xstart = None, ystart = None, toler if not graph_handle: #once we have a plot it will be updated automatically when the workspaces are updated graph_handle = mantidplot.plotSpectrum(centre.QUADS, 0) - graph_handle.activeLayer().setTitle( + graph_handle.activeLayer().setTitle(\ centre.status_str(it, resX, resY)) except : #if plotting is not available it probably means we are running outside a GUI, in which case do everything but don't plot diff --git a/Code/Mantid/scripts/SANS/SANSBatchMode.py b/Code/Mantid/scripts/SANS/SANSBatchMode.py index d1a15a85f1dd..58ba1a1287e5 100644 --- a/Code/Mantid/scripts/SANS/SANSBatchMode.py +++ b/Code/Mantid/scripts/SANS/SANSBatchMode.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # SANSBatchMode.py # diff --git a/Code/Mantid/scripts/SANS/SANSUtility.py b/Code/Mantid/scripts/SANS/SANSUtility.py index e66369da9fdc..59904b160692 100644 --- a/Code/Mantid/scripts/SANS/SANSUtility.py +++ b/Code/Mantid/scripts/SANS/SANSUtility.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name ######################################################### # This module contains utility functions common to the # SANS data reduction scripts @@ -143,9 +144,9 @@ def spectrumBlock(base, ylow, xlow, ydim, xdim, det_dimension, orientation): max_row = base + (y+1)*det_dimension - 1 min_row = base + (y)*det_dimension for x in range(0,xdim): - std_i = start_spec + x + (y*det_dimension) - diff_s = std_i - min_row - output += str(max_row - diff_s) + ',' + std_i = start_spec + x + (y*det_dimension) + diff_s = std_i - min_row + output += str(max_row - diff_s) + ',' return output.rstrip(",") @@ -618,28 +619,28 @@ def ScaleByVolume(inputWS, scalefactor, geomid, width, height, thickness): @deprecated def StripEndZeroes(workspace, flag_value = 0.0): - result_ws = mtd[workspace] - y_vals = result_ws.readY(0) - length = len(y_vals) + result_ws = mtd[workspace] + y_vals = result_ws.readY(0) + length = len(y_vals) # Find the first non-zero value - start = 0 - for i in range(0, length): - if ( y_vals[i] != flag_value ): - start = i - break + start = 0 + for i in range(0, length): + if y_vals[i] != flag_value : + start = i + break # Now find the last non-zero value - stop = 0 - length -= 1 - for j in range(length, 0,-1): - if ( y_vals[j] != flag_value ): - stop = j - break + stop = 0 + length -= 1 + for j in range(length, 0,-1): + if y_vals[j] != flag_value : + stop = j + break # Find the appropriate X values and call CropWorkspace - x_vals = result_ws.readX(0) - startX = x_vals[start] + x_vals = result_ws.readX(0) + startX = x_vals[start] # Make sure we're inside the bin that we want to crop - endX = 1.001*x_vals[stop + 1] - CropWorkspace(InputWorkspace=workspace,OutputWorkspace=workspace,XMin=startX,XMax=endX) + endX = 1.001*x_vals[stop + 1] + CropWorkspace(InputWorkspace=workspace,OutputWorkspace=workspace,XMin=startX,XMax=endX) @deprecated class Orientation(object): diff --git a/Code/Mantid/scripts/SANS/SANSadd2.py b/Code/Mantid/scripts/SANS/SANSadd2.py index 910687eb533e..a8a6436f50ad 100644 --- a/Code/Mantid/scripts/SANS/SANSadd2.py +++ b/Code/Mantid/scripts/SANS/SANSadd2.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import os from mantid.simpleapi import * from mantid.kernel import Logger @@ -7,54 +8,76 @@ _NO_INDIVIDUAL_PERIODS = -1 def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add','.RAW'), lowMem=False, binning='Monitors'): - if inst.upper() == "SANS2DTUBES": - inst = "SANS2D" + if inst.upper() == "SANS2DTUBES": + inst = "SANS2D" #check if there is at least one file in the list - if len(runs) < 1 : return + if len(runs) < 1 : return - if not defType.startswith('.') : defType = '.'+defType + if not defType.startswith('.') : defType = '.'+defType #these input arguments need to be arrays of strings, enforce this - if type(runs) == str : runs = (runs, ) - if type(rawTypes) == str : rawTypes = (rawTypes, ) + if type(runs) == str : runs = (runs, ) + if type(rawTypes) == str : rawTypes = (rawTypes, ) - if lowMem: - lowMem = _can_load_periods(runs, defType, rawTypes) - if lowMem: - period = 1 - else: - period = _NO_INDIVIDUAL_PERIODS + if lowMem: + lowMem = _can_load_periods(runs, defType, rawTypes) + if lowMem: + period = 1 + else: + period = _NO_INDIVIDUAL_PERIODS - userEntry = runs[0] + userEntry = runs[0] - while(True): + while True: - isFirstDataSetEvent = False + isFirstDataSetEvent = False #we need to catch all exceptions to ensure that a dialog box is raised with the error - try : - lastPath, lastFile, logFile, num_periods, isFirstDataSetEvent = _loadWS( + try : + lastPath, lastFile, logFile, num_periods, isFirstDataSetEvent = _loadWS(\ userEntry, defType, inst, 'AddFilesSumTempory', rawTypes, period) # if event data prevent loop over periods makes no sense - if isFirstDataSetEvent: - period = _NO_INDIVIDUAL_PERIODS - - if inst.upper() != 'SANS2D' and isFirstDataSetEvent: - error = 'Adding event data not supported for ' + inst + ' for now' - print error - logger.notice(error) - for workspaceName in ('AddFilesSumTempory','AddFilesSumTempory_monitors'): - if workspaceName in mtd: - DeleteWorkspace(workspaceName) - return "" - - for i in range(len(runs)-1): - userEntry = runs[i+1] - lastPath, lastFile, logFile, dummy, isDataSetEvent = _loadWS( + if isFirstDataSetEvent: + period = _NO_INDIVIDUAL_PERIODS + + if inst.upper() != 'SANS2D' and isFirstDataSetEvent: + error = 'Adding event data not supported for ' + inst + ' for now' + print error + logger.notice(error) + for workspaceName in ('AddFilesSumTempory','AddFilesSumTempory_monitors'): + if workspaceName in mtd: + DeleteWorkspace(workspaceName) + return "" + + for i in range(len(runs)-1): + userEntry = runs[i+1] + lastPath, lastFile, logFile, dummy, isDataSetEvent = _loadWS(\ userEntry, defType, inst,'AddFilesNewTempory', rawTypes, period) - if isDataSetEvent != isFirstDataSetEvent: - error = 'Datasets added must be either ALL histogram data or ALL event data' + if isDataSetEvent != isFirstDataSetEvent: + error = 'Datasets added must be either ALL histogram data or ALL event data' + print error + logger.notice(error) + for workspaceName in ('AddFilesSumTempory','AddFilesNewTempory'): + if workspaceName in mtd: + DeleteWorkspace(workspaceName) + return "" + + Plus(LHSWorkspace='AddFilesSumTempory',RHSWorkspace= 'AddFilesNewTempory',OutputWorkspace= 'AddFilesSumTempory') + if isFirstDataSetEvent: + Plus(LHSWorkspace='AddFilesSumTempory_monitors',RHSWorkspace= 'AddFilesNewTempory_monitors',OutputWorkspace= 'AddFilesSumTempory_monitors') + DeleteWorkspace("AddFilesNewTempory") + if isFirstDataSetEvent: + DeleteWorkspace("AddFilesNewTempory_monitors") + + except ValueError as e: + error = 'Error opening file ' + userEntry+': ' + str(e) + print error + logger.notice(error) + if 'AddFilesSumTempory' in mtd : DeleteWorkspace('AddFilesSumTempory') + return "" + except Exception as e: + error = 'Error finding files: ' + str(e) print error logger.notice(error) for workspaceName in ('AddFilesSumTempory','AddFilesNewTempory'): @@ -62,221 +85,199 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add' DeleteWorkspace(workspaceName) return "" - Plus(LHSWorkspace='AddFilesSumTempory',RHSWorkspace= 'AddFilesNewTempory',OutputWorkspace= 'AddFilesSumTempory') - if isFirstDataSetEvent: - Plus(LHSWorkspace='AddFilesSumTempory_monitors',RHSWorkspace= 'AddFilesNewTempory_monitors',OutputWorkspace= 'AddFilesSumTempory_monitors') - DeleteWorkspace("AddFilesNewTempory") - if isFirstDataSetEvent: - DeleteWorkspace("AddFilesNewTempory_monitors") - - except ValueError as e: - error = 'Error opening file ' + userEntry+': ' + str(e) - print error - logger.notice(error) - if 'AddFilesSumTempory' in mtd : DeleteWorkspace('AddFilesSumTempory') - return "" - except Exception as e: - error = 'Error finding files: ' + str(e) - print error - logger.notice(error) - for workspaceName in ('AddFilesSumTempory','AddFilesNewTempory'): - if workspaceName in mtd: - DeleteWorkspace(workspaceName) - return "" - # in case of event file force it into a histogram workspace - if isFirstDataSetEvent: - wsInMonitor = mtd['AddFilesSumTempory_monitors'] - if binning == 'Monitors': - monX = wsInMonitor.dataX(0) - binning = str(monX[0]) - binGap = monX[1] - monX[0] - binning = binning + "," + str(binGap) - for j in range(2,len(monX)): - nextBinGap = monX[j] - monX[j-1] - if nextBinGap != binGap: - binGap = nextBinGap - binning = binning + "," + str(monX[j-1]) + "," + str(binGap) - binning = binning + "," + str(monX[len(monX)-1]) - - logger.notice(binning) - Rebin(InputWorkspace='AddFilesSumTempory',OutputWorkspace='AddFilesSumTempory_Rebin',Params= binning, PreserveEvents=False) + if isFirstDataSetEvent: + wsInMonitor = mtd['AddFilesSumTempory_monitors'] + if binning == 'Monitors': + monX = wsInMonitor.dataX(0) + binning = str(monX[0]) + binGap = monX[1] - monX[0] + binning = binning + "," + str(binGap) + for j in range(2,len(monX)): + nextBinGap = monX[j] - monX[j-1] + if nextBinGap != binGap: + binGap = nextBinGap + binning = binning + "," + str(monX[j-1]) + "," + str(binGap) + binning = binning + "," + str(monX[len(monX)-1]) + + logger.notice(binning) + Rebin(InputWorkspace='AddFilesSumTempory',OutputWorkspace='AddFilesSumTempory_Rebin',Params= binning, PreserveEvents=False) # loading the nexus file using LoadNexus is necessary because it has some metadata # that is not in LoadEventNexus. This must be fixed. - filename, ext = _makeFilename(runs[0], defType, inst) - LoadNexus(Filename=filename, OutputWorkspace='AddFilesSumTempory', SpectrumMax=wsInMonitor.getNumberHistograms()) + filename, ext = _makeFilename(runs[0], defType, inst) + LoadNexus(Filename=filename, OutputWorkspace='AddFilesSumTempory', SpectrumMax=wsInMonitor.getNumberHistograms()) # User may have selected a binning which is different from the default - Rebin(InputWorkspace='AddFilesSumTempory',OutputWorkspace='AddFilesSumTempory',Params= binning) + Rebin(InputWorkspace='AddFilesSumTempory',OutputWorkspace='AddFilesSumTempory',Params= binning) # For now the monitor binning must be the same as the detector binning # since otherwise both cannot exist in the same output histogram file - Rebin(InputWorkspace='AddFilesSumTempory_monitors',OutputWorkspace='AddFilesSumTempory_monitors',Params= binning) + Rebin(InputWorkspace='AddFilesSumTempory_monitors',OutputWorkspace='AddFilesSumTempory_monitors',Params= binning) - wsInMonitor = mtd['AddFilesSumTempory_monitors'] - wsOut = mtd['AddFilesSumTempory'] - wsInDetector = mtd['AddFilesSumTempory_Rebin'] + wsInMonitor = mtd['AddFilesSumTempory_monitors'] + wsOut = mtd['AddFilesSumTempory'] + wsInDetector = mtd['AddFilesSumTempory_Rebin'] - mon_n = wsInMonitor.getNumberHistograms() - for i in range(mon_n): - wsOut.setY(i,wsInMonitor.dataY(i)) - wsOut.setE(i,wsInMonitor.dataE(i)) - ConjoinWorkspaces(wsOut, wsInDetector, CheckOverlapping=True) + mon_n = wsInMonitor.getNumberHistograms() + for i in range(mon_n): + wsOut.setY(i,wsInMonitor.dataY(i)) + wsOut.setE(i,wsInMonitor.dataE(i)) + ConjoinWorkspaces(wsOut, wsInDetector, CheckOverlapping=True) - if 'AddFilesSumTempory_Rebin' in mtd : DeleteWorkspace('AddFilesSumTempory_Rebin') + if 'AddFilesSumTempory_Rebin' in mtd : DeleteWorkspace('AddFilesSumTempory_Rebin') - lastFile = os.path.splitext(lastFile)[0] + lastFile = os.path.splitext(lastFile)[0] # now save the added file - outFile = lastFile+'-add.'+'nxs' - logger.notice('writing file: '+outFile) - if period == 1 or period == _NO_INDIVIDUAL_PERIODS: + outFile = lastFile+'-add.'+'nxs' + logger.notice('writing file: '+outFile) + if period == 1 or period == _NO_INDIVIDUAL_PERIODS: #replace the file the first time around - SaveNexusProcessed(InputWorkspace="AddFilesSumTempory", + SaveNexusProcessed(InputWorkspace="AddFilesSumTempory", Filename=outFile, Append=False) - else: + else: #then append - SaveNexusProcessed("AddFilesSumTempory", outFile, Append=True) + SaveNexusProcessed("AddFilesSumTempory", outFile, Append=True) - DeleteWorkspace("AddFilesSumTempory") - if isFirstDataSetEvent: + DeleteWorkspace("AddFilesSumTempory") + if isFirstDataSetEvent: DeleteWorkspace("AddFilesSumTempory_monitors") - if period == num_periods: - break + if period == num_periods: + break - if period == _NO_INDIVIDUAL_PERIODS: - break - else: - period += 1 + if period == _NO_INDIVIDUAL_PERIODS: + break + else: + period += 1 #this adds the path to the filename - path,base = os.path.split(outFile) - if path == '' or base not in os.listdir(path): - path = config['defaultsave.directory'] + path - assert(base in os.listdir(path)) - pathout = path - if logFile: - _copyLog(lastPath, logFile, pathout) + path,base = os.path.split(outFile) + if path == '' or base not in os.listdir(path): + path = config['defaultsave.directory'] + path + assert base in os.listdir(path) + pathout = path + if logFile: + _copyLog(lastPath, logFile, pathout) - return 'The following file has been created:\n'+outFile + return 'The following file has been created:\n'+outFile def _can_load_periods(runs, defType, rawTypes): - """ + """ Searches through the supplied list of run file names and returns False if some appear to be raw files else True """ - for i in runs: - dummy, ext = os.path.splitext(i) - if ext == '': ext = defType - if _isType(ext, rawTypes): - return False + for i in runs: + dummy, ext = os.path.splitext(i) + if ext == '': ext = defType + if _isType(ext, rawTypes): + return False #no raw files were found, assume we can specify the period number for each - return True + return True def _makeFilename(entry, ext, inst) : - """ + """ If entry not already a valid filename make it into one """ - try : - runNum = int(entry) #the user entered something that translates to a run number, convert it to a file - filename=inst+_padZero(runNum, inst)+ext - except ValueError : #we don't have a run number, assume it's a valid filename - filename = entry - dummy, ext = os.path.splitext(filename) + try : + runNum = int(entry) #the user entered something that translates to a run number, convert it to a file + filename=inst+_padZero(runNum, inst)+ext + except ValueError : #we don't have a run number, assume it's a valid filename + filename = entry + dummy, ext = os.path.splitext(filename) - return filename, ext + return filename, ext def _loadWS(entry, ext, inst, wsName, rawTypes, period=_NO_INDIVIDUAL_PERIODS) : - filename, ext = _makeFilename(entry, ext, inst) + filename, ext = _makeFilename(entry, ext, inst) - logger.notice('reading file: '+filename) + logger.notice('reading file: '+filename) - if period != _NO_INDIVIDUAL_PERIODS: + if period != _NO_INDIVIDUAL_PERIODS: #load just a single period - outWs = Load(Filename=filename, OutputWorkspace=wsName, EntryNumber=period) - else: - outWs = Load(Filename=filename,OutputWorkspace=wsName) + outWs = Load(Filename=filename, OutputWorkspace=wsName, EntryNumber=period) + else: + outWs = Load(Filename=filename,OutputWorkspace=wsName) - props = outWs.getHistory().lastAlgorithm() + props = outWs.getHistory().lastAlgorithm() - isDataSetEvent = False - wsDataSet = mtd[wsName] - if hasattr(wsDataSet, 'getNumberEvents'): - isDataSetEvent = True + isDataSetEvent = False + wsDataSet = mtd[wsName] + if hasattr(wsDataSet, 'getNumberEvents'): + isDataSetEvent = True - if isDataSetEvent: - LoadEventNexus(Filename=filename,OutputWorkspace=wsName, LoadMonitors=True) - runDetails = mtd[wsName].getRun() - timeArray = runDetails.getLogData("proton_charge").times + if isDataSetEvent: + LoadEventNexus(Filename=filename,OutputWorkspace=wsName, LoadMonitors=True) + runDetails = mtd[wsName].getRun() + timeArray = runDetails.getLogData("proton_charge").times # There should never be a time increment in the proton charge larger than say "two weeks" # SANS2D currently is run at 10 frames per second. This may be increated to 5Hz # (step of 0.2 sec). Although time between frames may be larger due to having the SMP veto switched on, # but hopefully not longer than two weeks! - for i in range(len(timeArray)-1): + for i in range(len(timeArray)-1): # cal time dif in seconds - timeDif = (timeArray[i+1].total_nanoseconds()-timeArray[i].total_nanoseconds())*1e-9 - if timeDif > 172800: - sanslog.warning('Time increments in the proton charge log of ' + filename + ' are suspicious large.' + + timeDif = (timeArray[i+1].total_nanoseconds()-timeArray[i].total_nanoseconds())*1e-9 + if timeDif > 172800: + sanslog.warning('Time increments in the proton charge log of ' + filename + ' are suspicious large.' +\ ' For example a time difference of ' + str(timeDif) + " seconds has been observed.") - break + break - path = props.getPropertyValue('FileName') - path, fName = os.path.split(path) - if path.find('/') == -1: + path = props.getPropertyValue('FileName') + path, fName = os.path.split(path) + if path.find('/') == -1: #looks like we're on a windows system, convert the directory separators - path = path.replace('\\', '/') + path = path.replace('\\', '/') - if _isType(ext, rawTypes): - LoadSampleDetailsFromRaw(InputWorkspace=wsName,Filename= path+'/'+fName) + if _isType(ext, rawTypes): + LoadSampleDetailsFromRaw(InputWorkspace=wsName,Filename= path+'/'+fName) - logFile = None + logFile = None #change below when logs in Nexus files work file types of .raw need their log files to be copied too - if True:#_isType(ext, rawTypes): - logFile = os.path.splitext(fName)[0]+'.log' + if True:#_isType(ext, rawTypes): + logFile = os.path.splitext(fName)[0]+'.log' - try: - samp = mtd[wsName].getRun() - numPeriods = samp.getLogData('nperiods').value - except: + try: + samp = mtd[wsName].getRun() + numPeriods = samp.getLogData('nperiods').value + except: #assume the run file didn't support multi-period data and so there is only one period - numPeriods = 1 + numPeriods = 1 - return path, fName, logFile, numPeriods, isDataSetEvent + return path, fName, logFile, numPeriods, isDataSetEvent def _padZero(runNum, inst): - numDigits = config.getInstrument(inst).zeroPadding(0) - run = str(runNum).zfill(numDigits) - return run + numDigits = config.getInstrument(inst).zeroPadding(0) + run = str(runNum).zfill(numDigits) + return run ########################################## # returns true if ext is in the tuple allTypes, ext # is intended to be a file extension and allTypes a # list of allowed extensions. '*' at the end is supported def _isType(ext, allTypes): - for oneType in allTypes: - oneType = str(oneType) - if oneType.endswith('*') : - oneType = oneType[0:len(oneType)-1] - if ext.startswith(oneType) : - return True - else : - if ext == oneType : - return True - return False + for oneType in allTypes: + oneType = str(oneType) + if oneType.endswith('*') : + oneType = oneType[0:len(oneType)-1] + if ext.startswith(oneType) : + return True + else : + if ext == oneType : + return True + return False def _copyLog(lastPath, logFile, pathout): - try : - logFile = os.path.join(lastPath, logFile) - if os.path.exists(logFile): - copyfile(logFile, os.path.join(pathout, os.path.basename(logFile))) - else: - logger.notice("Could not find log file %s" % logFile) - except Exception, reason: - error = 'Error copying log file ' + logFile + ' to directory ' + pathout+'\n' - print error - logger.notice(error) + try : + logFile = os.path.join(lastPath, logFile) + if os.path.exists(logFile): + copyfile(logFile, os.path.join(pathout, os.path.basename(logFile))) + else: + logger.notice("Could not find log file %s" % logFile) + except Exception, reason: + error = 'Error copying log file ' + logFile + ' to directory ' + pathout+'\n' + print error + logger.notice(error) if __name__ == '__main__': diff --git a/Code/Mantid/scripts/SANS/centre_finder.py b/Code/Mantid/scripts/SANS/centre_finder.py index caec3403e946..a3f2e4ca4658 100644 --- a/Code/Mantid/scripts/SANS/centre_finder.py +++ b/Code/Mantid/scripts/SANS/centre_finder.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import isis_reducer from isis_reduction_steps import StripEndNans from mantid.simpleapi import * @@ -98,10 +99,10 @@ def move(self, setup, x, y): """ x = -x y = -y - MoveInstrumentComponent(Workspace=setup.get_sample().wksp_name, + MoveInstrumentComponent(Workspace=setup.get_sample().wksp_name,\ ComponentName=self.detector, X=x, Y=y, RelativePosition=True) if setup.get_can(): - MoveInstrumentComponent(Workspace=setup.get_can().wksp_name, + MoveInstrumentComponent(Workspace=setup.get_can().wksp_name,\ ComponentName=self.detector, X=x, Y=y, RelativePosition=True) # Create a workspace with a quadrant value in it diff --git a/Code/Mantid/scripts/SANS/isis_instrument.py b/Code/Mantid/scripts/SANS/isis_instrument.py index 3257193467a4..1377abde7fae 100644 --- a/Code/Mantid/scripts/SANS/isis_instrument.py +++ b/Code/Mantid/scripts/SANS/isis_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import datetime import math import os @@ -87,8 +88,8 @@ def load_empty(self, workspace_name = None): return workspace_name -class DetectorBank: - class _DectShape: +class DetectorBank(object): + class _DectShape(object): """ Stores the dimensions of the detector, normally this is a square which is easy, but it can have a hole in it which is harder! @@ -127,7 +128,7 @@ def isRectangle(self): def n_pixels(self): return self._n_pixels - class _RescaleAndShift: + class _RescaleAndShift(object): """ Stores property about the detector which is used to rescale and shift data in the bank after data have been reduced. The scale attempts to @@ -162,9 +163,9 @@ def __init__(self, scale=1.0, shift=0.0, fitScale=False, fitShift=False, qMin=No def __init__(self, instr, det_type): #detectors are known by many names, the 'uni' name is an instrument independent alias the 'long' name is the instrument view name and 'short' name often used for convenience - self._names = { - 'uni' : det_type, - 'long': instr.getStringParameter(det_type+'-detector-name')[0], + self._names = {\ + 'uni' : det_type,\ + 'long': instr.getStringParameter(det_type+'-detector-name')[0],\ 'short': instr.getStringParameter(det_type+'-detector-short-name')[0]} #the bank is often also referred to by its location, as seen by the sample if det_type.startswith('low'): @@ -398,7 +399,7 @@ def crop_to_detector(self, input_name, output_name=None): try: wki = mtd[input_name] #Is it really necessary to crop? - if (wki.getNumberHistograms() != self.last_spec_num - self.get_first_spec_num() + 1): + if wki.getNumberHistograms() != self.last_spec_num - self.get_first_spec_num() + 1: CropWorkspace(InputWorkspace=input_name,OutputWorkspace= output_name, StartWorkspaceIndex = self.get_first_spec_num() - 1, EndWorkspaceIndex = self.last_spec_num - 1) @@ -698,7 +699,7 @@ def changeCalibration(self, ws_name): CopyInstrumentParameters(calib, ws_name) def setCalibrationWorkspace(self, ws_reference): - assert(isinstance(ws_reference, Workspace)) + assert isinstance(ws_reference, Workspace) # we do deep copy of singleton - to be removed in 8470 # this forces us to have 'copyable' objects. self._newCalibrationWS = str(ws_reference) @@ -822,7 +823,7 @@ def set_up_for_run(self, base_runno): first.set_first_spec_num(1) first.set_orien('Vertical') second.set_orien('Vertical') - elif (base_runno >= 568 and base_runno < 684): + elif base_runno >= 568 and base_runno < 684: first.set_first_spec_num(9) first.set_orien('Rotated') second.set_orien('Rotated') @@ -1178,6 +1179,7 @@ def cur_detector_position(self, ws_name): return [-pos.getX(), -pos.getY()] + class LARMOR(ISISInstrument): _NAME = 'LARMOR' WAV_RANGE_MIN = 2.2 @@ -1231,6 +1233,5 @@ def cur_detector_position(self, ws_name): return [-pos.getX(), -pos.getY()] - if __name__ == '__main__': pass diff --git a/Code/Mantid/scripts/SANS/isis_reducer.py b/Code/Mantid/scripts/SANS/isis_reducer.py index a5c5389ab84f..d22422c81400 100644 --- a/Code/Mantid/scripts/SANS/isis_reducer.py +++ b/Code/Mantid/scripts/SANS/isis_reducer.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ ISIS-specific implementation of the SANS Reducer. @@ -135,6 +136,31 @@ class ISISReducer(Reducer): ## Path for user settings files _user_file_path = '.' + _can = None + _tidy = None + _conv_Q = None + _reduction_steps = None + user_settings = None + _out_name = None + event2hist = None + crop_detector = None + mask = None + to_wavelen = None + norm_mon = None + transmission_calculator = None + _corr_and_scale = None + prep_normalize = None + to_Q = None + _background_subtracter = None + geometry_correcter = None + _rem_nans = None + _sample_run = None + _can_run = None + _slices_def = None + _slice_index = None + samp_trans_load = None + can_trans_load = None + def _to_steps(self): """ Defines the steps that are run and their order @@ -182,10 +208,10 @@ def _init_steps(self): # so currently do not understand why it is in isis_reduction_steps # Also the main purpose of this class is to use it as an input argument # to ConvertToQ below - self.prep_normalize = isis_reduction_steps.CalculateNormISIS( + self.prep_normalize = isis_reduction_steps.CalculateNormISIS(\ [self.norm_mon, self.transmission_calculator]) - self.to_Q = isis_reduction_steps.ConvertToQISIS( + self.to_Q = isis_reduction_steps.ConvertToQISIS(\ self.prep_normalize) self._background_subtracter = isis_reduction_steps.CanSubtraction() self.geometry_correcter = isis_reduction_steps.SampleGeomCor() @@ -313,7 +339,7 @@ def get_out_ws_name(self, show_period=True): name += '_' + self.to_Q.output_type name += '_' + self.to_wavelen.get_range() if self.to_Q.get_output_type() == "1D": - name += self.mask.get_phi_limits_tag() + name += self.mask.get_phi_limits_tag() if self.getNumSlices() > 0: limits = self.getCurrSliceLimit() @@ -421,7 +447,7 @@ def run_from_raw(self): return self._reduce(init=False, post=True) def set_Q_output_type(self, out_type): - self.to_Q.set_output_type(out_type) + self.to_Q.set_output_type(out_type) def pre_process(self): """ @@ -566,9 +592,9 @@ def set_beam_finder(self, finder, det_bank='rear'): """ if issubclass(finder.__class__, isis_reduction_steps.BaseBeamFinder) or finder is None: if det_bank == 'front': - self._front_beam_finder = finder + self._front_beam_finder = finder else: - self._beam_finder = finder + self._beam_finder = finder else: raise RuntimeError, "Reducer.set_beam_finder expects an object of class ReductionStep" @@ -599,7 +625,7 @@ def get_beam_center(self, bank = None): def getCurrSliceLimit(self): if not self._slices_def: self._slices_def = su.sliceParser("") - assert(self._slice_index == 0) + assert self._slice_index == 0 return self._slices_def[self._slice_index] def getNumSlices(self): diff --git a/Code/Mantid/scripts/SANS/isis_reduction_steps.py b/Code/Mantid/scripts/SANS/isis_reduction_steps.py index 13ec11a10297..308d8e5e8ec0 100644 --- a/Code/Mantid/scripts/SANS/isis_reduction_steps.py +++ b/Code/Mantid/scripts/SANS/isis_reduction_steps.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ This file defines what happens in each step in the data reduction, it's the guts of the reduction. See ISISReducer for order the steps are run @@ -204,7 +205,7 @@ def _loadFromWorkspace(self, reducer): If reload is True, it will try to get all the information necessary to reload this workspace from the data file. """ - assert(isinstance(self._data_file, Workspace)) + assert isinstance(self._data_file, Workspace) ws_pointer = self._data_file try: @@ -367,6 +368,9 @@ class LoadTransmissions(): sample or can """ + _direct_name = None + _trans_name = None + def __init__(self, is_can=False, reload=True): """ Two settings can be set at initialization, if this is for @@ -703,7 +707,7 @@ def parse_instruction(self, instName, details): self.time_mask = '' self.time_mask_r = '' self.time_mask_f = '' - elif (type == 'TIME' or type == 'T'): + elif type == 'TIME' or type == 'T': parts = parts[2].split() if len(parts) == 3: detname = parts[0].rstrip() @@ -717,7 +721,7 @@ def parse_instruction(self, instName, details): else: _issueWarning('Unrecognized masking line "' + details + '"') else: - _issueWarning('Unrecognized masking line "' + details + '"') + _issueWarning('Unrecognized masking line "' + details + '"') def add_mask_string(self, mask_string, detect): if detect.upper() == 'FRONT' or detect.upper() == 'HAB': @@ -847,7 +851,7 @@ def _mask_line(self, startPoint, length, width, angle): @param angle: angle of line in xy-plane in units of degrees @return: return xml shape string ''' - return self._finite_cylinder(startPoint, width/2000.0, length, + return self._finite_cylinder(startPoint, width/2000.0, length,\ [math.cos(angle*math.pi/180.0),math.sin(angle*math.pi/180.0),0.0], "arm") @@ -858,9 +862,9 @@ def get_phi_limits_tag(self): @return 'Phi'low'_'high if it has been set """ if self.mask_phi and self._lim_phi_xml != '' and (abs(self.phi_max - self.phi_min) != 180.0): - return 'Phi'+str(self.phi_min)+'_'+str(self.phi_max) + return 'Phi'+str(self.phi_min)+'_'+str(self.phi_max) else: - return '' + return '' def set_phi_limit(self, phimin, phimax, phimirror, override=True): ''' @@ -950,7 +954,7 @@ def execute(self, reducer, workspace): det = ws.getInstrument().getComponentByName('rear-detector') det_Z = det.getPos().getZ() start_point = [self.arm_x, self.arm_y, det_Z] - MaskDetectorsInShape(Workspace=workspace,ShapeXML= + MaskDetectorsInShape(Workspace=workspace,ShapeXML=\ self._mask_line(start_point, 1e6, self.arm_width, self.arm_angle)) output_ws, detector_list = ExtractMask(InputWorkspace=workspace, OutputWorkspace="__mask") @@ -1026,7 +1030,7 @@ def display(self, wksp, reducer, counts=None): Ys.append(flags.readY(i)[0]) Es.append(0) - if (vals.readY(i)[0] > maxval): + if vals.readY(i)[0] > maxval: #don't include masked or monitors if (flags.readY(i)[0] == 0) and (vals.readY(i)[0] < 5000): maxval = vals.readY(i)[0] @@ -1288,8 +1292,8 @@ def setup_wksp(self, inputWS, inst, wavbining, pre_monitor, post_monitor): #exclude unused spectra because the sometimes empty/sometimes not spectra can cause errors with interpolate spectrum1 = min(pre_monitor, post_monitor) spectrum2 = max(pre_monitor, post_monitor) - CropWorkspace(InputWorkspace=inputWS,OutputWorkspace= tmpWS, - StartWorkspaceIndex=self._get_index(spectrum1), + CropWorkspace(InputWorkspace=inputWS,OutputWorkspace= tmpWS,\ + StartWorkspaceIndex=self._get_index(spectrum1),\ EndWorkspaceIndex=self._get_index(spectrum2)) if inst.name() == 'LOQ': @@ -1300,7 +1304,7 @@ def setup_wksp(self, inputWS, inst, wavbining, pre_monitor, post_monitor): back_start, back_end = inst.get_TOFs(spectra_number) if back_start and back_end: index = spectra_number - spectrum1 - CalculateFlatBackground(InputWorkspace=tmpWS,OutputWorkspace= tmpWS, StartX=back_start, EndX=back_end, + CalculateFlatBackground(InputWorkspace=tmpWS,OutputWorkspace= tmpWS, StartX=back_start, EndX=back_end,\ WorkspaceIndexList=index, Mode='Mean') ConvertUnits(InputWorkspace=tmpWS,OutputWorkspace= tmpWS,Target="Wavelength") @@ -1399,12 +1403,12 @@ def calculate(self, reducer): wavbin +=','+str(translambda_max) #set up the input workspaces - trans_tmp_out = self.setup_wksp(trans_raw, reducer.instrument, + trans_tmp_out = self.setup_wksp(trans_raw, reducer.instrument,\ wavbin, pre_sample, post_sample) - direct_tmp_out = self.setup_wksp(direct_raw, reducer.instrument, + direct_tmp_out = self.setup_wksp(direct_raw, reducer.instrument,\ wavbin, pre_sample, post_sample) - fittedtransws, unfittedtransws = self.get_wksp_names( + fittedtransws, unfittedtransws = self.get_wksp_names(\ trans_raw, translambda_min, translambda_max, reducer) # If no fitting is required just use linear and get unfitted data from CalculateTransmission algorithm @@ -1610,7 +1614,7 @@ def calculate(self, reducer, wave_wks=[]): ConvertToHistogram(InputWorkspace=self.TMP_ISIS_NAME,OutputWorkspace= self.TMP_ISIS_NAME) ## try to redefine self._pixel_file to pass to CalculateNORM method calculate. detect_pixel_file = self.getPixelCorrFile(reducer.instrument.cur_detector().name()) - if (detect_pixel_file != ""): + if detect_pixel_file != "": self._pixel_file = detect_pixel_file for step in self._wave_steps: @@ -1695,7 +1699,7 @@ def set_gravity(self, flag, override=True): self._grav_set = True if (not self._grav_set) or override: - self._use_gravity = bool(flag) + self._use_gravity = bool(flag) else: msg = "User file can't override previous gravity setting, do gravity correction remains " + str(self._use_gravity) print msg @@ -1706,11 +1710,11 @@ def execute(self, reducer, workspace): Calculate the normalization workspaces and then call the chosen Q conversion algorithm. """ wavepixeladj = "" - if (reducer.wide_angle_correction and reducer.transmission_calculator.output_wksp): + if reducer.wide_angle_correction and reducer.transmission_calculator.output_wksp: #calculate the transmission wide angle correction _issueWarning("sans solid angle correction execution") - SANSWideAngleCorrection(SampleData=workspace, - TransmissionData = reducer.transmission_calculator.output_wksp, + SANSWideAngleCorrection(SampleData=workspace,\ + TransmissionData = reducer.transmission_calculator.output_wksp,\ OutputWorkspace='transmissionWorkspace') wavepixeladj = 'transmissionWorkspace' #create normalization workspaces @@ -1992,26 +1996,26 @@ def read_line(self, line, reducer): # SET CENTRE/HAB X Y main_str_pos = upper_line.find('MAIN') hab_str_pos = upper_line.find('HAB') - x_pos = 0.0; - y_pos = 0.0; - if (main_str_pos > 0): - values = upper_line[main_str_pos+5:].split() #remov the SET CENTRE/MAIN - x_pos = float(values[0])/1000.0 - y_pos = float(values[1])/1000.0 - elif (hab_str_pos > 0): - values = upper_line[hab_str_pos+4:].split() # remove the SET CENTRE/HAB - print ' convert values ',values - x_pos = float(values[0])/1000.0 - y_pos = float(values[1])/1000.0 + x_pos = 0.0 + y_pos = 0.0 + if main_str_pos > 0: + values = upper_line[main_str_pos+5:].split() #remov the SET CENTRE/MAIN + x_pos = float(values[0])/1000.0 + y_pos = float(values[1])/1000.0 + elif hab_str_pos > 0: + values = upper_line[hab_str_pos+4:].split() # remove the SET CENTRE/HAB + print ' convert values ',values + x_pos = float(values[0])/1000.0 + y_pos = float(values[1])/1000.0 else: - values = upper_line.split() - x_pos = float(values[2])/1000.0 - y_pos = float(values[3])/1000.0 - if (hab_str_pos > 0): - print 'Front values = ',x_pos,y_pos - reducer.set_beam_finder(BaseBeamFinder(x_pos, y_pos),'front') + values = upper_line.split() + x_pos = float(values[2])/1000.0 + y_pos = float(values[3])/1000.0 + if hab_str_pos > 0: + print 'Front values = ',x_pos,y_pos + reducer.set_beam_finder(BaseBeamFinder(x_pos, y_pos),'front') else: - reducer.set_beam_finder(BaseBeamFinder(x_pos, y_pos)) + reducer.set_beam_finder(BaseBeamFinder(x_pos, y_pos)) elif upper_line.startswith('SET SCALES'): values = upper_line.split() @@ -2077,9 +2081,9 @@ def read_line(self, line, reducer): reducer.transmission_calculator.loq_removePromptPeakMax = float(params[2]) else: if reducer.instrument.name() == 'LOQ': - _issueWarning('Incorrectly formatted FIT/MONITOR line, %s, line ignored' % upper_line) + _issueWarning('Incorrectly formatted FIT/MONITOR line, %s, line ignored' % upper_line) else: - _issueWarning('FIT/MONITOR line specific to LOQ instrument. Line ignored') + _issueWarning('FIT/MONITOR line specific to LOQ instrument. Line ignored') elif upper_line == 'SANS2D' or upper_line == 'LOQ': self._check_instrument(upper_line, reducer) @@ -2183,7 +2187,7 @@ def readLimitValues(self, limit_line, reducer): _issueWarning("General wave re-bin lines are not implemented, line ignored \"" + limit_line + "\"") return else: - reducer.to_wavelen.set_rebin( + reducer.to_wavelen.set_rebin(\ minval, step_type + step_size, maxval, override=False) elif limit_type.upper() == 'Q': if rebin_str: @@ -2532,9 +2536,9 @@ def _read_calibfile_line(self, arguments, reducer): path2file = parts[1] try: - file_path, suggested_name = getFileAndName(path2file) - __calibrationWs = Load(file_path, OutputWorkspace=suggested_name) - reducer.instrument.setCalibrationWorkspace(__calibrationWs) + file_path, suggested_name = getFileAndName(path2file) + __calibrationWs = Load(file_path, OutputWorkspace=suggested_name) + reducer.instrument.setCalibrationWorkspace(__calibrationWs) except: # If we throw a runtime here, then we cannot execute 'Load Data'. raise RuntimeError("Invalid input for tube calibration file (" + path2file + " ).\n" \ @@ -2730,7 +2734,7 @@ def set_height(self, height): # For a cylinder and sphere the height=width=radius if (not self._shape is None) and (self._shape.startswith('cylinder')): self._width = self._height - self._use_wksp_widtht = False + self._use_wksp_width = False def get_height(self): self.raise_if_zero(self._height, "height") @@ -2805,7 +2809,7 @@ def __init__(self): def calculate_volume(self, reducer): geo = reducer.get_sample().geometry - assert( issubclass(geo.__class__, GetSampleGeom)) + assert issubclass(geo.__class__, GetSampleGeom) try: if geo.shape == 'cylinder-axis-up': diff --git a/Code/Mantid/scripts/SANS/reduction_settings.py b/Code/Mantid/scripts/SANS/reduction_settings.py index 6b16926ccae1..97d4087e8776 100644 --- a/Code/Mantid/scripts/SANS/reduction_settings.py +++ b/Code/Mantid/scripts/SANS/reduction_settings.py @@ -79,7 +79,7 @@ def get_settings_object(settings_prop_man_name=REDUCTION_SETTINGS_OBJ_NAME): the ISIS SANS reduction code. Please make a single call to this function and then pass around the returned object to wherever it is needed. """ - class PropertyManagerPicklableWrapper: + class PropertyManagerPicklableWrapper(object): """ Pickling has not been enabled for PropertyManager, and this is needed in the Reducer so that the "deep copy" stuff does not complain. This diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py b/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py index 63749321d7d5..7702c2297123 100644 --- a/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py +++ b/Code/Mantid/scripts/SCD_Reduction/ReduceDictionary.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # # File: ReduceDictionary.py # @@ -14,44 +15,44 @@ # def LoadDictionary( *filenames, **kwargs ): # create a dictionary to load into - params_dictionary = kwargs.get("existing", {}) + params_dictionary = kwargs.get("existing", {}) # create a list of run numbers - run_nums = params_dictionary.get("run_nums", []) + run_nums = params_dictionary.get("run_nums", []) - file = open(filenames[0]) - for line in file: - line = line.strip(); - line = line.rstrip(); - if (not line.startswith('#')) and len(line) > 2: - words = line.split() + file = open(filenames[0]) + for line in file: + line = line.strip() + line = line.rstrip() + if (not line.startswith('#')) and len(line) > 2: + words = line.split() # error check the number of values - if len(words) < 2: - print "Syntax Error On Line: " + line + if len(words) < 2: + print "Syntax Error On Line: " + line # set the value - else: - (key, value) = words[0:2] + else: + (key, value) = words[0:2] # fix up special values - if value.lower() == "none": - value = None - elif value.lower() == "true": - value = True - elif value.lower() == "false": - value = False + if value.lower() == "none": + value = None + elif value.lower() == "true": + value = True + elif value.lower() == "false": + value = False # set the values - if key == "run_nums": - run_nums.extend(ParseRunList(value)) - else: - params_dictionary[key] = value + if key == "run_nums": + run_nums.extend(ParseRunList(value)) + else: + params_dictionary[key] = value - params_dictionary["run_nums"]=run_nums + params_dictionary["run_nums"]=run_nums # it isn't awesome without recursion - if len(filenames) > 1: - return LoadDictionary(*filenames[1:], existing=params_dictionary) - else: - return params_dictionary; + if len(filenames) > 1: + return LoadDictionary(*filenames[1:], existing=params_dictionary) + else: + return params_dictionary # # Return a list of run numbers from a string containing a comma separated @@ -59,17 +60,17 @@ def LoadDictionary( *filenames, **kwargs ): # with a colon separator. # def ParseRunList( run_string ): - run_list = [] - groups = run_string.split(",") - for group in groups: - runs = group.split(":") - if len(runs) == 1: - run_list.append( runs[0] ) - else: - first = int(runs[0]) - last = int(runs[1]) - for run in range(first, last+1): - run_list.append(str(run)) + run_list = [] + groups = run_string.split(",") + for group in groups: + runs = group.split(":") + if len(runs) == 1: + run_list.append( runs[0] ) + else: + first = int(runs[0]) + last = int(runs[1]) + for run in range(first, last+1): + run_list.append(str(run)) - return run_list + return run_list diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py index 68db7ee58d43..da992481ba3a 100644 --- a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py +++ b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_OneRun.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # File: ReduceOneSCD_Run.py # # Version 2.0, modified to work with Mantid's new python interface. @@ -53,9 +54,9 @@ # # Get the config file name and the run number to process from the command line # -if (len(sys.argv) < 3): - print "You MUST give the config file name(s) and run number on the command line" - exit(0) +if len(sys.argv) < 3: + print "You MUST give the config file name(s) and run number on the command line" + exit(0) config_files = sys.argv[1:-1] run = sys.argv[-1] @@ -125,18 +126,18 @@ # short_filename = "%s_%s_event.nxs" % (instrument_name, str(run)) if data_directory is not None: - full_name = data_directory + "/" + short_filename + full_name = data_directory + "/" + short_filename else: - candidates = FileFinder.findRuns(short_filename) - full_name = "" - for item in candidates: - if os.path.exists(item): - full_name = str(item) - - if not full_name.endswith('nxs'): - print "Exiting since the data_directory was not specified and" - print "findnexus failed for event NeXus file: " + instrument_name + " " + str(run) - exit(0) + candidates = FileFinder.findRuns(short_filename) + full_name = "" + for item in candidates: + if os.path.exists(item): + full_name = str(item) + + if not full_name.endswith('nxs'): + print "Exiting since the data_directory was not specified and" + print "findnexus failed for event NeXus file: " + instrument_name + " " + str(run) + exit(0) print "\nProcessing File: " + full_name + " ......\n" @@ -157,11 +158,11 @@ # can not be None. TOPAZ has one calibration file, but SNAP may have two. # if (calibration_file_1 is not None ) or (calibration_file_2 is not None): - if (calibration_file_1 is None ): - calibration_file_1 = "" - if (calibration_file_2 is None ): - calibration_file_2 = "" - LoadIsawDetCal( event_ws, + if calibration_file_1 is None : + calibration_file_1 = "" + if calibration_file_2 is None : + calibration_file_2 = "" + LoadIsawDetCal( event_ws,\ Filename=calibration_file_1, Filename2=calibration_file_2 ) monitor_ws = LoadNexusMonitors( Filename=full_name ) @@ -181,7 +182,7 @@ # Make MD workspace using Lorentz correction, to find peaks # MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", - dEAnalysisMode="Elastic", QConversionScales="Q in A^-1", + dEAnalysisMode="Elastic", QConversionScales="Q in A^-1",\ LorentzCorrection='1', MinValues=minVals, MaxValues=maxVals, SplitInto='2', SplitThreshold='50',MaxRecursionDepth='11' ) # @@ -196,19 +197,19 @@ # Read or find UB for the run if read_UB: # Read orientation matrix from file - LoadIsawUB(InputWorkspace=peaks_ws, Filename=UB_filename) - if optimize_UB: + LoadIsawUB(InputWorkspace=peaks_ws, Filename=UB_filename) + if optimize_UB: # Optimize the specifiec UB for better peak prediction - uc_a = peaks_ws.sample().getOrientedLattice().a() - uc_b = peaks_ws.sample().getOrientedLattice().b() - uc_c = peaks_ws.sample().getOrientedLattice().c() - uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() - uc_beta = peaks_ws.sample().getOrientedLattice().beta() - uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() - FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) + uc_a = peaks_ws.sample().getOrientedLattice().a() + uc_b = peaks_ws.sample().getOrientedLattice().b() + uc_c = peaks_ws.sample().getOrientedLattice().c() + uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() + uc_beta = peaks_ws.sample().getOrientedLattice().beta() + uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() + FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) else: # Find a Niggli UB matrix that indexes the peaks in this run - FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) + FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) IndexPeaks( PeaksWorkspace=peaks_ws, Tolerance=tolerance) @@ -227,27 +228,27 @@ # PeakIntegration algorithm. # if integrate_predicted_peaks: - print "PREDICTING peaks to integrate...." - peaks_ws = PredictPeaks( InputWorkspace=peaks_ws, - WavelengthMin=min_pred_wl, WavelengthMax=max_pred_wl, - MinDSpacing=min_pred_dspacing, MaxDSpacing=max_pred_dspacing, + print "PREDICTING peaks to integrate...." + peaks_ws = PredictPeaks( InputWorkspace=peaks_ws,\ + WavelengthMin=min_pred_wl, WavelengthMax=max_pred_wl,\ + MinDSpacing=min_pred_dspacing, MaxDSpacing=max_pred_dspacing,\ ReflectionCondition='Primitive' ) else: - print "Only integrating FOUND peaks ...." + print "Only integrating FOUND peaks ...." # # Set the monitor counts for all the peaks that will be integrated # num_peaks = peaks_ws.getNumberPeaks() for i in range(num_peaks): - peak = peaks_ws.getPeak(i) - if use_monitor_counts: - peak.setMonitorCount( monitor_count ) - else: - peak.setMonitorCount( proton_charge ) + peak = peaks_ws.getPeak(i) + if use_monitor_counts: + peak.setMonitorCount( monitor_count ) + else: + peak.setMonitorCount( proton_charge ) if use_monitor_counts: - print '\n*** Beam monitor counts used for scaling.' + print '\n*** Beam monitor counts used for scaling.' else: - print '\n*** Proton charge x 1000 used for scaling.\n' + print '\n*** Proton charge x 1000 used for scaling.\n' if use_sphere_integration: # @@ -256,16 +257,16 @@ # workspace to do raw integration (we don't need high resolution or # LorentzCorrection to do the raw sphere integration ) # - MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", - dEAnalysisMode="Elastic", QConversionScales="Q in A^-1", - LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals, + MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D",\ + dEAnalysisMode="Elastic", QConversionScales="Q in A^-1",\ + LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals,\ SplitInto='2', SplitThreshold='500',MaxRecursionDepth='10' ) - peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius, - CoordinatesToUse="Q (sample frame)", - BackgroundOuterRadius=bkg_outer_radius, - BackgroundInnerRadius=bkg_inner_radius, - PeaksWorkspace=peaks_ws, + peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius,\ + CoordinatesToUse="Q (sample frame)",\ + BackgroundOuterRadius=bkg_outer_radius,\ + BackgroundInnerRadius=bkg_inner_radius,\ + PeaksWorkspace=peaks_ws,\ IntegrateIfOnEdge=integrate_if_edge_peak ) elif use_cylindrical_integration: # @@ -274,51 +275,51 @@ # workspace to do raw integration (we don't need high resolution or # LorentzCorrection to do the raw sphere integration ) # - MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", - dEAnalysisMode="Elastic", QConversionScales="Q in A^-1", - LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals, + MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D",\ + dEAnalysisMode="Elastic", QConversionScales="Q in A^-1",\ + LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals,\ SplitInto='2', SplitThreshold='500',MaxRecursionDepth='10' ) - peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius, - CoordinatesToUse="Q (sample frame)", - BackgroundOuterRadius=bkg_outer_radius, - BackgroundInnerRadius=bkg_inner_radius, - PeaksWorkspace=peaks_ws, - IntegrateIfOnEdge=integrate_if_edge_peak, - Cylinder=use_cylindrical_integration,CylinderLength=cylinder_length, - PercentBackground=cylinder_percent_bkg, - IntegrationOption=cylinder_int_option, + peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=peak_radius,\ + CoordinatesToUse="Q (sample frame)",\ + BackgroundOuterRadius=bkg_outer_radius,\ + BackgroundInnerRadius=bkg_inner_radius,\ + PeaksWorkspace=peaks_ws,\ + IntegrateIfOnEdge=integrate_if_edge_peak,\ + Cylinder=use_cylindrical_integration,CylinderLength=cylinder_length,\ + PercentBackground=cylinder_percent_bkg,\ + IntegrationOption=cylinder_int_option,\ ProfileFunction=cylinder_profile_fit) elif use_fit_peaks_integration: - event_ws = Rebin( InputWorkspace=event_ws, + event_ws = Rebin( InputWorkspace=event_ws,\ Params=rebin_params, PreserveEvents=preserve_events ) - peaks_ws = PeakIntegration( InPeaksWorkspace=peaks_ws, InputWorkspace=event_ws, - IkedaCarpenterTOF=use_ikeda_carpenter, - MatchingRunNo=True, + peaks_ws = PeakIntegration( InPeaksWorkspace=peaks_ws, InputWorkspace=event_ws,\ + IkedaCarpenterTOF=use_ikeda_carpenter,\ + MatchingRunNo=True,\ NBadEdgePixels=n_bad_edge_pixels ) elif use_ellipse_integration: - peaks_ws= IntegrateEllipsoids( InputWorkspace=event_ws, PeaksWorkspace = peaks_ws, - RegionRadius = ellipse_region_radius, - SpecifySize = ellipse_size_specified, - PeakSize = peak_radius, - BackgroundOuterSize = bkg_outer_radius, + peaks_ws= IntegrateEllipsoids( InputWorkspace=event_ws, PeaksWorkspace = peaks_ws,\ + RegionRadius = ellipse_region_radius,\ + SpecifySize = ellipse_size_specified,\ + PeakSize = peak_radius,\ + BackgroundOuterSize = bkg_outer_radius,\ BackgroundInnerSize = bkg_inner_radius ) elif use_cylindrical_integration: - profiles_filename = output_directory + "/" + instrument_name + '_' + run + '.profiles' - MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D", - dEAnalysisMode="Elastic", QConversionScales="Q in A^-1", - LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals, + profiles_filename = output_directory + "/" + instrument_name + '_' + run + '.profiles' + MDEW = ConvertToMD( InputWorkspace=event_ws, QDimensions="Q3D",\ + dEAnalysisMode="Elastic", QConversionScales="Q in A^-1",\ + LorentzCorrection='0', MinValues=minVals, MaxValues=maxVals,\ SplitInto='2', SplitThreshold='500',MaxRecursionDepth='10' ) - peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=cylinder_radius, - CoordinatesToUse="Q (sample frame)", - Cylinder='1', CylinderLength = cylinder_length, - PercentBackground = '20', ProfileFunction = 'NoFit', - ProfilesFile = profiles_filename, - PeaksWorkspace=peaks_ws, + peaks_ws = IntegratePeaksMD( InputWorkspace=MDEW, PeakRadius=cylinder_radius,\ + CoordinatesToUse="Q (sample frame)",\ + Cylinder='1', CylinderLength = cylinder_length,\ + PercentBackground = '20', ProfileFunction = 'NoFit',\ + ProfilesFile = profiles_filename,\ + PeaksWorkspace=peaks_ws,\ ) # @@ -331,25 +332,25 @@ # Print warning if user is trying to integrate using the cylindrical method and transorm the cell if use_cylindrical_integration: - if (not cell_type is None) or (not centering is None): - print "WARNING: Cylindrical profiles are NOT transformed!!!" + if (not cell_type is None) or (not centering is None): + print "WARNING: Cylindrical profiles are NOT transformed!!!" # # If requested, also switch to the specified conventional cell and save the # corresponding matrix and integrate file # else: - if (not cell_type is None) and (not centering is None) : - run_conventional_matrix_file = output_directory + "/" + run + "_" + \ + if (not cell_type is None) and (not centering is None) : + run_conventional_matrix_file = output_directory + "/" + run + "_" + \ cell_type + "_" + centering + ".mat" - run_conventional_integrate_file = output_directory + "/" + run + "_" + \ + run_conventional_integrate_file = output_directory + "/" + run + "_" + \ cell_type + "_" + centering + ".integrate" - SelectCellOfType( PeaksWorkspace=peaks_ws, - CellType=cell_type, Centering=centering, - AllowPermutations=allow_perm, + SelectCellOfType( PeaksWorkspace=peaks_ws,\ + CellType=cell_type, Centering=centering,\ + AllowPermutations=allow_perm,\ Apply=True, Tolerance=tolerance ) - SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, + SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False,\ Filename=run_conventional_integrate_file ) - SaveIsawUB( InputWorkspace=peaks_ws, Filename=run_conventional_matrix_file ) + SaveIsawUB( InputWorkspace=peaks_ws, Filename=run_conventional_matrix_file ) end_time = time.time() print '\nReduced run ' + str(run) + ' in ' + str(end_time - start_time) + ' sec' diff --git a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py index 94f90ff2aede..16a978089c34 100644 --- a/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py +++ b/Code/Mantid/scripts/SCD_Reduction/ReduceSCD_Parallel.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # File: ReduceSCD_Parallel.py # @@ -54,23 +55,23 @@ # a thread that starts a command line process to reduce one run. # class ProcessThread ( threading.Thread ): - command = "" + command = "" - def setCommand( self, command="" ): - self.command = command + def setCommand( self, command="" ): + self.command = command - def run ( self ): - print 'STARTING PROCESS: ' + self.command - os.system( self.command ) + def run ( self ): + print 'STARTING PROCESS: ' + self.command + os.system( self.command ) # ------------------------------------------------------------------------- # # Get the config file name from the command line # -if (len(sys.argv) < 2): - print "You MUST give the config file name on the command line" - exit(0) +if len(sys.argv) < 2: + print "You MUST give the config file name on the command line" + exit(0) config_files = sys.argv[1:] @@ -105,7 +106,7 @@ def run ( self ): # determine what python executable to launch new jobs with python = sys.executable if python is None: # not all platforms define this variable - python = 'python' + python = 'python' # # Make the list of separate process commands. If a slurm queue name @@ -115,14 +116,14 @@ def run ( self ): list=[] index = 0 for r_num in run_nums: - list.append( ProcessThread() ) - cmd = '%s %s %s %s' % (python, reduce_one_run_script, " ".join(config_files), str(r_num)) - if slurm_queue_name is not None: - console_file = output_directory + "/" + str(r_num) + "_output.txt" - cmd = 'srun -p ' + slurm_queue_name + \ + list.append( ProcessThread() ) + cmd = '%s %s %s %s' % (python, reduce_one_run_script, " ".join(config_files), str(r_num)) + if slurm_queue_name is not None: + console_file = output_directory + "/" + str(r_num) + "_output.txt" + cmd = 'srun -p ' + slurm_queue_name + \ ' --cpus-per-task=3 -J ReduceSCD_Parallel.py -o ' + console_file + ' ' + cmd - list[index].setCommand( cmd ) - index = index + 1 + list[index].setCommand( cmd ) + index = index + 1 # # Now create and start a thread for each command to run the commands in parallel, @@ -131,17 +132,17 @@ def run ( self ): all_done = False active_list=[] while not all_done: - if ( len(list) > 0 and len(active_list) < max_processes ): - thread = list[0] - list.remove(thread) - active_list.append( thread ) - thread.start() - time.sleep(2) - for thread in active_list: - if not thread.isAlive(): - active_list.remove( thread ) - if len(list) == 0 and len(active_list) == 0 : - all_done = True + if len(list) > 0 and len(active_list) < max_processes : + thread = list[0] + list.remove(thread) + active_list.append( thread ) + thread.start() + time.sleep(2) + for thread in active_list: + if not thread.isAlive(): + active_list.remove( thread ) + if len(list) == 0 and len(active_list) == 0 : + all_done = True print "\n**************************************************************************************" print "************** Completed Individual Runs, Starting to Combine Results ****************" @@ -157,104 +158,104 @@ def run ( self ): first_time = True if not use_cylindrical_integration: - for r_num in run_nums: - one_run_file = output_directory + '/' + str(r_num) + '_Niggli.integrate' - peaks_ws = LoadIsawPeaks( Filename=one_run_file ) - if first_time: - if UseFirstLattice and not read_UB: + for r_num in run_nums: + one_run_file = output_directory + '/' + str(r_num) + '_Niggli.integrate' + peaks_ws = LoadIsawPeaks( Filename=one_run_file ) + if first_time: + if UseFirstLattice and not read_UB: # Find a UB (using FFT) for the first run to use in the FindUBUsingLatticeParameters - FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) - uc_a = peaks_ws.sample().getOrientedLattice().a() - uc_b = peaks_ws.sample().getOrientedLattice().b() - uc_c = peaks_ws.sample().getOrientedLattice().c() - uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() - uc_beta = peaks_ws.sample().getOrientedLattice().beta() - uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() - SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=niggli_integrate_file ) - - first_time = False - else: - SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=True, Filename=niggli_integrate_file ) + FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) + uc_a = peaks_ws.sample().getOrientedLattice().a() + uc_b = peaks_ws.sample().getOrientedLattice().b() + uc_c = peaks_ws.sample().getOrientedLattice().c() + uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() + uc_beta = peaks_ws.sample().getOrientedLattice().beta() + uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() + SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=niggli_integrate_file ) + + first_time = False + else: + SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=True, Filename=niggli_integrate_file ) # # Load the combined file and re-index all of the peaks together. # Save them back to the combined Niggli file (Or selcted UB file if in use...) # - peaks_ws = LoadIsawPeaks( Filename=niggli_integrate_file ) + peaks_ws = LoadIsawPeaks( Filename=niggli_integrate_file ) # # Find a Niggli UB matrix that indexes the peaks in this run # Load UB instead of Using FFT #Index peaks using UB from UB of initial orientation run/or combined runs from first iteration of crystal orientation refinement - if read_UB: - LoadIsawUB(InputWorkspace=peaks_ws, Filename=UB_filename) - if UseFirstLattice: + if read_UB: + LoadIsawUB(InputWorkspace=peaks_ws, Filename=UB_filename) + if UseFirstLattice: # Find UB using lattice parameters from the specified file - uc_a = peaks_ws.sample().getOrientedLattice().a() - uc_b = peaks_ws.sample().getOrientedLattice().b() - uc_c = peaks_ws.sample().getOrientedLattice().c() - uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() - uc_beta = peaks_ws.sample().getOrientedLattice().beta() - uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() - FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) + uc_a = peaks_ws.sample().getOrientedLattice().a() + uc_b = peaks_ws.sample().getOrientedLattice().b() + uc_c = peaks_ws.sample().getOrientedLattice().c() + uc_alpha = peaks_ws.sample().getOrientedLattice().alpha() + uc_beta = peaks_ws.sample().getOrientedLattice().beta() + uc_gamma = peaks_ws.sample().getOrientedLattice().gamma() + FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) #OptimizeCrystalPlacement(PeaksWorkspace=peaks_ws,ModifiedPeaksWorkspace=peaks_ws,FitInfoTable='CrystalPlacement_info',MaxIndexingError=tolerance) - elif UseFirstLattice and not read_UB: + elif UseFirstLattice and not read_UB: # Find UB using lattice parameters using the FFT results from first run if no UB file is specified - FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) - else: - FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) + FindUBUsingLatticeParameters(PeaksWorkspace= peaks_ws,a=uc_a,b=uc_b,c=uc_c,alpha=uc_alpha,beta=uc_beta, gamma=uc_gamma,NumInitial=num_peaks_to_find,Tolerance=tolerance) + else: + FindUBUsingFFT( PeaksWorkspace=peaks_ws, MinD=min_d, MaxD=max_d, Tolerance=tolerance ) - IndexPeaks( PeaksWorkspace=peaks_ws, Tolerance=tolerance ) - SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=niggli_integrate_file ) - SaveIsawUB( InputWorkspace=peaks_ws, Filename=niggli_matrix_file ) + IndexPeaks( PeaksWorkspace=peaks_ws, Tolerance=tolerance ) + SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=niggli_integrate_file ) + SaveIsawUB( InputWorkspace=peaks_ws, Filename=niggli_matrix_file ) # # If requested, also switch to the specified conventional cell and save the # corresponding matrix and integrate file # if not use_cylindrical_integration: - if (not cell_type is None) and (not centering is None) : - conv_name = output_directory + "/" + exp_name + "_" + cell_type + "_" + centering - conventional_integrate_file = conv_name + ".integrate" - conventional_matrix_file = conv_name + ".mat" + if (not cell_type is None) and (not centering is None) : + conv_name = output_directory + "/" + exp_name + "_" + cell_type + "_" + centering + conventional_integrate_file = conv_name + ".integrate" + conventional_matrix_file = conv_name + ".mat" - SelectCellOfType( PeaksWorkspace=peaks_ws, CellType=cell_type, Centering=centering, + SelectCellOfType( PeaksWorkspace=peaks_ws, CellType=cell_type, Centering=centering,\ AllowPermutations=allow_perm, Apply=True, Tolerance=tolerance ) - SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=conventional_integrate_file ) - SaveIsawUB( InputWorkspace=peaks_ws, Filename=conventional_matrix_file ) + SaveIsawPeaks( InputWorkspace=peaks_ws, AppendFile=False, Filename=conventional_integrate_file ) + SaveIsawUB( InputWorkspace=peaks_ws, Filename=conventional_matrix_file ) if use_cylindrical_integration: - if (not cell_type is None) or (not centering is None): - print "WARNING: Cylindrical profiles are NOT transformed!!!" + if (not cell_type is None) or (not centering is None): + print "WARNING: Cylindrical profiles are NOT transformed!!!" # Combine *.profiles files - filename = output_directory + '/' + exp_name + '.profiles' - output = open( filename, 'w' ) + filename = output_directory + '/' + exp_name + '.profiles' + output = open( filename, 'w' ) # Read and write the first run profile file with header. - r_num = run_nums[0] - filename = output_directory + '/' + instrument_name + '_' + r_num + '.profiles' - input = open( filename, 'r' ) - file_all_lines = input.read() - output.write(file_all_lines) - input.close() - os.remove(filename) + r_num = run_nums[0] + filename = output_directory + '/' + instrument_name + '_' + r_num + '.profiles' + input = open( filename, 'r' ) + file_all_lines = input.read() + output.write(file_all_lines) + input.close() + os.remove(filename) # Read and write the rest of the runs without the header. - for r_num in run_nums[1:]: - filename = output_directory + '/' + instrument_name + '_' + r_num + '.profiles' - input = open(filename, 'r') - for line in input: - if line[0] == '0': break - output.write(line) - for line in input: - output.write(line) - input.close() - os.remove(filename) + for r_num in run_nums[1:]: + filename = output_directory + '/' + instrument_name + '_' + r_num + '.profiles' + input = open(filename, 'r') + for line in input: + if line[0] == '0': break + output.write(line) + for line in input: + output.write(line) + input.close() + os.remove(filename) # Remove *.integrate file(s) ONLY USED FOR CYLINDRICAL INTEGRATION! - for file in os.listdir(output_directory): - if file.endswith('.integrate'): - os.remove(file) + for file in os.listdir(output_directory): + if file.endswith('.integrate'): + os.remove(file) end_time = time.time() diff --git a/Code/Mantid/scripts/TofConverter.py b/Code/Mantid/scripts/TofConverter.py index 8c395cb911a9..51002010f8e1 100644 --- a/Code/Mantid/scripts/TofConverter.py +++ b/Code/Mantid/scripts/TofConverter.py @@ -1,15 +1,16 @@ +#pylint: disable=invalid-name from TofConverter import converterGUI from PyQt4 import QtGui import sys def qapp(): if QtGui.QApplication.instance(): - app = QtGui.QApplication.instance() + _app = QtGui.QApplication.instance() else: - app = QtGui.QApplication(sys.argv) - return app + _app = QtGui.QApplication(sys.argv) + return _app app = qapp() reducer = converterGUI.MainWindow()#the main ui class in this file is called MainWindow reducer.show() -app.exec_() \ No newline at end of file +app.exec_() diff --git a/Code/Mantid/scripts/TofConverter/Ui_MainWindow.py b/Code/Mantid/scripts/TofConverter/Ui_MainWindow.py index 44bc763c0eff..4b89ca9c0aa9 100644 --- a/Code/Mantid/scripts/TofConverter/Ui_MainWindow.py +++ b/Code/Mantid/scripts/TofConverter/Ui_MainWindow.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'CONVERTER.ui' diff --git a/Code/Mantid/scripts/TofConverter/converterGUI.py b/Code/Mantid/scripts/TofConverter/converterGUI.py index ae01ad13ad93..51b6bcd9f31b 100644 --- a/Code/Mantid/scripts/TofConverter/converterGUI.py +++ b/Code/Mantid/scripts/TofConverter/converterGUI.py @@ -1,4 +1,5 @@ -from Ui_MainWindow import Ui_MainWindow #import line for the UI python class +#pylint: disable=invalid-name +from TofConverter.Ui_MainWindow import Ui_MainWindow #import line for the UI python class from PyQt4 import QtCore, QtGui import math diff --git a/Code/Mantid/scripts/Vates/Diffraction_Workflow.py b/Code/Mantid/scripts/Vates/Diffraction_Workflow.py index 42c36224f254..b751920f698b 100644 --- a/Code/Mantid/scripts/Vates/Diffraction_Workflow.py +++ b/Code/Mantid/scripts/Vates/Diffraction_Workflow.py @@ -1,42 +1,43 @@ +#pylint: disable=invalid-name # Basic parameters for Triphylite Crystal #Name of the workspaces to create ws_name = "TOPAZ_3132" filename = ws_name +"_event.nxs" ws = LoadEventNexus(Filename=filename,FilterByTofMin=3000, FilterByTofMax=16000) -# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +# ------------------------------------------------------------------------------------------------------------------------------------------ # Part 1. Basic Reduction # Spherical Absorption and Lorentz Corrections ws = AnvredCorrection(InputWorkspace=ws, LinearScatteringCoef=0.451, LinearAbsorptionCoef=0.993, Radius=0.14) # Convert to Q space -LabQ = ConvertToDiffractionMDWorkspace(InputWorkspace=ws, LorentzCorrection='0', +LabQ = ConvertToDiffractionMDWorkspace(InputWorkspace=ws, LorentzCorrection='0',\ OutputDimensions='Q (lab frame)', SplitInto=2, SplitThreshold=150) # Find peaks PeaksLattice = FindPeaksMD(InputWorkspace=LabQ,MaxPeaks=100) # 3d integration to centroid peaks -PeaksLattice = CentroidPeaksMD(InputWorkspace=LabQ, +PeaksLattice = CentroidPeaksMD(InputWorkspace=LabQ,\ PeakRadius=0.12, PeaksWorkspace=PeaksLattice) # Find the UB matrix using the peaks and known lattice parameters -FindUBUsingLatticeParameters(PeaksWorkspace=PeaksLattice, a=10.3522, b=6.0768, c=4.7276, +FindUBUsingLatticeParameters(PeaksWorkspace=PeaksLattice, a=10.3522, b=6.0768, c=4.7276,\ alpha=90, beta=90, gamma=90, NumInitial=20, Tolerance=0.12) # And index to HKL IndexPeaks(PeaksWorkspace=PeaksLattice, Tolerance=0.12) # Integrate peaks in Q space using spheres -PeaksLattice_Integrated = IntegratePeaksMD(InputWorkspace=LabQ,PeakRadius=0.12, - BackgroundOuterRadius=0.18,BackgroundInnerRadius=0.15, +PeaksLattice_Integrated = IntegratePeaksMD(InputWorkspace=LabQ,PeakRadius=0.12,\ + BackgroundOuterRadius=0.18,BackgroundInnerRadius=0.15,\ PeaksWorkspace=PeaksLattice) # Save for SHELX SaveHKL(InputWorkspace=PeaksLattice, Filename=ws_name + '.hkl') -# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +# ------------------------------------------------------------------------------------------------------------------------------------------ # Part 2. Alternative/Advanced Processing Steps @@ -44,7 +45,7 @@ PeaksLatticeFFT = FindPeaksMD(InputWorkspace=LabQ, MaxPeaks=100) # 3d integration to centroid peaks -PeaksLatticeFFT = CentroidPeaksMD(InputWorkspace=LabQ, +PeaksLatticeFFT = CentroidPeaksMD(InputWorkspace=LabQ,\ PeakRadius=0.12, PeaksWorkspace=PeaksLatticeFFT) # Find the UB matrix using FFT @@ -54,25 +55,25 @@ IndexPeaks(PeaksWorkspace=PeaksLatticeFFT, Tolerance=0.12) # Integrate peaks in Q space using spheres -PeaksLatticeFFT = IntegratePeaksMD(InputWorkspace=LabQ, PeakRadius=0.12, - BackgroundOuterRadius=0.18,BackgroundInnerRadius=0.15, +PeaksLatticeFFT = IntegratePeaksMD(InputWorkspace=LabQ, PeakRadius=0.12,\ + BackgroundOuterRadius=0.18,BackgroundInnerRadius=0.15,\ PeaksWorkspace=PeaksLatticeFFT) # Save for SHELX SaveHKL(InputWorkspace=PeaksLatticeFFT, Filename=ws_name + '.hkl') -# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +# ------------------------------------------------------------------------------------------------------------------------------------------ # Part 3. Utilising the UB # Copy the UB matrix back to the original workspace -CopySample(InputWorkspace=PeaksLattice, OutputWorkspace=ws, +CopySample(InputWorkspace=PeaksLattice, OutputWorkspace=ws,\ CopyName='0',CopyMaterial='0',CopyEnvironment='0',CopyShape='0', CopyLattice=1) # Convert to reciprocal space, in the sample frame -HKL = ConvertToDiffractionMDWorkspace(InputWorkspace=ws, +HKL = ConvertToDiffractionMDWorkspace(InputWorkspace=ws,\ OutputDimensions='HKL',LorentzCorrection='0', SplitInto='2',SplitThreshold='150') -# ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- +# ------------------------------------------------------------------------------------------------------------------------------------------ # Part 4. Displaying # Bin to a regular grid diff --git a/Code/Mantid/scripts/Vates/Inelastic_Workflow.py b/Code/Mantid/scripts/Vates/Inelastic_Workflow.py index 618a36358ae6..ecdb520d355a 100644 --- a/Code/Mantid/scripts/Vates/Inelastic_Workflow.py +++ b/Code/Mantid/scripts/Vates/Inelastic_Workflow.py @@ -1,23 +1,24 @@ +#pylint: disable=invalid-name #Common names filename = 'fe_demo_30.sqw' ws_in ='fe_demo_30' #Load an SQW file and internally convert to a Multidimensional event workspace (MDEW) if not mtd.doesExist(ws_in): - LoadSQW(filename, OutputWorkspace=ws_in) + LoadSQW(filename, OutputWorkspace=ws_in) #Bin the workspace in an axis aligned manner. Creates a Histogrammed MD workspace. -BinMD(InputWorkspace=ws_in,OutputWorkspace='binned_axis_aligned',AxisAligned=True, -AlignedDim0='Q_\\zeta,-1.5,5,100', -AlignedDim1='Q_\\xi,-6,6,100', -AlignedDim2='Q_\\eta,-6,6,100', +BinMD(InputWorkspace=ws_in,OutputWorkspace='binned_axis_aligned',AxisAligned=True,\ +AlignedDim0='Q_\\zeta,-1.5,5,100',\ +AlignedDim1='Q_\\xi,-6,6,100',\ +AlignedDim2='Q_\\eta,-6,6,100',\ AlignedDim3='E,0,150,30') #Bin the workpace using a coordinate transformation to rotate the output.. Creates a Histogrammed MD workspace. -BinMD(InputWorkspace=ws_in,OutputWorkspace='binned_rotated',AxisAligned=False, -BasisVector0='Qx,Ang,1,0.5,0,0,1,100', -BasisVector1='Qy,Ang,-0.5,1,0,0,1,100', -BasisVector2='Qz,Ang,0,0,1.25,0,1,100', +BinMD(InputWorkspace=ws_in,OutputWorkspace='binned_rotated',AxisAligned=False,\ +BasisVector0='Qx,Ang,1,0.5,0,0,1,100',\ +BasisVector1='Qy,Ang,-0.5,1,0,0,1,100',\ +BasisVector2='Qz,Ang,0,0,1.25,0,1,100',\ Origin='0,0,0,0') #Save the MDEW workspace in the MDEW nexus format. diff --git a/Code/Mantid/scripts/Vates/SXD_NaCl.py b/Code/Mantid/scripts/Vates/SXD_NaCl.py index fe550dfa0d75..409c422541ef 100644 --- a/Code/Mantid/scripts/Vates/SXD_NaCl.py +++ b/Code/Mantid/scripts/Vates/SXD_NaCl.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name def reportUnitCell(peaks_ws): latt = peaks_ws.sample().getOrientedLattice() print "-- Unit Cell --" @@ -39,24 +40,24 @@ def reportUnitCell(peaks_ws): # find the Niggli cell correctly, with all angle 60 degrees, and all sides 3.99 # if use_fft: - FindUBUsingFFT(PeaksWorkspace=peaks_qLab, MinD='3', MaxD='5',Tolerance=0.08) - print '\nNiggli cell found from FindUBUsingFFT:' + FindUBUsingFFT(PeaksWorkspace=peaks_qLab, MinD='3', MaxD='5',Tolerance=0.08) + print '\nNiggli cell found from FindUBUsingFFT:' if use_cubic_lat_par: - FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=5.6402,b=5.6402,c=5.6402,alpha=90,beta=90,gamma=90,NumInitial=25,Tolerance=0.12) - print '\nCubic cell found directly from FindUBUsingLatticeParameters' + FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=5.6402,b=5.6402,c=5.6402,alpha=90,beta=90,gamma=90,NumInitial=25,Tolerance=0.12) + print '\nCubic cell found directly from FindUBUsingLatticeParameters' if use_Niggli_lat_par: - FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=3.9882,b=3.9882,c=3.9882,alpha=60,beta=60,gamma=60,NumInitial=25,Tolerance=0.12) - print '\nNiggli cell found from FindUBUsingLatticeParameters:' + FindUBUsingLatticeParameters(PeaksWorkspace=peaks_qLab, a=3.9882,b=3.9882,c=3.9882,alpha=60,beta=60,gamma=60,NumInitial=25,Tolerance=0.12) + print '\nNiggli cell found from FindUBUsingLatticeParameters:' reportUnitCell(peaks_qLab) IndexPeaks(PeaksWorkspace=peaks_qLab,Tolerance=0.12,RoundHKLs=1) if use_fft or use_Niggli_lat_par: - ShowPossibleCells(PeaksWorkspace=peaks_qLab,MaxScalarError='0.5') - SelectCellOfType(PeaksWorkspace=peaks_qLab, CellType='Cubic', Centering='F', Apply=True) + ShowPossibleCells(PeaksWorkspace=peaks_qLab,MaxScalarError='0.5') + SelectCellOfType(PeaksWorkspace=peaks_qLab, CellType='Cubic', Centering='F', Apply=True) peaks_qLab_Integrated = IntegratePeaksMD(InputWorkspace=QLab, PeaksWorkspace=peaks_qLab, PeakRadius=0.2, BackgroundInnerRadius=0.3, BackgroundOuterRadius=0.4) diff --git a/Code/Mantid/scripts/migrate1to2.py b/Code/Mantid/scripts/migrate1to2.py index a0b7f81909ff..c710b7253946 100644 --- a/Code/Mantid/scripts/migrate1to2.py +++ b/Code/Mantid/scripts/migrate1to2.py @@ -6,4 +6,4 @@ import sys -sys.exit(main.main(sys.argv[1:])) \ No newline at end of file +sys.exit(main.main(sys.argv[1:])) diff --git a/Code/Mantid/scripts/reducer_singleton.py b/Code/Mantid/scripts/reducer_singleton.py index 4e0e18910a4e..5b2a860adff4 100644 --- a/Code/Mantid/scripts/reducer_singleton.py +++ b/Code/Mantid/scripts/reducer_singleton.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import random import string import os @@ -34,7 +35,7 @@ def execute(self, reducer, inputworkspace=None, outputworkspace=None): @param inputworkspace: Name of the workspace to apply this step to @param outputworkspace: Name of the workspace to have as an output. If this is None it will be set to inputworkspace """ - raise NotImplemented + raise NotImplementedError class Reducer(object): """ @@ -158,7 +159,7 @@ def reduce(self): -class ReductionSingleton: +class ReductionSingleton(object): """ Singleton reduction class """ ## storage for the instance reference diff --git a/Code/Mantid/scripts/reduction/__init__.py b/Code/Mantid/scripts/reduction/__init__.py index 1b13dcf29211..7093c3f8f1e8 100644 --- a/Code/Mantid/scripts/reduction/__init__.py +++ b/Code/Mantid/scripts/reduction/__init__.py @@ -1,3 +1,3 @@ -from reducer import * -from instrument import * -from find_data import find_data, find_file +from reduction.reducer import * +from reduction.instrument import * +from reduction.find_data import find_data, find_file diff --git a/Code/Mantid/scripts/reduction/command_interface.py b/Code/Mantid/scripts/reduction/command_interface.py index 7b6f2150cf5c..ad07259ac804 100644 --- a/Code/Mantid/scripts/reduction/command_interface.py +++ b/Code/Mantid/scripts/reduction/command_interface.py @@ -1,10 +1,11 @@ +#pylint: disable=invalid-name """ List of user commands. """ -from reducer import Reducer +from reduction.reducer import Reducer -class ReductionSingleton: +class ReductionSingleton(object): """ Singleton reduction class """ ## storage for the instance reference diff --git a/Code/Mantid/scripts/reduction/find_data.py b/Code/Mantid/scripts/reduction/find_data.py index 9e3a01832851..b8c98059fe35 100644 --- a/Code/Mantid/scripts/reduction/find_data.py +++ b/Code/Mantid/scripts/reduction/find_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import os import mantid.api as api from mantid.simpleapi import * diff --git a/Code/Mantid/scripts/reduction/instrument.py b/Code/Mantid/scripts/reduction/instrument.py index 28aeb890e6a3..3fb42264f30e 100644 --- a/Code/Mantid/scripts/reduction/instrument.py +++ b/Code/Mantid/scripts/reduction/instrument.py @@ -40,9 +40,9 @@ def load_instrument(self): """ wrksp = '__'+self._NAME+'instrument_definition' if not AnalysisDataService.doesExist(wrksp): - api.CreateWorkspace(OutputWorkspace=wrksp,DataX="1",DataY="1",DataE="1") + api.CreateWorkspace(OutputWorkspace=wrksp,DataX="1",DataY="1",DataE="1") #read the information about the instrument that stored in its xml - api.LoadInstrument(Workspace=wrksp, InstrumentName=self._NAME) + api.LoadInstrument(Workspace=wrksp, InstrumentName=self._NAME) return AnalysisDataService.retrieve(wrksp).getInstrument() diff --git a/Code/Mantid/scripts/reduction/instruments/example/ExampleRedStep.py b/Code/Mantid/scripts/reduction/instruments/example/ExampleRedStep.py index 78a7973d0534..29ce2d2ac9fc 100644 --- a/Code/Mantid/scripts/reduction/instruments/example/ExampleRedStep.py +++ b/Code/Mantid/scripts/reduction/instruments/example/ExampleRedStep.py @@ -1,3 +1,4 @@ +#pylint: disable=no-init from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * diff --git a/Code/Mantid/scripts/reduction/instruments/example/example_reducer.py b/Code/Mantid/scripts/reduction/instruments/example/example_reducer.py index 3f4a197f88fd..8d8f5be12b32 100644 --- a/Code/Mantid/scripts/reduction/instruments/example/example_reducer.py +++ b/Code/Mantid/scripts/reduction/instruments/example/example_reducer.py @@ -1,9 +1,9 @@ +#pylint: disable=invalid-name """ Simple Reducer example """ from reduction import Reducer from reduction.instruments.example.ExampleRedStep import ExampleRedStep -from reduction.instruments.example.ExampleRedStep import ExampleLoader # Validate_step is a decorator that allows both Python algorithms and ReductionStep objects to be passed to the Reducer. # It also does minimal type checking to ensure that the object that is passed is valid from reduction import validate_step, validate_loader diff --git a/Code/Mantid/scripts/reduction/instruments/inelastic/direct_command_interface.py b/Code/Mantid/scripts/reduction/instruments/inelastic/direct_command_interface.py index 23cd9fd62229..4f74c10fd217 100644 --- a/Code/Mantid/scripts/reduction/instruments/inelastic/direct_command_interface.py +++ b/Code/Mantid/scripts/reduction/instruments/inelastic/direct_command_interface.py @@ -1,8 +1,8 @@ +#pylint: disable=invalid-name """ Command set for Direct Geometry reduction """ # Import the specific commands that we need -import mantid from mantid.api import AlgorithmManager from reduction.command_interface import * from inelastic_reducer import InelasticReducer @@ -10,35 +10,26 @@ def ARCS(): Clear(InelasticReducer) - pass - def CNCS(): Clear(InelasticReducer) - pass def HYSPEC(): Clear(InelasticReducer) - pass def LET(): Clear(InelasticReducer) - pass def MAPS(): Clear(InelasticReducer) - pass def MARI(): Clear(InelasticReducer) - pass def MERLIN(): Clear(InelasticReducer) - pass def SEQUOIA(): Clear(InelasticReducer) - pass def DefaultLoader(): step = InelasticLoader() diff --git a/Code/Mantid/scripts/reduction/instruments/inelastic/inelastic_reducer.py b/Code/Mantid/scripts/reduction/instruments/inelastic/inelastic_reducer.py index 937313415847..4a508855dd0b 100644 --- a/Code/Mantid/scripts/reduction/instruments/inelastic/inelastic_reducer.py +++ b/Code/Mantid/scripts/reduction/instruments/inelastic/inelastic_reducer.py @@ -1,7 +1,7 @@ +#pylint: disable=invalid-name """ Inelastic specific implementation of the Reducer. """ -import mantid from reduction import Reducer # Validate_step is a decorator that allows both Python algorithms and # ReductionStep objects to be passed to the Reducer. diff --git a/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py b/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py index 636b843bc708..37c0a52e4346 100644 --- a/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py +++ b/Code/Mantid/scripts/reduction/instruments/reflectometer/data_manipulation.py @@ -1,5 +1,4 @@ -import mantidplot -import mantid +#pylint: disable=invalid-name import os from mantid.simpleapi import * @@ -55,7 +54,7 @@ def counts_vs_pixel_distribution(file_path, is_pixel_y=True, callback=None, ws_base = "__%s" % basename ws_output_base = '' - if (instrument == 'REFL'): + if instrument == 'REFL': if isPeak: type = 'Peak' else: @@ -104,7 +103,7 @@ def _load_entry(entry, ws, title=""): else: geo_base_file_x = "REFL_Detector_Grouping_Sum_X.xml" geo_base_file_y = "REFL_Detector_Grouping_Sum_Y.xml" - + if is_pixel_y: grouping_file = os.path.join(instr_dir, "Grouping", geo_base_file_x) @@ -138,12 +137,12 @@ def _load_entry(entry, ws, title=""): if is_pixel_y: grouping_file = os.path.join(instr_dir, "Grouping", "REFL_Detector_Grouping_Sum_X.xml") - output_2d = GroupDetectors(InputWorkspace=output_2d, + output_2d = GroupDetectors(InputWorkspace=output_2d,\ MapFile=grouping_file) else: grouping_file = os.path.join(instr_dir, "Grouping", "REFL_Detector_Grouping_Sum_Y.xml") - output_2d = GroupDetectors(InputWorkspace=output_2d, + output_2d = GroupDetectors(InputWorkspace=output_2d,\ MapFile=grouping_file) if instrument=="REFM": diff --git a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py index 0e37f61ed629..4269d3fb1607 100644 --- a/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py +++ b/Code/Mantid/scripts/reduction/instruments/reflectometer/wks_utility.py @@ -1,9 +1,9 @@ -from numpy import zeros, ones, arctan2, arange, shape, sqrt, fliplr, asfarray, where, mean, sum, empty, NAN +#pylint: disable=invalid-name +from numpy import zeros, arctan2, arange, shape, sqrt, fliplr, asfarray, mean, sum, NAN from mantid.simpleapi import * # from MantidFramework import * import math import os.path -import sys h = 6.626e-34 #m^2 kg s^-1 m = 1.675e-27 #kg @@ -82,7 +82,7 @@ def getSheight(mt, index): else: tag = 'S1VHeight' value = mt_run.getProperty(tag).value - + return value[0] def getS1h(mt=None): @@ -218,9 +218,9 @@ def findQaxisMinMax(q_axis): for i in arange(nbr_row - 1) + 1: _q_min = q_axis[i][-1] _q_max = q_axis[i][0] - if (_q_min > q_min): + if _q_min > q_min: q_min = _q_min - if (_q_max < q_max): + if _q_max < q_max: q_max = _q_max #find now the index of those min and max in each row @@ -386,13 +386,13 @@ def convertWorkspaceToQ(ws_data, #keep only the overlap region of Qs _q_min = _q_axis_min_max_index[_q_index, 0] - if (_q_min != 0): + if _q_min != 0: _y_axis_tmp[0:_q_min] = 0 _y_error_axis_tmp[0:_q_min] = 0 _q_max = int(_q_axis_min_max_index[_q_index, 1]) sz = shape(_y_axis_tmp)[0] - if (_q_max != sz): + if _q_max != sz: _index_q_max_range = arange(sz - _q_max) + _q_max for i in _index_q_max_range: _y_axis_tmp[i] = 0 @@ -414,7 +414,7 @@ def convertWorkspaceToQ(ws_data, outputWorkspace.setDistribution(True) - outputWorkspace = Rebin(InputWorkspace=outputWorkspace, + outputWorkspace = Rebin(InputWorkspace=outputWorkspace,\ Params=q_binning) else: @@ -437,7 +437,7 @@ def convertWorkspaceToQ(ws_data, a = y_range[y] _tmp_y_axis = mt1.readY(int(a))[:] - _y_axis[int(y), :] = _tmp_y_axis; + _y_axis[int(y), :] = _tmp_y_axis _tmp_y_error_axis = mt1.readE(int(a))[:] _y_error_axis[int(y),:] = _tmp_y_error_axis @@ -459,7 +459,7 @@ def convertWorkspaceToQ(ws_data, outputWorkspace.setDistribution(True) - outputWorkspace = Rebin(InputWorkspace=outputWorkspace, + outputWorkspace = Rebin(InputWorkspace=outputWorkspace,\ Params=q_binning) return outputWorkspace @@ -502,20 +502,20 @@ def angleUnitConversion(value, from_units='degree', to_units='rad'): """ - if (from_units == to_units): - return value; + if from_units == to_units: + return value - from_factor = 1; + from_factor = 1 #convert everything into rad - if (from_units == 'degree'): - from_factor = 1.745329252e-2; - value_rad = from_factor * value; + if from_units == 'degree': + from_factor = 1.745329252e-2 + value_rad = from_factor * value - if (to_units == 'rad'): - return value_rad; + if to_units == 'rad': + return value_rad else: - to_factor = 57.2957795; - return to_factor * value_rad; + to_factor = 57.2957795 + return to_factor * value_rad def convertToThetaVsLambda(_tof_axis, _pixel_axis, @@ -723,7 +723,7 @@ def ref_beamdiv_correct(cpix, det_secondary, xI = xF yI = yF - if (len(int_poly_x) > 2): + if len(int_poly_x) > 2: int_poly_x.append(int_poly_x[0]) int_poly_y.append(int_poly_y[0]) int_poly_x.append(int_poly_x[1]) @@ -800,13 +800,13 @@ def applySF(InputWorkspace, """ #check if config file is there - if (os.path.isfile(sfFile)): + if os.path.isfile(sfFile): #parse file and put info into array f = open(sfFile, 'r') sfFactorTable = [] for line in f.read().split('\n'): - if (len(line) > 0 and line[0] != '#'): + if len(line) > 0 and line[0] != '#': sfFactorTable.append(line.split(' ')) f.close() @@ -840,12 +840,12 @@ def applySF(InputWorkspace, print '--> Data S2H: {0:2f}'.format(s2h_value) print '--> Data S1W: {0:2f}'.format(s1w_value) print '--> Data S2W: {0:2f}'.format(s2w_value) - + print 'mERDDEEEEDEDEED' for i in range(nbr_row): _file_incidentMedium = getFieldValue(sfFactorTable,i,0) - if (_file_incidentMedium.strip() == _incidentMedium.strip()): + if _file_incidentMedium.strip() == _incidentMedium.strip(): print '--- incident medium match ---' _file_lambdaRequested = getFieldValue(sfFactorTable,i,1) if (isWithinPrecisionRange(_file_lambdaRequested, @@ -862,7 +862,7 @@ def applySF(InputWorkspace, s2h_value, valuePrecision)): print '--- S2H match ---' - if (slitsWidthFlag): + if slitsWidthFlag: print '--- (with Width flag) ----' _file_s1w = getFieldValue(sfFactorTable,i,4) if(isWithinPrecisionRange(_file_s1w, @@ -946,7 +946,7 @@ def loadNeXus(runNumbers, type): """ wks_name = '' - if (type == 'data'): + if type == 'data': wks_name = 'ws_event_data' else: wks_name = 'ws_event_norm' @@ -1005,7 +1005,7 @@ def rebinNeXus(inputWorkspace, params, type): print '--> rebin ', type ws_histo_data = Rebin(InputWorkspace=inputWorkspace, Params=params, - PreserveEvents=True); + PreserveEvents=True) return ws_histo_data def cropTOF(inputWorkspace, min, max, type): @@ -1014,8 +1014,8 @@ def cropTOF(inputWorkspace, min, max, type): used here to crop the TOF range """ print '--> crop ' , type , ' workspace in TOF' - ws_histo_data = CropWorkspace(InputWorkspace = inputWorkspace, - XMin = min, + ws_histo_data = CropWorkspace(InputWorkspace = inputWorkspace,\ + XMin = min,\ XMax = max) return ws_histo_data @@ -1027,9 +1027,9 @@ def normalizeNeXus(inputWorkspace, type): ws_histo_data = NormaliseByCurrent(InputWorkspace=inputWorkspace) return ws_histo_data -def integrateOverLowResRange(mt1, - dataLowResRange, - type, +def integrateOverLowResRange(mt1,\ + dataLowResRange,\ + type,\ is_nexus_detector_rotated_flag): """ This creates the integrated workspace over the low resolution range leaving @@ -1133,7 +1133,7 @@ def substractBackground(tof_axis, y_axis, y_error_axis, bMinBack = True _backMinArray = y_axis[backMin:peakMin, t] _backMinErrorArray = y_error_axis[backMin:peakMin, t] - [_backMin, _backMinError] = weightedMean(_backMinArray, + [_backMin, _backMinError] = weightedMean(_backMinArray,\ _backMinErrorArray, error_0) if (peakMax) < backMax: @@ -1170,18 +1170,18 @@ def weightedMean(data_array, error_array, error_0): sz = len(data_array) # calculate the numerator of mean - dataNum = 0; + dataNum = 0 for i in range(sz): - if (error_array[i] == 0): + if error_array[i] == 0: error_array[i] = error_0 tmpFactor = float(data_array[i]) / float((pow(error_array[i],2))) dataNum += tmpFactor # calculate denominator - dataDen = 0; + dataDen = 0 for i in range(sz): - if (error_array[i] == 0): + if error_array[i] == 0: error_array[i] = error_0 tmpFactor = 1./float((pow(error_array[i],2))) dataDen += tmpFactor @@ -1334,7 +1334,7 @@ def ouput_ascii_file(file_name, sz_x_axis = len(x_axis) for i in range(sz_x_axis-1): - f.write(str(x_axis[i]) + "," + str(y_axis[i]) + "," + str(y_error_axis[i]) + "\n"); + f.write(str(x_axis[i]) + "," + str(y_axis[i]) + "," + str(y_error_axis[i]) + "\n") f.close @@ -1361,9 +1361,9 @@ def ouput_big_ascii_file(file_name, -def ouput_big_Q_ascii_file(file_name, - x_axis, - y_axis, +def ouput_big_Q_ascii_file(file_name,\ + x_axis,\ + y_axis,\ y_error_axis): f=open(file_name,'w') @@ -1419,7 +1419,7 @@ def applyScalingFactor(tof_axis, file created by the sfCalculator procedure """ #sf_file = 'NaN' - if (os.path.isfile(sf_file)): + if os.path.isfile(sf_file): print '-> scaling factor file FOUND! (', sf_file, ')' @@ -1427,7 +1427,7 @@ def applyScalingFactor(tof_axis, f = open(sf_file, 'r') sfFactorTable = [] for line in f.read().split('\n'): - if (len(line) > 0 and line[0] != '#'): + if len(line) > 0 and line[0] != '#': sfFactorTable.append(line.split(' ')) f.close() @@ -1463,7 +1463,7 @@ def applyScalingFactor(tof_axis, for i in range(nbr_row): _file_incidentMedium = getFieldValue(sfFactorTable,i,0) - if (_file_incidentMedium.strip() == _incidentMedium.strip()): + if _file_incidentMedium.strip() == _incidentMedium.strip(): print '*** incident medium match ***' _file_lambdaRequested = getFieldValue(sfFactorTable,i,1) if (isWithinPrecisionRange(_file_lambdaRequested, @@ -1480,7 +1480,7 @@ def applyScalingFactor(tof_axis, s2h_value, valuePrecision)): print '*** s2h match ***' - if (slitsWidthFlag): + if slitsWidthFlag: print '*** (with slits width flag) ***' _file_s1w = getFieldValue(sfFactorTable,i,4) if(isWithinPrecisionRange(_file_s1w, @@ -1709,7 +1709,7 @@ def getQrange(ws_histo_data, theta, dMD, q_min, q_step): _Q = _const * math.sin(theta) / (tofm*1e-6) _q_axis[t] = _Q*1e-10 q_max = max(_q_axis) - if (q_min >= q_max): + if q_min >= q_max: q_min = min(_q_axis) print '----> q_min: ', q_min print '----> q_step: ', q_step @@ -1767,13 +1767,13 @@ def convertToQ(tof_axis, # keep only the overlap region of Qs _q_min = _q_axis_min_max_index[_y_index, 0] - if (_q_min != 0): + if _q_min != 0: _y_axis_tmp[0:_q_min] = 0 _y_error_axis_tmp[0:_q_min] = 0 _q_max = int(_q_axis_min_max_index[_y_index, 1]) sz = shape(_y_axis_tmp)[0] - if (_q_max != sz): + if _q_max != sz: _index_q_max_range = arange(sz - _q_max) + _q_max for i in _index_q_max_range: _y_axis_tmp[i] = 0 @@ -1787,14 +1787,14 @@ def convertToQ(tof_axis, return [q_axis_reverse, _y_axis, _y_error_axis] -def convertToQWithoutCorrection(tof_axis, - y_axis, - y_error_axis, - peak_range = None, - source_to_detector_distance = None, - sample_to_detector_distance = None, - theta = None, - first_slit_size = None, +def convertToQWithoutCorrection(tof_axis,\ + y_axis,\ + y_error_axis,\ + peak_range = None,\ + source_to_detector_distance = None,\ + sample_to_detector_distance = None,\ + theta = None,\ + first_slit_size = None,\ last_slit_size = None): """ will convert the tof_axis into q_axis according to q range specified @@ -1927,23 +1927,24 @@ def createQworkspace(q_axis, y_axis, y_error_axis): y_axis_1d = y_axis.flatten() y_error_axis_1d = y_error_axis.flatten() - q_workspace = CreateWorkspace(DataX=q_axis_1d, - DataY=y_axis_1d, - DataE=y_error_axis_1d, - Nspec=nbr_pixel, + q_workspace = CreateWorkspace(DataX=q_axis_1d,\ + DataY=y_axis_1d,\ + DataE=y_error_axis_1d,\ + Nspec=nbr_pixel,\ UnitX="Wavelength") q_workspace.setDistribution(True) return q_workspace -def createFinalWorkspace(q_axis, final_y_axis, final_error_axis, name_output_ws): +def createFinalWorkspace(q_axis, final_y_axis, final_error_axis, name_output_ws, parent_workspace): final_workspace = CreateWorkspace(OutputWorkspace=name_output_ws, DataX=q_axis, DataY=final_y_axis, DataE=final_error_axis, Nspec=1, - UnitX="Wavelength") + UnitX="Wavelength", + ParentWorkspace=parent_workspace) final_workspace.setDistribution(True) return final_workspace @@ -1957,8 +1958,8 @@ def cropAxisToOnlyNonzeroElements(q_rebin, dataPeakRange): x_axis = q_rebin.readX(0)[:] sz = x_axis.shape[0]-1 - index_first_non_zero_value = sz; - index_last_non_zero_value = 0; + index_first_non_zero_value = sz + index_last_non_zero_value = 0 for x in range(nbrPixel): _pixel_axis = q_rebin.readY(x)[:] @@ -2043,7 +2044,7 @@ def cleanupData1D(final_data_y_axis, final_data_y_error_axis): sz = final_data_y_axis.shape nbrTof = sz[0] - notYetRemoved = True; + notYetRemoved = True for t in range(nbrTof): @@ -2060,7 +2061,7 @@ def cleanupData1D(final_data_y_axis, final_data_y_error_axis): if abs(_error) >= abs(_data): _data_tmp = 0 _error_tmp = 1 - elif (_data< 1e-12): + elif _data< 1e-12: # if value is below 10^-12 _data_tmp = 0 _error_tmp = 1 @@ -2076,15 +2077,15 @@ def cleanupData1D(final_data_y_axis, final_data_y_error_axis): return [final_data_y_axis, final_data_y_error_axis] def isNexusTakeAfterRefDate(nexus_date): - ''' + ''' This function parses the output.date and returns true if this date is after the ref date ''' - nexus_date_acquistion = nexus_date.split('T')[0] - - if nexus_date_acquistion > ref_date: - return True - else: - return False + nexus_date_acquistion = nexus_date.split('T')[0] + + if nexus_date_acquistion > ref_date: + return True + else: + return False diff --git a/Code/Mantid/scripts/reduction/instruments/sans/sans_reducer.py b/Code/Mantid/scripts/reduction/instruments/sans/sans_reducer.py index 06af14e2fb0c..14ccf1aaa321 100644 --- a/Code/Mantid/scripts/reduction/instruments/sans/sans_reducer.py +++ b/Code/Mantid/scripts/reduction/instruments/sans/sans_reducer.py @@ -8,7 +8,6 @@ from reduction import validate_step import sans_reduction_steps import mantid.simpleapi as api -from mantid import simpleapi import warnings import inspect @@ -152,7 +151,8 @@ def set_mask(self, mask): """ self._mask = mask - def get_mask(self): return self._mask + def get_mask(self): + return self._mask def get_beam_center(self): """ @@ -186,7 +186,8 @@ def set_data_loader(self, loader): else: raise RuntimeError, "Reducer.set_data_loader expects an object of class ReductionStep" - def get_data_loader(self): return self._data_loader + def get_data_loader(self): + return self._data_loader @validate_step def set_sensitivity_correcter(self, correcter): @@ -259,7 +260,8 @@ def set_bck_transmission(self, trans): @param trans: ReductionStep object """ lineno = inspect.currentframe().f_code.co_firstlineno - warnings.warn_explicit("SANSReducer.set_bck_transmission id deprecated: use get_background().set_transmission()", DeprecationWarning, __file__, lineno) + warnings.warn_explicit("SANSReducer.set_bck_transmission id deprecated: use get_background().set_transmission()",\ + DeprecationWarning, __file__, lineno) if issubclass(trans.__class__, sans_reduction_steps.BaseTransmission) or trans is None: self._background_subtracter.set_transmission(trans) diff --git a/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py b/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py index 8b44f00236db..274030ee979f 100644 --- a/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py +++ b/Code/Mantid/scripts/reduction/instruments/sans/sans_reduction_steps.py @@ -1,14 +1,11 @@ +#pylint: disable=invalid-name """ Implementation of reduction steps for SANS """ -import os -import sys import math import pickle from reduction import ReductionStep -from reduction import extract_workspace_name, find_data from reduction import validate_step -import warnings # Mantid imports import mantid @@ -56,10 +53,10 @@ def _find_beam(self, direct_beam, reducer, workspace=None): if self._beam_center_x is not None and self._beam_center_y is not None: return "Using Beam Center at: %g %g" % (self._beam_center_x, self._beam_center_y) - beam_x,beam_y,msg = SANSBeamFinder(Filename=self._datafile, - UseDirectBeamMethod=direct_beam, - BeamRadius=self._beam_radius, - PersistentCorrection=self._persistent, + beam_x,beam_y,msg = SANSBeamFinder(Filename=self._datafile,\ + UseDirectBeamMethod=direct_beam,\ + BeamRadius=self._beam_radius,\ + PersistentCorrection=self._persistent,\ ReductionProperties=reducer.get_reduction_table_name()) self._beam_center_x = beam_x @@ -540,7 +537,7 @@ def set_gravity(self, flag, override=True): self._grav_set = True if (not self._grav_set) or override: - self._use_gravity = bool(flag) + self._use_gravity = bool(flag) else: msg = "User file can't override previous gravity setting, do gravity correction remains " + str(self._use_gravity) print msg @@ -755,7 +752,7 @@ def __init__(self): def calculate_volume(self, reducer): geo = reducer.get_sample().geometry - assert( issubclass(geo.__class__, GetSampleGeom)) + assert issubclass(geo.__class__, GetSampleGeom) try: if geo.shape == 'cylinder-axis-up': @@ -807,14 +804,14 @@ def execute(self, reducer, workspace): # Find the first non-zero value start = 0 for i in range(0, length): - if ( y_vals[i] != self._flag_value ): + if y_vals[i] != self._flag_value : start = i break # Now find the last non-zero value stop = 0 length -= 1 for j in range(length, 0,-1): - if ( y_vals[j] != self._flag_value ): + if y_vals[j] != self._flag_value : stop = j break # Find the appropriate X values and call CropWorkspace diff --git a/Code/Mantid/scripts/reduction/reducer.py b/Code/Mantid/scripts/reduction/reducer.py index 71c901353107..fa33ef3385d1 100644 --- a/Code/Mantid/scripts/reduction/reducer.py +++ b/Code/Mantid/scripts/reduction/reducer.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Base reduction class. Hold a list of data and a list of reduction steps to apply to them. @@ -22,14 +23,14 @@ import time import types import inspect -from instrument import Instrument +from reduction.instrument import Instrument import mantid from mantid import simpleapi import warnings import inspect import random import string -from find_data import find_data +from reduction.find_data import find_data ## Version number @@ -537,7 +538,7 @@ def execute(self, reducer, inputworkspace=None, outputworkspace=None): @param inputworkspace: Name of the workspace to apply this step to @param outputworkspace: Name of the workspace to have as an output. If this is None it will be set to inputworkspace """ - raise NotImplemented + raise NotImplementedError def extract_workspace_name(filepath, suffix=''): diff --git a/Code/Mantid/scripts/reduction_workflow/command_interface.py b/Code/Mantid/scripts/reduction_workflow/command_interface.py index 20306ab30c4a..6df622f1a156 100644 --- a/Code/Mantid/scripts/reduction_workflow/command_interface.py +++ b/Code/Mantid/scripts/reduction_workflow/command_interface.py @@ -1,10 +1,11 @@ +#pylint: disable=invalid-name """ List of user commands. """ -from reducer import Reducer +from reduction_workflow.reducer import Reducer -class ReductionSingleton: +class ReductionSingleton(object): """ Singleton reduction class """ ## storage for the instance reference diff --git a/Code/Mantid/scripts/reduction_workflow/find_data.py b/Code/Mantid/scripts/reduction_workflow/find_data.py index e6701e647799..0ecd916bf341 100644 --- a/Code/Mantid/scripts/reduction_workflow/find_data.py +++ b/Code/Mantid/scripts/reduction_workflow/find_data.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import os from mantid.kernel import ConfigService, Logger from mantid.api import FileFinder diff --git a/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py b/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py index 75518979f283..b3ef207a81c9 100644 --- a/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py +++ b/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py @@ -1,12 +1,11 @@ +#pylint: disable=invalid-name """ List of common user commands for HFIR SANS """ from reduction_workflow.command_interface import * from reduction_workflow.find_data import * from reduction_workflow.instruments.sans import hfir_instrument -from mantid.api import AlgorithmManager from mantid.kernel import Logger -import mantid.simpleapi as simpleapi import os ## List of user commands ###################################################### @@ -236,9 +235,9 @@ def BckDirectBeamTransmission(sample_file, empty_file, beam_radius=3.0, theta_de ReductionSingleton().reduction_properties["BckTransmissionEmptyDataFile"] = empty_file ReductionSingleton().reduction_properties["BckThetaDependentTransmission"] = theta_dependent -def BckBeamSpreaderTransmission(sample_spreader, direct_spreader, - sample_scattering, direct_scattering, - spreader_transmission=1.0, spreader_transmission_err=0.0, +def BckBeamSpreaderTransmission(sample_spreader, direct_spreader,\ + sample_scattering, direct_scattering,\ + spreader_transmission=1.0, spreader_transmission_err=0.0,\ theta_dependent=True ): sample_spreader = find_data(sample_spreader, instrument=ReductionSingleton().get_instrument()) direct_spreader = find_data(direct_spreader, instrument=ReductionSingleton().get_instrument()) diff --git a/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_instrument.py b/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_instrument.py index aeb9d3dc9b83..f22af8ef87cf 100644 --- a/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_instrument.py +++ b/Code/Mantid/scripts/reduction_workflow/instruments/sans/hfir_instrument.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name import sys def get_default_beam_center(workspace=None): @@ -53,7 +54,7 @@ def get_masked_pixels(nx_low, nx_high, ny_low, ny_high, workspace): @param ny_high: number of pixels to mask on the higher-y side of the detector @param workspace: the pixel number and size info will be taken from the workspace """ - nx_pixels, ny_pixels, pixel_size_x, pixel_size_y = _get_pixel_info(workspace) + nx_pixels, ny_pixels, dummy_pixel_size_x, dummy_pixel_size_y = _get_pixel_info(workspace) if nx_low<0 or nx_high<0 or ny_low<0 or ny_high<0: raise RuntimeError, "Pixel edges should be greater than zero" diff --git a/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py b/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py index ccf511c21708..38eec69d5a98 100644 --- a/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py +++ b/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_command_interface.py @@ -1,7 +1,8 @@ +#pylint: disable=invalid-name,unused-import """ Command set for EQSANS reduction """ -# Import the specific commands that we need +# Import the specific commands that we need - some of these are used in systemtests from reduction_workflow.command_interface import * from hfir_command_interface import DarkCurrent, NoDarkCurrent, NoNormalization @@ -30,9 +31,9 @@ from hfir_command_interface import SetAbsoluteScale, SetDirectBeamAbsoluteScale from hfir_command_interface import Stitch -from mantid.api import AlgorithmManager -from mantid.kernel import Logger -import mantid.simpleapi as simpleapi +#from mantid.api import AlgorithmManager +#from mantid.kernel import Logger +#import mantid.simpleapi as simpleapi from reduction_workflow.find_data import find_data def EQSANS(keep_events=False, property_manager=None): diff --git a/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_instrument.py b/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_instrument.py index 7536177cf452..3d26584fb37f 100644 --- a/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_instrument.py +++ b/Code/Mantid/scripts/reduction_workflow/instruments/sans/sns_instrument.py @@ -1,9 +1,9 @@ +#pylint: disable=invalid-name """ Instrument-specific utility functions for EQSANS """ -from hfir_instrument import get_default_beam_center, _get_pixel_info +from hfir_instrument import _get_pixel_info -import sys def get_pixel_from_coordinate(x, y, workspace): """ diff --git a/Code/Mantid/scripts/reduction_workflow/reducer.py b/Code/Mantid/scripts/reduction_workflow/reducer.py index 5b9a5ab4ba6f..d9cbdad20735 100644 --- a/Code/Mantid/scripts/reduction_workflow/reducer.py +++ b/Code/Mantid/scripts/reduction_workflow/reducer.py @@ -1,3 +1,4 @@ +#pylint: disable=invalid-name """ Base reduction class. Uses version 2 python API. """ @@ -6,10 +7,8 @@ import time import random import string -import mantid.simpleapi as simpleapi from mantid.api import AlgorithmManager, AnalysisDataService from mantid.kernel import ConfigService, Logger -from find_data import find_data class Reducer(object): """ diff --git a/Code/Mantid/scripts/test/ConvertToWavelengthTest.py b/Code/Mantid/scripts/test/ConvertToWavelengthTest.py index a4ad82fb1423..e6e8c0467b2b 100644 --- a/Code/Mantid/scripts/test/ConvertToWavelengthTest.py +++ b/Code/Mantid/scripts/test/ConvertToWavelengthTest.py @@ -134,4 +134,5 @@ def test_convert(self): self.assertTrue(x_max <= 10.0) if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() + diff --git a/Code/Mantid/scripts/test/DirectEnergyConversionTest.py b/Code/Mantid/scripts/test/DirectEnergyConversionTest.py index 8575dba4e63a..897c2e03e105 100644 --- a/Code/Mantid/scripts/test/DirectEnergyConversionTest.py +++ b/Code/Mantid/scripts/test/DirectEnergyConversionTest.py @@ -128,7 +128,7 @@ def test_do_white_wb(self) : white_ws = tReducer.do_white(wb_ws, None, None) self.assertTrue(white_ws) - + def test_get_set_attributes(self): tReducer = self.reducer @@ -163,17 +163,17 @@ def test_get_abs_normalization_factor(self) : tReducer.prop_man.incident_energy = 5. tReducer.prop_man.monovan_integr_range=[-10,10] - (nf1,nf2,nf3,nf4) = tReducer.get_abs_normalization_factor(mono_ws.getName(),5.) + (nf1,nf2,nf3,nf4) = tReducer.get_abs_normalization_factor(mono_ws.getName(),5.) self.assertAlmostEqual(nf1,0.58561121802167193,7) self.assertAlmostEqual(nf1,nf2) self.assertAlmostEqual(nf2,nf3) self.assertAlmostEqual(nf3,nf4) - # check warning. WB spectra with 0 signal indicate troubles. + # check warning. WB spectra with 0 signal indicate troubles. mono_ws = CreateSampleWorkspace(NumBanks=1, BankPixelWidth=4, NumEvents=10000,XUnit='DeltaE',XMin=-5,XMax=15,BinWidth=0.1,function='Flat background') LoadInstrument(mono_ws,InstrumentName='MARI') sig = mono_ws.dataY(0) - sig[:]=0 + sig[:]=0 (nf1,nf2,nf3,nf4) = tReducer.get_abs_normalization_factor(mono_ws.getName(),5.) self.assertAlmostEqual(nf1,0.585611218022,7) @@ -204,8 +204,8 @@ def test_dgreduce_works(self): #abs_units(wb_for_run,sample_run,monovan_run,wb_for_monovanadium,samp_rmm,samp_mass,ei_guess,rebin,map_file='default',monovan_mapfile='default',**kwargs): ws = dgreduce.abs_units(wb_ws,run_ws,None,wb_ws,10,100,8.8,[-10,0.1,7],None,None,**par) self.assertTrue(isinstance(ws,api.MatrixWorkspace)) - - + + ##def test_diag_call(self): ## tReducer = self.reducer ## # should do nothing as already initialized above, but if not will initiate the instrument @@ -215,7 +215,7 @@ def test_dgreduce_works(self): def test_energy_to_TOF_range(self): ws = Load(Filename='MAR11001.raw',LoadMonitors='Include') - + en_range = [0.8*13,13,1.2*13] detIDs=[1,2,3,10] red = DirectEnergyConversion() @@ -273,7 +273,7 @@ def test_late_rebinning(self): # References used to test against ordinary reduction ref_ws = Rebin(run,Params=[tMin,1,tMax],PreserveEvents=False) ref_ws_monitors = CloneWorkspace('run_monitors') - # just in case, wb should work without clone too. + # just in case, wb should work without clone too. wb_clone = CloneWorkspace(wb_ws) # Run Mono @@ -339,7 +339,7 @@ def test_multirep_mode(self): XUnit='TOF',xMin=tMin,xMax=tMax) LoadInstrument(run,InstrumentName='MARI') - # do second + # do second run2 = CloneWorkspace(run) run2_monitors = CloneWorkspace(run_monitors) @@ -372,7 +372,7 @@ def test_multirep_mode(self): # rename samples from previous workspace to avoid deleting them on current run for ind,item in enumerate(result): result[ind]=RenameWorkspace(item,OutputWorkspace='SampleRez#'+str(ind)) - # + # result2 = tReducer.convert_to_energy(None,run2,[67.,122.],[-2,0.02,0.8]) rez = CheckWorkspacesMatch(result[0],result2[0]) @@ -438,7 +438,7 @@ def test_multirep_abs_units_mode(self): # rename samples from previous workspace to avoid deleting them on current run for ind,item in enumerate(result): result[ind]=RenameWorkspace(item,OutputWorkspace='SampleRez#'+str(ind)) - # + # result2 = tReducer.convert_to_energy(None,run2) rez = CheckWorkspacesMatch(result[0],result2[0]) @@ -447,9 +447,6 @@ def test_multirep_abs_units_mode(self): self.assertEqual(rez,'Success!') - - - - if __name__=="__main__": - unittest.main() + unittest.main() + diff --git a/Code/Mantid/scripts/test/DirectPropertyManagerTest.py b/Code/Mantid/scripts/test/DirectPropertyManagerTest.py index ba4e7ef402ed..2ef643c166d4 100644 --- a/Code/Mantid/scripts/test/DirectPropertyManagerTest.py +++ b/Code/Mantid/scripts/test/DirectPropertyManagerTest.py @@ -32,12 +32,12 @@ def getInstrument(InstrumentName='MAR'): idf_file=api.ExperimentInfo.getInstrumentFilename(InstrumentName) tmp_ws_name = '__empty_' + InstrumentName if not mtd.doesExist(tmp_ws_name): - LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) + LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) return mtd[tmp_ws_name].getInstrument() - + def test_init_reducer(self): - + propman=self.prop_man self.assertEqual(propman.deltaE_mode,'direct') @@ -50,7 +50,7 @@ def test_set_non_default_wrong_value(self): # non-existing property can not be set! self.assertRaises(KeyError,setattr,propman,'non_existing_property',"Something_Meaningfull") - # existing simple assignment works + # existing simple assignment works propman.load_monitors_with_workspace = False propman.load_monitors_with_workspace = True self.assertTrue(propman.load_monitors_with_workspace) @@ -154,7 +154,7 @@ def test_set_non_default_complex_value(self): self.assertEqual(propman.ei_mon_spectra,[2,3]," Default ei monitors on MARI should be as described in MARI_Parameters.xml file") - + propman.norm_mon_integration_range = [50,1050] range=propman.norm_mon_integration_range self.assertAlmostEqual(range[0],50.,7) @@ -183,7 +183,7 @@ def test_set_non_default_complex_value_synonims(self): self.assertTrue("ei-mon2-spec" in prop_changed,"changing test_ei2_mon_spectra should change ei-mon2-spectra") - propman.test_mon_spectra_composite = [10000,2000] + propman.test_mon_spectra_composite = [10000,2000] self.assertEqual(propman.ei_mon_spectra,[10000,2000]) prop_changed = propman.getChangedProperties() @@ -344,13 +344,13 @@ def test_diag_spectra(self): self.assertEqual(len(spectra),4) self.assertEqual(spectra[0],(1,17280)) self.assertEqual(spectra[3],(32257,41472)) - + def test_get_diagnostics_parameters(self): propman = self.prop_man params = propman.get_diagnostics_parameters() self.assertEqual(len(params),20) - + bkg_test_range0 = propman.background_test_range bkg_test_range = params['background_test_range'] bkg_range = propman.background_range @@ -362,25 +362,24 @@ def test_get_diagnostics_parameters(self): self.assertEqual(bkg_test_range,[1000,2000]) def test_check_monovan_changed(self): - propman = self.prop_man - - non_changed = propman._check_monovan_par_changed() - # nothing have changed initially - self.assertEqual(len(non_changed),2) + propman = self.prop_man + + non_changed = propman._check_monovan_par_changed() + # nothing have changed initially + self.assertEqual(len(non_changed),2) - propman.monovan_run = 102 - propman.log_changed_values() + propman.monovan_run = 102 + propman.log_changed_values() - propman.sample_mass = 1 - non_changed = propman._check_monovan_par_changed() - self.assertEqual(len(non_changed),1) - propman.sample_rmm = 200 - non_changed = propman._check_monovan_par_changed() - self.assertEqual(len(non_changed),0) + propman.sample_mass = 1 + non_changed = propman._check_monovan_par_changed() + self.assertEqual(len(non_changed),1) + propman.sample_rmm = 200 + non_changed = propman._check_monovan_par_changed() + self.assertEqual(len(non_changed),0) + propman.log_changed_values() - propman.log_changed_values() - def test_set_defailts_from_instrument(self) : ws = CreateSampleWorkspace(NumBanks=1, BankPixelWidth=4, NumEvents=100) @@ -394,7 +393,7 @@ def test_set_defailts_from_instrument(self) : self.assertAlmostEqual(propman.TestParam1,3.5) self.assertEquals(propman.TestParam2,"initial1") self.assertEquals(propman.TestParam3,"initial2") - + propman.TestParam2="gui_changed1" self.assertEquals(propman.TestParam2,"gui_changed1") @@ -408,7 +407,7 @@ def test_set_defailts_from_instrument(self) : self.assertTrue('TestParam2' in changes) self.assertTrue(not('TestParam3' in changes)) - + changes = propman.update_defaults_from_instrument(ws.getInstrument()) @@ -460,8 +459,8 @@ def test_set_complex_defailts_from_instrument(self) : self.assertEqual(propman.ParaPara,'OtherVal2') self.assertEqual(propman.BaseParam2,'OtherVal2') - - self.assertEquals(propman.BaseParam1,"OtherVal1") + + self.assertEquals(propman.BaseParam1,"OtherVal1") def test_set_all_defaults_from_instrument(self) : ws = CreateSampleWorkspace(NumBanks=1, BankPixelWidth=4, NumEvents=10) @@ -557,7 +556,7 @@ def test_set_energy_bins_and_ei(self): propman.energy_bins = None self.assertFalse(propman.energy_bins) - + def test_multirep_ei_iterate_over(self): propman = self.prop_man @@ -617,7 +616,7 @@ def test_multirep_ei_iterate_over(self): self.assertAlmostEqual(bins[2],0.8*en) ic+=1 self.assertEqual(ic,3) - # + # ic=0 for en in PropertyManager.incident_energy: self.assertAlmostEqual(en,eng[ic]) @@ -694,55 +693,55 @@ def test_ignore_complex_defailts_single_fom_instrument(self) : def test_monovan_integration_range(self): - propman = self.prop_man + propman = self.prop_man - propman.incident_energy = 10 - propman.monovan_lo_frac = -0.6 - propman.monovan_hi_frac = 0.7 + propman.incident_energy = 10 + propman.monovan_lo_frac = -0.6 + propman.monovan_hi_frac = 0.7 - range = propman.abs_units_van_range - self.assertAlmostEqual(range[0],-6.) - self.assertAlmostEqual(range[1], 7.) + range = propman.abs_units_van_range + self.assertAlmostEqual(range[0],-6.) + self.assertAlmostEqual(range[1], 7.) - range = propman.monovan_integr_range - self.assertAlmostEqual(range[0],-6.) - self.assertAlmostEqual(range[1], 7.) + range = propman.monovan_integr_range + self.assertAlmostEqual(range[0],-6.) + self.assertAlmostEqual(range[1], 7.) - propman.monovan_lo_value = -10 - propman.monovan_hi_value = 10 + propman.monovan_lo_value = -10 + propman.monovan_hi_value = 10 - range = propman.abs_units_van_range - self.assertAlmostEqual(range[0],-6.) - self.assertAlmostEqual(range[1], 7.) + range = propman.abs_units_van_range + self.assertAlmostEqual(range[0],-6.) + self.assertAlmostEqual(range[1], 7.) - propman.abs_units_van_range=[-40,40] - self.assertAlmostEqual(propman.monovan_lo_value,-40) - self.assertAlmostEqual(propman.monovan_hi_value,40) + propman.abs_units_van_range=[-40,40] + self.assertAlmostEqual(propman.monovan_lo_value,-40) + self.assertAlmostEqual(propman.monovan_hi_value,40) - range = propman.monovan_integr_range - self.assertAlmostEqual(range[0],-40) - self.assertAlmostEqual(range[1], 40) + range = propman.monovan_integr_range + self.assertAlmostEqual(range[0],-40) + self.assertAlmostEqual(range[1], 40) - propman.abs_units_van_range=None + propman.abs_units_van_range=None - range = propman.monovan_integr_range - self.assertAlmostEqual(range[0],-6.) - self.assertAlmostEqual(range[1], 7.) - # - propman.monovan_lo_frac = -0.7 - range = propman.monovan_integr_range - self.assertAlmostEqual(range[0],-7.) + range = propman.monovan_integr_range + self.assertAlmostEqual(range[0],-6.) + self.assertAlmostEqual(range[1], 7.) + # + propman.monovan_lo_frac = -0.7 + range = propman.monovan_integr_range + self.assertAlmostEqual(range[0],-7.) def test_save_filename(self): - propman = self.prop_man + propman = self.prop_man - propman.incident_energy = 10 - propman.sample_run = 0 - propman.monovan_run = None + propman.incident_energy = 10 + propman.sample_run = 0 + propman.monovan_run = None - name = propman.save_file_name - self.assertEqual(name,'MAR00000Ei10d00meV') + name = propman.save_file_name + self.assertEqual(name,'MAR00000Ei10d00meV') def test_log_to_Mantid(self): propman = self.prop_man @@ -781,7 +780,7 @@ def test_hadmask_options(self): self.assertTrue(propman.hard_mask_file is None) def test_hadmask_options_locked(self): - # + # propman1 = self.prop_man propman1.setChangedProperties() propman1.hardmaskPlus = 'a_hard_mask_file' @@ -815,7 +814,7 @@ def test_hadmask_options_locked(self): self.assertTrue(propman1.run_diagnostics) - + #def test_do_white(self) : # tReducer = self.reducer # monovan = 1000 @@ -823,8 +822,8 @@ def test_hadmask_options_locked(self): # name = tReducer.make_ckpt_name('do_white',monovan,data,'t1') # self.assertEqual('do_white1000t1',name) - - + + def test_monitors_list(self): propman = self.prop_man diff --git a/Code/Mantid/scripts/test/DirectPropertyManater_OldInterfaceXest.py b/Code/Mantid/scripts/test/DirectPropertyManater_OldInterfaceXest.py index bbc5e44094e5..c498af67b719 100644 --- a/Code/Mantid/scripts/test/DirectPropertyManater_OldInterfaceXest.py +++ b/Code/Mantid/scripts/test/DirectPropertyManater_OldInterfaceXest.py @@ -17,7 +17,7 @@ def __init__(self, methodName): def setUp(self): if self.reducer == None or type(self.reducer) != type(DirectEnergyConversion): - self.reducer = DirectEnergyConversion("MAPS"); + self.reducer = DirectEnergyConversion("MAPS") def tearDown(self): pass @@ -34,17 +34,17 @@ def test_set_non_default_wrong_value(self): def test_set_non_default_simple_value(self): tReducer = self.reducer # should do nothing as already initialized above - tReducer.initialise("MAP"); + tReducer.initialise("MAP") prop_changed=tReducer.set_input_parameters(van_mass=100,det_cal_file='det4to1_1912.dat') self.assertTrue("van_mass" in prop_changed) self.assertTrue("det_cal_file" in prop_changed) - self.assertEqual(tReducer.van_mass,100); - self.assertEqual(tReducer.det_cal_file,'det4to1_1912.dat'); + self.assertEqual(tReducer.van_mass,100) + self.assertEqual(tReducer.det_cal_file,'det4to1_1912.dat') self.assertAlmostEqual(tReducer.van_sig,0.,7) - kw=dict(); + kw=dict() kw["vanadium-mass"]=200 kw["diag_van_median_sigma"]=1 kw["det_cal_file"]=None @@ -54,8 +54,8 @@ def test_set_non_default_simple_value(self): self.assertTrue("van_mass" in prop_changed,"vanadium-mass should correspond to van_mass") self.assertTrue("van_sig" in prop_changed," diag_van_median_sigma should correspond to van_sig ") - self.assertEqual(tReducer.van_mass,200); - self.assertEqual(tReducer.det_cal_file,None); + self.assertEqual(tReducer.van_mass,200) + self.assertEqual(tReducer.det_cal_file,None) self.assertAlmostEqual(tReducer.van_sig,1.,7) @@ -63,7 +63,7 @@ def test_set_non_default_simple_value(self): def test_set_non_default_complex_value(self): tReducer = self.reducer # should do nothing as already initialized above, but if not will initiate the instrument - tReducer.initialise("MAP"); + tReducer.initialise("MAP") range = tReducer.norm_mon_integration_range self.assertAlmostEqual(range[0],1000.,7," Default integration min range on MAPS should be as described in MAPS_Parameters.xml file") @@ -73,7 +73,7 @@ def test_set_non_default_complex_value(self): self.assertRaises(KeyError,tReducer.set_input_parameters,mon_norm_range=1) self.assertRaises(KeyError,tReducer.set_input_parameters,mon_norm_range=[10,100,100]) - kw=dict(); + kw=dict() kw["norm_mon_integration_range"]=[50,1050] kw["ei-mon1-spec"]=10 prop_changed=tReducer.set_input_parameters(**kw) @@ -89,9 +89,9 @@ def test_set_non_default_complex_value(self): def test_set_non_default_complex_value_synonims(self): tReducer = self.reducer # should do nothing as already initialized above, but if not will initiate the instrument - tReducer.initialise("MAP"); + tReducer.initialise("MAP") # - kw = dict(); + kw = dict() kw["test_ei2_mon_spectra"]=10000 prop_changed=tReducer.set_input_parameters(**kw) @@ -106,7 +106,7 @@ def test_set_non_default_complex_value_synonims(self): def test_set_get_mono_range(self): tReducer = self.reducer # should do nothing as already initialized above, but if not will initiate the instrument - tReducer.initialise("MAP"); + tReducer.initialise("MAP") energy_incident = 100 tReducer.incident_energy = energy_incident @@ -118,7 +118,7 @@ def test_set_get_mono_range(self): def test_comlex_get(self): tReducer = self.reducer - van_rmm = tReducer.van_rmm; + van_rmm = tReducer.van_rmm self.assertEqual(50.9415,van_rmm) def test_comlex_set(self): @@ -154,7 +154,7 @@ def test_comlex_set(self): def test_set_format(self): tReducer = self.reducer - tReducer.save_format = ''; + tReducer.save_format = '' self.assertTrue(tReducer.save_format is None) #self.assertRaises(KeyError,tReducer.energy_bins=20,None) @@ -193,30 +193,27 @@ def test_get_parameter(self): def test_save_formats(self): - tReducer = self.reducer; + tReducer = self.reducer ws_name = '__empty_'+tReducer._instr_name pws = mtd[ws_name] - self.assertEqual(pws.name(),ws_name); + self.assertEqual(pws.name(),ws_name) self.assertTrue(tReducer.save_format is None) # do nothing tReducer.save_results(pws,'test_path') - tReducer.test_name=''; + tReducer.test_name='' def f_spe(workspace, filename): - tReducer.test_name += (workspace.name()+'_file_spe_' + filename) + tReducer.test_name += (workspace.name()+'_file_spe_' + filename) def f_nxspe(workspace, filename): - tReducer.test_name += (workspace.name()+'_file_nxspe_' + filename) + tReducer.test_name += (workspace.name()+'_file_nxspe_' + filename) def f_nxs(workspace, filename): - tReducer.test_name += (workspace.name()+'_file_nxs_' + filename) - + tReducer.test_name += (workspace.name()+'_file_nxs_' + filename) # redefine test save methors to produce test ouptut - tReducer._DirectEnergyConversion__save_formats['.spe']=lambda workspace,filename: f_spe(workspace,filename); - tReducer._DirectEnergyConversion__save_formats['.nxspe']=lambda workspace,filename : f_nxspe(workspace,filename); - tReducer._DirectEnergyConversion__save_formats['.nxs']=lambda workspace,filename : f_nxs(workspace,filename); - - + tReducer._DirectEnergyConversion__save_formats['.spe']=lambda workspace,filename: f_spe(workspace,filename) + tReducer._DirectEnergyConversion__save_formats['.nxspe']=lambda workspace,filename : f_nxspe(workspace,filename) + tReducer._DirectEnergyConversion__save_formats['.nxs']=lambda workspace,filename : f_nxs(workspace,filename) # set non-exisiting format tReducer.save_format = 'non-existing-format' @@ -228,62 +225,62 @@ def f_nxs(workspace, filename): tReducer.save_format = '.spe' self.assertEqual(tReducer.save_format,['.spe']) - tReducer.test_name=''; + tReducer.test_name='' tReducer.save_results(pws) self.assertEquals(ws_name+'_file_spe_'+ws_name+'.spe',tReducer.test_name) file_long_name = ws_name+'_file_spe_other_file_name.spe' - tReducer.test_name=''; + tReducer.test_name='' tReducer.save_results(pws,'other_file_name') self.assertEquals(file_long_name,tReducer.test_name) file_long_name=ws_name+'_file_nxspe_ofn.nxspe'+ws_name+'_file_nxs_ofn.nxs' - tReducer.test_name=''; + tReducer.test_name='' tReducer.save_results(pws,'ofn',['.nxspe','.nxs']) self.assertEquals(file_long_name,tReducer.test_name) #clear all previous default formats - tReducer.save_format=[]; + tReducer.save_format=[] self.assertTrue(tReducer.save_format is None) format_list = ['.nxspe','.nxs','.spe'] - file_long_name = ''; - tReducer.save_format = format_list; + file_long_name = '' + tReducer.save_format = format_list for i in xrange(len(format_list)): - self.assertEqual(tReducer.save_format[i],format_list[i]); - end = len(format_list[i]); + self.assertEqual(tReducer.save_format[i],format_list[i]) + end = len(format_list[i]) file_long_name+=ws_name+'_file_'+format_list[i][1:end]+'_ofn'+format_list[i] - tReducer.test_name=''; + tReducer.test_name='' tReducer.save_results(pws,'ofn') self.assertEquals(file_long_name,tReducer.test_name) def test_set_spectra_to_mon(self): - tReducer = self.reducer; + tReducer = self.reducer - self.assertTrue(tReducer.spectra_to_monitors_list is None); + self.assertTrue(tReducer.spectra_to_monitors_list is None) - tReducer.spectra_to_monitors_list = 35; - self.assertTrue(isinstance(tReducer.spectra_to_monitors_list,list)); - self.assertEquals(35,tReducer.spectra_to_monitors_list[0]); + tReducer.spectra_to_monitors_list = 35 + self.assertTrue(isinstance(tReducer.spectra_to_monitors_list,list)) + self.assertEquals(35,tReducer.spectra_to_monitors_list[0]) - tReducer.spectra_to_monitors_list = None; - self.assertTrue(tReducer.spectra_to_monitors_list is None); - tReducer.spectra_to_monitors_list = 'None'; - self.assertTrue(tReducer.spectra_to_monitors_list is None); - tReducer.spectra_to_monitors_list = []; - self.assertTrue(tReducer.spectra_to_monitors_list is None); + tReducer.spectra_to_monitors_list = None + self.assertTrue(tReducer.spectra_to_monitors_list is None) + tReducer.spectra_to_monitors_list = 'None' + self.assertTrue(tReducer.spectra_to_monitors_list is None) + tReducer.spectra_to_monitors_list = [] + self.assertTrue(tReducer.spectra_to_monitors_list is None) - tReducer.spectra_to_monitors_list = '467'; - self.assertEquals(467,tReducer.spectra_to_monitors_list[0]); + tReducer.spectra_to_monitors_list = '467' + self.assertEquals(467,tReducer.spectra_to_monitors_list[0]) - tReducer.spectra_to_monitors_list = '467,444'; - self.assertEquals(467,tReducer.spectra_to_monitors_list[0]); - self.assertEquals(444,tReducer.spectra_to_monitors_list[1]); + tReducer.spectra_to_monitors_list = '467,444' + self.assertEquals(467,tReducer.spectra_to_monitors_list[0]) + self.assertEquals(444,tReducer.spectra_to_monitors_list[1]) - tReducer.spectra_to_monitors_list = ['467','444']; - self.assertEquals(467,tReducer.spectra_to_monitors_list[0]); - self.assertEquals(444,tReducer.spectra_to_monitors_list[1]); + tReducer.spectra_to_monitors_list = ['467','444'] + self.assertEquals(467,tReducer.spectra_to_monitors_list[0]) + self.assertEquals(444,tReducer.spectra_to_monitors_list[1]) @@ -291,35 +288,35 @@ def test_set_spectra_to_mon(self): def test_process_copy_spectra_to_monitors(self): pass def test_set_get_ei_monitor(self): - tReducer = self.reducer; + tReducer = self.reducer self.assertEqual(41474,tReducer.ei_mon_spectra[0]) self.assertEqual(41475,tReducer.ei_mon_spectra[1]) # HOW TO MAKE IT WORK? it fails silently - # tReducer.ei_mon_spectra[1]=100; + # tReducer.ei_mon_spectra[1]=100 # self.assertEqual(41474,tReducer.ei_mon_spectra[0]) # self.assertEqual(100,tReducer.ei_mon_spectra[1]) - tReducer.ei_mon_spectra=[100,200]; + tReducer.ei_mon_spectra=[100,200] self.assertEqual(100,tReducer.ei_mon_spectra[0]) self.assertEqual(200,tReducer.ei_mon_spectra[1]) - tReducer.init_idf_params(True); + tReducer.init_idf_params(True) self.assertEqual(41474,tReducer.ei_mon_spectra[0]) self.assertEqual(41475,tReducer.ei_mon_spectra[1]) def test_load_monitors_with_workspacer(self): - tReducer =self.reducer; + tReducer =self.reducer self.assertFalse(tReducer.load_monitors_with_workspace) - tReducer.load_monitors_with_workspace=True; + tReducer.load_monitors_with_workspace=True self.assertTrue(tReducer.load_monitors_with_workspace) - tReducer.load_monitors_with_workspace=0; + tReducer.load_monitors_with_workspace=0 self.assertFalse(tReducer.load_monitors_with_workspace) - tReducer.load_monitors_with_workspace=10; + tReducer.load_monitors_with_workspace=10 self.assertTrue(tReducer.load_monitors_with_workspace) #def test_diag_call(self): @@ -331,4 +328,4 @@ def test_load_monitors_with_workspacer(self): if __name__=="__main__": - unittest.main() + unittest.main() diff --git a/Code/Mantid/scripts/test/DirectReductionHelpersTest.py b/Code/Mantid/scripts/test/DirectReductionHelpersTest.py index 9759ea4df4f7..e0878b314686 100644 --- a/Code/Mantid/scripts/test/DirectReductionHelpersTest.py +++ b/Code/Mantid/scripts/test/DirectReductionHelpersTest.py @@ -1,26 +1,26 @@ import os -#os.environ["PATH"] = r"c:/Mantid/Code/builds/br_master/bin/Release;"+os.environ["PATH"] +#os.environ["PATH"] = r"c:/Mantid/Code/builds/br_master/bin/Release"+os.environ["PATH"] from mantid.simpleapi import * from mantid import api import unittest import Direct.ReductionHelpers as helpers class SomeDescriptor(object): - def __init__(self): - self._val=None + def __init__(self): + self._val=None - def __get__(self,instance,owner=None): - if instance is None: - return self + def __get__(self,instance,owner=None): + if instance is None: + return self - return self._val + return self._val - def __set__(self,instance,value): - self._val = value - def get_helper(self): - return "using helper" - def set_helper(self,value): - self._val=value + def __set__(self,instance,value): + self._val = value + def get_helper(self): + return "using helper" + def set_helper(self,value): + self._val=value @@ -35,42 +35,42 @@ def getInstrument(InstrumentName='MAR'): idf_file=api.ExperimentInfo.getInstrumentFilename(InstrumentName) tmp_ws_name = '__empty_' + InstrumentName if not mtd.doesExist(tmp_ws_name): - LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) - return mtd[tmp_ws_name].getInstrument(); + LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) + return mtd[tmp_ws_name].getInstrument() def test_build_subst_dictionary(self): - self.assertEqual(dict(), helpers.build_subst_dictionary("")) - self.assertEqual(dict(),helpers.build_subst_dictionary()) + self.assertEqual(dict(), helpers.build_subst_dictionary("")) + self.assertEqual(dict(), helpers.build_subst_dictionary()) - self.assertRaises(AttributeError,helpers.build_subst_dictionary,10) - self.assertRaises(AttributeError,helpers.build_subst_dictionary,"A=") - self.assertRaises(AttributeError,helpers.build_subst_dictionary,"B=C;A=") + self.assertRaises(AttributeError, helpers.build_subst_dictionary, 10) + self.assertRaises(AttributeError, helpers.build_subst_dictionary, "A=") + self.assertRaises(AttributeError, helpers.build_subst_dictionary, "B=C;A=") - rez=dict(); - rez['A']='B'; - self.assertEqual(rez, helpers.build_subst_dictionary(rez)) + rez=dict() + rez['A']='B' + self.assertEqual(rez, helpers.build_subst_dictionary(rez)) - myDict = helpers.build_subst_dictionary("A=B") - self.assertEqual(myDict['B'],'A') + myDict = helpers.build_subst_dictionary("A=B") + self.assertEqual(myDict['B'],'A') - myDict = helpers.build_subst_dictionary("A=B;C=DD") - self.assertEqual(myDict['B'],'A') - self.assertEqual(myDict['DD'],'C') - myDict = helpers.build_subst_dictionary("A=B=C=DD") - self.assertEqual(myDict['B'],'A') - self.assertEqual(myDict['DD'],'A') - self.assertEqual(myDict['C'],'A') + myDict = helpers.build_subst_dictionary("A=B;C=DD") + self.assertEqual(myDict['B'],'A') + self.assertEqual(myDict['DD'],'C') + myDict = helpers.build_subst_dictionary("A=B=C=DD") + self.assertEqual(myDict['B'],'A') + self.assertEqual(myDict['DD'],'A') + self.assertEqual(myDict['C'],'A') - myDict = helpers.build_subst_dictionary("A = B = C=DD") - self.assertEqual(myDict['B'],'A') - self.assertEqual(myDict['DD'],'A') - self.assertEqual(myDict['C'],'A') + myDict = helpers.build_subst_dictionary("A = B = C=DD") + self.assertEqual(myDict['B'],'A') + self.assertEqual(myDict['DD'],'A') + self.assertEqual(myDict['C'],'A') def test_get_default_idf_param_list(self): - pInstr=self.getInstrument(); + pInstr=self.getInstrument() - param_list = helpers.get_default_idf_param_list(pInstr); + param_list = helpers.get_default_idf_param_list(pInstr) self.assertTrue(isinstance(param_list,dict)) # check couple of parameters which are certainly in IDF self.assertTrue('deltaE-mode' in param_list) @@ -79,31 +79,31 @@ def test_get_default_idf_param_list(self): def testbuild_properties_dict(self): - kkdict = {}; - kkdict['first']='kkk1:kkk2'; - kkdict['kkk1']=19; - kkdict['kkk2']=1000; - kkdict['other']='unrelated'; - kkdict['second']='ssss1:ssss2:third'; - kkdict['third']='Babara'; - - subst = {}; - subst['ssss1']='kkk1'; - subst['ssss2']='other'; + kkdict = {} + kkdict['first']='kkk1:kkk2' + kkdict['kkk1']=19 + kkdict['kkk2']=1000 + kkdict['other']='unrelated' + kkdict['second']='ssss1:ssss2:third' + kkdict['third']='Babara' + + subst = {} + subst['ssss1']='kkk1' + subst['ssss2']='other' subst_dict,descr = helpers.build_properties_dict(kkdict,subst) - self.assertEqual(len(subst_dict),6); + self.assertEqual(len(subst_dict),6) - val = subst_dict['_first']; + val = subst_dict['_first'] self.assertTrue(type(val) is helpers.ComplexProperty) - #self.assertEqual(val[0],'kkk1'); - #self.assertEqual(val[1],'kkk2'); + #self.assertEqual(val[0],'kkk1') + #self.assertEqual(val[1],'kkk2') val = subst_dict['other'] self.assertFalse(type(val) is helpers.ComplexProperty) - self.assertEqual(val,'unrelated'); + self.assertEqual(val,'unrelated') val = subst_dict['_second'] @@ -115,10 +115,10 @@ def testbuild_properties_dict(self): def testbuild_properties_dict_pref(self): - kkdict = {}; + kkdict = {} kkdict['first']='kkk1:kkk2' kkdict['kkk1']=19 - kkdict['kkk2']=1000; + kkdict['kkk2']=1000 kkdict['other']='unrelated' kkdict['second']='ssss1:ssss2:third' kkdict['third']='Babara' @@ -144,12 +144,12 @@ def testbuild_properties_dict_pref(self): val = prop_dict['_first'] self.assertTrue(type(val) is helpers.ComplexProperty) - #elf.assertEqual(val[0],'_kkk1'); - #self.assertEqual(val[1],'_kkk2'); + #elf.assertEqual(val[0],'_kkk1') + #self.assertEqual(val[1],'_kkk2') val = prop_dict['other'] self.assertFalse(type(val) is helpers.ComplexProperty) - self.assertEqual(val,'unrelated'); + self.assertEqual(val,'unrelated') val = prop_dict['_second'] self.assertTrue(type(val) is helpers.ComplexProperty) @@ -165,34 +165,34 @@ def testbuild_properties_dict_pref(self): def test_build_properties_dict_ksubst(self): - kkdict = {}; - kkdict['first']='kkk1:kkk2'; - kkdict['kkk1']=19; - kkdict['kkk2']=1000; - kkdict['other']='unrelated'; - kkdict['second']='ssss1:ssss2:third'; - kkdict['third']='Babara'; - - subst = {}; - subst['first']=1; - subst['ssss1']='kkk1'; - subst['ssss2']='other'; - subst['third']=3; - subst['second']=2; + kkdict = {} + kkdict['first']='kkk1:kkk2' + kkdict['kkk1']=19 + kkdict['kkk2']=1000 + kkdict['other']='unrelated' + kkdict['second']='ssss1:ssss2:third' + kkdict['third']='Babara' + + subst = {} + subst['first']=1 + subst['ssss1']='kkk1' + subst['ssss2']='other' + subst['third']=3 + subst['second']=2 subst_dict,descr_dict = helpers.build_properties_dict(kkdict,subst) - self.assertEqual(len(subst_dict),6); + self.assertEqual(len(subst_dict),6) val = subst_dict['_1'] self.assertTrue(type(val) is helpers.ComplexProperty) - #self.assertEqual(val[0],'kkk1'); - #self.assertEqual(val[1],'kkk2'); + #self.assertEqual(val[0],'kkk1') + #self.assertEqual(val[1],'kkk2') val = subst_dict['other'] self.assertFalse(type(val) is helpers.ComplexProperty) - self.assertEqual(val,'unrelated'); + self.assertEqual(val,'unrelated') val = subst_dict['_2'] self.assertTrue(type(val) is helpers.ComplexProperty) @@ -202,55 +202,55 @@ def test_build_properties_dict_ksubst(self): #self.assertEqual(val[2],'3') def test_gen_getter(self): - kkdict = {}; - kkdict['first']='kkk1:kkk2'; - kkdict['kkk1']=19; - kkdict['kkk2']=1000; - kkdict['other']='unrelated'; - kkdict['second']='ssss1:ssss2:third'; - kkdict['third']='Babara'; - - subst = {}; - subst['ssss1']='kkk1'; - subst['ssss2']='other'; + kkdict = {} + kkdict['first']='kkk1:kkk2' + kkdict['kkk1']=19 + kkdict['kkk2']=1000 + kkdict['other']='unrelated' + kkdict['second']='ssss1:ssss2:third' + kkdict['third']='Babara' + + subst = {} + subst['ssss1']='kkk1' + subst['ssss2']='other' subst_dict,descr = helpers.build_properties_dict(kkdict,subst) - self.assertEqual(helpers.gen_getter(subst_dict,'kkk1'),19); - self.assertEqual(helpers.gen_getter(subst_dict,'kkk2'),1000); - self.assertEqual(helpers.gen_getter(subst_dict,'first'),[19,1000]); - self.assertEqual(helpers.gen_getter(subst_dict,'other'),'unrelated'); - self.assertEqual(helpers.gen_getter(subst_dict,'second'),[19,'unrelated','Babara']); - self.assertEqual(helpers.gen_getter(subst_dict,'third'),'Babara'); + self.assertEqual(helpers.gen_getter(subst_dict,'kkk1'),19) + self.assertEqual(helpers.gen_getter(subst_dict,'kkk2'),1000) + self.assertEqual(helpers.gen_getter(subst_dict,'first'),[19,1000]) + self.assertEqual(helpers.gen_getter(subst_dict,'other'),'unrelated') + self.assertEqual(helpers.gen_getter(subst_dict,'second'),[19,'unrelated','Babara']) + self.assertEqual(helpers.gen_getter(subst_dict,'third'),'Babara') def test_gen_setter(self): - kkdict = {}; - kkdict['A']=helpers.ComplexProperty(['B','C']); - kkdict['B']=19; - kkdict['C']=1000; - + kkdict = {} + kkdict['A']=helpers.ComplexProperty(['B','C']) + kkdict['B']=19 + kkdict['C']=1000 + helpers.gen_setter(kkdict,'B',0) - self.assertEqual(kkdict['B'],0); + self.assertEqual(kkdict['B'],0) helpers.gen_setter(kkdict,'C',10) - self.assertEqual(kkdict['C'],10); + self.assertEqual(kkdict['C'],10) self.assertRaises(KeyError,helpers.gen_setter,kkdict,'A',100) - self.assertEqual(kkdict['B'],0); + self.assertEqual(kkdict['B'],0) helpers.gen_setter(kkdict,'A',[1,10]) - self.assertEqual(kkdict['B'],1); - self.assertEqual(kkdict['C'],10); + self.assertEqual(kkdict['B'],1) + self.assertEqual(kkdict['C'],10) def test_class_property_setter(self): - + class test_class(object): def __init__(self): object.__setattr__(self,'A',helpers.ComplexProperty(['B','C'])) #kkdict['A']= - kkdict = {}; - kkdict['B']=19; - kkdict['C']=1000; + kkdict = {} + kkdict['B']=19 + kkdict['C']=1000 self.__dict__.update(kkdict) oveloaded_prop = SomeDescriptor() @@ -269,130 +269,130 @@ def __setattr__(self,name,val): #object.__setattr__(self,name,val) return raise KeyError("Property {0} is not defined for class {1}".format(name,self.__class__)) - #helpers.gen_setter(self,name,val); + #helpers.gen_setter(self,name,val) #object.__setattr__(self,name,val) - + def __getattribute__(self,name): if name[:2] == '__': - attr = object.__getattribute__(self,name); + attr = object.__getattribute__(self,name) return attr else: - attr_dic = object.__getattribute__(self,'__dict__'); + attr_dic = object.__getattribute__(self,'__dict__') if name is '__dict__': - return attr_dic; + return attr_dic else: return helpers.gen_getter(attr_dic,name) pass - t1 =test_class(); + t1 =test_class() - self.assertEqual(t1.B,19); + self.assertEqual(t1.B,19) - t1.B=0; - self.assertEqual(t1.B,0); + t1.B=0 + self.assertEqual(t1.B,0) self.assertRaises(KeyError,setattr,t1,'non_existing_property','some value') - t1.A = [1,10]; - self.assertEqual(t1.A,[1,10]); + t1.A = [1,10] + self.assertEqual(t1.A,[1,10]) # This does not work as the assignment occurs to temporary vector # lets ban partial assignment - #t1.D[0] = 200; - #self.assertEqual(t1.B,200); - # This kind of assignment requests the whole list to be setup + #t1.D[0] = 200 + #self.assertEqual(t1.B,200) + # This kind of assignment requests the whole list to be setup self.assertRaises(KeyError,setattr,t1,'A',200) # Very bad -- fails silently - t1.A[0] = 10; - self.assertEqual(t1.A,[1,10]); + t1.A[0] = 10 + self.assertEqual(t1.A,[1,10]) t1.oveloaded_prop = 'BlaBla' #And this become too complicated:: to implement access to __class__.__dict__ - #self.assertEqual(t1.oveloaded_prop ,'BlaBla'); + #self.assertEqual(t1.oveloaded_prop ,'BlaBla') def test_class_property_setter2(self): class test_class(object): def __init__(self): - kkdict = {}; - kkdict['_A']=helpers.ComplexProperty(['B','C']); - kkdict['B']=19; - kkdict['C']=1000; - class_decor = '_'+type(self).__name__; + kkdict = {} + kkdict['_A']=helpers.ComplexProperty(['B','C']) + kkdict['B']=19 + kkdict['C']=1000 + class_decor = '_'+type(self).__name__ - kkdict[class_decor+'__special']='D'; + kkdict[class_decor+'__special']='D' self.__dict__.update(kkdict) some_descriptor = SomeDescriptor() def __setattr__(self,name,val): if name is 'special': - return; + return elif name in self.__class__.__dict__: fp = self.__class__.__dict__[name] fp.__set__(self,val) else: - helpers.gen_setter(self.__dict__,name,val); + helpers.gen_setter(self.__dict__,name,val) + - def __getattr__(self,name): if name is 'special': - return self.__special; + return self.__special else: - tDict = object.__getattribute__(self,'__dict__'); + tDict = object.__getattribute__(self,'__dict__') return helpers.gen_getter(tDict,name) - + def access(self,obj_name): - try: - obj = self.__class__.__dict__[obj_name] - return obj - except: - priv_name = '_'+obj_name - if priv_name in self.__dict__: - return self.__dict__[priv_name] - else: - raise KeyError("Property {0} is not among class descriptors or complex properties ".format(obj_name)) - + try: + obj = self.__class__.__dict__[obj_name] + return obj + except: + priv_name = '_'+obj_name + if priv_name in self.__dict__: + return self.__dict__[priv_name] + else: + raise KeyError("Property {0} is not among class descriptors or complex properties ".format(obj_name)) + t1 =test_class() - self.assertEqual(t1.B,19); + self.assertEqual(t1.B,19) - t1.B=0; - self.assertEqual(t1.B,0); + t1.B=0 + self.assertEqual(t1.B,0) self.assertRaises(KeyError,setattr,t1,'non_existing_property','some value') - t1.A = [1,10]; - self.assertEqual(t1.A,[1,10]); + t1.A = [1,10] + self.assertEqual(t1.A,[1,10]) # This does not work as the assignment occurs to temporary vector # lets ban partial assignment - #t1.D[0] = 200; - #self.assertEqual(t1.B,200); - # This kind of assignment requests the whole list to be setup + #t1.D[0] = 200 + #self.assertEqual(t1.B,200) + # This kind of assignment requests the whole list to be setup self.assertRaises(KeyError,setattr,t1,'A',200) # Very bad -- fails silently - t1.A[0] = 10; - self.assertEqual(t1.A,[1,10]); + t1.A[0] = 10 + self.assertEqual(t1.A,[1,10]) - t1.special = 10; - self.assertEqual(t1.special,'D'); + t1.special = 10 + self.assertEqual(t1.special,'D') t1.some_descriptor = 'blaBla' - self.assertEqual(t1.some_descriptor ,'blaBla'); + self.assertEqual(t1.some_descriptor ,'blaBla') - self.assertEqual(t1.access('some_descriptor').get_helper() ,'using helper'); + self.assertEqual(t1.access('some_descriptor').get_helper() ,'using helper') t1.access('some_descriptor').set_helper('other') - self.assertEqual(t1.some_descriptor ,'other'); + self.assertEqual(t1.some_descriptor ,'other') dep = t1.access('A').dependencies() self.assertEqual(dep[0],'B') @@ -406,14 +406,14 @@ def __init__(self): for meth in all_methods: if meth[:1] != '_': existing.append(meth) - kkdict = {}; - kkdict['_A']=helpers.ComplexProperty(['B','C']); - kkdict['B']=19; - kkdict['C']=1000; + kkdict = {} + kkdict['_A']=helpers.ComplexProperty(['B','C']) + kkdict['B']=19 + kkdict['C']=1000 - class_decor = '_'+type(self).__name__; + class_decor = '_'+type(self).__name__ object.__setattr__(self,class_decor+'__exmeth',existing) - + self.__dict__.update(kkdict) @@ -423,57 +423,57 @@ def __setattr__(self,name,val): if name in self.__exmeth: object.__setattr__(self,name,val) else: - helpers.gen_setter(self.__dict__,name,val); + helpers.gen_setter(self.__dict__,name,val) #raise KeyError("Property {0} is not among recognized properties".format(name)) def __getattr__(self,name): - return helpers.gen_getter(self.__dict__,name); + return helpers.gen_getter(self.__dict__,name) + - def access(self,obj_name): - try: - obj = self.__class__.__dict__[obj_name] - return obj - except: - priv_name = '_'+obj_name - if priv_name in self.__dict__: - return self.__dict__[priv_name] - else: - raise KeyError("Property {0} is not among class descriptors or complex properties ".format(obj_name)) - + try: + obj = self.__class__.__dict__[obj_name] + return obj + except: + priv_name = '_'+obj_name + if priv_name in self.__dict__: + return self.__dict__[priv_name] + else: + raise KeyError("Property {0} is not among class descriptors or complex properties ".format(obj_name)) + t1 =test_class() - self.assertEqual(t1.B,19); + self.assertEqual(t1.B,19) - t1.B=0; - self.assertEqual(t1.B,0); + t1.B=0 + self.assertEqual(t1.B,0) self.assertRaises(KeyError,setattr,t1,'non_existing_property','some value') - t1.A = [1,10]; - self.assertEqual(t1.A,[1,10]); + t1.A = [1,10] + self.assertEqual(t1.A,[1,10]) # This does not work as the assignment occurs to temporary vector # lets ban partial assignment - #t1.D[0] = 200; - #self.assertEqual(t1.B,200); - # This kind of assignment requests the whole list to be setup + #t1.D[0] = 200 + #self.assertEqual(t1.B,200) + # This kind of assignment requests the whole list to be setup self.assertRaises(KeyError,setattr,t1,'A',200) # Very bad -- fails silently - t1.A[0] = 10; - self.assertEqual(t1.A,[1,10]); + t1.A[0] = 10 + self.assertEqual(t1.A,[1,10]) t1.some_descriptor = 'blaBla' - self.assertEqual(t1.some_descriptor ,'blaBla'); + self.assertEqual(t1.some_descriptor ,'blaBla') self.assertEqual(t1.access('some_descriptor').get_helper() ,'using helper') t1.access('some_descriptor').set_helper('other') - self.assertEqual(t1.some_descriptor ,'other'); + self.assertEqual(t1.some_descriptor ,'other') dep = t1.access('A').dependencies() self.assertEqual(dep[0],'B') @@ -501,10 +501,7 @@ def test_split_file_name(self): self.assertEqual(len(nums),5) - -if __name__=="__main__": - unittest.main() - - +if __name__=="__main__": + unittest.main() diff --git a/Code/Mantid/scripts/test/IndirectApplyCorrectionsTest.py b/Code/Mantid/scripts/test/IndirectApplyCorrectionsTest.py index 6c99dc274fa5..3d1762cdc58c 100644 --- a/Code/Mantid/scripts/test/IndirectApplyCorrectionsTest.py +++ b/Code/Mantid/scripts/test/IndirectApplyCorrectionsTest.py @@ -30,6 +30,9 @@ def _decorator(self, *args, **kwargs): class ApplyCorrectionsTests(unittest.TestCase): def setUp(self): + self._config_defaults = config + config['default.facility'] = 'ISIS' + self._sample_workspace = self.make_sample_workspace() self._can_workspace = '' self._corrections_workspace = '' @@ -49,6 +52,8 @@ def tearDown(self): mtd.clear() self.clean_up_saved_workspaces() + config = self._config_defaults + @setup_can_test def test_with_can_workspace(self): output_workspaces = self.run_apply_corrections() diff --git a/Code/Mantid/scripts/test/IndirectCommonTests.py b/Code/Mantid/scripts/test/IndirectCommonTests.py index db4249d96b49..48b88d94cdbc 100644 --- a/Code/Mantid/scripts/test/IndirectCommonTests.py +++ b/Code/Mantid/scripts/test/IndirectCommonTests.py @@ -16,23 +16,11 @@ class IndirectCommonTests(unittest.TestCase): def setUp(self): self._config_defaults = config + config['default.facility'] = 'ISIS' def tearDown(self): config = self._config_defaults - def test_loadInst(self): - indirect_common.loadInst('IRIS') - - ws_name = '__empty_IRIS' - ws = mtd[ws_name] - instrument = ws.getInstrument() - self.assertEqual(instrument.getName(), 'IRIS') - - def test_loadNexus(self): - ws_name = indirect_common.loadNexus('IRS26173_ipg.nxs') - self.assertEqual(ws_name, 'IRS26173_ipg') - self.assertTrue(mtd.doesExist(ws_name)) - def test_getInstrRun_from_name(self): ws = self.make_dummy_QENS_workspace() (instrument, run_number) = indirect_common.getInstrRun(ws) diff --git a/Code/Mantid/scripts/test/MariReduction.py b/Code/Mantid/scripts/test/MariReduction.py index 4c7f2909eda2..44a63b6fa310 100644 --- a/Code/Mantid/scripts/test/MariReduction.py +++ b/Code/Mantid/scripts/test/MariReduction.py @@ -1,4 +1,4 @@ -""" Sample MARI reduction scrip used in testing ReductionWrapper """ +""" Sample MARI reduction scrip used in testing ReductionWrapper """ from Direct.ReductionWrapper import * try: @@ -11,49 +11,49 @@ class ReduceMARI(ReductionWrapper): #-------------------------------------------------------------------------------------------------# - @MainProperties - def def_main_properties(self): - """ Define main properties used in reduction """ - prop = {} - prop['sample_run'] = 11001 - prop['wb_run'] = 11060 - prop['incident_energy'] = 12 - prop['energy_bins'] = [-11,0.05,11] + @MainProperties + def def_main_properties(self): + """ Define main properties used in reduction """ + prop = {} + prop['sample_run'] = 11001 + prop['wb_run'] = 11060 + prop['incident_energy'] = 12 + prop['energy_bins'] = [-11,0.05,11] - # Absolute units reduction properties. - prop['monovan_run'] = 11015 - prop['sample_mass'] = 10 - prop['sample_rmm'] = 435.96 - return prop + # Absolute units reduction properties. + prop['monovan_run'] = 11015 + prop['sample_mass'] = 10 + prop['sample_rmm'] = 435.96 + return prop #-------------------------------------------------------------------------------------------------# - @AdvancedProperties - def def_advanced_properties(self): - """ separation between simple and advanced properties depends - on scientist, experiment and user. - main properties override advanced properties. - """ - prop = {} - prop['map_file'] = "mari_res.map" - prop['monovan_mapfile'] = "mari_res.map" - prop['hard_mask_file'] = "mar11015.msk" - prop['det_cal_file'] = "11060" - prop['save_format'] = '' - return prop + @AdvancedProperties + def def_advanced_properties(self): + """ separation between simple and advanced properties depends + on scientist, experiment and user. + main properties override advanced properties. + """ + prop = {} + prop['map_file'] = "mari_res.map" + prop['monovan_mapfile'] = "mari_res.map" + prop['hard_mask_file'] = "mar11015.msk" + prop['det_cal_file'] = "11060" + prop['save_format'] = '' + return prop # #-------------------------------------------------------------------------------------------------# - @iliad - def reduce(self,input_file=None,output_directory=None): - """ Method executes reduction over single file + @iliad + def reduce(self,input_file=None,output_directory=None): + """ Method executes reduction over single file - Overload only if custom reduction is needed - """ - ws = ReductionWrapper.reduce(input_file,output_directory) - #SaveNexus(ws,Filename = 'MARNewReduction.nxs') - return ws + Overload only if custom reduction is needed + """ + ws = ReductionWrapper.reduce(input_file,output_directory) + #SaveNexus(ws,Filename = 'MARNewReduction.nxs') + return ws - def __init__(self,web_var=None): - """ sets properties defaults for the instrument with Name""" - ReductionWrapper.__init__(self,'MAR',web_var) + def __init__(self,web_var=None): + """ sets properties defaults for the instrument with Name""" + ReductionWrapper.__init__(self,'MAR',web_var) #-------------------------------------------------------------------------------------------------# #-------------------------------------------------------------------------------------------------# #-------------------------------------------------------------------------------------------------# @@ -64,10 +64,10 @@ def main(input_file=None,output_directory=None): exception to change the output folder to save data to """ - # note web variables initialization + # note web variables initialization rd = ReduceMARI(web_var) rd.reduce(input_file,output_directory) - + # Define folder for web service to copy results to output_folder = '' return output_folder @@ -77,30 +77,30 @@ def main(input_file=None,output_directory=None): # SECTION USED TO RUN REDUCTION FROM MANTID SCRIPT WINDOW # #-------------------------------------------------------------------------------------------------# ##### Here one sets up folders where to find input data and where to save results ##### - # It can be done here or from Mantid GUI + # It can be done here or from Mantid GUI # Folder where map files are located: - map_mask_dir = 'd:/Data/MantidSystemTests/Data' + map_mask_dir = 'd:/Data/MantidSystemTests/Data' # folder where input data can be found - data_dir = 'd:/Data/Mantid_Testing/14_11_27' - # auxiliary folder with results - ref_data_dir = 'd:/Data/MantidSystemTests/SystemTests/AnalysisTests/ReferenceResults' - # Set input path to - config.setDataSearchDirs('{0};{1};{2}'.format(data_dir,map_mask_dir,ref_data_dir)) - # use appendDataSearch directory to add to existing data search path - #config.appendDataSearchDir('d:/Data/Mantid_GIT/Test/AutoTestData') - # folder to save resulting spe/nxspe files. - config['defaultsave.directory'] = data_dir + data_dir = 'd:/Data/Mantid_Testing/14_11_27' + # auxiliary folder with results + ref_data_dir = 'd:/Data/MantidSystemTests/SystemTests/AnalysisTests/ReferenceResults' + # Set input path to + config.setDataSearchDirs('{0};{1};{2}'.format(data_dir,map_mask_dir,ref_data_dir)) + # use appendDataSearch directory to add to existing data search path + #config.appendDataSearchDir('d:/Data/Mantid_GIT/Test/AutoTestData') + # folder to save resulting spe/nxspe files. + config['defaultsave.directory'] = data_dir ###### Initialize reduction class above and set up reduction properties. Note no parameters ###### - rd = ReduceMARI() - # set up advanced and main properties - rd.def_advanced_properties() - rd.def_main_properties() + rd = ReduceMARI() + # set up advanced and main properties + rd.def_advanced_properties() + rd.def_main_properties() - # uncomment rows below to save web variables to use in web services. - #run_dir = os.path.dirname(os.path.realpath(__file__)) - #file = os.path.join(run_dir,'reduce_vars.py') - #rd.save_web_variables(file) + # uncomment rows below to save web variables to use in web services. + #run_dir = os.path.dirname(os.path.realpath(__file__)) + #file = os.path.join(run_dir,'reduce_vars.py') + #rd.save_web_variables(file) - rd.reduce() + rd.reduce() diff --git a/Code/Mantid/scripts/test/ReductionSettingsTest.py b/Code/Mantid/scripts/test/ReductionSettingsTest.py index 3b4a2b51d0a4..ac4491750ad1 100644 --- a/Code/Mantid/scripts/test/ReductionSettingsTest.py +++ b/Code/Mantid/scripts/test/ReductionSettingsTest.py @@ -74,4 +74,5 @@ def test_clone_name_already_exists_is_cleared(self): self.assertFalse("a" in c) if __name__ == '__main__': - unittest.main() \ No newline at end of file + unittest.main() + diff --git a/Code/Mantid/scripts/test/ReductionWrapperTest.py b/Code/Mantid/scripts/test/ReductionWrapperTest.py index ed8b1e042043..cda0accc84f1 100644 --- a/Code/Mantid/scripts/test/ReductionWrapperTest.py +++ b/Code/Mantid/scripts/test/ReductionWrapperTest.py @@ -20,7 +20,6 @@ class ReductionWrapperTest(unittest.TestCase): def __init__(self, methodName): return super(ReductionWrapperTest, self).__init__(methodName) - pass def setUp(self): pass @@ -80,5 +79,5 @@ def test_export_advanced_values(self): os.remove(fcomp) if __name__=="__main__": - unittest.main() + unittest.main() diff --git a/Code/Mantid/scripts/test/RunDescriptorTest.py b/Code/Mantid/scripts/test/RunDescriptorTest.py index 77a7ecb06a12..5ab61fe01be7 100644 --- a/Code/Mantid/scripts/test/RunDescriptorTest.py +++ b/Code/Mantid/scripts/test/RunDescriptorTest.py @@ -1,5 +1,5 @@ import os,sys,inspect -#os.environ["PATH"] = r"c:/Mantid/Code/builds/br_master/bin/Release;"+os.environ["PATH"] +#os.environ["PATH"] = r"c:/Mantid/Code/builds/br_master/bin/Release"+os.environ["PATH"] from mantid.simpleapi import * from mantid import api import unittest @@ -20,7 +20,7 @@ def __init__(self, methodName): def setUp(self): if self.prop_man == None or type(self.prop_man) != type(PropertyManager): - self.prop_man = PropertyManager("MAR"); + self.prop_man = PropertyManager("MAR") def tearDown(self): pass @@ -31,17 +31,17 @@ def getInstrument(InstrumentName='MAR'): idf_file=api.ExperimentInfo.getInstrumentFilename(InstrumentName) tmp_ws_name = '__empty_' + InstrumentName if not mtd.doesExist(tmp_ws_name): - LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) + LoadEmptyInstrument(Filename=idf_file,OutputWorkspace=tmp_ws_name) return mtd[tmp_ws_name].getInstrument() - + def test_descr_basic(self): propman = PropertyManager('MAR') self.assertTrue(propman.sample_run is None) self.assertTrue(PropertyManager.sample_run.get_workspace() is None) - - propman.sample_run = 10; + + propman.sample_run = 10 self.assertEqual(propman.sample_run,10) run_ws = CreateSampleWorkspace( Function='Multiple Peaks', NumBanks=1, BankPixelWidth=4, NumEvents=100) @@ -84,7 +84,7 @@ def test_find_file(self): # create two test files to check search for appropriate extension f=open(testFile1,'w') - f.write('aaaaaa'); + f.write('aaaaaa') f.close() f=open(testFile2,'w') @@ -118,8 +118,8 @@ def test_load_workspace(self): mon_ws = PropertyManager.sample_run.get_monitors_ws() self.assertTrue(isinstance(mon_ws, api.Workspace)) - self.assertEqual(mon_ws.name(),ws.name()) - + self.assertEqual(mon_ws.name(),ws.name()) + def test_copy_spectra2monitors(self): propman = self.prop_man run_ws = CreateSampleWorkspace( Function='Multiple Peaks', WorkspaceType = 'Event',NumBanks=1, BankPixelWidth=5, NumEvents=100) @@ -183,7 +183,7 @@ def test_ws_name(self): propman.sample_run = None self.assertFalse(ws_name+'_monitors' in mtd) - # name of empty property workspace + # name of empty property workspace self.assertEqual(PropertyManager.sample_run.get_ws_name(),'SR_') @@ -231,7 +231,7 @@ def test_sum_runs(self): self.assertEqual(ws.name(),ws_name) - + def test_assign_fname(self): propman = self.prop_man propman.sample_run = 'MAR11001.RAW' @@ -330,7 +330,7 @@ def test_chop_ws_part(self): api.AnalysisDataService.clear() - + if __name__=="__main__": unittest.main() diff --git a/Code/Mantid/scripts/test/SANSUtilitytests.py b/Code/Mantid/scripts/test/SANSUtilitytests.py index 764ab7cbc3f6..81ff7648cb09 100644 --- a/Code/Mantid/scripts/test/SANSUtilitytests.py +++ b/Code/Mantid/scripts/test/SANSUtilitytests.py @@ -6,7 +6,7 @@ class TestSliceStringParser(unittest.TestCase): def checkValues(self, list1, list2): def _check_single_values( v1, v2): - self.assertAlmostEqual(v1, v2) + self.assertAlmostEqual(v1, v2) self.assertEqual(len(list1), len(list2)) for v1,v2 in zip(list1, list2): diff --git a/Code/Tools/Pylint/pylint.cfg b/Code/Tools/Pylint/pylint.cfg index e3675ca90a4e..45bc53816b56 100644 --- a/Code/Tools/Pylint/pylint.cfg +++ b/Code/Tools/Pylint/pylint.cfg @@ -81,7 +81,7 @@ comment=no [FORMAT] # Maximum number of characters on a single line. -max-line-length=100 +max-line-length=140 # Maximum number of lines in a module max-module-lines=1000 @@ -213,16 +213,16 @@ max-args=5 ignored-argument-names=_.* # Maximum number of locals for function / method body -max-locals=15 +max-locals=25 # Maximum number of return / yield for function / method body max-returns=6 # Maximum number of branch for function / method body -max-branchs=12 +max-branchs=25 # Maximum number of statements in function / method body -max-statements=50 +max-statements=150 # Maximum number of parents for a class (see R0901). max-parents=7 diff --git a/README.md b/README.md index 71a05dea8d76..0057183c12e8 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ Useful links ------------ * Homepage: http://www.mantidproject.org * Download: http://download.mantidproject.org - * Asking for help: http://download.mantidproject.org/webmailer/index.php + * Asking for help: http://www.mantidproject.org/Contact * Issue tracking: http://trac.mantidproject.org/mantid/ * Build server: http://builds.mantidproject.org * Developer site: http://developer.mantidproject.org diff --git a/Test/AutoTestData/UsageData/INES_Definition.vtp b/Test/AutoTestData/UsageData/INES_Definition.vtp deleted file mode 100644 index 23a71effa310..000000000000 --- a/Test/AutoTestData/UsageData/INES_Definition.vtp +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - -