diff --git a/Framework/PythonInterface/plugins/algorithms/GSASIIRefineFitPeaks.py b/Framework/PythonInterface/plugins/algorithms/GSASIIRefineFitPeaks.py
index 4bf52120e8fd7c36082ea84f286e1825fd52861c..d7b86221146e43e69cbd279f367ae3a2f97b6238 100644
--- a/Framework/PythonInterface/plugins/algorithms/GSASIIRefineFitPeaks.py
+++ b/Framework/PythonInterface/plugins/algorithms/GSASIIRefineFitPeaks.py
@@ -470,6 +470,8 @@ class GSASIIRefineFitPeaks(PythonAlgorithm):
         @return a tuple with: 1) a tuple with the Rwp and GoF values (weighted profile
         R-factor, goodness of fit), 2) the parameters dictionary
         """
+        import GSASIIpwd
+
         (limits, peaks_list, background_def) = fit_inputs
         (inst_parm1, inst_parm2) = gs2_rd.pwdparms['Instrument Parameters']
         # peaks: ['pos','int','alp','bet','sig','gam'] / with the refine flag each
@@ -538,6 +540,8 @@ class GSASIIRefineFitPeaks(PythonAlgorithm):
         # algorithm finishes and is destroyed!
         # This seems to destroy/close safely
         import wx
+        import GSASII
+
         self._gsas2_app = wx.App()
 
         gs2 = GSASII.GSASII(None)
@@ -700,7 +704,7 @@ class GSASIIRefineFitPeaks(PythonAlgorithm):
                                                             usedRanIdList=['noGUI'], Start=False)
         if err_msg:
             raise RuntimeError("There was a problem while importing the phase information file ({0}. "
-                               "Error details: {1}".format(phase_filename, errm_msg))
+                               "Error details: {1}".format(phase_filename, err_msg))
 
         phase_reader = phase_readers_list[0]
         GSASIIphsGUI.SetupGeneralWithoutGUI(gs2, phase_reader.Phase)
@@ -744,7 +748,9 @@ class GSASIIRefineFitPeaks(PythonAlgorithm):
 
         @param phase_data :: from GSAS-II, the first entry in 'Phases'
         """
+        import GSASII
         import GSASIIspc
+
         SGData = phase_data['General']['SGData']
         use_list = phase_data['Histograms']
         NShkl = len(GSASIIspc.MustrainNames(SGData))
diff --git a/Framework/PythonInterface/plugins/algorithms/RefLReduction.py b/Framework/PythonInterface/plugins/algorithms/RefLReduction.py
index 5da86fd3a5bbc0b31f0a38f1d395e233bdabc6b3..f3779d9528b4347793eea11ebfe04822258c0c3b 100644
--- a/Framework/PythonInterface/plugins/algorithms/RefLReduction.py
+++ b/Framework/PythonInterface/plugins/algorithms/RefLReduction.py
@@ -181,14 +181,6 @@ class RefLReduction(PythonAlgorithm):
         is_nexus_detector_rotated_flag = wks_utility.isNexusTakeAfterRefDate(ws_event_data.getRun().getProperty('run_start').value)
         print('-> is NeXus taken with new detector geometry: ' + str(is_nexus_detector_rotated_flag))
 
-        #dimension of the detector (256 by 304 pixels)
-        if is_nexus_detector_rotated_flag:
-            maxX = 256
-            maxY = 304
-        else:
-            maxX = 304
-            maxY = 256
-
         ## retrieve general informations
         # calculate the central pixel (using weighted average)
         print('-> retrieving general informations')
diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py
index ae543a541616c1167211ac1502365103b7e308f5..666057fedeffefd5400e51c5f236a09a8bf23434 100644
--- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py
+++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py
@@ -302,12 +302,6 @@ def subtract_dark_current(self, workspace, property_manager):
     use_sample_dc = self.getProperty("UseSampleDarkCurrent").value
     dark_current_data = self.getPropertyValue("DarkCurrentFilename")
     property_manager_name = self.getProperty("ReductionProperties").value
-    # Get instrument to use with FileFinder
-    #instrument = ''
-    #if property_manager.existsProperty("InstrumentName"):
-    #    instrument = property_manager.getProperty("InstrumentName").value
-
-    dark_current_property = "DefaultDarkCurrentAlgorithm"
 
     def _dark(ws, dark_current_property, dark_current_file=None):
         if property_manager.existsProperty(dark_current_property):
diff --git a/Testing/SystemTests/tests/analysis/EQSANSBeamCenterAPIv2.py b/Testing/SystemTests/tests/analysis/EQSANSBeamCenterAPIv2.py
index 1b412bdc0637fe6398dbe8094bacb18d9edef369..982b6cc5471c45d1d564126578e22c816034f32b 100644
--- a/Testing/SystemTests/tests/analysis/EQSANSBeamCenterAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/EQSANSBeamCenterAPIv2.py
@@ -1,9 +1,11 @@
 #pylint: disable=no-init,attribute-defined-outside-init
 import stresstesting
 from mantid.simpleapi import *
-from reduction_workflow.instruments.sans.sns_command_interface import *
 from mantid.api import *
 
+from reduction_workflow.instruments.sans.sns_command_interface import *
+from reduction_workflow.instruments.sans.hfir_command_interface import DirectBeamCenter, NoSolidAngle, SetTransmission
+
 import os
 
 
diff --git a/Testing/SystemTests/tests/analysis/EQSANSDarkCurrentAPIv2.py b/Testing/SystemTests/tests/analysis/EQSANSDarkCurrentAPIv2.py
index 59851d70863a350ec17e560b5ea5c49f9c0c0f0b..4385450b9ca03f1edf2c288c95b2956e272aaee1 100644
--- a/Testing/SystemTests/tests/analysis/EQSANSDarkCurrentAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/EQSANSDarkCurrentAPIv2.py
@@ -2,6 +2,7 @@
 import stresstesting
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.sns_command_interface import *
+from reduction_workflow.instruments.sans.hfir_command_interface import DarkCurrent,SetTransmission
 from mantid.api import *
 
 import os
diff --git a/Testing/SystemTests/tests/analysis/EQSANSEffAPIv2.py b/Testing/SystemTests/tests/analysis/EQSANSEffAPIv2.py
index 5baca714eb34699552cc164f231c6e19d15bfadd..9435a56ca14cccd4e62fbba1720f730ce546d419 100644
--- a/Testing/SystemTests/tests/analysis/EQSANSEffAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/EQSANSEffAPIv2.py
@@ -2,6 +2,7 @@
 import stresstesting
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.sns_command_interface import *
+from reduction_workflow.instruments.sans.hfir_command_interface import SensitivityCorrection, SetTransmission
 from mantid.api import FileFinder
 
 import os
diff --git a/Testing/SystemTests/tests/analysis/EQSANSFlatTestAPIv2.py b/Testing/SystemTests/tests/analysis/EQSANSFlatTestAPIv2.py
index defe5ed58801cf96c9c603354689547452397c4e..987dbfc82ed514451a7d0404f878d5e1b4ea44d7 100644
--- a/Testing/SystemTests/tests/analysis/EQSANSFlatTestAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/EQSANSFlatTestAPIv2.py
@@ -2,6 +2,7 @@
 import stresstesting
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.sns_command_interface import *
+from reduction_workflow.instruments.sans.hfir_command_interface import *
 
 FILE_LOCATION = "/SNS/EQSANS/IPTS-5636/data/"
 
diff --git a/Testing/SystemTests/tests/analysis/EQSANSIQOutputAPIv2.py b/Testing/SystemTests/tests/analysis/EQSANSIQOutputAPIv2.py
index 06e12aca27d2494c8d9674c0ddc70f18cbd595a0..ab569c401bd75b9ace1dfb3699fbd10a7c879218 100644
--- a/Testing/SystemTests/tests/analysis/EQSANSIQOutputAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/EQSANSIQOutputAPIv2.py
@@ -4,6 +4,7 @@ import math
 import os
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.sns_command_interface import *
+from reduction_workflow.instruments.sans.hfir_command_interface import *
 from mantid.api import *
 
 
diff --git a/Testing/SystemTests/tests/analysis/EQSANSProcessedEffAPIv2.py b/Testing/SystemTests/tests/analysis/EQSANSProcessedEffAPIv2.py
index bb2bc5f7b3b1bad72903d3e9d7d3dda722225df4..5c58f593d89b9772174f23eee7ea19f59991e068 100644
--- a/Testing/SystemTests/tests/analysis/EQSANSProcessedEffAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/EQSANSProcessedEffAPIv2.py
@@ -2,6 +2,7 @@
 import stresstesting
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.sns_command_interface import *
+from reduction_workflow.instruments.sans.hfir_command_interface import SensitivityCorrection, SetTransmission
 from mantid.api import FileFinder
 
 import os
diff --git a/Testing/SystemTests/tests/analysis/EQSANSSolidAPIv2.py b/Testing/SystemTests/tests/analysis/EQSANSSolidAPIv2.py
index 125b40c3046f3adda65c380db7ca9ee6745be8e8..f518d2ca37e720e53c41bd7aa91b52a0ff41df5f 100644
--- a/Testing/SystemTests/tests/analysis/EQSANSSolidAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/EQSANSSolidAPIv2.py
@@ -2,6 +2,7 @@
 import stresstesting
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.sns_command_interface import *
+from reduction_workflow.instruments.sans.hfir_command_interface import *
 from mantid.api import *
 
 import os
diff --git a/Testing/SystemTests/tests/analysis/EQSANSTransAPIv2.py b/Testing/SystemTests/tests/analysis/EQSANSTransAPIv2.py
index 29e3ebba3aaa63b6b8958bc1083126bb0c2c2ffb..4746a5cb6252f80dbb3f44b64b17242e73e6eede 100644
--- a/Testing/SystemTests/tests/analysis/EQSANSTransAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/EQSANSTransAPIv2.py
@@ -2,6 +2,7 @@
 import stresstesting
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.sns_command_interface import *
+from reduction_workflow.instruments.sans.hfir_command_interface import *
 from mantid.api import *
 
 import os
diff --git a/Testing/SystemTests/tests/analysis/HFIRBackgroundAPIv2.py b/Testing/SystemTests/tests/analysis/HFIRBackgroundAPIv2.py
index 9d70413b3d4d3aac3d1ebf338b19cdfd8acf9018..925598081392de11638c79fa55e48d96ec2c22c2 100644
--- a/Testing/SystemTests/tests/analysis/HFIRBackgroundAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/HFIRBackgroundAPIv2.py
@@ -3,6 +3,7 @@ import stresstesting
 from mantid.api import FileFinder
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.hfir_command_interface import *
+from reduction_workflow.command_interface import AppendDataFile, Reduce1D
 
 import os
 
diff --git a/Testing/SystemTests/tests/analysis/HFIREffAPIv2.py b/Testing/SystemTests/tests/analysis/HFIREffAPIv2.py
index 804419f7bc2ff105704f3bd8f0c77dbdcf0a09ff..507ee341ae3c94375d353db26292912414e00945 100644
--- a/Testing/SystemTests/tests/analysis/HFIREffAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/HFIREffAPIv2.py
@@ -3,6 +3,7 @@ import stresstesting
 from mantid.api import FileFinder
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.hfir_command_interface import *
+from reduction_workflow.command_interface import AppendDataFile, Reduce1D
 
 import os
 
diff --git a/Testing/SystemTests/tests/analysis/HFIRReductionAPIv2.py b/Testing/SystemTests/tests/analysis/HFIRReductionAPIv2.py
index d0ab5a1d523f1f31d3bed108232209d3b0b6026e..6a2f37cbcec421aee254eebb406e57bf31df90c3 100644
--- a/Testing/SystemTests/tests/analysis/HFIRReductionAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/HFIRReductionAPIv2.py
@@ -3,6 +3,7 @@ import stresstesting
 from mantid.api import FileFinder
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.hfir_command_interface import *
+from reduction_workflow.command_interface import AppendDataFile, Reduce
 
 import os
 
diff --git a/Testing/SystemTests/tests/analysis/HFIRTestsAPIv2.py b/Testing/SystemTests/tests/analysis/HFIRTestsAPIv2.py
index 66c3cc4dca7840daa25b28cb231b1430ea568e93..43d23b90f658696e83aec63f8c543f9ac778ec75 100644
--- a/Testing/SystemTests/tests/analysis/HFIRTestsAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/HFIRTestsAPIv2.py
@@ -17,6 +17,7 @@ import stresstesting
 from mantid.api import *
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.hfir_command_interface import *
+from reduction_workflow.command_interface import AppendDataFile, Reduce, Reduce1D
 
 
 # Set directory containing the test data, relative to the Mantid release
diff --git a/Testing/SystemTests/tests/analysis/HFIRTransAPIv2.py b/Testing/SystemTests/tests/analysis/HFIRTransAPIv2.py
index 7c53a24adf8c92c0999fe2f8cb9461aa29391e33..1fe141c924c7fca709450b5483807aa06c95fd4f 100644
--- a/Testing/SystemTests/tests/analysis/HFIRTransAPIv2.py
+++ b/Testing/SystemTests/tests/analysis/HFIRTransAPIv2.py
@@ -3,6 +3,7 @@ import stresstesting
 from mantid.api import FileFinder
 from mantid.simpleapi import *
 from reduction_workflow.instruments.sans.hfir_command_interface import *
+from reduction_workflow.command_interface import AppendDataFile, Reduce1D
 
 import os
 
diff --git a/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py b/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py
index 9054bd94ec97217b7ceab4e5330602e19dffd887..cda7cc19a66fe3c5bd9b00d922264f7caefe6b92 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 """
 Tube Calibration Demonstration for MAPS instrument.
 
@@ -52,21 +52,21 @@ Calibration technique: Finding tubes not well calibrated
 
 """
 
-from mantid.simpleapi import *
+import mantid.simpleapi as mantid
 import tube
 import numpy
 
 
 def loadingStep(filename):
     filename = str(filename)
-    rangeLower = 2000 # Integrate counts in each spectra from rangeLower to rangeUpper
-    rangeUpper = 10000 #
+    rangeLower = 2000  # Integrate counts in each spectra from rangeLower to rangeUpper
+    rangeUpper = 10000  #
     # Get calibration raw file and integrate it
-    rawCalibInstWS = Load(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 = mantid.Load(filename)  # 'raw' in 'rawCalibInstWS' means unintegrated.
+    print("Integrating Workspace")
+    CalibInstWS = mantid.Integration(rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper)
+    mantid.DeleteWorkspace(rawCalibInstWS)
+    print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate")
     return CalibInstWS
 
 
@@ -89,12 +89,12 @@ def minimalInput(filename):
     # Set what we want to calibrate (e.g whole intrument or one door )
     CalibratedComponent = 'MAPS'  # Calibrate all
     # define the known positions and function factor (edge, peak, peak, peak, edge)
-    knownPos, funcFactor = [-0.50,-0.16,-0.00, 0.16, 0.50 ],[2,1,1,1,2]
+    knownPos, funcFactor = [-0.50, -0.16, -0.00, 0.16, 0.50], [2, 1, 1, 1, 2]
 
     # == Get the calibration and put results into calibration table ==
     calibrationTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor)
     # == Apply the Calibation ==
-    ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
+    mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
 
 
 def provideTheExpectedValue(filename):
@@ -111,7 +111,7 @@ def provideTheExpectedValue(filename):
     # Set what we want to calibrate (e.g whole intrument or one door )
     CalibratedComponent = 'MAPS'  # Calibrate all
     # define the known positions and function factor (edge, peak, peak, peak, edge)
-    knownPos, funcFactor = [-0.50,-0.16,-0.00, 0.16, 0.50 ],[2,1,1,1,2]
+    knownPos, funcFactor = [-0.50, -0.16, -0.00, 0.16, 0.50], [2, 1, 1, 1, 2]
 
     # the expected positions in pixels for the special points
     expectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0]
@@ -122,7 +122,7 @@ def provideTheExpectedValue(filename):
     calibrationTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
                                       fitPar=fitPar)
     # == Apply the Calibation ==
-    ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
+    mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
 
 
 def changeMarginAndExpectedValue(filename):
@@ -153,7 +153,7 @@ def changeMarginAndExpectedValue(filename):
     # Set what we want to calibrate (e.g whole intrument or one door )
     CalibratedComponent = 'MAPS'  # Calibrate all
     # define the known positions and function factor (edge, peak, peak, peak, edge)
-    knownPos, funcFactor = [-0.50,-0.16,-0.00, 0.16, 0.50 ],[2,1,1,1,2]
+    knownPos, funcFactor = [-0.50, -0.16, -0.00, 0.16, 0.50], [2, 1, 1, 1, 2]
 
     # the expected positions in pixels for the special points
     expectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0]
@@ -161,10 +161,10 @@ def changeMarginAndExpectedValue(filename):
     fitPar.setAutomatic(True)
 
     # == Get the calibration and put results into calibration table ==
-    calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
-                                                fitPar=fitPar, plotTube=[1,10,100], outputPeak=True, margin=10)
+    calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
+                                                 fitPar=fitPar, plotTube=[1, 10, 100], outputPeak=True, margin=10)
     # == Apply the Calibation ==
-    ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
+    mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
 
     tube.savePeak(peakTable, 'TubeDemoMaps01.txt')
 
@@ -202,7 +202,7 @@ def improvingCalibrationSingleTube(filename):
     # Set what we want to calibrate (e.g whole intrument or one door )
     CalibratedComponent = 'MAPS'  # Calibrate all
     # define the known positions and function factor (edge, peak, peak, peak, edge)
-    knownPos, funcFactor = [-0.50,-0.16,-0.00, 0.16, 0.50 ],[2,1,1,1,2]
+    knownPos, funcFactor = [-0.50, -0.16, -0.00, 0.16, 0.50], [2, 1, 1, 1, 2]
 
     # the expected positions in pixels for the special points
     expectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0]
@@ -210,10 +210,11 @@ def improvingCalibrationSingleTube(filename):
     fitPar.setAutomatic(True)
 
     # == Get the calibration and put results into calibration table ==
-    calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
-                                                fitPar=fitPar, outputPeak=True, plotTube=[18,19,20], rangeList=[18,19,20])
+    calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
+                                                 fitPar=fitPar, outputPeak=True, plotTube=[18, 19, 20],
+                                                 rangeList=[18, 19, 20])
 
-    ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
+    mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
 
     # reload to reset the calibration applied
     CalibInstWS = loadingStep(filename)
@@ -221,16 +222,17 @@ def improvingCalibrationSingleTube(filename):
     # as 14.9788, -0.303511, 9.74828
     # let's change the peak from  -0.303511 to 8.14
 
-    #to override the peaks definition, we use the overridePeaks
+    # to override the peaks definition, we use the overridePeaks
     overridePeaks = {19: [8.14, 80.9771, 123.221, 164.993, 245.717]}
 
     # == Get the calibration and put results into calibration table ==
     # we will not plot anymore, because it will not plot the overrided peaks
-    calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
-                                                fitPar=fitPar, outputPeak=True, rangeList=[18,19,20], overridePeaks=overridePeaks)
+    calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
+                                                 fitPar=fitPar, outputPeak=True, rangeList=[18, 19, 20],
+                                                 overridePeaks=overridePeaks)
 
-    ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-    #check using the InstrumentView and you will see that it is better than before
+    mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
+    # check using the InstrumentView and you will see that it is better than before
 
 
 def improvingCalibrationOfListOfTubes(filename):
@@ -255,7 +257,7 @@ def improvingCalibrationOfListOfTubes(filename):
     # Set what we want to calibrate (e.g whole intrument or one door )
     CalibratedComponent = 'MAPS'  # Calibrate all
     # define the known positions and function factor (edge, peak, peak, peak, edge)
-    knownPos, funcFactor = [-0.50,-0.16,-0.00, 0.16, 0.50 ],[2,1,1,1,2]
+    knownPos, funcFactor = [-0.50, -0.16, -0.00, 0.16, 0.50], [2, 1, 1, 1, 2]
 
     # the expected positions in pixels for the special points
     expectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0]
@@ -263,28 +265,28 @@ def improvingCalibrationOfListOfTubes(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=not_good, rangeList=not_good)
 
-    #CalibInstWS = loadingStep(filename)
+    # CalibInstWS = loadingStep(filename)
 
     # it is defined as the mean values around the neighbours
-    define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717], # the first one was bad
-                    37: [6.36, 80.9347, 122.941, 165.104, 248.32], # the first one was bad
-                    71: [8.62752, 85.074, 124.919, 164.116, 246.82 ], # the last one was bad - check if we can inprove
-                    75: [14.4285, 90.087, 128.987, 167.047, 242.62], # the last one was bad - check if we can inprove
-                    181: [11.726, 94.0496, 137.816,  180, 255], # the third peak was lost
-                    186:[11.9382, 71.5203, 107, 147.727, 239.041], #lost the second peak
-                    234: [4.84, 82.7824, 123.125, 163.945, 241.877], # the first one was bad
-                    235: [4.84, 80.0077, 121.002, 161.098, 238.502], # the first one was bad
-                    245: [9.88089, 93.0593, 136.911, 179.5, 255], # the third peak was bad
-                    273: [18.3711, 105.5, 145.5, 181.6, 243.252], # lost first and third peaks
-                    345: [4.6084, 87.0351, 128.125, 169.923, 245.3] # the last one was bad
+    define_peaks = {19: [10, 80.9771, 123.221, 164.993, 245.717],  # the first one was bad
+                    37: [6.36, 80.9347, 122.941, 165.104, 248.32],  # the first one was bad
+                    71: [8.62752, 85.074, 124.919, 164.116, 246.82],  # the last one was bad - check if we can inprove
+                    75: [14.4285, 90.087, 128.987, 167.047, 242.62],  # the last one was bad - check if we can inprove
+                    181: [11.726, 94.0496, 137.816, 180, 255],  # the third peak was lost
+                    186: [11.9382, 71.5203, 107, 147.727, 239.041],  # lost the second peak
+                    234: [4.84, 82.7824, 123.125, 163.945, 241.877],  # the first one was bad
+                    235: [4.84, 80.0077, 121.002, 161.098, 238.502],  # the first one was bad
+                    245: [9.88089, 93.0593, 136.911, 179.5, 255],  # the third peak was bad
+                    273: [18.3711, 105.5, 145.5, 181.6, 243.252],  # lost first and third peaks
+                    345: [4.6084, 87.0351, 128.125, 169.923, 245.3]  # the last one was bad
                     }
-    calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
-                                                fitPar=fitPar, outputPeak=True, overridePeaks=define_peaks)
+    calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
+                                                 fitPar=fitPar, outputPeak=True, overridePeaks=define_peaks)
 
-    ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
+    mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
 
 
 def calibrateB2Window(filename):
@@ -305,14 +307,14 @@ def calibrateB2Window(filename):
     """
     from tube_calib_fit_params import TubeCalibFitParams
     # b2 with 2 peaks range
-    b2_range = range(196,212) + range(222,233)
+    b2_range = list(range(196, 212)) + list(range(222, 233))
 
     CalibInstWS = loadingStep(filename)
     # == Set parameters for calibration ==
     # Set what we want to calibrate (e.g whole intrument or one door )
     CalibratedComponent = 'MAPS'  # Calibrate all
     # define the known positions and function factor (edge, peak, peak, peak, edge)
-    knownPos, funcFactor = [-0.50,-0.16, 0.16, 0.50 ],[2,1,1,2]
+    knownPos, funcFactor = [-0.50, -0.16, 0.16, 0.50], [2, 1, 1, 2]
 
     # the expected positions in pixels for the special points
     expectedPositions = [4.0, 85.0, 161.0, 252.0]
@@ -320,10 +322,11 @@ def calibrateB2Window(filename):
     fitPar.setAutomatic(True)
 
     # == Get the calibration and put results into calibration table ==
-    calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
-                                                fitPar=fitPar, outputPeak=True, plotTube=[b2_range[0], b2_range[-1]], rangeList=b2_range)
+    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)
+    mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
 
 
 def findThoseTubesThatNeedSpecialCareForCalibration(filename):
@@ -354,7 +357,7 @@ def findThoseTubesThatNeedSpecialCareForCalibration(filename):
     # Set what we want to calibrate (e.g whole intrument or one door )
     CalibratedComponent = 'MAPS'  # Calibrate all
     # define the known positions and function factor (edge, peak, peak, peak, edge)
-    knownPos, funcFactor = [-0.50,-0.16,-0.00, 0.16, 0.50 ],[2,1,1,1,2]
+    knownPos, funcFactor = [-0.50, -0.16, -0.00, 0.16, 0.50], [2, 1, 1, 1, 2]
 
     # the expected positions in pixels for the special points
     expectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0]
@@ -362,50 +365,50 @@ def findThoseTubesThatNeedSpecialCareForCalibration(filename):
     fitPar.setAutomatic(True)
 
     # == Get the calibration and put results into calibration table ==
-    calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
-                                                fitPar=fitPar, outputPeak=True)
+    calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
+                                                 fitPar=fitPar, outputPeak=True)
 
     # == now, lets investigate the peaks
 
-    #parsing the peakTable to produce a numpy array with dimension (number_of_tubes x number_of_peaks)
-    print 'parsing the peak table'
+    # parsing the peakTable to produce a numpy array with dimension (number_of_tubes x number_of_peaks)
+    print('parsing the peak table')
     n = len(peakTable)
-    peaksId = n*['']
-    data = numpy.zeros((n,5))
+    peaksId = n * ['']
+    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
+        data_row = [row['Peak%d' % (i)] for i in [1, 2, 3, 4, 5]]
+        data[line, :] = data_row
         peaksId[line] = row['TubeId']
-        line+=1
+        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)
-    #calculate how far from the expected position each peak position is
-    distance_from_expected =  numpy.abs(data - expected_peak_pos)
+    expected_peak_pos = numpy.mean(data, axis=0)
+    # calculate how far from the expected position each peak position is
+    distance_from_expected = numpy.abs(data - expected_peak_pos)
 
-    print 'Creating the Peaks Workspace that shows the distance from the expected value for all peaks for each tube'
+    print('Creating the Peaks Workspace that shows the distance from the expected value for all peaks for each tube')
     # Let's see these peaks:
-    CreateWorkspace(range(n),distance_from_expected,NSpec=5,OutputWorkspace='Peaks')
+    mantid.CreateWorkspace(list(range(n)), distance_from_expected, NSpec=5, OutputWorkspace='Peaks')
 
     # plot all the 5 peaks for Peaks Workspace. You will see that most of the tubes differ
     # at most 12 pixels from the expected values.
 
-    #so let's investigate those that differ more than 12
+    # so let's investigate those that differ more than 12
     # return an array with the indexes for the first axis which is the tube indentification
     check = numpy.where(distance_from_expected > 12)[0]
 
-    #remove repeated values
-    #select only those tubes inside the problematic_tubes
+    # remove repeated values
+    # select only those tubes inside the problematic_tubes
     problematic_tubes = list(set(check))
 
-    print 'Tubes whose distance is far from the expected value: ', problematic_tubes
+    print('Tubes whose distance is far from the expected value: ', problematic_tubes)
 
-    print 'Calibrating again only these tubes'
-    #let's confir that our suspect works
+    print('Calibrating again only these tubes')
+    # let's confir that our suspect works
     CalibInstWS = loadingStep(filename)
     tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor,
-                   fitPar=fitPar, rangeList= problematic_tubes, plotTube=problematic_tubes)
+                   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.
 
 
@@ -430,16 +433,16 @@ def completeCalibration(filename):
     CalibratedComponent = 'MAPS'  # Calibrate all
 
     # define the known positions and function factor (edge, peak, peak, peak, edge)
-    knownPos, funcFactor = [-0.50,-0.16,-0.00, 0.16, 0.50 ],[2,1,1,1,2]
+    knownPos, funcFactor = [-0.50, -0.16, -0.00, 0.16, 0.50], [2, 1, 1, 1, 2]
 
     # the expected positions in pixels for the special points
     expectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0]
     fitPar = TubeCalibFitParams(expectedPositions)
     fitPar.setAutomatic(True)
 
-    #execute the improvingCalibrationOfListOfTubes excluding the range of b2 window
+    # execute the improvingCalibrationOfListOfTubes excluding the range of b2 window
     # correct the definition of the peaks for the folowing indexes
-    #define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717], # the first one was bad
+    # define_peaks = {19:[10, 80.9771, 123.221, 164.993, 245.717], # the first one was bad
     #	37: [6.36, 80.9347, 122.941, 165.104, 248.32], # the first one was bad
     #	71: [8.62752, 85.074, 124.919, 164.116, 246.82 ], # the last one was bad - check if we can inprove
     #	75: [14.4285, 90.087, 128.987, 167.047, 242.62], # the last one was bad - check if we can inprove
@@ -450,34 +453,35 @@ 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],
+    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 ],
+                    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],
+                    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)
+    b2_window = list(range(196, 212)) + list(range(222, 233))
 
-    complete_range = range(648)
+    complete_range = list(range(648))
 
     # this data can not be used to calibrate the E1 window, so, let's remove it.
-    e1_window = range(560,577)
+    e1_window = list(range(560, 577))
     aux = numpy.setdiff1d(complete_range, b2_window)
     # 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,
-                                                 fitPar=fitPar, outputPeak=True, overridePeaks=define_peaks, rangeList=range_3_strips)
+    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
     # define the known positions and function factor (edge, peak, peak, edge)
-    knownPos, funcFactor = [-0.50,-0.16, 0.16, 0.50 ],[2,1,1,2]
+    knownPos, funcFactor = [-0.50, -0.16, 0.16, 0.50], [2, 1, 1, 2]
 
     # the expected positions in pixels for the special points
     expectedPositions = [4.0, 85.0, 161.0, 252.0]
@@ -486,31 +490,31 @@ 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
+                                                  knownPos,  # these parameters now have only 4 points
                                                   funcFactor,
                                                   fitPar=fitPar,
                                                   outputPeak=True,
-                                                  calibTable = calibrationTable, # it will append to the calibTable
-                                                  rangeList = b2_window)
+                                                  calibTable=calibrationTable,  # it will append to the calibTable
+                                                  rangeList=b2_window)
 
-    ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
+    mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
 
     # == Save workspace ==
-    #SaveNexusProcessed( CalibInstWS, path+'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
-    #print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs"
+    # SaveNexusProcessed( CalibInstWS, path+'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
+    # print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs"
 
 
 ####
 ## Uncomment one of the following lines to execute one of the examples
 #####
-filename = 'MAP14919.raw' #found at \\isis\inst$\NDXMAPS\Instrument\data\cycle_09_5
+filename = 'MAP14919.raw'  # found at \\isis\inst$\NDXMAPS\Instrument\data\cycle_09_5
 if __name__ == "__main__":
     filename = 'MAP14919.raw'
-    #minimalInput(filename)
-    #provideTheExpectedValue(filename)
-    #changeMarginAndExpectedValue(filename)
-    #improvingCalibrationSingleTube(filename)
-    #improvingCalibrationOfListOfTubes(filename)
-    #calibrateB2Window(filename)
+    # minimalInput(filename)
+    # provideTheExpectedValue(filename)
+    # changeMarginAndExpectedValue(filename)
+    # improvingCalibrationSingleTube(filename)
+    # improvingCalibrationOfListOfTubes(filename)
+    # calibrateB2Window(filename)
     completeCalibration(filename)
-    #findThoseTubesThatNeedSpecialCareForCalibration(filename)
+    # findThoseTubesThatNeedSpecialCareForCalibration(filename)
diff --git a/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py b/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py
index b049ea959d1d815ab3f5ac87c5ae392bbc423a8c..37a02fa1e3e6d709f086607a7f1f19f4b86e3873 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoMaps_B1.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 #
 # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this
 #
@@ -7,56 +7,56 @@
 #
 import tube
 from tube_calib_fit_params import TubeCalibFitParams
+import mantid.simpleapi as mantid
+
 # == Set parameters for calibration ==
 
-filename = 'MAP14919.raw' # Calibration run ( found in \\isis\inst$\NDXMAPS\Instrument\data\cycle_09_5 )
-rangeLower = 2000 # Integrate counts in each spectra from rangeLower to rangeUpper
-rangeUpper = 10000 #
+filename = 'MAP14919.raw'  # Calibration run ( found in \\isis\inst$\NDXMAPS\Instrument\data\cycle_09_5 )
+rangeLower = 2000  # Integrate counts in each spectra from rangeLower to rangeUpper
+rangeUpper = 10000  #
 
 # 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)
+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)
 
 # Set what we want to calibrate (e.g whole intrument or one door )
 CalibratedComponent = 'B1_window'  # Calibrate B1 window
 
-
 # Get calibration raw file and integrate it
-rawCalibInstWS = Load(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 = mantid.Load(filename)  # 'raw' in 'rawCalibInstWS' means unintegrated.
+print("Integrating Workspace")
+CalibInstWS = mantid.Integration(rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper)
+mantid.DeleteWorkspace(rawCalibInstWS)
+print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate")
 
 # == Create Objects needed for calibration ==
 # The positions of the shadows and ends here are an intelligent guess.
 # First array gives positions in Metres and second array gives type 1=Gaussian peak 2=edge.
 # See http://www.mantidproject.org/IdealTube for details.
-knownPos = [-0.50,-0.165,-0.00, 0.165, 0.50 ]
-funcForm = [2,1,1,1,2]
+knownPos = [-0.50, -0.165, -0.00, 0.165, 0.50]
+funcForm = [2, 1, 1, 1, 2]
 
 # Get fitting parameters
-fitPar = TubeCalibFitParams( ExpectedPositions, ExpectedHeight, ExpectedWidth )
+fitPar = TubeCalibFitParams(ExpectedPositions, ExpectedHeight, ExpectedWidth)
 fitPar.setAutomatic(True)
 
-print "Created objects needed for calibration."
+print("Created objects needed for calibration.")
 
 # == Get the calibration and put results into calibration table ==
 # also put peaks into PeakFile
 calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm,
                                              fitPar=fitPar, outputPeak=True)
-print "Got calibration (new positions of detectors) "
+print("Got calibration (new positions of detectors) ")
 
 # == Apply the Calibation ==
-ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-print "Applied calibration"
-
+mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
+print("Applied calibration")
 
 # == Save workspace ==
-SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps_B1.py")
-print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs"
+mantid.SaveNexusProcessed(CalibInstWS, 'TubeCalibDemoMapsResult.nxs', "Result of Running TCDemoMaps_B1.py")
+print("saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs")
 
 # == Save Peak File ==
 tube.savePeak(peakTable, 'TubeDemoMaps01.txt')
diff --git a/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py b/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py
index 5413f517d0750a6bf9e7812f43a568e5645a08ed..493a8207be9ea0296fec99a244ad2979d283e877 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 #
 # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this
 #
@@ -8,26 +8,27 @@
 #
 import tube
 from tube_spec import TubeSpec
-#from tube_calib_fit_params import  # To handle fit parameters
+import mantid.simpleapi as mantid
+
+# from tube_calib_fit_params import  # To handle fit parameters
 
 
 # == Set parameters for calibration ==
 
-filename = 'MAP14919.raw' # Name of calibration run
-rangeLower = 2000 # Integrate counts in each spectra from rangeLower to rangeUpper
-rangeUpper = 10000 #
+filename = 'MAP14919.raw'  # Name of calibration run
+rangeLower = 2000  # Integrate counts in each spectra from rangeLower to rangeUpper
+rangeUpper = 10000  #
 
 # Set what we want to calibrate (e.g whole intrument or one door )
 CalibratedComponent1 = 'C4_window'  # Calibrate C4 window
 CalibratedComponent2 = 'C3_window'  # Calibrate C3 window
 
-
 # Get calibration raw file and integrate it
-rawCalibInstWS = Load(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 = mantid.Load(filename)  # 'raw' in 'rawCalibInstWS' means unintegrated.
+print("Integrating Workspace")
+CalibInstWS = mantid.Integration(rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper)
+mantid.DeleteWorkspace(rawCalibInstWS)
+print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate")
 
 # == Create Objects needed for calibration ==
 
@@ -37,22 +38,21 @@ thisTubeSet.setTubeSpecByString(CalibratedComponent1)
 thisTubeSet.setTubeSpecByString(CalibratedComponent2)
 
 # Specify the known positions
-knownPos = [-0.50,-0.16,-0.00, 0.16, 0.50 ]
-funcForm = [2,1,1,1,2]
+knownPos = [-0.50, -0.16, -0.00, 0.16, 0.50]
+funcForm = [2, 1, 1, 1, 2]
 
-print "Created objects needed for calibration."
+print("Created objects needed for calibration.")
 
 # == Get the calibration and put results into calibration table ==
 
 calibrationTable, peakTable = tube.calibrate(CalibInstWS, thisTubeSet, knownPos, funcForm,
                                              outputPeak=True)
-print "Got calibration (new positions of detectors) "
+print("Got calibration (new positions of detectors) ")
 
 # == Apply the Calibation ==
-ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-print "Applied calibration"
-
+mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
+print("Applied calibration")
 
 # == Save workspace ==
-#SaveNexusProcessed( CalibInstWS, path+'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
-print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs"
+# SaveNexusProcessed( CalibInstWS, path+'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
+print("saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs")
diff --git a/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py b/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py
index e8340cca0de9ad1305e273ffc09afe280b02c8c5..916de7b178c4374b3be97742a9af00adb74eda00 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3C2.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 #
 # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this
 #
@@ -6,44 +6,43 @@
 # specifying them in an array of strings.
 
 import tube
+import mantid.simpleapi as mantid
 
 # == Set parameters for calibration ==
 
-filename = 'MAP14919.raw' # Name of calibration run
-rangeLower = 2000 # Integrate counts in each spectra from rangeLower to rangeUpper
-rangeUpper = 10000 #
+filename = 'MAP14919.raw'  # Name of calibration run
+rangeLower = 2000  # Integrate counts in each spectra from rangeLower to rangeUpper
+rangeUpper = 10000  #
 
 # Set what we want to calibrate (e.g whole intrument or one door )
 # Set what we want to calibrate (e.g whole intrument or one door )
-CalibratedComponents = ['C4_window','C3_window','C2_window']  # Calibrate three C windows
-
+CalibratedComponents = ['C4_window', 'C3_window', 'C2_window']  # Calibrate three C windows
 
 # Get calibration raw file and integrate it
-rawCalibInstWS = Load(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 = mantid.Load(filename)  # 'raw' in 'rawCalibInstWS' means unintegrated.
+print("Integrating Workspace")
+CalibInstWS = mantid.Integration(rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper)
+mantid.DeleteWorkspace(rawCalibInstWS)
+print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate")
 
 # == Create Objects needed for calibration ==
 
 # Specify the known positions
-knownPos = [-0.50,-0.16,-0.00, 0.16, 0.50 ]
-funcForm = [2,1,1,1,2]
+knownPos = [-0.50, -0.16, -0.00, 0.16, 0.50]
+funcForm = [2, 1, 1, 1, 2]
 
-print "Created objects needed for calibration."
+print("Created objects needed for calibration.")
 
 # == Get the calibration and put results into calibration table ==
 
 calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponents, knownPos, funcForm,
                                              outputPeak=True)
-print "Got calibration (new positions of detectors) "
+print("Got calibration (new positions of detectors) ")
 
 # == Apply the Calibation ==
-ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-print "Applied calibration"
-
+mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
+print("Applied calibration")
 
 # == Save workspace ==
-#SaveNexusProcessed( CalibInstWS, path+'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
-print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs"
+# SaveNexusProcessed( CalibInstWS, path+'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
+print("saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs")
diff --git a/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py b/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py
index 5a725371cdcdd4811124ec2a0ed2d78b6ca8dc67..a59232d971d617dc1d1df65238335c270acaf0e6 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 #
 # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this
 #
@@ -7,50 +7,51 @@
 #
 import tube
 from tube_calib_fit_params import TubeCalibFitParams
+import mantid.simpleapi as mantid
+
 # == Set parameters for calibration ==
 
-filename = 'MAP14919.raw' # Calibration run ( found in \\isis\inst$\NDXMAPS\Instrument\data\cycle_09_5 )
+filename = 'MAP14919.raw'  # Calibration run ( found in \\isis\inst$\NDXMAPS\Instrument\data\cycle_09_5 )
 # Set what we want to calibrate (e.g whole intrument or one door )
 CalibratedComponent = 'D2_window'  # Calibrate D2 window
 
-
 # Get calibration raw file and integrate it
-rawCalibInstWS = Load(filename)  #'raw' in 'rawCalibInstWS' means unintegrated.
-print "Integrating Workspace"
-rangeLower = 2000 # Integrate counts in each spectra from rangeLower to rangeUpper
-rangeUpper = 10000 #
-CalibInstWS = Integration( rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper )
-DeleteWorkspace(rawCalibInstWS)
-print "Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate"
+rawCalibInstWS = mantid.Load(filename)  # 'raw' in 'rawCalibInstWS' means unintegrated.
+print("Integrating Workspace")
+rangeLower = 2000  # Integrate counts in each spectra from rangeLower to rangeUpper
+rangeUpper = 10000  #
+CalibInstWS = mantid.Integration(rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper)
+mantid.DeleteWorkspace(rawCalibInstWS)
+print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate")
 
 # == Create Objects needed for calibration ==
 
 # The positions of the shadows and ends here are an intelligent guess.
 # First array gives positions in Metres and second array gives type 1=Gaussian peak 2=edge.
 
-knownPos = [-0.65,-0.22,-0.00, 0.22, 0.65 ]
-funcForm = [2,1,1,1,2]
+knownPos = [-0.65, -0.22, -0.00, 0.22, 0.65]
+funcForm = [2, 1, 1, 1, 2]
 
 # Get fitting parameters
 # 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)
-fitPar = TubeCalibFitParams( ExpectedPositions, ExpectedHeight, ExpectedWidth)
+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)
+fitPar = TubeCalibFitParams(ExpectedPositions, ExpectedHeight, ExpectedWidth)
 fitPar.setAutomatic(True)
 
-print "Created objects needed for calibration."
+print("Created objects needed for calibration.")
 
 # == Get the calibration and put results into calibration table ==
 calibrationTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm,
-                                  fitPar = fitPar)
-print "Got calibration (new positions of detectors) "
+                                  fitPar=fitPar)
+print("Got calibration (new positions of detectors) ")
 
 # == Apply the Calibation ==
-ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-print "Applied calibration"
+mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
+print("Applied calibration")
 
 # == Save workspace ==
-#SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
-#print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs"
+# SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
+# print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs"
diff --git a/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py b/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py
index 1131eadedcbc170fec22a0a4121df0f1d8bab222..a5a42ac3e0e2ff7c8a1fbac3456e83f893338502 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoMaps_D2_WideMargins.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 #
 # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MAPS - Execute this
 #
@@ -6,42 +6,41 @@
 
 #
 import tube
+import mantid.simpleapi as mantid
 
 # == Set parameters for calibration ==
 
-filename = 'MAP14919.raw' # Name of calibration run
-rangeLower = 2000 # Integrate counts in each spectra from rangeLower to rangeUpper
-rangeUpper = 10000 #
-
+filename = 'MAP14919.raw'  # Name of calibration run
+rangeLower = 2000  # Integrate counts in each spectra from rangeLower to rangeUpper
+rangeUpper = 10000  #
 
 # Set what we want to calibrate (e.g whole intrument or one door )
 CalibratedComponent = 'D2_window'  # Calibrate D2 window
 
-
 # Get calibration raw file and integrate it
-rawCalibInstWS = Load(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 = mantid.Load(filename)  # 'raw' in 'rawCalibInstWS' means unintegrated.
+print("Integrating Workspace")
+CalibInstWS = mantid.Integration(rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper)
+mantid.DeleteWorkspace(rawCalibInstWS)
+print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate")
 
 # == Create Objects needed for calibration ==
 
 # The positions of the shadows and ends here are an intelligent guess.
-knownPos = [-0.65,-0.22,-0.00, 0.22, 0.65 ]
-funcForm = [2,1,1,1,2]
+knownPos = [-0.65, -0.22, -0.00, 0.22, 0.65]
+funcForm = [2, 1, 1, 1, 2]
 
-print "Created objects needed for calibration."
+print("Created objects needed for calibration.")
 
 # == Get the calibration and put results into calibration table ==
 calibrationTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm)
-print "Got calibration (new positions of detectors) "
+print("Got calibration (new positions of detectors) ")
 
 # == Apply the Calibation ==
-ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-print "Applied calibration"
+mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
+print("Applied calibration")
 
 
 # == Save workspace ==
-#SaveNexusProcessed( CalibInstWS, path+'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
-#print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs"
+# SaveNexusProcessed( CalibInstWS, path+'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
+# print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs"
diff --git a/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py b/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py
index efdb96e9dbbdfb55633e524e7fe4760d4c698ce3..fb89634c6cd1655365e5748e352e38daedfa0e39 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoMaps_D4.py
@@ -7,6 +7,7 @@
 #
 import tube
 from tube_calib_fit_params import TubeCalibFitParams
+import mantid.simpleapi as mantid
 
 # == Set parameters for calibration ==
 
@@ -15,13 +16,13 @@ filename = 'MAP14919.raw' # Calibration run ( found in \\isis\inst$\NDXMAPS\Inst
 CalibratedComponent = 'D4_window'  # Calibrate D4 window
 
 # Get calibration raw file and integrate it
-rawCalibInstWS = Load(filename)  #'raw' in 'rawCalibInstWS' means unintegrated.
-print "Integrating Workspace"
+rawCalibInstWS = mantid.Load(filename)  #'raw' in 'rawCalibInstWS' means unintegrated.
+print("Integrating Workspace")
 rangeLower = 2000 # Integrate counts in each spectra from rangeLower to rangeUpper
 rangeUpper = 10000 #
-CalibInstWS = Integration( rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper )
-DeleteWorkspace(rawCalibInstWS)
-print "Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate"
+CalibInstWS = mantid.Integration( rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper )
+mantid.DeleteWorkspace(rawCalibInstWS)
+print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate")
 
 # == Create Objects needed for calibration ==
 
@@ -39,18 +40,18 @@ ExpectedPositions = [4.0, 85.0, 128.0, 165.0, 252.0] # Expected positions of the
 fitPar = TubeCalibFitParams( ExpectedPositions, ExpectedHeight, ExpectedWidth)
 fitPar.setAutomatic(True)
 
-print "Created objects needed for calibration."
+print("Created objects needed for calibration.")
 
 # == Get the calibration and put results into calibration table ==
 calibrationTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm,
                                   fitPar = fitPar)
-print "Got calibration (new positions of detectors) "
+print("Got calibration (new positions of detectors) ")
 
 # == Apply the Calibation ==
-ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-print "Applied calibration"
+mantid.ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
+print("Applied calibration")
 
 
 # == Save workspace ==
-SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
-print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs"
+mantid.SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoMapsResult.nxs',"Result of Running TCDemoMaps.py")
+print("saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMapsResult.nxs")
diff --git a/scripts/Calibration/Examples/TubeCalibDemoMerlin.py b/scripts/Calibration/Examples/TubeCalibDemoMerlin.py
index f6b27a28541094f3a1e78a911b6b66a7f1b7e9a8..aa7eeabfd432d0662121e4e3d01ecad45ab71ac4 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoMerlin.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoMerlin.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 """
 Tube Calibration Demonstration program for MERLIN.
 
@@ -43,70 +43,72 @@ The previous calibrated instrument view:
 .. sectionauthor:: Gesner Passos - ISIS
 """
 import numpy
-from mantid.simpleapi import *
+import mantid.simpleapi as mantid
 import tube
 
 
 def analisePeakTable(pTable, peaksName='Peaks'):
-    print 'parsing the peak table'
+    print('parsing the peak table')
     n = len(pTable)
-    peaks = pTable.columnCount() -1
-    peaksId = n*['']
-    data = numpy.zeros((n,peaks))
+    peaks = pTable.columnCount() - 1
+    peaksId = n * ['']
+    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
+        data_row = [row['Peak%d' % (i)] for i in range(1, peaks + 1)]
+        data[line, :] = data_row
         peaksId[line] = row['TubeId']
-        line+=1
+        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)
-    print expected_peak_pos
-    #calculate how far from the expected position each peak position is
-    distance_from_expected =  numpy.abs(data - expected_peak_pos)
+    expected_peak_pos = numpy.mean(data, axis=0)
+    print(expected_peak_pos)
+    # calculate how far from the expected position each peak position is
+    distance_from_expected = numpy.abs(data - expected_peak_pos)
 
-    CreateWorkspace(range(n),distance_from_expected,NSpec=peaks, OutputWorkspace=peaksName)
+    mantid.CreateWorkspace(list(range(n)), distance_from_expected, NSpec=peaks, OutputWorkspace=peaksName)
     check = numpy.where(distance_from_expected > 10)[0]
     problematic_tubes = list(set(check))
-    print 'Tubes whose distance is far from the expected value: ', problematic_tubes
+    print('Tubes whose distance is far from the expected value: ', problematic_tubes)
 
 
 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 = mantid.LoadRaw(filename)  # 'raw' in 'rawCalibInstWS' means unintegrated.
+    print("Integrating Workspace")
+    CalibInstWS = mantid.Integration(rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper)
+    mantid.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
+    CalibratedComponent = 'MERLIN/door9'  # door9
     # == Get the calibration and put results into calibration table ==
     # also put peaks into PeakFile
     calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door9pos, door9func,
                                                  outputPeak=True,
                                                  margin=30,
-                                                 rangeList=range(20) # because 20, 21, 22, 23 are defective detectors
+                                                 rangeList=list(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"
+    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
@@ -115,118 +117,119 @@ def calibrateMerlin(filename):
     CalibratedComponent = 'MERLIN/door8'
     calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, door8pos,
                                                  door8func,
-                                                 outputPeak = True, #change to peakTable to append to peakTable
-                                                 calibTable = calibrationTable,
-                                                 margin = 30)
+                                                 outputPeak=True,  # change to peakTable to append to peakTable
+                                                 calibTable=calibrationTable,
+                                                 margin=30)
     analisePeakTable(peakTable, 'door8_peaks')
 
-  # For the doors 7,6,5,4, 2, 1 we may use the 9 points
+    # 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]]
+    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)
+                                                 outputPeak=True,
+                                                 calibTable=calibrationTable,
+                                                 margin=30)
     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
-  # obeys the same rules as the doors 7, 6, 5, 4, 2, 1
-  # For the tubes 3_3, 3_2, 3_1 -> it is better to skip the central peak
-  # For the tubes 1_x (smaller tube below), it is better to take the final part of known positions: peak4,peak5,edge6,edge7
-  # For the tubes 2_x (smaller tube above, it is better to take the first part of known positions: edge1, edge2, peak1,peak2
+    # 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
+    # obeys the same rules as the doors 7, 6, 5, 4, 2, 1
+    # For the tubes 3_3, 3_2, 3_1 -> it is better to skip the central peak
+    # For the tubes 1_x (smaller tube below), it is better to take the final part of known positions: peak4,peak5,edge6,edge7
+    # For the tubes 2_x (smaller tube above, it is better to take the first part of known positions: edge1, edge2, peak1,peak2
 
-  # 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
+    # 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
 
-  # calibrating tubes 1_x
-    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
-
-  # 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 #
-
-  # 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]
-  # 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
+    # calibrating tubes 1_x
+    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 here a little bit of attempts is necessary.
+    # The effective 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  #
+
+    # 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]
+    # 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,
-                                                 margin = 30)
+                                                 outputPeak=True,
+                                                 fitPar=fitPar,
+                                                 calibTable=calibrationTable,
+                                                 margin=30)
     analisePeakTable(peakTable, 'door3_tube1_peaks')
 
-  # calibrating tubes 2_x
-    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
-  # print doorpos
-    doorfunc = [2,2,1,1]
+    # calibrating tubes 2_x
+    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
+    # print doorpos
+    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
+    # 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,
-                                                 margin = 30)
+                                                 outputPeak=True,
+                                                 calibTable=calibrationTable,
+                                                 fitPar=fitPar,
+                                                 margin=30)
 
     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]]
+    # 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,
-                                                 margin = 30)
+                                                 outputPeak=True,
+                                                 calibTable=calibrationTable,
+                                                 margin=30)
     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)]
+    # 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,
-                                                 margin = 30)
+                                                 outputPeak=True,
+                                                 calibTable=calibrationTable,
+                                                 margin=30)
     analisePeakTable(peakTable, 'door3_peaks')
 
-  # == Apply the Calibation ==
-    ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-    print "Applied calibration"
+    # == Apply the Calibation ==
+    mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
+    print("Applied calibration")
 
-  # == Save workspace ==
-  #SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoMerlinResult.nxs',"Result of Running TCDemoMerlin.py")
-  #print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMerlinResult.nxs"
+    # == Save workspace ==
+    # SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoMerlinResult.nxs',"Result of Running TCDemoMerlin.py")
+    # print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMerlinResult.nxs"
 
 
-if __name__=="__main__":
-    filename = 'MER12024.raw' # Calibration run ( found in \\isis\inst$\NDXMERLIN\Instrument\data\cycle_11_5 )
+if __name__ == "__main__":
+    filename = 'MER12024.raw'  # Calibration run ( found in \\isis\inst$\NDXMERLIN\Instrument\data\cycle_11_5 )
     calibrateMerlin(filename)
diff --git a/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py b/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py
index 6631ad1169c75cc3846a009923f2968e2d8c9e16..a7ab13a619276a9dca00095ef3c81543cdf7ccb2 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoMerlin_Simple.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 #
 # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR MERLIN
 #
@@ -15,40 +15,42 @@
 import tube
 from tube_calib_fit_params import TubeCalibFitParams
 import numpy
+import mantid.simpleapi as mantid
 
 RunNumber = 12024
 
 
 def CalibrateMerlin(RunNumber):
     # == Set parameters for calibration ==
-    previousDefaultInstrument = config['default.instrument']
-    config['default.instrument']="MERLIN"
-    filename = str(RunNumber) # Name of calibration run.
-    rangeLower = 3000 # Integrate counts in each spectra from rangeLower to rangeUpper
-    rangeUpper = 20000 #
+    previousDefaultInstrument = mantid.config['default.instrument']
+    mantid.config['default.instrument'] = "MERLIN"
+    filename = str(RunNumber)  # Name of calibration run.
+    rangeLower = 3000  # Integrate counts in each spectra from rangeLower to rangeUpper
+    rangeUpper = 20000  #
 
     # Set parameters for ideal tube.
-    Left = 2.0 # Where the left end of tube should be in pixels (target for AP)
-    Centre = 512.5 # Where the centre of the tube should be in pixels (target for CP)
-    Right = 1023.0 # Where the right of the tube should be in pixels (target for BP)
-    ActiveLength = 2.9 # Active length of tube in Metres
+    Left = 2.0  # Where the left end of tube should be in pixels (target for AP)
+    Centre = 512.5  # Where the centre of the tube should be in pixels (target for CP)
+    Right = 1023.0  # Where the right of the tube should be in pixels (target for BP)
+    ActiveLength = 2.9  # Active length of tube in Metres
 
     # Set initial parameters for peak finding
-    ExpectedHeight = 1000.0 # Expected Height of Gaussian Peaks (initial value of fit parameter)
-    ExpectedWidth = 32.0 # Expected width of centre peak in Pixels (initial value of fit parameter)
-    ExpectedPositions = [35.0, 512.0, 989.0] # Expected positions of the edges and peak in pixels (initial values of fit parameters)
+    ExpectedHeight = 1000.0  # Expected Height of Gaussian Peaks (initial value of fit parameter)
+    ExpectedWidth = 32.0  # Expected width of centre peak in Pixels (initial value of fit parameter)
+    ExpectedPositions = [35.0, 512.0,
+                         989.0]  # Expected positions of the edges and peak in pixels (initial values of fit parameters)
 
     # Set what we want to calibrate (e.g whole intrument or one door )
     CalibratedComponent = 'MERLIN'  # Calibrate door 2
 
     # Get calibration raw file and integrate it
-    print filename
-    rawCalibInstWS = LoadRaw(filename)
+    print(filename)
+    rawCalibInstWS = mantid.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"
+    print("Integrating Workspace")
+    CalibInstWS = mantid.Integration(rawCalibInstWS, RangeLower=rangeLower, RangeUpper=rangeUpper)
+    mantid.DeleteWorkspace(rawCalibInstWS)
+    print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate")
 
     # == Create Objects needed for calibration ==
 
@@ -60,31 +62,32 @@ def CalibrateMerlin(RunNumber):
     ##
     ## for merlin: npixels = 1024
 
-    knownPos = ActiveLength * (numpy.array([Left, Centre, Right])/1024.0 - 0.5)
-    funcForm = 3*[1]
+    knownPos = ActiveLength * (numpy.array([Left, Centre, Right]) / 1024.0 - 0.5)
+    funcForm = 3 * [1]
 
     # Get fitting parameters
-    fitPar = TubeCalibFitParams( ExpectedPositions, ExpectedHeight, ExpectedWidth, margin=40)
+    fitPar = TubeCalibFitParams(ExpectedPositions, ExpectedHeight, ExpectedWidth, margin=40)
 
-    print "Created objects needed for calibration."
+    print("Created objects needed for calibration.")
 
     # == Get the calibration and put results into calibration table ==
     # also put peaks into PeakFile
-    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"
+    calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcForm,
+                                                 outputPeak=True, fitPar=fitPar, plotTube=list(range(0, 280, 20)))
+    print("Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt")
 
     # == Apply the Calibation ==
-    ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-    print "Applied calibration"
+    mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
+    print("Applied calibration")
 
     # == Save workspace ==
-    #SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoMerlinResult.nxs',"Result of Running TubeCalibDemoMerlin_Simple.py")
-    #print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMerlinResult.nxs"
+    # SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoMerlinResult.nxs',"Result of Running TubeCalibDemoMerlin_Simple.py")
+    # print "saved calibrated workspace (CalibInstWS) into Nexus file TubeCalibDemoMerlinResult.nxs"
 
     # == Reset dafault instrument ==
-    config['default.instrument'] = previousDefaultInstrument
+    mantid.config['default.instrument'] = previousDefaultInstrument
 
     # ==== End of CalibrateMerlin() ====
 
-CalibrateMerlin( RunNumber )
+
+CalibrateMerlin(RunNumber)
diff --git a/scripts/Calibration/Examples/TubeCalibDemoWish0.py b/scripts/Calibration/Examples/TubeCalibDemoWish0.py
index 515be0cd67a9932d8d2c07b9a36f355557953f38..79607d0f2ef11682b7b37bfb48047625aa47676a 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoWish0.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoWish0.py
@@ -10,24 +10,26 @@
 # WISH instrument.
 #
 import tube
+import mantid.simpleapi as mantid
+
 filename = 'WISH00017701.raw' # Calibration run ( found in \\isis\inst$\NDXWISH\Instrument\data\cycle_11_1 )
-rawCalibInstWS = Load(filename)  #'raw' in 'rawCalibInstWS' means unintegrated.
-CalibInstWS = Integration( rawCalibInstWS, RangeLower=1, RangeUpper=20000 )
-DeleteWorkspace(rawCalibInstWS)
-print "Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate"
+rawCalibInstWS = mantid.Load(filename)  #'raw' in 'rawCalibInstWS' means unintegrated.
+CalibInstWS = mantid.Integration( rawCalibInstWS, RangeLower=1, RangeUpper=20000 )
+mantid.DeleteWorkspace(rawCalibInstWS)
+print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate")
 
 CalibratedComponent = 'WISH/panel03'
 
 knownPos = [-0.41,-0.31,-0.21,-0.11,-0.02, 0.09, 0.18, 0.28, 0.39 ]
 funcForm = 9*[1] # all special points are gaussian peaks
 
-print "Created objects needed for calibration."
+print("Created objects needed for calibration.")
 
 # Get the calibration and put it into the calibration table
 calibrationTable = tube.calibrate(CalibInstWS, CalibratedComponent,
                                   knownPos, funcForm)
-print "Got calibration (new positions of detectors)"
+print("Got calibration (new positions of detectors)")
 
 #Apply the calibration
-ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-print "Applied calibration"
+mantid.ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
+print("Applied calibration")
diff --git a/scripts/Calibration/Examples/TubeCalibDemoWish1.py b/scripts/Calibration/Examples/TubeCalibDemoWish1.py
index b56785e2f74c98966d21e3c465bb5134cd6b3b34..43185f51137ac67585e055973984b3c35af8c81a 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoWish1.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoWish1.py
@@ -10,12 +10,13 @@ reload(tube) # noqa
 from tube_spec import TubeSpec
 import tube_calib #from tube_calib import constructIdealTubeFromRealTube
 from tube_calib_fit_params import TubeCalibFitParams
+import mantid.simpleapi as mantid
 
 filename = 'WISH00017701.raw' # Calibration run ( found in \\isis\inst$\NDXWISH\Instrument\data\cycle_11_1 )
-rawCalibInstWS = Load(filename)  #'raw' in 'rawCalibInstWS' means unintegrated.
-CalibInstWS = Integration( rawCalibInstWS, RangeLower=1, RangeUpper=20000 )
-DeleteWorkspace(rawCalibInstWS)
-print "Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate"
+rawCalibInstWS = mantid.Load(filename)  #'raw' in 'rawCalibInstWS' means unintegrated.
+CalibInstWS = mantid.Integration( rawCalibInstWS, RangeLower=1, RangeUpper=20000 )
+mantid.DeleteWorkspace(rawCalibInstWS)
+print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate")
 
 CalibratedComponent = 'WISH/panel03/tube038'
 
@@ -25,7 +26,7 @@ ExpectedHeight = 2000.0 # Expected Height of Gaussian Peaks (initial value of fi
 ExpectedWidth = 32.0 # Expected width of Gaussian peaks in pixels  (initial value of fit parameter)
 fitPar = TubeCalibFitParams( eP, ExpectedHeight, ExpectedWidth )
 fitPar.setAutomatic(True)
-print "Created objects needed for calibration."
+print("Created objects needed for calibration.")
 func_form = 9*[1]
 
 # Use first tube as ideal tube
@@ -34,12 +35,12 @@ tube1.setTubeSpecByString('WISH/panel03/tube038')
 iTube = tube_calib.constructIdealTubeFromRealTube( CalibInstWS, tube1, fitPar, func_form)
 
 known_pos = iTube.getArray()
-print known_pos
+print(known_pos)
 
 # Get the calibration and put it into the calibration table
 calibrationTable = tube.calibrate( CalibInstWS, 'WISH/panel03', known_pos, func_form, fitPar=fitPar)
-print "Got calibration (new positions of detectors)"
+print("Got calibration (new positions of detectors)")
 
 #Apply the calibration
-ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-print "Applied calibration"
+mantid.ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
+print("Applied calibration")
diff --git a/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py b/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py
index 93594265bf16c22c96292744245b849fd2c1574b..ce40f500fa8628115d0378736d5dbdfabb66117e 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoWish_5panels.py
@@ -12,7 +12,7 @@ to calibrate the whole instrument.
 
 """
 import numpy
-from mantid.simpleapi import *
+import mantid.simpleapi as mantid
 
 import tube
 from tube_spec import TubeSpec
@@ -25,28 +25,28 @@ def CalibrateWish(run_per_panel_list):
     run_per_panel_list =  [ (17706, 'panel01'), (17705, 'panel02'),  (17701, 'panel03'), (17702, 'panel04'), (17695, 'panel05')]
     '''
     # == Set parameters for calibration ==
-    previousDefaultInstrument = config['default.instrument']
-    config['default.instrument']="WISH"
+    previousDefaultInstrument = mantid.config['default.instrument']
+    mantid.config['default.instrument']="WISH"
 
     # definition of the parameters static for the calibration
     lower_tube = numpy.array([-0.41,-0.31,-0.21,-0.11,-0.02, 0.09, 0.18, 0.28, 0.39 ])
     upper_tube = numpy.array(lower_tube+0.003)
     funcForm = 9*[1] # 9 gaussian peaks
     margin = 15
-    low_range = range(0,76)
-    high_range = range(76,152)
+    low_range = list(range(0,76))
+    high_range = list(range(76,152))
     kwargs = {'margin':margin}
 
     # it will copy all the data from the runs to have a single instrument with the calibrated data.
-    whole_instrument = LoadRaw(str(run_per_panel_list[0][0]))
-    whole_instrument = Integration(whole_instrument)
+    whole_instrument = mantid.LoadRaw(str(run_per_panel_list[0][0]))
+    whole_instrument = mantid.Integration(whole_instrument)
 
     for (run_number, panel_name) in run_per_panel_list:
         panel_name = str(panel_name)
         run_number = str(run_number)
         # load your data and integrate it
-        ws = LoadRaw(run_number, OutputWorkspace=panel_name)
-        ws = Integration(ws, 1, 20000, OutputWorkspace=panel_name)
+        ws = mantid.LoadRaw(run_number, OutputWorkspace=panel_name)
+        ws = mantid.Integration(ws, 1, 20000, OutputWorkspace=panel_name)
 
         # use the TubeSpec object to be able to copy the data to the whole_instrument
         tube_set = TubeSpec(ws)
@@ -63,7 +63,7 @@ def CalibrateWish(run_per_panel_list):
         calibrationTable = tube.calibrate(ws, tube_set, upper_tube, funcForm, **kwargs)
         kwargs['calibTable'] = calibrationTable
 
-        ApplyCalibration(ws, calibrationTable)
+        mantid.ApplyCalibration(ws, calibrationTable)
 
         # copy data from the current panel to the whole_instrument
         for i in range(tube_set.getNumTubes()):
@@ -72,9 +72,9 @@ def CalibrateWish(run_per_panel_list):
 
     # calibrate the whole_instrument with the last calibrated panel which has the calibration accumulation
     # of all the others
-    CopyInstrumentParameters(run_per_panel_list[-1][1],whole_instrument)
+    mantid.CopyInstrumentParameters(run_per_panel_list[-1][1],whole_instrument)
 
-    config['default.instrument'] = previousDefaultInstrument
+    mantid.config['default.instrument'] = previousDefaultInstrument
     # ==== End of CalibrateWish() ====
 
 
diff --git a/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py b/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py
index f3cfb7e655f795744f1dd645f5241166ceaa6592..48bda575fbeb7af16024f262a1846a6e68e953cd 100644
--- a/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py
+++ b/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py
@@ -1,4 +1,4 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 #
 # TUBE CALIBRATION DEMONSTRATION PROGRAM FOR WISH
 #
@@ -6,67 +6,70 @@
 #
 import numpy
 import tube
-from mantid.simpleapi import *
+import mantid.simpleapi as mantid
 
 
-def CalibrateWish( RunNumber, PanelNumber):
+def CalibrateWish(RunNumber, PanelNumber):
     '''
     :param RunNumber: is the run number of the calibration.
     :param PanelNumber: is a string of two-digit number of the panel being calibrated
     '''
     # == Set parameters for calibration ==
-    previousDefaultInstrument = config['default.instrument']
-    config['default.instrument']="WISH"
+    previousDefaultInstrument = mantid.config['default.instrument']
+    mantid.config['default.instrument'] = "WISH"
     filename = str(RunNumber)
-    CalibratedComponent = 'WISH/panel'+PanelNumber
+    CalibratedComponent = 'WISH/panel' + PanelNumber
 
     # Get calibration raw file and integrate it
-    print "Loading",filename
-    rawCalibInstWS = Load(filename)  #'raw' in 'rawCalibInstWS' means unintegrated.
-    CalibInstWS = Integration( rawCalibInstWS, RangeLower=1, RangeUpper=20000 )
-    DeleteWorkspace(rawCalibInstWS)
-    print "Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate"
+    print("Loading", filename)
+    rawCalibInstWS = mantid.Load(filename)  # 'raw' in 'rawCalibInstWS' means unintegrated.
+    CalibInstWS = mantid.Integration(rawCalibInstWS, RangeLower=1, RangeUpper=20000)
+    mantid.DeleteWorkspace(rawCalibInstWS)
+    print("Created workspace (CalibInstWS) with integrated data from run and instrument to calibrate")
 
     # Give y-positions of slit points (gotten for converting first tube's slit point to Y)
 
     # WISH instrument has a particularity. It is composed by a group of upper tubes and lower tubes,
     # they are disposed 3 milimiters in difference one among the other
-    lower_tube = numpy.array([-0.41,-0.31,-0.21,-0.11,-0.02, 0.09, 0.18, 0.28, 0.39 ])
-    upper_tube = numpy.array(lower_tube+0.003)
-    funcForm = 9*[1] # 9 gaussian peaks
-    print "Created objects needed for calibration."
+    lower_tube = numpy.array([-0.41, -0.31, -0.21, -0.11, -0.02, 0.09, 0.18, 0.28, 0.39])
+    upper_tube = numpy.array(lower_tube + 0.003)
+    funcForm = 9 * [1]  # 9 gaussian peaks
+    print("Created objects needed for calibration.")
 
     # Get the calibration and put it into the calibration table
 
-    #calibrate the lower tubes
+    # calibrate the lower tubes
     calibrationTable, peakTable = tube.calibrate(CalibInstWS, CalibratedComponent, lower_tube, funcForm,
-                                                 rangeList = range(0,76), outputPeak=True)
+                                                 rangeList=list(range(0, 76)), outputPeak=True)
 
-    #calibrate the upper tubes
+    # 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
+                                                 rangeList=list(range(76, 152)),
+                                                 calibTable=calibrationTable,
+                                                 # give the calibration table to append data
+                                                 outputPeak=peakTable  # give peak table to append data
                                                  )
 
-    print "Got calibration (new positions of detectors)"
+    print("Got calibration (new positions of detectors)")
 
-    #Apply the calibration
-    ApplyCalibration( Workspace=CalibInstWS, PositionTable=calibrationTable)
-    print "Applied calibration"
+    # Apply the calibration
+    mantid.ApplyCalibration(Workspace=CalibInstWS, PositionTable=calibrationTable)
+    print("Applied calibration")
 
     # == Save workspace ==
-    #uncomment these lines to save the workspace
-    #nexusName = "TubeCalibDemoWish"+PanelNumber+"Result.nxs"
-    #SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoWishResult.nxs',"Result of Running TubeCalibWishMerlin_Simple.py")
-    #print "saved calibrated workspace (CalibInstWS) into Nexus file",nexusName
+    # uncomment these lines to save the workspace
+    # nexusName = "TubeCalibDemoWish"+PanelNumber+"Result.nxs"
+    # SaveNexusProcessed( CalibInstWS, 'TubeCalibDemoWishResult.nxs',"Result of Running TubeCalibWishMerlin_Simple.py")
+    # print "saved calibrated workspace (CalibInstWS) into Nexus file",nexusName
 
     # == Reset dafault instrument ==
-    config['default.instrument'] = previousDefaultInstrument
+    mantid.config['default.instrument'] = previousDefaultInstrument
 
     # ==== End of CalibrateWish() ====
+
+
 if __name__ == "__main__":
-  # this file is found on cycle_11_1
+    # this file is found on cycle_11_1
     RunNumber = 17701
     PanelNumber = '03'
     CalibrateWish(RunNumber, PanelNumber)
diff --git a/scripts/DiamondAttenuationCorrection/FitTrans.py b/scripts/DiamondAttenuationCorrection/FitTrans.py
index e18aeebdae721a3b435c6f046bc4b3b1968f57f2..c10e68ac4b57422cbf3f18ab50608d2604807075 100644
--- a/scripts/DiamondAttenuationCorrection/FitTrans.py
+++ b/scripts/DiamondAttenuationCorrection/FitTrans.py
@@ -59,8 +59,8 @@ def calcDspacing(a, b, c, alp, bet, gam, h, k, l):
     sb = np.sin(np.radians(bet))
     sg = np.sin(np.radians(gam))
 
-    oneoverdsq = (1.0 - ca**2 - cb**2 - cg**2 + 2 * ca * cb * cg)**(-1) * \
-                 ((h * sa / a)**2 + (k * sb / b)**2 + (l * sg / c)**2
+    oneoverdsq = (1.0 - ca ** 2 - cb ** 2 - cg ** 2 + 2 * ca * cb * cg) ** (-1) * \
+                 ((h * sa / a) ** 2 + (k * sb / b) ** 2 + (l * sg / c) ** 2
                   + (2 * k * l / (b * c)) * (cb * cg - ca) + (2 * l * h / (c * a)) * (cg * ca - cb)
                   + (2 * h * k / (a * b)) * (ca * cb - cg))
 
@@ -121,22 +121,22 @@ def forbidden(h, k, l):
         result = 0
 
     # condition 1
-    if ((h != 0)and (k != 0) and (l != 0)):  # general hkl
+    if ((h != 0) and (k != 0) and (l != 0)):  # general hkl
         term1 = h + k
         term2 = h + l  # all have to be even
         term3 = k + l
-        if not((term1 % 2) == 0 and (term2 % 2) == 0 and (term3 % 2) == 0):
+        if not ((term1 % 2) == 0 and (term2 % 2) == 0 and (term3 % 2) == 0):
             result = 1
             boolresult = bool(result)
             return boolresult
         else:
             result = 0
 
-    #% condition 2
+    # % condition 2
     if ((h == 0) and (k != 0) and (l != 0)):  # 0kl reflections
         term1 = k + l
         mod4 = mod(term1, 4)
-        if not(mod4 == 0 and mod(k, 2) == 0 and mod(l, 2) == 0):
+        if not (mod4 == 0 and mod(k, 2) == 0 and mod(l, 2) == 0):
             result = 1
             boolresult = bool(result)
             return boolresult
@@ -145,7 +145,7 @@ def forbidden(h, k, l):
 
     # condition 3
     if (h == k):  # hhl reflections
-        if not(mod(h + l, 2) == 0):
+        if not (mod(h + l, 2) == 0):
             result = 1
             boolresult = bool(result)
             return boolresult
@@ -153,9 +153,9 @@ def forbidden(h, k, l):
             result = 0
 
     # condition 4
-    if ((h == 0) and (k == 0) and (l != 0)):   # 00l reflections not including 000
+    if ((h == 0) and (k == 0) and (l != 0)):  # 00l reflections not including 000
         mod4 = mod(l, 4)
-        if not(mod4 == 0):
+        if not (mod4 == 0):
             result = 1
             boolresult = bool(result)
             return boolresult
@@ -191,7 +191,7 @@ def allowedDiamRefs(hmin, hmax, kmin, kmax, lmin, lmax):
     # create new array with all h!=0 k!=0 l!=0
     hkl = np.zeros(shape=(0, 3))
     for i in range(n):
-        if not(allhkl[i][0] == 0 and allhkl[i][1] == 0 and allhkl[i][2] == 0):
+        if not (allhkl[i][0] == 0 and allhkl[i][1] == 0 and allhkl[i][2] == 0):
             hkl = np.vstack((hkl, [allhkl[i][0], allhkl[i][1], allhkl[i][2]]))
             d.append(calcDspacing(3.56683, 3.56683, 3.56683, 90,
                                   90, 90, hkl[k][0], hkl[k][1], hkl[k][2]))
@@ -224,7 +224,7 @@ def getISAWub(fullfilename):
     '''
     fileID = fullfilename
     if fileID == 1:
-        print('Error opening file: ' + fullfilename)
+        print(('Error opening file: ' + fullfilename))
     f = open(fileID, "r")
     lines = f.readlines()
     f.close()
@@ -236,7 +236,9 @@ def getISAWub(fullfilename):
         UB[i][0], UB[i][1], UB[i][2] = lines[i].split()
     UB = UB.transpose()
     for i in range(3, 5):
-        lattice[i - 3][0], lattice[i - 3][1], lattice[i - 3][2], lattice[i - 3][3], lattice[i - 3][4], lattice[i - 3][5], \
+        lattice[i - 3][0], lattice[i - 3][1], \
+            lattice[i - 3][2], lattice[i - 3][3], \
+            lattice[i - 3][4], lattice[i - 3][5], \
             non = lines[i].split()
 
     print('Successfully got UB and lattice')
@@ -260,93 +262,93 @@ def pkintread(hkl, loc):
 
     returns pkint = np. array - 1D vector
     '''
-    #A = np.genfromtxt('diamond_reflist.csv', delimiter=',', skip_header=True)
+    # A = np.genfromtxt('diamond_reflist.csv', delimiter=',', skip_header=True)
     # print A
-    A = np.array([[1.00000000e+00,   1.00000000e+00,   1.00000000e+00,   8.00000000e+00,
-                   2.06110000e+00,   5.54000000e+04],
-                  [2.00000000e+00,   2.00000000e+00,   0.00000000e+00,   1.20000000e+01,
-                   1.26220000e+00,   7.52000000e+04],
-                  [3.00000000e+00,   1.00000000e+00,   1.00000000e+00,   2.40000000e+01,
-                   1.07640000e+00,   2.98000000e+04],
-                  [2.00000000e+00,   2.00000000e+00,   2.00000000e+00,   8.00000000e+00,
-                   1.03060000e+00,   2.50000000e-25],
-                  [4.00000000e+00,   0.00000000e+00,   0.00000000e+00,   6.00000000e+00,
-                   8.92500000e-01,   4.05000000e+04],
-                  [3.00000000e+00,   3.00000000e+00,   1.00000000e+00,   2.40000000e+01,
-                   8.19000000e-01,  1.61000000e+04],
-                  [4.00000000e+00,   2.00000000e+00,   2.00000000e+00,   2.40000000e+01,
-                   7.28700000e-01,   2.18000000e+04],
-                  [5.00000000e+00,   1.00000000e+00,   1.00000000e+00,   2.40000000e+01,
-                   6.87000000e-01,   8.64000000e+03],
-                  [3.00000000e+00,   3.00000000e+00,   3.00000000e+00,   8.00000000e+00,
-                   6.87000000e-01,   8.64000000e+03],
-                  [4.00000000e+00,   4.00000000e+00,   0.00000000e+00,  1.20000000e+01,
-                   6.31100000e-01,   1.17000000e+04],
-                  [5.00000000e+00,   3.00000000e+00,   1.00000000e+00,   4.80000000e+01,
-                   6.03400000e-01,   4.65000000e+03],
-                  [4.00000000e+00,   4.00000000e+00,   2.00000000e+00,   2.40000000e+01,
-                   5.95000000e-01,   1.83000000e-12],
-                  [6.00000000e+00,   2.00000000e+00,   0.00000000e+00,   2.40000000e+01,
-                   5.64500000e-01,   6.31000000e+03],
-                  [5.00000000e+00,   3.00000000e+00,   3.00000000e+00,   2.40000000e+01,
-                   5.44400000e-01,   2.50000000e+03],
-                  [6.00000000e+00,   2.00000000e+00,   2.00000000e+00,   2.40000000e+01,
-                   5.38200000e-01,   8.80000000e-26],
-                  [4.00000000e+00,   4.00000000e+00,   4.00000000e+00,   8.00000000e+00,
-                   5.15300000e-01,   3.40000000e+03],
-                  [5.00000000e+00,   5.00000000e+00,   1.00000000e+00,   2.40000000e+01,
-                   4.99900000e-01,   1.35000000e+03],
-                  [7.00000000e+00,   1.00000000e+00,   1.00000000e+00,   2.40000000e+01,
-                   4.99900000e-01,   1.35000000e+03],
-                  [6.00000000e+00,   4.00000000e+00,   2.00000000e+00,   4.80000000e+01,
-                   4.77100000e-01,   1.83000000e+03],
-                  [7.00000000e+00,   3.00000000e+00,   1.00000000e+00,   4.80000000e+01,
-                   4.64800000e-01,   7.25000000e+02],
-                  [5.00000000e+00,   5.00000000e+00,   3.00000000e+00,   2.40000000e+01,
-                   4.64800000e-01,   7.25000000e+02],
-                  [8.00000000e+00,   0.00000000e+00,   0.00000000e+00,   6.00000000e+00,
-                   4.46200000e-01,   9.84000000e+02],
-                  [7.00000000e+00,   3.00000000e+00,   3.00000000e+00,   2.40000000e+01,
-                   4.36100000e-01,   3.90000000e+02],
-                  [6.00000000e+00,   4.00000000e+00,   4.00000000e+00,   2.40000000e+01,
-                   4.32900000e-01,   1.53000000e-13],
-                  [6.00000000e+00,   6.00000000e+00,   0.00000000e+00,   1.20000000e+01,
-                   4.20700000e-01,   5.30000000e+02],
-                  [8.00000000e+00,   2.00000000e+00,   2.00000000e+00,   2.40000000e+01,
-                   4.20700000e-01,   5.30000000e+02],
-                  [5.00000000e+00,   5.00000000e+00,   5.00000000e+00,   8.00000000e+00,
-                   4.12200000e-01,   2.10000000e+02],
-                  [7.00000000e+00,   5.00000000e+00,   1.00000000e+00,   4.80000000e+01,
-                   4.12200000e-01,   2.10000000e+02],
-                  [6.00000000e+00,   6.00000000e+00,   2.00000000e+00,   2.40000000e+01,
-                   4.09500000e-01,   1.98000000e-26],
-                  [8.00000000e+00,   4.00000000e+00,   0.00000000e+00,   2.40000000e+01,
-                   3.99100000e-01,   2.85000000e+02],
-                  [7.00000000e+00,   5.00000000e+00,   3.00000000e+00,   4.80000000e+01,
-                   3.91900000e-01,   1.13000000e+02],
-                  [9.00000000e+00,   1.00000000e+00,   1.00000000e+00,   2.40000000e+01,
-                   3.91900000e-01,   1.13000000e+02],
-                  [8.00000000e+00,   4.00000000e+00,   2.00000000e+00,   4.80000000e+01,
-                   3.89500000e-01,   4.44000000e-14],
-                  [6.00000000e+00,   6.00000000e+00,   4.00000000e+00,   2.40000000e+01,
-                   3.80600000e-01,   1.53000000e+02],
-                  [9.00000000e+00,   3.00000000e+00,   1.00000000e+00,   4.80000000e+01,
-                   3.74200000e-01,   6.08000000e+01],
-                  [8.00000000e+00,   4.00000000e+00,   4.00000000e+00,   2.40000000e+01,
-                   3.64400000e-01,   8.26000000e+01],
-                  [9.00000000e+00,   3.00000000e+00,   3.00000000e+00,   2.40000000e+01,
-                   3.58800000e-01,   3.27000000e+01],
-                  [7.00000000e+00,   5.00000000e+00,   5.00000000e+00,   2.40000000e+01,
-                   3.58800000e-01,   3.27000000e+01],
-                  [7.00000000e+00,   7.00000000e+00,   1.00000000e+00,   2.40000000e+01,
-                   3.58800000e-01,   3.27000000e+01]])
+    A = np.array([[1.00000000e+00, 1.00000000e+00, 1.00000000e+00, 8.00000000e+00,
+                   2.06110000e+00, 5.54000000e+04],
+                  [2.00000000e+00, 2.00000000e+00, 0.00000000e+00, 1.20000000e+01,
+                   1.26220000e+00, 7.52000000e+04],
+                  [3.00000000e+00, 1.00000000e+00, 1.00000000e+00, 2.40000000e+01,
+                   1.07640000e+00, 2.98000000e+04],
+                  [2.00000000e+00, 2.00000000e+00, 2.00000000e+00, 8.00000000e+00,
+                   1.03060000e+00, 2.50000000e-25],
+                  [4.00000000e+00, 0.00000000e+00, 0.00000000e+00, 6.00000000e+00,
+                   8.92500000e-01, 4.05000000e+04],
+                  [3.00000000e+00, 3.00000000e+00, 1.00000000e+00, 2.40000000e+01,
+                   8.19000000e-01, 1.61000000e+04],
+                  [4.00000000e+00, 2.00000000e+00, 2.00000000e+00, 2.40000000e+01,
+                   7.28700000e-01, 2.18000000e+04],
+                  [5.00000000e+00, 1.00000000e+00, 1.00000000e+00, 2.40000000e+01,
+                   6.87000000e-01, 8.64000000e+03],
+                  [3.00000000e+00, 3.00000000e+00, 3.00000000e+00, 8.00000000e+00,
+                   6.87000000e-01, 8.64000000e+03],
+                  [4.00000000e+00, 4.00000000e+00, 0.00000000e+00, 1.20000000e+01,
+                   6.31100000e-01, 1.17000000e+04],
+                  [5.00000000e+00, 3.00000000e+00, 1.00000000e+00, 4.80000000e+01,
+                   6.03400000e-01, 4.65000000e+03],
+                  [4.00000000e+00, 4.00000000e+00, 2.00000000e+00, 2.40000000e+01,
+                   5.95000000e-01, 1.83000000e-12],
+                  [6.00000000e+00, 2.00000000e+00, 0.00000000e+00, 2.40000000e+01,
+                   5.64500000e-01, 6.31000000e+03],
+                  [5.00000000e+00, 3.00000000e+00, 3.00000000e+00, 2.40000000e+01,
+                   5.44400000e-01, 2.50000000e+03],
+                  [6.00000000e+00, 2.00000000e+00, 2.00000000e+00, 2.40000000e+01,
+                   5.38200000e-01, 8.80000000e-26],
+                  [4.00000000e+00, 4.00000000e+00, 4.00000000e+00, 8.00000000e+00,
+                   5.15300000e-01, 3.40000000e+03],
+                  [5.00000000e+00, 5.00000000e+00, 1.00000000e+00, 2.40000000e+01,
+                   4.99900000e-01, 1.35000000e+03],
+                  [7.00000000e+00, 1.00000000e+00, 1.00000000e+00, 2.40000000e+01,
+                   4.99900000e-01, 1.35000000e+03],
+                  [6.00000000e+00, 4.00000000e+00, 2.00000000e+00, 4.80000000e+01,
+                   4.77100000e-01, 1.83000000e+03],
+                  [7.00000000e+00, 3.00000000e+00, 1.00000000e+00, 4.80000000e+01,
+                   4.64800000e-01, 7.25000000e+02],
+                  [5.00000000e+00, 5.00000000e+00, 3.00000000e+00, 2.40000000e+01,
+                   4.64800000e-01, 7.25000000e+02],
+                  [8.00000000e+00, 0.00000000e+00, 0.00000000e+00, 6.00000000e+00,
+                   4.46200000e-01, 9.84000000e+02],
+                  [7.00000000e+00, 3.00000000e+00, 3.00000000e+00, 2.40000000e+01,
+                   4.36100000e-01, 3.90000000e+02],
+                  [6.00000000e+00, 4.00000000e+00, 4.00000000e+00, 2.40000000e+01,
+                   4.32900000e-01, 1.53000000e-13],
+                  [6.00000000e+00, 6.00000000e+00, 0.00000000e+00, 1.20000000e+01,
+                   4.20700000e-01, 5.30000000e+02],
+                  [8.00000000e+00, 2.00000000e+00, 2.00000000e+00, 2.40000000e+01,
+                   4.20700000e-01, 5.30000000e+02],
+                  [5.00000000e+00, 5.00000000e+00, 5.00000000e+00, 8.00000000e+00,
+                   4.12200000e-01, 2.10000000e+02],
+                  [7.00000000e+00, 5.00000000e+00, 1.00000000e+00, 4.80000000e+01,
+                   4.12200000e-01, 2.10000000e+02],
+                  [6.00000000e+00, 6.00000000e+00, 2.00000000e+00, 2.40000000e+01,
+                   4.09500000e-01, 1.98000000e-26],
+                  [8.00000000e+00, 4.00000000e+00, 0.00000000e+00, 2.40000000e+01,
+                   3.99100000e-01, 2.85000000e+02],
+                  [7.00000000e+00, 5.00000000e+00, 3.00000000e+00, 4.80000000e+01,
+                   3.91900000e-01, 1.13000000e+02],
+                  [9.00000000e+00, 1.00000000e+00, 1.00000000e+00, 2.40000000e+01,
+                   3.91900000e-01, 1.13000000e+02],
+                  [8.00000000e+00, 4.00000000e+00, 2.00000000e+00, 4.80000000e+01,
+                   3.89500000e-01, 4.44000000e-14],
+                  [6.00000000e+00, 6.00000000e+00, 4.00000000e+00, 2.40000000e+01,
+                   3.80600000e-01, 1.53000000e+02],
+                  [9.00000000e+00, 3.00000000e+00, 1.00000000e+00, 4.80000000e+01,
+                   3.74200000e-01, 6.08000000e+01],
+                  [8.00000000e+00, 4.00000000e+00, 4.00000000e+00, 2.40000000e+01,
+                   3.64400000e-01, 8.26000000e+01],
+                  [9.00000000e+00, 3.00000000e+00, 3.00000000e+00, 2.40000000e+01,
+                   3.58800000e-01, 3.27000000e+01],
+                  [7.00000000e+00, 5.00000000e+00, 5.00000000e+00, 2.40000000e+01,
+                   3.58800000e-01, 3.27000000e+01],
+                  [7.00000000e+00, 7.00000000e+00, 1.00000000e+00, 2.40000000e+01,
+                   3.58800000e-01, 3.27000000e+01]])
 
     diamd = A[:, 4]
-    #diamMult = A[:, 3] # unused variable
+    # diamMult = A[:, 3] # unused variable
     diamFCalcSq = A[:, 5]
     nref = hkl.shape[0]
-    #% disp(['there are: ' num2str(nref) ' reflections']);
-    #% whos loc
+    # % disp(['there are: ' num2str(nref) ' reflections']);
+    # % whos loc
 
     '''
     % [i,j] = size(x);
@@ -363,10 +365,10 @@ def pkintread(hkl, loc):
 
     for i in range(nref):
         if loc[i][0] > 0:
-            #% satisfies Bragg condition (otherwise ignore)
+            # % satisfies Bragg condition (otherwise ignore)
             Fsq = Fsqcalc(loc[i][1], diamd, diamFCalcSq)
-            #% Fsq = 1;
-            L = (np.sin(np.radians(loc[i][2] / 2.0)))**2  # Lorentz correction
+            # % Fsq = 1;
+            L = (np.sin(np.radians(loc[i][2] / 2.0))) ** 2  # Lorentz correction
             R = 1.0  # %dipLam(i)^4; %reflectivity correction
             A = 1.0  # %Absorption correction
             Ecor = 1
@@ -393,7 +395,7 @@ def Fsqcalc(d, diamd, diamFCalcSq):
 
     % global sf111 sf220 sf311 sf400 sf331
     '''
-    #n = len(diamd) # unused variable
+    # n = len(diamd) # unused variable
     ref = d
     dif = abs(diamd - ref)
     i = dif.argmin(0)  # i is index of diamd closest to d
@@ -496,7 +498,7 @@ def getMANTIDdat_keepbinning(csvfile):
     y = []
     e = []
     if fid < 0:
-        print('Error opening file: ' + csvfile)
+        print(('Error opening file: ' + csvfile))
     for i in range(1, len(lines)):
         a, b, c = lines[i].split(",")
         x.append(float(a))
@@ -534,7 +536,7 @@ def findeqvs(hkl):
                 nperm = len(permcomphkl)
                 for k in range(nperm):
                     if refhkl[0] == permcomphkl[k][0] and refhkl[1] == permcomphkl[k][1] and \
-                            refhkl[2] == permcomphkl[k][2]:
+                                    refhkl[2] == permcomphkl[k][2]:
                         eqvlab[j] = lab
         lab += 1
 
@@ -558,8 +560,8 @@ def showx3(x):
     global neqv1, eqvlab1, neqv2, eqvlab2
     global difa, function_verbose
 
-    #nref1 = hkl1.shape[0]  # % number of reflections to integrate over # unused variable
-    #nref2 = hkl2.shape[0]  # % number of reflections to integrate over # unused variable
+    # nref1 = hkl1.shape[0]  # % number of reflections to integrate over # unused variable
+    # nref2 = hkl2.shape[0]  # % number of reflections to integrate over # unused variable
     # % returns array with same dim as input labelling equivs
     eqvlab1, neqv1 = findeqvs(hkl1)
     eqvlab2, neqv2 = findeqvs(hkl2)
@@ -569,7 +571,7 @@ def showx3(x):
     pkmult2 = x[6 + neqv1:7 + neqv1 + neqv2 - 1]
     sf = x[neqv1 + neqv2 + 7 - 1]
     pkwid1 = x[neqv1 + neqv2 + 8 - 1]
-    #bgd = x[neqv1 + neqv2 + 8 - 1:neqv1 + neqv2 + 9 + 2 - 1] # unused variable
+    # bgd = x[neqv1 + neqv2 + 8 - 1:neqv1 + neqv2 + 9 + 2 - 1] # unused variable
     pkwid2 = x[neqv1 + neqv2 + 10]
     # % if diamond intensities the same, allow single scale f
     relsf = x[neqv1 + neqv2 + 11]
@@ -577,18 +579,18 @@ def showx3(x):
     L2 = x[neqv1 + neqv2 + 13]
 
     print('_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/\n')
-    print('Setting angles diam {0} : \nalp {1} bet {2} gam {3} \n'.format(
-        1, setang1[0], setang1[1], setang1[2]))
-    print('pkmult1: {0}\n'.format(pkmult1))
-    print('Setting angles diam {0} : \nalp {1} bet {2} gam {3} \n'.format(
-        2, setang2[0], setang2[1], setang2[2]))
-    print('pkmult2: {0}\n'.format(pkmult2))
-    print('Scale factor: {0}\n'.format(sf))
-    print('pkwid1: {0}\n'.format(pkwid1))
-    print('pkwid2: {0}\n'.format(pkwid2))
-    print('Rel. scale factor : {0}\n'.format(relsf))
-    print('Lambda multiplier: {0}\n'.format(delam))
-    print('L2 sample to detector: {0} m\n'.format(L2))
+    print(('Setting angles diam {0} : \nalp {1} bet {2} gam {3} \n'.format(
+        1, setang1[0], setang1[1], setang1[2])))
+    print(('pkmult1: {0}\n'.format(pkmult1)))
+    print(('Setting angles diam {0} : \nalp {1} bet {2} gam {3} \n'.format(
+        2, setang2[0], setang2[1], setang2[2])))
+    print(('pkmult2: {0}\n'.format(pkmult2)))
+    print(('Scale factor: {0}\n'.format(sf)))
+    print(('pkwid1: {0}\n'.format(pkwid1)))
+    print(('pkwid2: {0}\n'.format(pkwid2)))
+    print(('Rel. scale factor : {0}\n'.format(relsf)))
+    print(('Lambda multiplier: {0}\n'.format(delam)))
+    print(('L2 sample to detector: {0} m\n'.format(L2)))
     print('_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/\n')
 
 
@@ -646,7 +648,7 @@ def SimTransOutput3(name, x):
     delam = x[neqv1 + neqv2 + 12]
     L2 = x[neqv1 + neqv2 + 13]
 
-    shftlam = 0.0039558 * TOF / (L1 + L2) + difa * (TOF**2)
+    shftlam = 0.0039558 * TOF / (L1 + L2) + difa * (TOF ** 2)
     # number of lambda points to calculate over
     npt = shftlam.shape[0]
     # calculate information for peaks for crystal 1 using hkl,UB1, setang,
@@ -672,47 +674,45 @@ def SimTransOutput3(name, x):
     # calculate background profile by multiplying this with coefficients
     # themselves
     bgdprof = nonzerobgd.dot(X)
-    #bgdprof = np.outer(nonzerobgd, X)
+    # bgdprof = np.outer(nonzerobgd, X)
     # print bgdprof
-    #bgdprof = bgdprof[0, :]
+    # bgdprof = bgdprof[0, :]
     # calculate peaks for crystal 1
 
     t1 = np.zeros(npt)  # initialise array containing profile
     for i in range(nref1):
         if pktype == 1:
             pkpars1[i][0] = pkpars1[i][0] * delam  # linear lambda shift
-            sig = pkwid1 * pkpars1[i][0] + pkwid2 * \
-                (pkpars1[i][0]**2.)  # const del(lambda)/lambda
-            extScl = pkpars1[i][0]**0  # lambda dependent extinction effect
+            sig = pkwid1 * pkpars1[i][0] + pkwid2 * (pkpars1[i][0] ** 2.)  # const del(lambda)/lambda
+            extScl = pkpars1[i][0] ** 0  # lambda dependent extinction effect
             t1 = t1 - extScl * pkmult1[int(eqvlab1[i])] * pkcalcint1[i] * (
-                np.exp(-((shftlam - pkpars1[i][0])**2.) / (2 * (sig**2))))
+                np.exp(-((shftlam - pkpars1[i][0]) ** 2.) / (2 * (sig ** 2))))
 
     # calculate peaks for crystal 2
     t2 = np.zeros(npt)  # initialise array containing profile
     for i in range(nref2):
         if pktype == 1:
             pkpars2[i][0] = pkpars2[i][0] * delam  # linear lambda shift
-            sig = pkwid1 * pkpars2[i][0] + pkwid2 * \
-                (pkpars2[i][0]**2.)  # const del(lambda)/lambda
-            extScl = pkpars2[i][0]**0  # lambda dependent extinction effect
+            sig = pkwid1 * pkpars2[i][0] + pkwid2 * (pkpars2[i][0] ** 2.)  # const del(lambda)/lambda
+            extScl = pkpars2[i][0] ** 0  # lambda dependent extinction effect
             t2 = t2 - extScl * pkmult2[int(eqvlab2[i])] * pkcalcint2[i] * (
-                np.exp(-(shftlam - pkpars2[i][0])**2. / (2 * (sig**2))))
+                np.exp(-(shftlam - pkpars2[i][0]) ** 2. / (2 * (sig ** 2))))
 
     # calculate final profile
     ttot = (bgdprof + sf * t1) * (bgdprof + sf * t2)
-    #t1 = 1.0;
+    # t1 = 1.0;
     # t2 = 1.0;
     # introduce weighting function and calc chi2...
     w = np.ones(len(shftlam))  # equal weighting everywhere
-    #i1 = np.where(shftlam > 2.15)[0][0]
-    #j1 = np.where(shftlam > 2.65)[0][0]
+    # i1 = np.where(shftlam > 2.15)[0][0]
+    # j1 = np.where(shftlam > 2.65)[0][0]
     # w[i1:j1] = 5 #extra weighting in region of first peaks
     # i1 = find(lam>1.68,1,'first');
     # j1 = find(lam>2.05,1,'first');
     # w(i1:j1)=5; %extra weighting but not too much
 
     resid = (y - ttot) * w
-    chi2 = np.sum(resid**2. / (2 * e**2)) / npt
+    chi2 = np.sum(resid ** 2. / (2 * e ** 2)) / npt
 
     output = 1
     if output == 1:
@@ -810,7 +810,7 @@ def SimTrans3(x):
     delam = x[neqv1 + neqv2 + 12]
     L2 = x[neqv1 + neqv2 + 13]
 
-    shftlam = 0.0039558 * TOF / (L1 + L2) + difa * (TOF**2)
+    shftlam = 0.0039558 * TOF / (L1 + L2) + difa * (TOF ** 2)
     # number of lambda points to calculate over
     npt = shftlam.shape[0]
     # calculate information for peaks for crystal 1 using hkl,UB1, setang,
@@ -836,51 +836,49 @@ def SimTrans3(x):
     # calculate background profile by multiplying this with coefficients
     # themselves
     bgdprof = nonzerobgd.dot(X)
-    #bgdprof = np.outer(nonzerobgd, X)
+    # bgdprof = np.outer(nonzerobgd, X)
     # print bgdprof
-    #bgdprof = bgdprof[0, :]
+    # bgdprof = bgdprof[0, :]
     # calculate peaks for crystal 1
 
     t1 = np.zeros(npt)  # initialise array containing profile
     for i in range(nref1):
         if pktype == 1:
             pkpars1[i][0] = pkpars1[i][0] * delam  # linear lambda shift
-            sig = pkwid1 * pkpars1[i][0] + pkwid2 * \
-                (pkpars1[i][0]**2.)  # const del(lambda)/lambda
-            extScl = pkpars1[i][0]**0  # lambda dependent extinction effect
+            sig = pkwid1 * pkpars1[i][0] + pkwid2 * (pkpars1[i][0] ** 2.)  # const del(lambda)/lambda
+            extScl = pkpars1[i][0] ** 0  # lambda dependent extinction effect
             t1 = t1 - extScl * pkmult1[int(eqvlab1[i])] * pkcalcint1[i] * (
-                np.exp(-((shftlam - pkpars1[i][0])**2.) / (2 * (sig**2))))
+                np.exp(-((shftlam - pkpars1[i][0]) ** 2.) / (2 * (sig ** 2))))
 
     # calculate peaks for crystal 2
     t2 = np.zeros(npt)  # initialise array containing profile
     for i in range(nref2):
         if pktype == 1:
             pkpars2[i][0] = pkpars2[i][0] * delam  # linear lambda shift
-            sig = pkwid1 * pkpars2[i][0] + pkwid2 * \
-                (pkpars2[i][0]**2.)  # const del(lambda)/lambda
-            extScl = pkpars2[i][0]**0  # lambda dependent extinction effect
+            sig = pkwid1 * pkpars2[i][0] + pkwid2 * (pkpars2[i][0] ** 2.)  # const del(lambda)/lambda
+            extScl = pkpars2[i][0] ** 0  # lambda dependent extinction effect
             t2 = t2 - extScl * pkmult2[int(eqvlab2[i])] * pkcalcint2[i] * (
-                np.exp(-(shftlam - pkpars2[i][0])**2. / (2 * (sig**2))))
+                np.exp(-(shftlam - pkpars2[i][0]) ** 2. / (2 * (sig ** 2))))
 
     # calculate final profile
     ttot = (bgdprof + sf * t1) * (bgdprof + sf * t2)
-    #t1 = 1.0;
+    # t1 = 1.0;
     # t2 = 1.0;
     # introduce weighting function and calc chi2...
     w = np.ones(len(shftlam))  # equal weighting everywhere
-    #i1 = np.where(shftlam > 2.15)[0][0]
-    #j1 = np.where(shftlam > 2.65)[0][0]
+    # i1 = np.where(shftlam > 2.15)[0][0]
+    # j1 = np.where(shftlam > 2.65)[0][0]
     # w[i1:j1] = 5 #extra weighting in region of first peaks
     # i1 = find(lam>1.68,1,'first');
     # j1 = find(lam>2.05,1,'first');
     # w(i1:j1)=5; %extra weighting but not too much
 
     resid = (y - ttot) * w
-    chi2 = np.sum(resid**2. / (2 * e**2)) / npt
+    chi2 = np.sum(resid ** 2. / (2 * e ** 2)) / npt
 
     # Print if the user wants verbose minimization
     if function_verbose == 'y':
-        print('Chi^2 ... ' + str(chi2))
+        print(('Chi^2 ... ' + str(chi2)))
 
     return chi2
 
@@ -921,10 +919,10 @@ def FitTrans():
         print('*diamonds allowed to have different dip intensities!*')
 
     if cnstang == 1:
-        print(
-            '*Diam {0} setting angles constrained to range of +/- {1} about their current values*'.format(1, anglim1))
-        print(
-            '*Diam {0} setting angles constrained to range of +/- {1} about their current values*'.format(2, anglim2))
+        print((
+            '*Diam {0} setting angles constrained to range of +/- {1} about their current values*'.format(1, anglim1)))
+        print((
+            '*Diam {0} setting angles constrained to range of +/- {1} about their current values*'.format(2, anglim2)))
     else:
         print('no constraint on setting angles')
 
@@ -932,13 +930,13 @@ def FitTrans():
         print('*intensity multipliers fixed*')
 
     # Get Input Files...
-    peaks_file = str(raw_input('Name of file containing diamond peaks: '))
+    peaks_file = str(input('Name of file containing diamond peaks: '))
 
-    run_number = str(raw_input('Input run number for transmission data: '))
+    run_number = str(input('Input run number for transmission data: '))
 
     # Build input filenames
-    #fullfilename_ub1 = str(run_number) + 'UB1.dat' # unused variable
-    #fullfilename_ub2 = str(run_number) + 'UB2.dat' # unused variable
+    # fullfilename_ub1 = str(run_number) + 'UB1.dat' # unused variable
+    # fullfilename_ub2 = str(run_number) + 'UB2.dat' # unused variable
     fullfilename_trans = 'transNorm' + str(run_number) + '.dat'
 
     # get both UB's
@@ -948,13 +946,13 @@ def FitTrans():
     #     uigetfile('*.dat','Choose UB matrix for upstream diamond:');
     # fullfilename = [pathname filename];
     # fullfilename_ub1 = 'snap13108UB1.dat'
-    #UB1, remainder = getISAWub(fullfilename_ub1)
+    # UB1, remainder = getISAWub(fullfilename_ub1)
 
     # [filename pathname ~] = ...
     #     uigetfile('*.dat','Choose UB matrix for downstream diamond:');
     # fullfilename = [pathname filename];
     # fullfilename_ub2 = 'snap13108UB2.dat'
-    #UB2, remainder = getISAWub(fullfilename_ub2)
+    # UB2, remainder = getISAWub(fullfilename_ub2)
 
     # get transmission data...
     # [filename,pathname,~] = ...
@@ -963,7 +961,7 @@ def FitTrans():
     fullfilename_trans = 'transNorm13148.csv'
     TOF, yin, ein = getMANTIDdat_keepbinning(fullfilename_trans)
 
-    print('Starting refinement for: ' + fullfilename_trans)
+    print(('Starting refinement for: ' + fullfilename_trans))
 
     # set-up simulation
 
@@ -982,8 +980,8 @@ def FitTrans():
     # rebin transmission data
     lam = 0.0039558 * TOF / (L1 + initL2)
 
-    print('wavelength limits: ' +
-          str(lam[0]) + ' and ' + str(lam[len(lam) - 1]))
+    print(('wavelength limits: ' +
+           str(lam[0]) + ' and ' + str(lam[len(lam) - 1])))
     minlam = 0.8
     maxlam = 3.5
     imin = np.where(lam >= minlam)[0][0]
@@ -1009,7 +1007,7 @@ def FitTrans():
 
     # initial conditions for crystal 2
     setang2 = np.zeros(3)
-    #setang2[1:3][0] = 0.0
+    # setang2[1:3][0] = 0.0
     a, b, c = pkposcalc(allhkl, UB2, setang2)
     pkpars2 = np.column_stack((a, b, c))
 
@@ -1034,8 +1032,8 @@ def FitTrans():
             hkl2 = np.vstack([hkl2, allhkl[i]])
             k2 += 1
 
-    print('There are: ' + str(k1) + ' expected dips due to Crystal 1')
-    print('There are: ' + str(k2) + ' expected dips due to Crystal 2')
+    print(('There are: ' + str(k1) + ' expected dips due to Crystal 1'))
+    print(('There are: ' + str(k2) + ' expected dips due to Crystal 2'))
 
     # determine equivalents
     # returns array with same dim as input labelling equivs
@@ -1058,7 +1056,7 @@ def FitTrans():
     pkcalcint2 *= 1e-6
     pkmult2 = np.ones(neqv2)  # peak intensity multiplier
 
-    relsf = 1.0    # default value
+    relsf = 1.0  # default value
     delam = 1.0
     L2 = initL2
     tbgd = bgd
@@ -1066,38 +1064,37 @@ def FitTrans():
     # Either generate, or read variable array from file
     # This is one big array with all the parameters to be refined in it.
 
-    prevf = str(raw_input('Look for pars from a previous run ([y]/n)? '))
+    prevf = str(input('Look for pars from a previous run ([y]/n)? '))
 
     if prevf == 'n':
         x0 = np.hstack((setang1, pkmult1, setang2, pkmult2, sf,
                         pkwid, tbgd, pkwid2, relsf, delam, L2))
     else:
-            # choose which file to use
-        parfilename = str(raw_input('Choose file with starting pars: '))
+        # choose which file to use
+        parfilename = str(input('Choose file with starting pars: '))
         parfullfilename = parfilename
         x0 = dlmread(parfullfilename)
-        tog = str(raw_input('Got parameters from: \n' +
-                            parfilename + '\nUse these ([y]/n)?'))
+        tog = str(input('Got parameters from: \n' +
+                        parfilename + '\nUse these ([y]/n)?'))
         if tog == 'n':
             x0 = np.hstack((setang1, pkmult1, setang2, pkmult2,
                             sf, pkwid, tbgd, pkwid2, relsf, delam, L2))
             print('discarding pars from previous run')
 
-    print(str(len(x0)) + ' parameters will be refined')
+    print((str(len(x0)) + ' parameters will be refined'))
 
     nvar = len(x0)
-    print('number of variables: ' + str(nvar))
-    #nref1 = hkl1.shape[0] # unused variable
-    #nref2 = hkl2.shape[0] # unused variable
+    print(('number of variables: ' + str(nvar)))
+    # nref1 = hkl1.shape[0] # unused variable
+    # nref2 = hkl2.shape[0] # unused variable
 
     # need to apply correction in the case that pars from previous run had
     # fxsamediam==1 and current run also has fxsamediam==1
     # to avoid a double multiplication by relsf
 
     if fxsamediam == 1 and x0[neqv1 + neqv2 + 11] != 1:
-        x0[6 + neqv1:7 + neqv1 + neqv2 - 1] = x0[3:4 +
-                                                 neqv2 - 1] / x0[neqv1 + neqv2 + 11]
-        print('Diam 2 peak multipliers reset: ' + str(x0[neqv1 + neqv2 + 11]))
+        x0[6 + neqv1:7 + neqv1 + neqv2 - 1] = x0[3:4 + neqv2 - 1] / x0[neqv1 + neqv2 + 11]
+        print(('Diam 2 peak multipliers reset: ' + str(x0[neqv1 + neqv2 + 11])))
 
     # check starting point
 
@@ -1113,7 +1110,7 @@ def FitTrans():
     plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                ncol=3, mode="expand", borderaxespad=0.)
     plt.show()
-    print('Initial chi^2 is: ' + str(chi2))
+    print(('Initial chi^2 is: ' + str(chi2)))
 
     showx3(x0)
 
@@ -1125,7 +1122,7 @@ def FitTrans():
     A[3:4 + neqv1 - 1] = -1.0  # pkmult1 Contrains intensities to be positive
     A[4 + neqv1 - 1:6 + neqv1] = 0.0  # setang2 *no constraint
     A[6 + neqv1:7 + neqv1 + neqv2 - 1] = -1.0  # pkmult2
-    A[6 + neqv1 + neqv2] = -1.0     # sf Scale factor must be +ve
+    A[6 + neqv1 + neqv2] = -1.0  # sf Scale factor must be +ve
     A[7 + neqv1 + neqv2] = -1.0  # pkwid peak width must be +ve
     A[neqv1 + neqv2 + 8:neqv1 + neqv2 + 9 + 2 - 1] = 0.0  # bgd *no constraint
     A[(neqv1 + neqv2 + 10)] = 0.0  # *no constraint
@@ -1139,7 +1136,7 @@ def FitTrans():
     Aeq[3:4 + neqv1 - 1] = 0.0  # pkmult1
     Aeq[4 + neqv1 - 1:6 + neqv1] = 0.0  # setang2
     Aeq[6 + neqv1:7 + neqv1 + neqv2 - 1] = 0.0  # pkmult2
-    Aeq[6 + neqv1 + neqv2] = 0.0     # sf
+    Aeq[6 + neqv1 + neqv2] = 0.0  # sf
     Aeq[7 + neqv1 + neqv2] = 0.0  # pkwid
     Aeq[neqv1 + neqv2 + 8:neqv1 + neqv2 + 9 + 2 - 1] = 0  # unfixed bgd
     Aeq[neqv1 + neqv2 + 10] = 0
@@ -1147,7 +1144,7 @@ def FitTrans():
     Aeq[neqv1 + neqv2 + 12] = 0
     Aeq[neqv1 + neqv2 + 13] = 0
 
-    #beq = 0 # unused variable
+    # beq = 0 # unused variable
 
     # lower bounds
     lb = np.zeros(len(x0))
@@ -1155,7 +1152,7 @@ def FitTrans():
     lb[3:4 + neqv1 - 1] = 0.5  # pkmult1
     lb[4 + neqv1 - 1:6 + neqv1] = -10  # setang2
     lb[6 + neqv1:7 + neqv1 + neqv2 - 1] = 0.5  # pkmult2
-    lb[6 + neqv1 + neqv2] = 0.0     # sf
+    lb[6 + neqv1 + neqv2] = 0.0  # sf
     lb[7 + neqv1 + neqv2] = 0.0005  # pkwid
     lb[neqv1 + neqv2 + 8:neqv1 + neqv2 + 9 + 2 - 1] = [0.995, -0.0005]  # bgd
     lb[neqv1 + neqv2 + 10] = 0.5e-4  # 2nd order pkwid
@@ -1170,7 +1167,7 @@ def FitTrans():
     ub[3:4 + neqv1 - 1] = 50  # pkmult1
     ub[4 + neqv1 - 1:6 + neqv1] = 10  # setang2
     ub[6 + neqv1:7 + neqv1 + neqv2 - 1] = 50  # pkmult2
-    ub[6 + neqv1 + neqv2] = 50     # sf
+    ub[6 + neqv1 + neqv2] = 50  # sf
     ub[7 + neqv1 + neqv2] = 0.01  # pkwid
     ub[neqv1 + neqv2 + 8:neqv1 + neqv2 + 9 + 2 - 1] = [1.005, 0.0005]  # bgd
     ub[neqv1 + neqv2 + 10] = 1.0e-2  # 2nd order pkwid
@@ -1206,12 +1203,12 @@ def FitTrans():
         ub[6 + neqv1:7 + neqv1 + neqv2 - 1] = x0[6 +
                                                  neqv1:7 + neqv1 + neqv2 - 1] + 0.01
 
-    prompt = str(raw_input('Enter anything to begin refinement...'))
+    prompt = str(input('Enter anything to begin refinement...'))
     print('Refining...\nMight take quite a long time...')
 
     max_number_iterations = int(
-        raw_input('Maximum number of iterations for minimization: '))
-    function_verbose = str(raw_input('Verbose minimization ([y]/n): '))
+        input('Maximum number of iterations for minimization: '))
+    function_verbose = str(input('Verbose minimization ([y]/n): '))
 
     # make dictionary holding constraints for minimization
     # equalities (all must equal 0) and inequalities
@@ -1222,8 +1219,8 @@ def FitTrans():
 
     # bounds have to be list of tuples with (lower, upper) for each parameter
     bds = np.vstack((lb, ub)).T
-    res = sp.minimize(SimTrans3, x0, method='SLSQP', bounds=bds, constraints=cons, options={'disp': True,
-                                                                                            'maxiter': max_number_iterations})
+    res = sp.minimize(SimTrans3, x0, method='SLSQP', bounds=bds, constraints=cons,
+                      options={'disp': True, 'maxiter': max_number_iterations})
 
     # tolerance limits to put in minimization if you want so : 'ftol': 0.001
 
@@ -1244,10 +1241,8 @@ def FitTrans():
         # len(x)
         # neqv1+neqv2+11
         # x[neqv1+neqv2+11]
-        x[6 + neqv1:7 + neqv1 + neqv2 - 1] = x[3:4 +
-                                               neqv2 - 1] * x[neqv1 + neqv2 + 11]
-        print('Diam 2 peak multipliers reset with factor: ' +
-              str(x[neqv1 + neqv2 + 11]))
+        x[6 + neqv1:7 + neqv1 + neqv2 - 1] = x[3:4 + neqv2 - 1] * x[neqv1 + neqv2 + 11]
+        print(('Diam 2 peak multipliers reset with factor: ' + str(x[neqv1 + neqv2 + 11])))
     else:
         # label ensuring I know that run did not use fxsamediam
         x[neqv1 + neqv2 + 11] = 1.0
@@ -1261,13 +1256,13 @@ def FitTrans():
 
     # calculate chi2 for best fit
     chi2 = SimTrans3(x)
-    print('Final Chi2 = ' + str(chi2))
+    print(('Final Chi2 = ' + str(chi2)))
 
     # determine output wavelength range using refined L2 value
 
-    #lamscale = x[neqv1 + neqv2 + 12] # unused variable
+    # lamscale = x[neqv1 + neqv2 + 12] # unused variable
     L2 = x[neqv1 + neqv2 + 13]
-    outlam = 0.0039558 * TOF / (L1 + L2) + difa * (TOF**2)
+    outlam = 0.0039558 * TOF / (L1 + L2) + difa * (TOF ** 2)
 
     fig_name_final = 'Final result ' + run_number
     plt.figure(fig_name_final)
@@ -1290,15 +1285,16 @@ def FitTrans():
     plt.ylabel('Transmission')
     plt.show()
 
-    prompt = str(raw_input('output best fit to file ([y]/n): '))
+    prompt = str(input('output best fit to file ([y]/n): '))
     if prompt == 'n':
         print('Ending')
     else:
         fitparname = str(run_number) + '.best_fit_pars3.dat'
         np.savetxt(fitparname, x, delimiter=',')
-        print('output parameters written to file: \n' + fitparname)
+        print(('output parameters written to file: \n' + fitparname))
         ofilename = str(run_number) + '.fitted3.dat'
         SimTransOutput3(ofilename, x)  # generate output file with fitted data
 
+
 if __name__ == "__main__":
     FitTrans()
diff --git a/scripts/Examples/HRPDDialog_Example.py b/scripts/Examples/HRPDDialog_Example.py
index e372796edf2c6de4fc69121638f8b7b3ae24c4fc..60f2dd88c7261fc6b126a045899a9e63da632967 100644
--- a/scripts/Examples/HRPDDialog_Example.py
+++ b/scripts/Examples/HRPDDialog_Example.py
@@ -1,10 +1,13 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 # First a function definition for the Loading algorithms which loads the data and immediately aligns the detectors
+import mantid.simpleapi as mantid
 
 
 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")
+    mantid.LoadRawDialog(OutputWorkspace=outputArea, Message="Enter path to the file containing the " + _type)
+    mantid.AlignDetectorsDialog(InputWorkspace=outputArea, OutputWorkspace=outputArea,
+                                Message="Enter path to calibration file")
+
 
 # ========== The script starts here ============
 dataWorkspace = "Vanadium"
@@ -12,31 +15,32 @@ LoadAndAlign("data", dataWorkspace)
 LoadAndAlign("empty run", "Empty")
 
 # ==== Just want pure Vanadium so subtract the empty instrument ===
-Minus(LHSWorkspace=dataWorkspace,RHSWorkspace="Empty",OutputWorkspace=dataWorkspace)
+mantid.Minus(LHSWorkspace=dataWorkspace, RHSWorkspace="Empty", OutputWorkspace=dataWorkspace)
 # Calculate absorption and correct for it
-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")
-Divide(dataWorkspace, transWorkspace, OutputWorkspace=dataWorkspace)
+transWorkspace = "Transmission"
+# The input workspace needs to be in units of wavelength for the CylinderAbsorption algorithm
+mantid.ConvertUnits(InputWorkspace=dataWorkspace, OutputWorkspace=dataWorkspace, Target="Wavelength")
+mantid.CylinderAbsorptionDialog(InputWorkspace=dataWorkspace, OutputWorkspace=transWorkspace,
+                                SampleNumberDensity="0.072",
+                                ScatteringXSection="5.08", AttenuationXSection="5.1", Message="Enter size parameters")
+mantid.Divide(dataWorkspace, transWorkspace, OutputWorkspace=dataWorkspace)
 
 # === Save as a Nexus file ===
-#SaveNexusProcessDialog(InputWorkspace=sampleWorkspace, message="Enter path to save Nexus file")
+# SaveNexusProcessDialog(InputWorkspace=sampleWorkspace, message="Enter path to save Nexus file")
 
 # === Load the sample data file ===
-sampleWorkspace="Sample"
+sampleWorkspace = "Sample"
 LoadAndAlign("sample", sampleWorkspace)
 
 # === Focus the data ===
-ConvertUnits(dataWorkspace,dataWorkspace,'dSpacing')
-alg = DiffractionFocussingDialog(InputWorkspace=dataWorkspace,OutputWorkspace=dataWorkspace)
+mantid.ConvertUnits(dataWorkspace, dataWorkspace, 'dSpacing')
+alg = mantid.DiffractionFocussingDialog(InputWorkspace=dataWorkspace, OutputWorkspace=dataWorkspace)
 calibFile = alg.getPropertyValue("GroupingFileName")
-StripPeaks(InputWorkspace=dataWorkspace, OutputWorkspace=dataWorkspace)
+mantid.StripPeaks(InputWorkspace=dataWorkspace, OutputWorkspace=dataWorkspace)
 
 # === Focus the sample ===
-DiffractionFocussing(InputWorkspace=sampleWorkspace,OutputWorkspace=sampleWorkspace,GroupingFileName=calibFile)
+mantid.DiffractionFocussing(InputWorkspace=sampleWorkspace, OutputWorkspace=sampleWorkspace, GroupingFileName=calibFile)
 
 # === The result is the sample corrected by the vandium ===
-resultSpace="Result"
-Divide(sampleWorkspace, dataWorkspace, OutputWorkspace=resultSpace)
+resultSpace = "Result"
+mantid.Divide(sampleWorkspace, dataWorkspace, OutputWorkspace=resultSpace)
diff --git a/scripts/Examples/InstrumentView_Example.py b/scripts/Examples/InstrumentView_Example.py
index 91fe8ee0b8b0941faa4c4f3be6c223e7cc668a68..c20e7f4258e42f6522d86cf2fea40d76f1085864 100644
--- a/scripts/Examples/InstrumentView_Example.py
+++ b/scripts/Examples/InstrumentView_Example.py
@@ -1,24 +1,23 @@
-#pylint: disable=invalid-name
-#
 # Example: Instrument view control
 #
+import mantid.simpleapi as mantid
 
 # Get some data
-LoadRaw("LOQ48094.raw","LOQTest")
+mantid.LoadRaw("LOQ48094.raw", "LOQTest")
 
-insView = getInstrumentView("LOQTest")
+insView = mantid.getInstrumentView("LOQTest")
 
-#insView.changeColorMap("../../../repo/installers/colormaps/Jet.map")   # Change to the correct path
+# insView.changeColorMap("../../../repo/installers/colormaps/Jet.map")   # Change to the correct path
 
-insView.setColorMapRange(0.,195)
+insView.setColorMapRange(0., 195)
 # Or can set a minimum and maximum separately
-#insView.setColorMapMinValue(1.)
-#insView.setColorMapMaxValue(10.)
+# insView.setColorMapMinValue(1.)
+# insView.setColorMapMaxValue(10.)
 
 # Alter the binning range
-insView.setBinRange(10000,15000)
+insView.setBinRange(10000, 15000)
 
 # Select an individual component
-#insView.selectComponent("main-detector-pixel")
+# insView.selectComponent("main-detector-pixel")
 
 insView.show()
diff --git a/scripts/Examples/PlotAsymmetryByLogValue_Example.py b/scripts/Examples/PlotAsymmetryByLogValue_Example.py
index b9ea09ffbcfdcd48bff7eeb336ccf3b581244492..d1c5abd91f684e7fff8a2e473267b3884d645bb1 100644
--- a/scripts/Examples/PlotAsymmetryByLogValue_Example.py
+++ b/scripts/Examples/PlotAsymmetryByLogValue_Example.py
@@ -1,22 +1,23 @@
-#pylint: disable=invalid-name
 # -----------------------------------------------------
-#  Runs PlotAssymetryByLogValue algorithm
+#  Runs PlotAsymmetryByLogValue algorithm
 #  and plots the output in MantidPlot using a Python
 #  dictionary
-#------------------------------------------------------
+# ------------------------------------------------------
+import mantid.simpleapi as mantid
+from six import iteritems
 
 # Execute the algorithm
-alg = PlotAsymmetryByLogValueDialog()
+alg = mantid.PlotAsymmetryByLogValueDialog()
 
 # Get the output workspace
 ws = alg.getPropertyValue("OutputWorkspace")
 
-spectra_plot = { 0 : 'Difference' }
+spectra_plot = {0: 'Difference'}
 if int(alg.getPropertyValue("Green")) < 1000:
     spectra_plot[1] = 'Red'
     spectra_plot[2] = 'Green'
     spectra_plot[3] = 'Sum'
 
-gs = plotSpectrum(ws, spectra_plot.keys())
-for key, value in spectra_plot.iteritems():
+gs = mantid.plotSpectrum(ws, spectra_plot.keys())
+for key, value in iteritems(spectra_plot):
     gs.activeLayer().setCurveTitle(key, value)
diff --git a/scripts/Examples/SampleLogs_Demo.py b/scripts/Examples/SampleLogs_Demo.py
index b1c54bb46fd4a8c2cee4d733c21012c674cadcb5..c91da1e28b0efd4f42d481571f4bc607c51078f1 100644
--- a/scripts/Examples/SampleLogs_Demo.py
+++ b/scripts/Examples/SampleLogs_Demo.py
@@ -1,24 +1,24 @@
-#pylint: disable=invalid-name
 #
 # Example: Retrieving log information from a data set
 #
+import mantid.simpleapi as mantid
 
 datadir = "../../../repo/Test/Data/"
 rawDataTitle="outputSpace"
 # Load the crisp data set which we have log information for
-ws = LoadRaw(Filename = datadir+"Full point detector CRISP dataset/csp79590.raw",OutputWorkspace=rawDataTitle)
+ws = mantid.LoadRaw(Filename = datadir+"Full point detector CRISP dataset/csp79590.raw",OutputWorkspace=rawDataTitle)
 
 if isinstance(ws,tuple):
     ws = ws[0]
 
 # This is a grouped file so get the first workspace
-rawWS = mtd[ws.getNames()[0]]
+rawWS = mantid.mtd[ws.getNames()[0]]
 logs = rawWS.getRun().getLogData()
 
 # Print all of the log information
 for i in range(0, len(logs)):
-    print "----- " + logs[i].name + " -------\n" +  str(logs[i].value)
+    print("----- " + logs[i].name + " -------\n" +  str(logs[i].value))
 
 # Just get a single log by name
 status = rawWS.getRun().getLogData("status")
-print status.value
+print(status.value)
diff --git a/scripts/Examples/SimpleMtdCommands_Example.py b/scripts/Examples/SimpleMtdCommands_Example.py
index ed5b145a58cd273a2e98c72643054b2df4fe10a7..c4f2bcdded5305173a5e03faa2359a7429bb7d86 100644
--- a/scripts/Examples/SimpleMtdCommands_Example.py
+++ b/scripts/Examples/SimpleMtdCommands_Example.py
@@ -1,25 +1,26 @@
-#pylint: disable=invalid-name
 #
 # Example: Basic Mantid commands
 #
 
+import mantid.simpleapi as mantid
+
 # Print the available algorithms
-mtdHelp()
+mantid.mtdHelp()
 
 # Print information on a specific algorithm
-mtdHelp(LoadRaw)
+mantid.mtdHelp(mantid.LoadRaw)
 
 # Perform some algorithms
-LoadRaw("HET15869.raw", OutputWorkspace="test")
-ConvertUnits("test","dSpacing", OutputWorkspace="converted")
-Rebin("converted","0.1,0.001,5", OutputWorkspace="rebinned")
+mantid.LoadRaw("HET15869.raw", OutputWorkspace="test")
+mantid.ConvertUnits("test", "dSpacing", OutputWorkspace="converted")
+mantid.Rebin("converted", "0.1,0.001,5", OutputWorkspace="rebinned")
 
 # clear up intermediate workspaces
-DeleteWorkspace("test")
-DeleteWorkspace("converted")
+mantid.DeleteWorkspace("test")
+mantid.DeleteWorkspace("converted")
 
 # extract the one we want
-wksp = mtd['rebinned']
+wksp = mantid.mtd['rebinned']
 
-print "Rebinned workspace has " + str(wksp.getNumberHistograms()) + " histograms"
-print "Spectrum 450's X data size = " + str(len(wksp.readX(450))) + " bin boundaries"
+print("Rebinned workspace has " + str(wksp.getNumberHistograms()) + " histograms")
+print("Spectrum 450's X data size = " + str(len(wksp.readX(450))) + " bin boundaries")
diff --git a/scripts/Examples/SolidAngle_Example.py b/scripts/Examples/SolidAngle_Example.py
index c6b2bc50220d521ecc0f5cbbced38a60bbda959f..90fcc206f82b169e37a76427738f414492c3734b 100644
--- a/scripts/Examples/SolidAngle_Example.py
+++ b/scripts/Examples/SolidAngle_Example.py
@@ -1,4 +1,3 @@
-#pylint: disable=invalid-name
 ##-------------------------------------------------------------------------
 ##
 ## Example: Calculating the solid angle for a spectrum with respect to the
@@ -6,8 +5,11 @@
 ##
 ##-------------------------------------------------------------------------
 # Prompt for a raw file to load
+import mantid.simpleapi as mantid
+import math
+
 rawWSTitle = "RawFile"
-LoadRawDialog(OutputWorkspace=rawWSTitle)
+mantid.LoadRawDialog(OutputWorkspace=rawWSTitle)
 
 # Get the loaded workspace from Mantid
 rawData = mantid.getMatrixWorkspace(rawWSTitle)
@@ -26,11 +28,11 @@ r = detector.getDistance(sample)
 twoTheta = detector.getTwoTheta(samplePos, beamPos)*180./math.pi
 phi = detector.getPhi()
 
-print 'R = ' + str(r) + ', TwoTheta = ' + str(twoTheta)+ ', Phi = ' + str(phi)
+print('R = ' + str(r) + ', TwoTheta = ' + str(twoTheta)+ ', Phi = ' + str(phi))
 
 # Check if the spectrum is masked out and calculate the result if not
 solidAngle = 0.0
 if not rawData.spectrumInfo().isMasked(0):
-    sAngle = detector.solidAngle(samplePos)
+    solidAngle = detector.solidAngle(samplePos)
 
-print "The solid angle of the spectrum located at index " + str(wsIndex) + " is: " + str(sAngle) + " steradians"
+print("The solid angle of the spectrum located at index " + str(wsIndex) + " is: " + str(solidAngle) + " steradians")
diff --git a/scripts/Examples/StripPeaks.py b/scripts/Examples/StripPeaks.py
index 32bd47a83b62412f8ace86f974295bf87d16866a..c36cdb76b4469689efea66dde5b772a0a78b85d6 100644
--- a/scripts/Examples/StripPeaks.py
+++ b/scripts/Examples/StripPeaks.py
@@ -1,20 +1,20 @@
-#pylint: disable=invalid-name
 # MantidPlot example script
 #
 # Using StripPeaks + dialog boxes
 #
+import mantid.simpleapi as mantid
 
-LoadRawDialog(OutputWorkspace="GEM40979")
-alg= AlignDetectorsDialog("GEM40979",OutputWorkspace="aligned")
-DeleteWorkspace("GEM40979")
+mantid.LoadRawDialog(OutputWorkspace="GEM40979")
+alg = mantid.AlignDetectorsDialog("GEM40979", OutputWorkspace="aligned")
+mantid.DeleteWorkspace("GEM40979")
 calfile = alg.getPropertyValue("CalibrationFile")
-DiffractionFocussing("aligned",calfile,OutputWorkspace="focussed")
-DeleteWorkspace("aligned")
-StripPeaks("focussed",OutputWorkspace="stripped")
+mantid.DiffractionFocussing("aligned", calfile, OutputWorkspace="focussed")
+mantid.DeleteWorkspace("aligned")
+mantid.StripPeaks("focussed", OutputWorkspace="stripped")
 
 # Plot a spectrum from each remaining workspace
-g1 = plotSpectrum(["focussed","stripped"],5)
+g1 = mantid.plotSpectrum(["focussed", "stripped"], 5)
 
 # Rescale the x-axis to show an interesting region
-g1.activeLayer().setScale(Layer.Bottom,0,2.3)
-print "Done!"
+g1.activeLayer().setScale(Layer.Bottom, 0, 2.3)
+print("Done!")
diff --git a/scripts/Examples/TableWorkspace_Example.py b/scripts/Examples/TableWorkspace_Example.py
index 8c79a9dcb0f585933ad6ed249d72e1736c97dc56..aab4b55aad0073004438752a30082696ce0d2c4e 100644
--- a/scripts/Examples/TableWorkspace_Example.py
+++ b/scripts/Examples/TableWorkspace_Example.py
@@ -1,20 +1,21 @@
-#pylint: disable=invalid-name
 # Perform some algorithms
-LoadRaw(Filename="GEM40979.raw",OutputWorkspace="GEM40979")
-AlignDetectors("GEM40979",OutputWorkspace="aligned",CalibrationFile="offsets_2006_cycle064.cal")
-DeleteWorkspace("GEM40979")
-DiffractionFocussing("aligned","offsets_2006_cycle064.cal",OutputWorkspace="focussed")
-DeleteWorkspace("aligned")
-FindPeaks("focussed",PeaksList="peakslist")
+import mantid.simpleapi as mantid
 
-peaks = mtd["peakslist"]
+mantid.LoadRaw(Filename="GEM40979.raw", OutputWorkspace="GEM40979")
+mantid.AlignDetectors("GEM40979", OutputWorkspace="aligned", CalibrationFile="offsets_2006_cycle064.cal")
+mantid.DeleteWorkspace("GEM40979")
+mantid.DiffractionFocussing("aligned", "offsets_2006_cycle064.cal", OutputWorkspace="focussed")
+mantid.DeleteWorkspace("aligned")
+mantid.FindPeaks("focussed", PeaksList="peakslist")
+
+peaks = mantid.mtd["peakslist"]
 help(peaks)
-print "Number of Columns: " + str(peaks.columnCount()) + " , Number of rows: "+ str(peaks.rowCount())
+print("Number of Columns: " + str(peaks.columnCount()) + " , Number of rows: " + str(peaks.rowCount()))
 
 colNames = peaks.getColumnNames()
 for i in colNames:
-    print i
+    print(i)
 
 for i in range(peaks.rowCount()):
     row = peaks.row(i)
-    print "Spectrum %d has peak at pos %f" % (row['spectrum'], row['centre'])
+    print("Spectrum %d has peak at pos %f" % (row['spectrum'], row['centre']))
diff --git a/scripts/HFIRPowderReduction/HfirPDReductionControl.py b/scripts/HFIRPowderReduction/HfirPDReductionControl.py
index be3b265ba0fa1198bfed47c7c783c0df216493f9..e826905c598351da8115edb8f4b9f314c8d72ab0 100644
--- a/scripts/HFIRPowderReduction/HfirPDReductionControl.py
+++ b/scripts/HFIRPowderReduction/HfirPDReductionControl.py
@@ -1,4 +1,4 @@
-#pylint: disable=too-many-lines,relative-import,invalid-name,too-many-instance-attributes,too-many-arguments
+# pylint: disable=too-many-lines,relative-import,invalid-name,too-many-instance-attributes,too-many-arguments
 ############################################################################
 #
 # HFIR powder reduction control class
@@ -6,21 +6,24 @@
 #
 ############################################################################
 import os
-import urllib2
+import urllib.request
+import urllib.error
+import urllib.parse
 import math
 
 import numpy
 
-import HfirUtility as hutil
+from . import HfirUtility as hutil
 
 # Import mantid
 import mantid.simpleapi as api
 from mantid.simpleapi import AnalysisDataService
-#from mantid.kernel import ConfigService
 
+# from mantid.kernel import ConfigService
 
-VanadiumPeakPositions = [0.5044,0.5191,0.5350,0.5526,0.5936,0.6178,0.6453,0.6768,
-                         0.7134,0.7566,0.8089,0.8737,0.9571,1.0701,1.2356,1.5133,2.1401]
+
+VanadiumPeakPositions = [0.5044, 0.5191, 0.5350, 0.5526, 0.5936, 0.6178, 0.6453, 0.6768,
+                         0.7134, 0.7566, 0.8089, 0.8737, 0.9571, 1.0701, 1.2356, 1.5133, 2.1401]
 
 
 class PDRManager(object):
@@ -54,8 +57,8 @@ class PDRManager(object):
 
         self._wavelength = None
 
-        #register startup
-        mantid.UsageService.registerFeatureUsage("Interface","HfirPowderReduction",False)
+        # register startup
+        api.UsageService.registerFeatureUsage("Interface", "HfirPowderReduction", False)
 
         return
 
@@ -88,11 +91,11 @@ class PDRManager(object):
         # Sum and average
         numpts = self._rawSpiceTableWS.rowCount()
         totalcounts = 0
-        for irow in xrange(numpts):
+        for irow in range(numpts):
             moncounts = self._rawSpiceTableWS.cell(irow, imonitor)
             totalcounts += moncounts
 
-        return float(totalcounts)/float(numpts)
+        return float(totalcounts) / float(numpts)
 
     def getProcessedVanadiumWS(self):
         """
@@ -141,7 +144,7 @@ class PDRManager(object):
         try:
             self.binsize = float(binsize)
         except TypeError as e:
-            print e
+            print(e)
 
         return
 
@@ -149,7 +152,7 @@ class PDRManager(object):
         """ Set 2 raw SPICE workspaces
         """
         # Validate
-        if  spice_table_ws.id() != 'TableWorkspace' or log_matrix_ws.id() != 'Workspace2D':
+        if spice_table_ws.id() != 'TableWorkspace' or log_matrix_ws.id() != 'Workspace2D':
             raise NotImplementedError("Input workspaces for setRawWorkspaces() are not of correct types.")
 
         self._rawSpiceTableWS = spice_table_ws
@@ -213,7 +216,8 @@ class PDRManager(object):
 
         return
 
-#pylint: disable=too-many-public-methods
+
+# pylint: disable=too-many-public-methods
 
 
 class HFIRPDRedControl(object):
@@ -224,8 +228,8 @@ class HFIRPDRedControl(object):
         """ Initialization
         """
         self._myWorkspaceDict = {}  # dictionary to manage all the workspaces reduced
-                                    # key = Exp/Scan
-        self._myMergedWSDict = {}   # key = Exp/Scan list
+        # key = Exp/Scan
+        self._myMergedWSDict = {}  # key = Exp/Scan list
 
         self._myWavelengthDict = {}
 
@@ -238,7 +242,7 @@ class HFIRPDRedControl(object):
         """
         if ((expno, scanno) in self._myWorkspaceDict) is False:
             raise NotImplementedError("Exp %d Scan %d does not have reduced \
-                    workspace." % (exp, scan))
+                    workspace." % (expno, scanno))
         else:
             rmanager = self._myWorkspaceDict[(expno, scanno)]
             rmanager.applySmoothVanadium(applysmooth)
@@ -276,18 +280,18 @@ class HFIRPDRedControl(object):
         # FUTURE: use **args
         if xlabel is None:
             tempoutws = \
-                    api.GetSpiceDataRawCountsFromMD(InputWorkspace=datamdws,
-                                                    MonitorWorkspace=monitormdws,
-                                                    Mode='Detector',
-                                                    DetectorID = detid,
-                                                    NormalizeByMonitorCounts=normalized)
+                api.GetSpiceDataRawCountsFromMD(InputWorkspace=datamdws,
+                                                MonitorWorkspace=monitormdws,
+                                                Mode='Detector',
+                                                DetectorID=detid,
+                                                NormalizeByMonitorCounts=normalized)
         else:
-            print "Plot detector %d's counts vs. sample log %s."%(detid, xlabel)
+            print("Plot detector %d's counts vs. sample log %s." % (detid, xlabel))
             tempoutws = \
                 api.GetSpiceDataRawCountsFromMD(InputWorkspace=datamdws,
                                                 MonitorWorkspace=monitormdws,
                                                 Mode='Detector',
-                                                DetectorID = detid,
+                                                DetectorID=detid,
                                                 XLabel=xlabel,
                                                 NormalizeByMonitorCounts=normalized)
 
@@ -326,7 +330,7 @@ class HFIRPDRedControl(object):
             tempoutws = api.GetSpiceDataRawCountsFromMD(InputWorkspace=datamdws,
                                                         MonitorWorkspace=monitormdws,
                                                         Mode='Pt.',
-                                                        Pt = ptno)
+                                                        Pt=ptno)
 
             vecx = tempoutws.readX(0)[:]
             vecy = tempoutws.readY(0)[:]
@@ -343,7 +347,7 @@ class HFIRPDRedControl(object):
         # check
         if ((expno, scanno) in self._myWorkspaceDict) is False:
             raise NotImplementedError("Exp %d Scan %d does not have reduced \
-                    workspace." % (exp, scan))
+                    workspace." % (expno, scanno))
 
         # get data
         rmanager = self._myWorkspaceDict[(expno, scanno)]
@@ -382,7 +386,7 @@ class HFIRPDRedControl(object):
         # ptnolist = self._getRunNumberList(datamdws=rmanager.datamdws)
 
         # get data
-        print "[DB] Plot sample log: XLabel = %s" % (xlabel)
+        print("[DB] Plot sample log: XLabel = %s" % (xlabel))
         tempoutws = api.GetSpiceDataRawCountsFromMD(InputWorkspace=datamdws,
                                                     MonitorWorkspace=monitormdws,
                                                     Mode='Sample Log',
@@ -424,7 +428,7 @@ class HFIRPDRedControl(object):
             procVanWs = wsmanager.getProcessedVanadiumWSTemp()
         else:
             procVanWs = wsmanager.getProcessedVanadiumWS()
-            #procVanWs = wsmanager._processedVanWS
+            # procVanWs = wsmanager._processedVanWS
 
         if procVanWs is None:
             raise NotImplementedError("Exp %d Scan %d does not have processed vanadium workspace." % (exp, scan))
@@ -470,7 +474,7 @@ class HFIRPDRedControl(object):
         wsmanager = self.getWorkspace(exp, scan, raiseexception=True)
         if wsmanager.datamdws is None:
             self._logError("Unable to rebin the data for exp=%d, scan=%d because either data MD workspace and \
-                monitor MD workspace is not present."  % (exp, scan))
+                monitor MD workspace is not present." % (exp, scan))
             return False
 
         wavelength = wsmanager.getWavelength()
@@ -478,12 +482,12 @@ class HFIRPDRedControl(object):
         # Convert the vanadium peaks' position from dSpacing to 2theta
         vanpeakpos2theta = []
         for peakpos in VanadiumPeakPositions:
-            lambda_over_2d =  wavelength/2./peakpos
+            lambda_over_2d = wavelength / 2. / peakpos
             if abs(lambda_over_2d) <= 1.:
-                twotheta = math.asin(lambda_over_2d)*2.*180/math.pi
+                twotheta = math.asin(lambda_over_2d) * 2. * 180 / math.pi
                 vanpeakpos2theta.append(twotheta)
             else:
-                print "Vanadium peak %f is out of d-Spacing range." % (peakpos)
+                print("Vanadium peak %f is out of d-Spacing range." % (peakpos))
 
         vanpeakpos2theta = sorted(vanpeakpos2theta)
         wsmanager.setVanadiumPeaks(vanpeakpos2theta)
@@ -535,7 +539,7 @@ class HFIRPDRedControl(object):
         """ Check whether an Exp/Scan has a reduced workspace
         """
         if ((exp, scan) in self._myWorkspaceDict) is False:
-            print self._myWorkspaceDict.keys()
+            print(list(self._myWorkspaceDict.keys()))
             return False
 
         if self._myWorkspaceDict[(exp, scan)].reducedws is None:
@@ -554,12 +558,12 @@ class HFIRPDRedControl(object):
 
         # load SPICE
         tablewsname = basewsname + "_RawTable"
-        infowsname  = basewsname + "ExpInfo"
+        infowsname = basewsname + "ExpInfo"
         api.LoadSpiceAscii(Filename=datafilename,
                            OutputWorkspace=tablewsname, RunInfoWorkspace=infowsname)
 
         tablews = AnalysisDataService.retrieve(tablewsname)
-        infows  = AnalysisDataService.retrieve(infowsname)
+        infows = AnalysisDataService.retrieve(infowsname)
         if tablews is None or infows is None:
             raise NotImplementedError('Unable to retrieve either spice table workspace %s or log workspace %s' % (
                 tablewsname, infowsname))
@@ -581,7 +585,7 @@ class HFIRPDRedControl(object):
         monitormdwslist = []
         self._lastWkspToMerge = []
 
-        print "[Checkpoint 0] Scans = ", str(scannolist)
+        print("[Checkpoint 0] Scans = ", str(scannolist))
         for scanno in sorted(scannolist):
             try:
                 wsmanager = self.getWorkspace(expno, scanno, True)
@@ -589,21 +593,21 @@ class HFIRPDRedControl(object):
                 monitormdwslist.append(wsmanager.monitormdws)
                 self._lastWkspToMerge.append(wsmanager)
             except KeyError as ne:
-                print '[Error] Unable to retrieve MDWorkspaces for Exp %d Scan %d due to %s.' % (
-                    expno, scanno, str(ne))
+                print('[Error] Unable to retrieve MDWorkspaces for Exp %d Scan %d due to %s.' % (
+                    expno, scanno, str(ne)))
                 scannolist.remove(scanno)
         # ENDFOR
 
-        print "[Checkpoing 1] Scans = ", str(scannolist)
+        print("[Checkpoing 1] Scans = ", str(scannolist))
 
         # Merge and binning
         if len(datamdwslist) > 1:
-            mg_datamdws = datamdwslist[0] +  datamdwslist[1]
+            mg_datamdws = datamdwslist[0] + datamdwslist[1]
             mg_monitormdws = monitormdwslist[0] + monitormdwslist[1]
         else:
             mg_datamdws = datamdwslist[0]
             mg_monitormdws = monitormdwslist[0]
-        for iw in xrange(2, len(datamdwslist)):
+        for iw in range(2, len(datamdwslist)):
             mg_datamdws += datamdwslist[iw]
             mg_monitormdws += monitormdwslist[iw]
 
@@ -659,7 +663,8 @@ class HFIRPDRedControl(object):
         if instrument.upper() == 'HB2A':
             excldetlist, errmsg = hutil.parseDetExclusionFile(excldetfname)
         else:
-            raise NotImplementedError('Instrument %s is not supported for parsing excluded detectors file.'%(instrument))
+            raise NotImplementedError(
+                'Instrument %s is not supported for parsing excluded detectors file.' % (instrument))
 
         return excldetlist, errmsg
 
@@ -668,13 +673,13 @@ class HFIRPDRedControl(object):
         """
         # Get reduction manager
         try:
-            wsmanager = self._myWorkspaceDict[ (int(expno), int(scanno) )]
+            wsmanager = self._myWorkspaceDict[(int(expno), int(scanno))]
         except KeyError:
-            raise NotImplementedError("Exp %d Scan %d has not been loaded yet." % (int(expno),int(scanno)))
+            raise NotImplementedError("Exp %d Scan %d has not been loaded yet." % (int(expno), int(scanno)))
 
         # Convert to MDWorkspace
         tablews = wsmanager.getRawSpiceTable()
-        infows  = wsmanager.getRawInfoMatrixWS()
+        infows = wsmanager.getRawInfoMatrixWS()
 
         basewsname = tablews.name().split('_RawTable')[0]
         datamdwsname = basewsname + "_DataMD"
@@ -718,7 +723,7 @@ class HFIRPDRedControl(object):
                 wsmanager = self._myWorkspaceDict[(exp, scan)]
             except ValueError:
                 # type error, return with false
-                return False, 'Scan number %s is not integer.'%(str(scan))
+                return False, 'Scan number %s is not integer.' % (str(scan))
             except KeyError:
                 # data has not been reduced yet. Reduce dat
                 self.reduceSpicePDData(exp, scan, unit='2theta',
@@ -731,7 +736,7 @@ class HFIRPDRedControl(object):
                 self.reduceSpicePDData(exp, scan, unit='2theta', xmin=min_x, xmax=max_x, binsize=bin_size)
 
             monitorcounts = wsmanager.getAverageMonitorCounts()
-            print '[DB] Exp %d Scan %d: average monitor counts = %.5f' % (exp, scan, monitorcounts)
+            print('[DB] Exp %d Scan %d: average monitor counts = %.5f' % (exp, scan, monitorcounts))
             # FUTURE: implement method ws_manager.reset_to_normalized() instead
             wsmanager.reducedws = wsmanager.reducedws / monitorcounts
         # END_FOR(scan)
@@ -758,7 +763,7 @@ class HFIRPDRedControl(object):
                 wsmanager = self._myWorkspaceDict[(exp, scan)]
             except ValueError:
                 # type error, return with false
-                return False, 'Scan number %s is not integer.'%(str(scan))
+                return False, 'Scan number %s is not integer.' % (str(scan))
             except KeyError:
                 # data has not been reduced yet. Reduce dat
                 self.reduceSpicePDData(exp, scan, unit='2theta',
@@ -771,14 +776,14 @@ class HFIRPDRedControl(object):
                 self.reduceSpicePDData(exp, scan, unit='2theta', xmin=min_x, xmax=max_x, binsize=bin_size)
 
             monitorcounts = wsmanager.getAverageMonitorCounts()
-            print '[DB] Exp %d Scan %d: average monitor counts = %.5f' % (exp, scan, monitorcounts)
+            print('[DB] Exp %d Scan %d: average monitor counts = %.5f' % (exp, scan, monitorcounts))
             wsmanager.reducedws = wsmanager.reducedws * monitorcounts
         # END_FOR(scan)
 
         return True, ''
 
     def reduceSpicePDData(self, exp, scan, unit, xmin, xmax, binsize, wavelength=None,
-                          excludeddetlist=None,scalefactor=None):
+                          excludeddetlist=None, scalefactor=None):
         """ Reduce SPICE powder diffraction data from MDEventWorkspaces
         Return - Boolean as reduction is successful or not
         """
@@ -804,14 +809,14 @@ class HFIRPDRedControl(object):
             scalefactor = 1.
         else:
             scalefactor = float(scalefactor)
-            print "[DB] Scale factor is %f." % (scalefactor)
+            print("[DB] Scale factor is %f." % (scalefactor))
 
         # Excluded detectors
         if excludeddetlist is None:
             excludeddetlist = []
         else:
-            print "[DB] Excluded detectors: %s"%(excludeddetlist), "Convert to numpy array", \
-                numpy.array(excludeddetlist)
+            print("[DB] Excluded detectors: %s" % (excludeddetlist), "Convert to numpy array",
+                  numpy.array(excludeddetlist))
 
         basewsname = datamdws.name().split("_DataMD")[0]
         outwsname = basewsname + "_Reduced"
@@ -819,12 +824,12 @@ class HFIRPDRedControl(object):
                                    InputMonitorWorkspace=monitormdws,
                                    OutputWorkspace=outwsname,
                                    BinningParams=binpar,
-                                   UnitOutput = unit,
+                                   UnitOutput=unit,
                                    NeutronWaveLength=wavelength,
                                    ExcludedDetectorIDs=numpy.array(excludeddetlist),
                                    ScaleFactor=scalefactor)
 
-        print "[DB] Reduction is finished.  Data is in workspace %s. " % (outwsname)
+        print("[DB] Reduction is finished.  Data is in workspace %s. " % (outwsname))
 
         # Set up class variable for min/max and
         outws = AnalysisDataService.retrieve(outwsname)
@@ -873,11 +878,11 @@ class HFIRPDRedControl(object):
                 raise e
             if detefffname is not None:
                 localdetefffname = os.path.join(localdatadir, detefffname)
-                print "[DB] Detector efficiency file name: %s From %s" % (detefffname, deteffurl)
+                print("[DB] Detector efficiency file name: %s From %s" % (detefffname, deteffurl))
                 if os.path.exists(localdetefffname) is False:
                     downloadFile(deteffurl, localdetefffname)
                 else:
-                    print "[Info] Detector efficiency file %s exists in directory %s." % (detefffname, localdatadir)
+                    print("[Info] Detector efficiency file %s exists in directory %s." % (detefffname, localdatadir))
             else:
                 localdetefffname = None
             # ENDIF
@@ -885,14 +890,14 @@ class HFIRPDRedControl(object):
             # excluded detectors file
             excldetfname, exclurl = hutil.makeExcludedDetectorFileName(exp)
             localexcldetfname = os.path.join(localdatadir, excldetfname)
-            print "[DB] Excluded det file name: %s From %s" % (excldetfname, exclurl)
+            print("[DB] Excluded det file name: %s From %s" % (excldetfname, exclurl))
             if os.path.exists(localexcldetfname) is False:
                 downloadstatus, errmsg = downloadFile(exclurl, localexcldetfname)
                 if downloadstatus is False:
                     localexcldetfname = None
-                    print "[Error] %s" % (errmsg)
+                    print("[Error] %s" % (errmsg))
             else:
-                print "[Info] Detector exclusion file %s exists in directory %s." % (excldetfname, localdatadir)
+                print("[Info] Detector exclusion file %s exists in directory %s." % (excldetfname, localdatadir))
 
             # Set to ws manager
             wsmanager.setWavelength(wavelength)
@@ -926,7 +931,7 @@ class HFIRPDRedControl(object):
         wsmanager = self.getWorkspace(exp, scan, raiseexception=True)
         if wsmanager.reducedws is None:
             raise NotImplementedError("Unable to rebin the data for exp=%d, scan=%d because \
-                    either data MD workspace and monitor MD workspace is not present."  % (exp, scan))
+                    either data MD workspace and monitor MD workspace is not present." % (exp, scan))
         else:
             wksp = wsmanager.reducedws
 
@@ -955,9 +960,8 @@ class HFIRPDRedControl(object):
         # ENDIF
 
         if "topas" in filetype:
-            sfilename = sfilename[:-4]+".xye"
+            sfilename = sfilename[:-4] + ".xye"
             api.SaveFocusedXYE(InputWorkspace=wksp,
-                               StartAtBankNumber=info["bank"],
                                Filename=sfilename,
                                Format="TOPAS")
         # ENDIF
@@ -1000,7 +1004,7 @@ class HFIRPDRedControl(object):
         # Get reduced workspace
         wsmanager = self.getWorkspace(expno, scanno, raiseexception=True)
         vanRun = wsmanager.getProcessedVanadiumWS()
-        outws = vanRun.name()+"_smooth"
+        outws = vanRun.name() + "_smooth"
 
         outws = api.FFTSmooth(InputWorkspace=vanRun,
                               OutputWorkspace=outws,
@@ -1028,7 +1032,7 @@ class HFIRPDRedControl(object):
         wksp = wsmanager.reducedws
         if wksp is None:
             raise NotImplementedError("Unable to rebin the data for exp=%d, scan=%d because either data MD workspace and \
-                monitor MD workspace is not present."  % (exp, scan))
+                monitor MD workspace is not present." % (exp, scan))
 
         # Convert unit to Time-of-flight by rebinning
         xaxis_unit = wksp.getAxis(0).getUnit().unitID()
@@ -1044,7 +1048,7 @@ class HFIRPDRedControl(object):
                 raise NotImplementedError('No vanadium peaks has been set up.')
         # ENDIF
 
-        outwsname = wksp.name()+"_rmVan"
+        outwsname = wksp.name() + "_rmVan"
         wksp = api.StripPeaks(InputWorkspace=wksp,
                               OutputWorkspace=outwsname,
                               PeakPositions=numpy.array(vanpeakposlist))
@@ -1062,7 +1066,7 @@ class HFIRPDRedControl(object):
         tablews.addColumn('double', 'Correction')
 
         for detid in sorted(vancorrdict.keys()):
-            tablews.addRow( [detid, vancorrdict[detid]] )
+            tablews.addRow([detid, vancorrdict[detid]])
 
         return tablews
 
@@ -1074,7 +1078,7 @@ class HFIRPDRedControl(object):
         ptnolist = []
 
         numexpinfo = datamdws.getNumExperimentInfo()
-        for i in xrange(numexpinfo):
+        for i in range(numexpinfo):
             expinfo = datamdws.getExperimentInfo(i)
             runid = expinfo.run().getProperty('run_number').value
             if runid >= 0:
@@ -1095,9 +1099,10 @@ class HFIRPDRedControl(object):
 
         return rvalue
 
-#-------------------------------------------------------------------------------
+
+# -------------------------------------------------------------------------------
 # External Methods
-#-------------------------------------------------------------------------------
+# -------------------------------------------------------------------------------
 
 
 def downloadFile(url, localfilepath):
@@ -1109,9 +1114,9 @@ def downloadFile(url, localfilepath):
     """
     # open URL
     try:
-        response = urllib2.urlopen(url)
+        response = urllib.request.urlopen(url)
         wbuf = response.read()
-    except urllib2.HTTPError as e:
+    except urllib.error.HTTPError as e:
         # Unable to download file
         if str(e).count('HTTP Error 404') == 1:
             return (False, str(e))
diff --git a/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py b/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py
index cb0e622476ba439a44369b7fb85c4159d2d24881..51dba73f12d11e3603b7c712d59467a76a123bc1 100644
--- a/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py
+++ b/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py
@@ -155,16 +155,17 @@ class UserProperties(object):
         else:
             pass
 
-    def get_rb_num(self,exp_date):
+    def get_rb_num(self, exp_date):
         """Returns short name of user's RB folder
            consisting of string RB and string representation of
            RB number e.g. RB1510324,
            used on the date specified
         """
         return os.path.basename(self._rb_dirs[exp_date])
+
     #
 
-    def get_rb_dir(self,exp_date):
+    def get_rb_dir(self, exp_date):
         """Returns full name name of user's RB folder corresponding to the
            experiment, with the data provided.
         """
@@ -197,7 +198,7 @@ class UserProperties(object):
             raise RuntimeError("User's experiment date is not defined. User undefined")
             #
 
-    def get_instrument(self,cycle_date_id):
+    def get_instrument(self, cycle_date_id):
         """Return the instrument, used in the cycle with the date specified"""
         return self._instrument[cycle_date_id]
 
@@ -263,6 +264,7 @@ class UserProperties(object):
         if error:
             raise RuntimeError("Experiment start date should be defined as"
                                " a sting in the form YYYYMMDD or YYMMDD but it is: {0}".format(start_date))
+
         #
 
         def convert_cycle_int(cycle_int):
@@ -351,6 +353,7 @@ class MantidConfigDirectInelastic(object):
        The class have to change/to be amended if the configuration
        changes or has additional features.
     """
+
     # pylint: disable=too-many-instance-attributes
     # It has as many as parameters describing ISIS configuration.
 
@@ -465,9 +468,10 @@ class MantidConfigDirectInelastic(object):
         else:
             return False
             #
+
     #
 
-    def get_user_file_description(self,instr_name=None):
+    def get_user_file_description(self, instr_name=None):
         """returbs full file name (with path) for an xml file which describes
            files, which should be copied to a user.
 
@@ -477,8 +481,8 @@ class MantidConfigDirectInelastic(object):
         """
         if self._user:
             if not instr_name:
-                instr_name =  self._user.instrument
-            return os.path.join(self._script_repo, 'direct_inelastic',instr_name,
+                instr_name = self._user.instrument
+            return os.path.join(self._script_repo, 'direct_inelastic', instr_name,
                                 self._user_files_descr)
         else:
             return self._user_files_descr
@@ -504,7 +508,7 @@ class MantidConfigDirectInelastic(object):
             return False
             #
 
-    def _fullpath_to_copy(self, short_source_file=None, short_target_file=None,cycle_id=None):
+    def _fullpath_to_copy(self, short_source_file=None, short_target_file=None, cycle_id=None):
         """Append full path to source and target files """
 
         if cycle_id:
@@ -526,7 +530,7 @@ class MantidConfigDirectInelastic(object):
         return full_source, full_target
 
     #
-    def copy_reduction_sample(self, user_file_description=None,cycle_id=None,rb_group=None):
+    def copy_reduction_sample(self, user_file_description=None, cycle_id=None, rb_group=None):
         """copy sample reduction scripts from Mantid script repository
            to user folder.
         """
@@ -535,9 +539,9 @@ class MantidConfigDirectInelastic(object):
         if rb_group is None:
             rb_group = self._user.userID
 
-        info_to_copy = self._parse_user_files_description(user_file_description,cycle_id)
-        for source_file,dest_file,subst_list in info_to_copy:
-            self._copy_user_file_job(source_file,dest_file,rb_group,subst_list)
+        info_to_copy = self._parse_user_files_description(user_file_description, cycle_id)
+        for source_file, dest_file, subst_list in info_to_copy:
+            self._copy_user_file_job(source_file, dest_file, rb_group, subst_list)
 
     def _copy_and_parse_user_file(self, input_file, output_file, replacemets_list):
         """Method processes file provided for user and replaces list of keywords, describing user
@@ -557,7 +561,7 @@ class MantidConfigDirectInelastic(object):
         fh_targ.close()
 
     #
-    def _copy_user_file_job(self, input_file, output_file, rb_group,replacement_list=None):
+    def _copy_user_file_job(self, input_file, output_file, rb_group, replacement_list=None):
         """Method copies file provided into the requested destination
            and replaces keys specified in replacement list dictionary with their
            values if replacement_list is provided.
@@ -576,7 +580,7 @@ class MantidConfigDirectInelastic(object):
             self._copy_and_parse_user_file(input_file, output_file, replacement_list)
         os.chmod(output_file, 0o777)
 
-        ownership_str = "chown {0}:{1} {2}".format(self._user.userID,rb_group, output_file)
+        ownership_str = "chown {0}:{1} {2}".format(self._user.userID, rb_group, output_file)
         if platform.system() != 'Windows':
             os.system(ownership_str)
         # Set up the file creation and modification dates to the users start date
@@ -584,7 +588,7 @@ class MantidConfigDirectInelastic(object):
         file_time = time.mktime(start_date.timetuple())
         os.utime(output_file, (file_time, file_time))
 
-    def _get_file_attributes(self, file_node,cycle=None):
+    def _get_file_attributes(self, file_node, cycle=None):
         """processes xml file_node to retrieve file attributes to copy """
 
         source_file = file_node.getAttribute("file_name")
@@ -597,7 +601,7 @@ class MantidConfigDirectInelastic(object):
         else:
             if "$" in target_file:
                 target_file = self._user.replace_variables(target_file)
-        full_source, full_target = self._fullpath_to_copy(source_file, target_file,cycle)
+        full_source, full_target = self._fullpath_to_copy(source_file, target_file, cycle)
 
         return (full_source, full_target)
 
@@ -615,13 +619,13 @@ class MantidConfigDirectInelastic(object):
         # what should be replaced in the file
         source = repl_info.getAttribute("var")
         if len(source) == 0:
-            raise InvalidArgument(
+            raise ValueError(
                 '"replace" field of {0} file for instrument {1} has to contain attribute "var" and its value'
                 .format(self._user_files_descr, self._user.instrument))
         # what should be placed instead of the replacement
         dest = repl_info.getAttribute("by_var")
         if len(dest) == 0:
-            raise InvalidArgument(
+            raise ValueError(
                 '"replace" field of {0} file for instrument {1} has to contain attribute "by_var" and its value'
                 .format(self._user_files_descr, self._user.instrument))
 
@@ -630,7 +634,7 @@ class MantidConfigDirectInelastic(object):
             dest = self._user.replace_variables(dest)
         return (source, dest)
 
-    def _parse_user_files_description(self, job_description_file,cycle_id=None):
+    def _parse_user_files_description(self, job_description_file, cycle_id=None):
         """ Method parses xml file used to describe files to provide to user"""
 
         # mainly for debugging purposes
@@ -646,7 +650,7 @@ class MantidConfigDirectInelastic(object):
         # have no idea what minidom specific exception is:
         # pylint: disable=W0703
         except Exception:
-            input_file, output_file = self._fullpath_to_copy(None,None,cycle_id)
+            input_file, output_file = self._fullpath_to_copy(None, None, cycle_id)
             filenames_to_copy.append((input_file, output_file, None))
             return filenames_to_copy
 
@@ -655,7 +659,7 @@ class MantidConfigDirectInelastic(object):
         # go through all files in the description and define file copying operations
         for file_node in files_to_copy:
             # retrieve file attributes or its default values if the attributes are missing
-            input_file, output_file = self._get_file_attributes(file_node,cycle_id)
+            input_file, output_file = self._get_file_attributes(file_node, cycle_id)
             if input_file is None:
                 continue
 
@@ -715,7 +719,7 @@ class MantidConfigDirectInelastic(object):
         users_instruments = theUser.get_all_instruments()
         for instr in users_instruments:
             if not self.is_inelastic(instr):
-                raise RuntimeError('Instrument {0} is not among acceptable instruments'.format(instrument))
+                raise RuntimeError('Instrument {0} is not among acceptable instruments'.format(instr))
         self._user = theUser
 
         # pylint: disable=W0201
@@ -830,7 +834,7 @@ class MantidConfigDirectInelastic(object):
         self._dynamic_configuration.append('datasearch.directories=' + map_mask_dir + ';' + data_dir)
 
     #
-    def generate_config(self,key_users_list=None):
+    def generate_config(self, key_users_list=None):
         """Save generated Mantid configuration file into user's home folder
            and copy other files, necessary for Mantid to work properly
         """
@@ -849,19 +853,19 @@ class MantidConfigDirectInelastic(object):
         self.make_map_mask_links(user_path)
 
         users_cycles = self._user.get_all_cycles()
-        users_rb     = self._user.get_all_rb()
+        users_rb = self._user.get_all_rb()
         # extract rb folder without path, which gives RB group name
-        users_rb     = list(map(os.path.basename,users_rb))
+        users_rb = list(map(os.path.basename, users_rb))
         #
-        for cycle,rb_name in zip(users_cycles,users_rb):
+        for cycle, rb_name in zip(users_cycles, users_rb):
             if key_users_list:
                 key_user = str(key_users_list[rb_name])
                 if self._fedid.lower() != key_user.lower():
                     continue
 
             instr = self._user.get_instrument(cycle)
-            self.copy_reduction_sample(self.get_user_file_description(instr),cycle,rb_name)
-        #
+            self.copy_reduction_sample(self.get_user_file_description(instr), cycle, rb_name)
+            #
 
     #
     def make_map_mask_links(self, user_path):
@@ -911,6 +915,7 @@ class MantidConfigDirectInelastic(object):
         file_time = time.mktime(start_date.timetuple())
         os.utime(config_file_name, (file_time, file_time))
 
+
 # pylint: disable = invalid-name
 
 if __name__ == "__main__":
@@ -947,9 +952,7 @@ if __name__ == "__main__":
 
     # initialize Mantid configuration
     # its testing route under main so it rightly imports itself
-    #pylint: disable=W0406
-    from .ISISDirecInelasticConfig import MantidConfigDirectInelastic, UserProperties
-
+    # pylint: disable=W0406
     mcf = MantidConfigDirectInelastic(MantidDir, rootDir, UserScriptRepoDir, MapMaskDir)
     print("Successfully initialized ISIS Inelastic Configuration script generator")
 
diff --git a/scripts/Inelastic/Direct/NonIDF_Properties.py b/scripts/Inelastic/Direct/NonIDF_Properties.py
index 6b1fffb112e70a62e8137ba21c4643b8aef656f7..2029ade3f5b308b68a3124c1b107374b0c1cd797 100644
--- a/scripts/Inelastic/Direct/NonIDF_Properties.py
+++ b/scripts/Inelastic/Direct/NonIDF_Properties.py
@@ -2,6 +2,8 @@
 from __future__ import (absolute_import, division, print_function)
 from Direct.PropertiesDescriptors import *
 from Direct.RunDescriptor import RunDescriptor,RunDescriptorDependent
+from mantid.simpleapi import *
+from mantid import geometry
 
 
 class NonIDF_Properties(object):
diff --git a/scripts/Inelastic/Direct/PropertiesDescriptors.py b/scripts/Inelastic/Direct/PropertiesDescriptors.py
index 8ba0a0dde6235f6509d4f8fe220beed695aee3cb..2cc58aa0567b55996d54b8c101518b29c2458144 100644
--- a/scripts/Inelastic/Direct/PropertiesDescriptors.py
+++ b/scripts/Inelastic/Direct/PropertiesDescriptors.py
@@ -1,5 +1,5 @@
-#pylint: disable=too-many-lines
-#pylint: disable=invalid-name
+# pylint: disable=too-many-lines
+# pylint: disable=invalid-name
 """ File contains collection of Descriptors used to define complex
     properties in NonIDF_Properties and PropertyManager classes
 """
@@ -9,44 +9,42 @@ import numpy as np
 import math
 from collections import Iterable
 
-from mantid.simpleapi import *
-#pylint: disable=unused-import
-from mantid.kernel import funcinspect
-#pylint: disable=unused-import
-from mantid import api,geometry,config
+import mantid.simpleapi as mantid
+from mantid import api
 
 import Direct.ReductionHelpers as prop_helpers
-#pylint: disable=unused-import
-import Direct.CommonFunctions as common
 import collections
 
 
-#-----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
 # Descriptors, providing overloads for complex properties in NonIDF_Properties
 # class
-#-----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
 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"""
         return []
-#pylint: disable=unused-argument
 
-    def validate(self,instance, owner):
+    # pylint: disable=unused-argument
+
+    def validate(self, instance, owner):
         """Interface to validate property descriptor,
            provided to check properties interaction before long run
 
            Return validation result, errors severity (0 -- fine, 1 -- warning, 2-- error)
            and error message if any
         """
-        return (True,0,'')
+        return (True, 0, '')
+
+
 # end PropDescriptor
 
-#-----------------------------------------------------------------------------------------
-#-----------------------------------------------------------------------------------------
-#-----------------------------------------------------------------------------------------
-#-----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
 
 
 class SumRuns(PropDescriptor):
@@ -54,25 +52,27 @@ class SumRuns(PropDescriptor):
        should be summed.
     """
 
-    def __init__(self,sample_run_prop):
+    def __init__(self, sample_run_prop):
         # internal reference to sample run property
         self._sample_run = sample_run_prop
         # class containing this property
         #
         self._sum_runs = False
+
     #
 
-    def __get__(self,instance,holder_class):
+    def __get__(self, instance, holder_class):
         if instance is None:
             return self
         return self._sum_runs
+
     #
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
         old_value = self._sum_runs
-        if isinstance(value,bool):
+        if isinstance(value, bool):
             self._sum_runs = value
-        elif isinstance(value,int):
+        elif isinstance(value, int):
             if value > 0:
                 self._sum_runs = True
             else:
@@ -81,8 +81,10 @@ class SumRuns(PropDescriptor):
             self._sum_runs = bool(value)
         #
         if old_value != self._sum_runs:
-            self._sample_run.notify_sum_runs_changed(old_value,self._sum_runs)
-#--------------------------------------------------------------------------------------------------------------------
+            self._sample_run.notify_sum_runs_changed(old_value, self._sum_runs)
+
+
+# --------------------------------------------------------------------------------------------------------------------
 
 
 class AvrgAccuracy(PropDescriptor):
@@ -93,14 +95,14 @@ class AvrgAccuracy(PropDescriptor):
     def __init__(self):
         self._accuracy = 2
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         """ return current number of significant digits"""
         if instance is None:
             return self
         else:
             return self._accuracy
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
         """ Set up incident energy or range of energies in various formats
             or define autoEi"""
         val = int(value)
@@ -108,24 +110,24 @@ class AvrgAccuracy(PropDescriptor):
             raise ValueError("Averaging accuracy can be only a positive number >= 1")
         self._accuracy = val
 
-    def roundoff(self,value):
+    def roundoff(self, value):
         """Round specified sequence for specified number of significant digits"""
-        if isinstance(value,Iterable):
+        if isinstance(value, Iterable):
             vallist = value
         else:
             vallist = [value]
         rez = []
-        lim = 10**(self._accuracy-1)
+        lim = 10 ** (self._accuracy - 1)
 
-        def out(a,b,mult):
-            if mult>1:
-                return a<b
+        def out(a, b, mult):
+            if mult > 1:
+                return a < b
             else:
-                return false
+                return False
 
         for val in vallist:
             if abs(val) > lim:
-                rez.append(round(val,0))
+                rez.append(round(val, 0))
                 continue
             elif abs(val) < lim:
                 mult = 10
@@ -133,11 +135,11 @@ class AvrgAccuracy(PropDescriptor):
                 mult = 1
 
             tv = abs(val)
-            fin_mult  = 1
-            while out(tv,lim,mult):
-                fin_mult*=mult
-                tv      *= mult
-            fin_rez = math.copysign(round(tv,0)/fin_mult,val)
+            fin_mult = 1
+            while out(tv, lim, mult):
+                fin_mult *= mult
+                tv *= mult
+            fin_rez = math.copysign(round(tv, 0) / fin_mult, val)
             rez.append(fin_rez)
         if len(rez) == 1:
             return rez[0]
@@ -145,7 +147,7 @@ class AvrgAccuracy(PropDescriptor):
             return rez
 
 
-#--------------------------------------------------------------------------------------------------------------------
+# --------------------------------------------------------------------------------------------------------------------
 class IncidentEnergy(PropDescriptor):
     """Provide incident energy or range of incident energies to be processed.
 
@@ -165,7 +167,7 @@ class IncidentEnergy(PropDescriptor):
         self._autoEiRunNumber = None
         self._autoEiCalculated = False
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         """ return  incident energy or list of incident energies """
         if instance is None:
             return self
@@ -173,33 +175,33 @@ class IncidentEnergy(PropDescriptor):
             return 'AUTO'
         else:
             return self._incident_energy
-#pylint: disable=too-many-branches
+            # pylint: disable=too-many-branches
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
         """ Set up incident energy or range of energies in various formats
             or define autoEi"""
         if value is not None:
-            if isinstance(value,str):
+            if isinstance(value, str):
                 # Check autoEi
                 if value.lower() == 'auto':
                     self._use_autoEi = True
                     currentRun = instance.sample_run
-                    if isinstance(currentRun,api.Workspace):
+                    if isinstance(currentRun, api.Workspace):
                         currentRun = currentRun.getRunNumber()
                     if currentRun != self._autoEiRunNumber or currentRun is None:
                         self._autoEiRunNumber = currentRun
                         self._autoEiCalculated = False
-                        self._incident_energy  = 0
+                        self._incident_energy = 0
                     self._cur_iter_en = 0
                     return
                 # Ei in string form is provided
                 else:
                     if value.find('[') > -1:
                         energy_list = True
-                        value = value.replace('[','').replace(']','').strip()
+                        value = value.replace('[', '').replace(']', '').strip()
                     else:
                         energy_list = False
-                    en_list = str.split(value,',')
+                    en_list = str.split(value, ',')
                     if len(en_list) > 1:
                         rez = []
                         for en_str in en_list:
@@ -212,7 +214,7 @@ class IncidentEnergy(PropDescriptor):
                         else:
                             self._incident_energy = float(value)
             else:
-                if isinstance(value,list):
+                if isinstance(value, list):
                     rez = []
                     for val in value:
                         en_val = float(val)
@@ -228,67 +230,72 @@ class IncidentEnergy(PropDescriptor):
         # here we have set specific energy or range of incident energies
         self._use_autoEi = False
 
-        if isinstance(self._incident_energy,list):
+        if isinstance(self._incident_energy, list):
             self._num_energies = len(self._incident_energy)
         else:
             self._num_energies = 1
         self._cur_iter_en = 0
-#pylint: disable=unused-variable
-        ok,sev,message = self.validate(instance)
+        # pylint: disable=unused-variable
+        ok, sev, message = self.validate(instance)
         if not ok:
             raise KeyError(message)
+
     #
 
     def autoEi_mode(self):
         """Return true if energies should be calculated in autoEi mode"""
         return self._use_autoEi
+
     #
 
     def multirep_mode(self):
         """ return true if energy is defined as list of energies or multirep m and false otherwise """
-        if isinstance(self._incident_energy,list) or self._use_autoEi:
+        if isinstance(self._incident_energy, list) or self._use_autoEi:
             return True
         else:
             return False
+
     #
 
     def getAllEiList(self):
         """Return incident energy(ies) range, defined by the property"""
-        if isinstance(self._incident_energy,list):
+        if isinstance(self._incident_energy, list):
             return self._incident_energy
         else:
-            if self._incident_energy==0:
+            if self._incident_energy == 0:
                 return []
             else:
                 return [self._incident_energy]
+
     #
 
     def get_current(self):
         """ Return current energy out of range of energies"""
-        if isinstance(self._incident_energy,list):
+        if isinstance(self._incident_energy, list):
             ind = self._cur_iter_en
             return self._incident_energy[ind]
         else:
             return self._incident_energy
+
     #
 
     def next(self):
-        if isinstance(self._incident_energy,list):
-            self._cur_iter_en +=1
+        if isinstance(self._incident_energy, list):
+            self._cur_iter_en += 1
             if self._cur_iter_en >= len(self._incident_energy):
                 raise StopIteration
         else:
             raise StopIteration
 
     #
-    def set_current_ind(self,ind=None):
+    def set_current_ind(self, ind=None):
         """ set current energy value (used in multirep mode) as
             energy estimate for the reduction
 
             ind -- if provided, the number of the value in the list of
             values (can be used together with enumerate)
         """
-        if isinstance(self._incident_energy,list):
+        if isinstance(self._incident_energy, list):
             if ind is None:
                 self._cur_iter_en = 0
             else:
@@ -297,9 +304,10 @@ class IncidentEnergy(PropDescriptor):
                 self._cur_iter_en = ind
         else:
             self._cur_iter_en = 0
+
     #
 
-    def set_auto_Ei(self,monitor_ws,instance,ei_mon_spec=None):
+    def set_auto_Ei(self, monitor_ws, instance, ei_mon_spec=None):
         """Calculate autoEi and set it as input for iterations over energy"""
         if not self._use_autoEi:
             return
@@ -310,47 +318,50 @@ class IncidentEnergy(PropDescriptor):
         self._autoEiCalculated = False
         if ei_mon_spec is None:
             ei_mon_spec = instance.ei_mon_spectra
-        guess_ei_ws = GetAllEi(Workspace=monitor_ws,Monitor1SpecID = ei_mon_spec[0],
-                               Monitor2SpecID = ei_mon_spec[1])
-        guessEi  = guess_ei_ws.readX(0)
+        guess_ei_ws = mantid.GetAllEi(Workspace=monitor_ws, Monitor1SpecID=ei_mon_spec[0],
+                                      Monitor2SpecID=ei_mon_spec[1])
+        guessEi = guess_ei_ws.readX(0)
         fin_ei = []
         for ei in guessEi:
             try:
-                ei_ref,_,_,_=GetEi(InputWorkspace=monitor_ws,
-                                   Monitor1Spec=ei_mon_spec[0], Monitor2Spec=ei_mon_spec[1], EnergyEstimate=ei)
+                ei_ref, _, _, _ = mantid.GetEi(InputWorkspace=monitor_ws,
+                                               Monitor1Spec=ei_mon_spec[0], Monitor2Spec=ei_mon_spec[1],
+                                               EnergyEstimate=ei)
                 fin_ei.append(ei_ref)
-#pylint: disable=bare-except
+            # pylint: disable=bare-except
             except:
-                instance.log("Can not refine guess energy {0:f}. Ignoring it.".format(ei),'warning')
+                instance.log("Can not refine guess energy {0:f}. Ignoring it.".format(ei), 'warning')
         if len(fin_ei) == 0:
             raise RuntimeError("Was not able to identify auto-energies for workspace: {0}".format(monitor_ws.name()))
         # Success! Set up estimated energies
         self._autoEiCalculated = True
-        self._autoEiRunNumber  = newRunNum
+        self._autoEiRunNumber = newRunNum
         self._incident_energy = fin_ei
         self._num_energies = len(fin_ei)
         self._cur_iter_en = 0
         # Clear dataservice from unnecessary workspace
-        DeleteWorkspace(guess_ei_ws)
+        mantid.DeleteWorkspace(guess_ei_ws)
 
-    def validate(self,instance,owner=None):
-       #
-        if self._use_autoEi: # nothing much to validate. The ei will be auto if possible
-            return (True,0,'')
+    def validate(self, instance, owner=None):
+        #
+        if self._use_autoEi:  # nothing much to validate. The ei will be auto if possible
+            return (True, 0, '')
 
         inc_en = self._incident_energy
-        if isinstance(inc_en,list):
-            for ind,en in enumerate(inc_en):
+        if isinstance(inc_en, list):
+            for ind, en in enumerate(inc_en):
                 if en <= 0:
-                    return (False,2,"Incident energy have to be positive number or list of positive numbers.\n"
-                            "For input argument {0} got negative energy {1}".format(ind,en))
+                    return (False, 2, "Incident energy have to be positive number or list of positive numbers.\n"
+                                      "For input argument {0} got negative energy {1}".format(ind, en))
         else:
             if inc_en <= 0:
-                return (False,2,"Incident energy have to be positive number or list of positive numbers.\n"
-                        "Got single negative incident energy {0} ".format(inc_en))
-        return (True,0,'')
+                return (False, 2, "Incident energy have to be positive number or list of positive numbers.\n"
+                                  "Got single negative incident energy {0} ".format(inc_en))
+        return (True, 0, '')
+
+
 # end IncidentEnergy
-#-----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
 
 
 class EnergyBins(PropDescriptor):
@@ -367,40 +378,41 @@ class EnergyBins(PropDescriptor):
        (e.g. prop_man.incident_energy=[100])/
     """
 
-    def __init__(self,IncidentEnergyProp,AccuracyProp):
+    def __init__(self, IncidentEnergyProp, AccuracyProp):
         self._incident_energy = IncidentEnergyProp
         self._averager = AccuracyProp
         self._energy_bins = None
         # how close you are ready to rebin w.r.t.  the incident energy
         self._range = 0.99999
 
-    def __get__(self,instance,owner=None):
+    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._energy_bins
 
-    def __set__(self,instance,values):
+    def __set__(self, instance, values):
         if values is not None:
-            if isinstance(values,str):
-                values = values.replace('[','').replace(']','').strip()
+            if isinstance(values, str):
+                values = values.replace('[', '').replace(']', '').strip()
                 lst = values.split(',')
-                self.__set__(instance,lst)
+                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]))
+                    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]))
         else:
             value = None
-       #TODO: implement single value settings according to rebin?
+            # TODO: implement single value settings according to rebin?
         self._energy_bins = value
 
-    def get_abs_range(self,instance=None):
+    def get_abs_range(self, instance=None):
         """ return energies related to incident energies.
         """
-        if self._incident_energy.multirep_mode(): # Relative energy
+        if self._incident_energy.multirep_mode():  # Relative energy
             ei = self._incident_energy.get_current()
             if self._incident_energy.autoEi_mode():
                 # we need to average ei nicely, as it will give energy jitter otherwise
@@ -412,16 +424,16 @@ class EnergyBins(PropDescriptor):
                 else:
                     if instance:
                         instance.log("*** WARNING! Got energy_bins specified as absolute values in multirep mode.\n"
-                                     "             Will normalize these values by max value and treat as relative values ",
+                                     "          Will normalize these values by max value and treat as relative values",
                                      "warning")
                     mult = self._range / self._energy_bins[2]
-                    rez = self._calc_relative_range(ei,mult)
+                    rez = self._calc_relative_range(ei, mult)
                 if self._incident_energy.autoEi_mode():
                     rez = self._averager.roundoff(rez)
                 return rez
             else:
                 return None
-        else: # Absolute energy ranges
+        else:  # Absolute energy ranges
             if self.is_range_valid():
                 return self._energy_bins
             else:
@@ -431,7 +443,7 @@ class EnergyBins(PropDescriptor):
                                  "warning")
                     mult = self._range / self._energy_bins[2]
                     ei = self._incident_energy.get_current()
-                    return self._calc_relative_range(ei,mult)
+                    return self._calc_relative_range(ei, mult)
 
     def is_range_valid(self):
         """Method verifies if binning range is consistent with incident energy """
@@ -440,27 +452,30 @@ class EnergyBins(PropDescriptor):
         else:
             return self._energy_bins[2] <= self._incident_energy.get_current()
 
-    def _calc_relative_range(self,ei,range_mult=1):
+    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)
+        return (self._energy_bins[0] * mult, self._energy_bins[1] * mult, self._energy_bins[2] * mult)
 
-    def validate(self,instance,owner):
+    def validate(self, instance, owner):
         """ function verifies if the energy binning is consistent with incident energies """
         ei = instance.incident_energy
         ebin = instance.energy_bins
-        if isinstance(ei,list) or owner.incident_energy.autoEi_mode(): # ebin expected to be relative
+        if isinstance(ei, list) or owner.incident_energy.autoEi_mode():  # ebin expected to be relative
             if ebin[2] > 1:
-                return(False,1,"Binning for multiple energy range should be relative to incident energy. Got ebin_max={0} > 1\n" +
-                       "Energy range will be normalized and treated as relative range")
+                return (False, 1,
+                        "Binning for multiple energy range should be relative to incident energy. Got ebin_max={0} > 1\n" +
+                        "Energy range will be normalized and treated as relative range")
         else:
             if not owner.incident_energy.autoEi_mode() and ebin[2] > ei:
-                return (False,2,'Max rebin range {0:f} exceeds incident energy {1:f}'.format(ebin[2],en))
-        return(True,0,'')
-#-----------------------------------------------------------------------------------------
+                return (False, 2, 'Max rebin range {0:f} exceeds incident energy {1:f}'.format(ebin[2], ei))
+        return (True, 0, '')
 
-#end EnergyBins
-#-----------------------------------------------------------------------------------------
+
+# -----------------------------------------------------------------------------------------
+
+# end EnergyBins
+# -----------------------------------------------------------------------------------------
 
 
 class SaveFileName(PropDescriptor):
@@ -471,11 +486,11 @@ class SaveFileName(PropDescriptor):
       used instead.
     """
 
-    def __init__(self,Name=None):
+    def __init__(self, Name=None):
         self._file_name = Name
         self._custom_print = None
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         # getter functional interface.
         if instance is None:
             return self
@@ -501,18 +516,18 @@ class SaveFileName(PropDescriptor):
             sr = 0
         try:
             ei = owner.incident_energy.get_current()
-            name +='{0:0<5}Ei{1:_<4.2f}meV'.format(sr,ei)
+            name += '{0:0<5}Ei{1:_<4.2f}meV'.format(sr, ei)
             if instance.sum_runs:
-                name +='sum'
+                name += 'sum'
             if owner.monovan_run.run_number():
-                name +='_Abs'
-            name = name.replace('.','d')
-#pylint: disable=bare-except
+                name += '_Abs'
+            name = name.replace('.', 'd')
+        # pylint: disable=bare-except
         except:
             name = None
         return name
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
 
         if value is None:
             self._file_name = None
@@ -521,10 +536,12 @@ class SaveFileName(PropDescriptor):
         else:
             self._file_name = str(value)
 
-    def set_custom_print(self,routine):
+    def set_custom_print(self, routine):
         self._custom_print = routine
-#end SaveFileName
-#-----------------------------------------------------------------------------------------
+
+
+# end SaveFileName
+# -----------------------------------------------------------------------------------------
 
 
 class InstrumentDependentProp(PropDescriptor):
@@ -532,44 +549,48 @@ class InstrumentDependentProp(PropDescriptor):
        which are undefined if no instrument is defined.
     """
 
-    def __init__(self,prop_name):
+    def __init__(self, prop_name):
         self._prop_name = prop_name
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
 
         if instance is None:
             return self
-#pylint: disable=protected-access
+        # pylint: disable=protected-access
         if instance._pInstrument is None:
             raise KeyError("Attempt to use uninitialized property manager")
         else:
-            return getattr(instance,self._prop_name)
+            return getattr(instance, self._prop_name)
 
-    def __set__(self,instance,values):
+    def __set__(self, instance, values):
         raise AttributeError("Property {0} can not be assigned. It defined by instrument".format(self._prop_name))
-#end InstrumentDependentProp
-#-----------------------------------------------------------------------------------------
+
+
+# end InstrumentDependentProp
+# -----------------------------------------------------------------------------------------
 
 
 class VanadiumRMM(PropDescriptor):
     """Defines constant static rmm for vanadium."""
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         """ return rmm for vanadium """
 
         return 50.9415
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
         raise AttributeError("Can not change vanadium rmm")
-#end VanadiumRMM
-#-----------------------------------------------------------------------------------------
+
+
+# end VanadiumRMM
+# -----------------------------------------------------------------------------------------
 # END Descriptors for NonIDF_Properties class
-#-----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
 
-#-----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
 # Descriptors, providing overloads for some complex properties in
 # PropertyManager
-#-----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
 
 
 class mon2NormalizationEnergyRange(PropDescriptor):
@@ -585,105 +606,112 @@ class mon2NormalizationEnergyRange(PropDescriptor):
 
     def __init__(self):
         # default range
-        self._relative_range = [0.8,1.2]
+        self._relative_range = [0.8, 1.2]
 
-    def __get__(self,instance,owner):
+    def __get__(self, instance, owner):
         """ Return actual energy range from internal relative range and incident energy """
         if instance is None:
             return self
         ei = owner.incident_energy.get_current()
         return [self._relative_range[0] * ei, self._relative_range[1] * ei]
 
-    def __set__(self,instance,val):
+    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):
+        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)
+            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)))
+                           'Trying to assign value {0} of unknown type {1}'.format(val, type(val)))
+
     #
 
-    def _check_range(self,val,instance):
+    def _check_range(self, val, instance):
         """ method to check if list of values acceptable as ranges """
 
         if len(val) != 2:
-            raise KeyError("mon2_norm_energy_range needs to be initialized by lost of two values. Got {0}".format(len(val)))
-        self._relative_range = (float(val[0]),float(val[1]))
-        ok,sev,message = self.validate(instance)
+            raise KeyError(
+                "mon2_norm_energy_range needs to be initialized by lost of two values. Got {0}".format(len(val)))
+        self._relative_range = (float(val[0]), float(val[1]))
+        ok, sev, message = self.validate(instance)
         if not ok:
             if sev == 1:
-                instance.log(message,'warning')
+                instance.log(message, 'warning')
             else:
                 raise KeyError(message)
 
         return self._relative_range
+
     #
 
-    def _parce_string2list(self,val):
+    def _parce_string2list(self, val):
         """ method splits input string containing comma into list of strings"""
         value = val.strip('[]()')
         val = value.split(',')
         return val
 
-    def validate(self,instance,owner=None):
+    def validate(self, instance, owner=None):
         """ function verifies if the energy range is consistent with incident energies """
         en_range = self._relative_range
         if len(en_range) != 2:
-            return(False,2,'mon2_normalization_energy_range can be initialized by list of two values only.'
-                   ' Got {0} values'.format(len(range)))
+            return (False, 2, 'mon2_normalization_energy_range can be initialized by list of two values only.'
+                              ' Got {0} values'.format(len(range)))
 
-        result = (True,0,'')
+        result = (True, 0, '')
 
         val1 = float(en_range[0])
         if val1 < 0.1 or val1 > 0.9:
-            message = "Lower mon2_norm_energy_range describes lower 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(val1)
+            message = "Lower mon2_norm_energy_range describes lower limit of energy to integrate neutron signal after" \
+                      " the chopper.\nThe limit is defined as (this value)*incident_energy." \
+                      " Are you sure you want to set this_value to {0}?\n".format(val1)
             if val1 > 1:
-                return(False,2,message)
+                return (False, 2, message)
             else:
-                result = (False,1,message)
+                result = (False, 1, message)
 
         val2 = float(en_range[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"\
-                     "The limit is defined as (this value)*incident_energy. Are you sure you want to set this_value to {0}?\n".format(val2)
+            message = "Upper mon2_norm_energy_range describes upper limit of energy to integrate neutron signal after" \
+                      " the chopper.\nThe 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:
                 if result[0]:
-                    result = (False,1,message)
+                    result = (False, 1, message)
                 else:
-                    result = (False,1,result[2] + message)
+                    result = (False, 1, result[2] + message)
             else:
-                return (False,2,message)
+                return (False, 2, message)
 
         return result
 
-#-----------------------------------------------------------------------------------------
+
+# -----------------------------------------------------------------------------------------
 
 
 class PropertyFromRange(PropDescriptor):
     """Generic descriptor for property, which can have one value from a list of values."""
 
-    def __init__(self,availible_values,default_value):
+    def __init__(self, availible_values, default_value):
         self._availible_values = availible_values
-        self.__set__(None,default_value)
+        self.__set__(None, default_value)
 
-    def __get__(self,instance,owner):
+    def __get__(self, instance, owner):
         """ Return current value for the property with range of values. """
         if instance is None:
             return self
         return self._current_value
 
-    def __set__(self,instance,val):
+    def __set__(self, instance, val):
         if val in self._availible_values:
-#pylint: disable=attribute-defined-outside-init
+            # pylint: disable=attribute-defined-outside-init
             self._current_value = val
         else:
             raise KeyError(' Property can not have value {0}'.format(val))
 
-#-----------------------------------------------------------------------------------------
+
+# -----------------------------------------------------------------------------------------
 
 
 class DetCalFile(PropDescriptor):
@@ -698,26 +726,26 @@ class DetCalFile(PropDescriptor):
         self._det_cal_file = None
         self._calibrated_by_run = False
 
-    def __get__(self,instance,owner):
+    def __get__(self, instance, owner):
         if instance is None:
             return self
 
         return self._det_cal_file
 
-    def __set__(self,instance,val):
+    def __set__(self, instance, val):
         """ set detector calibration file using various formats """
 
-        if val is None or isinstance(val,api.Workspace):
-       # nothing provided or workspace provided or filename probably provided
-            if str(val) in mtd:
-             # workspace name provided
-                val = mtd[str(val)]
+        if val is None or isinstance(val, api.Workspace):
+            # nothing provided or workspace provided or filename probably provided
+            if str(val) in mantid.mtd:
+                # workspace name provided
+                val = mantid.mtd[str(val)]
             self._det_cal_file = val
             self._calibrated_by_run = False
             return
-        if isinstance(val,str):
-            if val in mtd:
-                val = mtd[val]
+        if isinstance(val, str):
+            if val in mantid.mtd:
+                val = mantid.mtd[val]
                 self._det_cal_file = val
                 self._calibrated_by_run = False
                 return
@@ -729,14 +757,16 @@ class DetCalFile(PropDescriptor):
                 return
             val = intVal
 
-        if isinstance(val,int):
-          #if val in instance.all_run_numbers: TODO: retrieve workspace from
-          #run numbers
+        if isinstance(val, int):
+            # if val in instance.all_run_numbers: TODO: retrieve workspace from
+            # run numbers
             self._det_cal_file = val
             self._calibrated_by_run = True
             return
-        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 :
+        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
     #        Reducer.log('Setting detector calibration file to
@@ -744,67 +774,70 @@ class DetCalFile(PropDescriptor):
     #    else:
     #       Reducer.log('Setting detector calibration to {0}, which is probably
     #       a workspace '.format(str(Reducer.det_cal_file)))
-    #else:
+    # else:
     #    Reducer.log('Setting detector calibration to detector block info from
     #    '+str(sample_run))
 
     def calibrated_by_run(self):
         """ reports if the detector calibration is in a run-file or separate file(workspace)"""
         return self._calibrated_by_run
-#pylint: disable=unused-argument
 
-    def find_file(self,instance,**kwargs):
+    # pylint: disable=unused-argument
+
+    def find_file(self, instance, **kwargs):
         """ Method to find file, correspondent to
             current _det_cal_file file hint
         """
         if self._det_cal_file is None:
-        # nothing to look for
-            return (True,"No Detector calibration file defined")
+            # nothing to look for
+            return (True, "No Detector calibration file defined")
 
-        if isinstance(self._det_cal_file,api.Workspace):
-        # nothing to do.  Workspace used for calibration
-            return (True,'Workspace {0} used for detectors calibration'.format(self._det_cal_file.name()))
+        if isinstance(self._det_cal_file, api.Workspace):
+            # nothing to do.  Workspace used for calibration
+            return (True, 'Workspace {0} used for detectors calibration'.format(self._det_cal_file.name()))
 
         dcf_val = self._det_cal_file
-        if isinstance(dcf_val,str): # it may be string representation of runN
+        if isinstance(dcf_val, str):  # it may be string representation of runN
             try:
                 dcf_val = int(dcf_val)
             except ValueError:
                 pass
 
-        if isinstance(dcf_val,int): # this is a run number
+        if isinstance(dcf_val, int):  # this is a run number
             inst_short_name = instance.short_inst_name
-            fac             = instance.facility
-            zero_padding    = fac.instrument(inst_short_name).zeroPadding(dcf_val)
-            file_hint = inst_short_name+str(dcf_val).zfill(zero_padding)
+            fac = instance.facility
+            zero_padding = fac.instrument(inst_short_name).zeroPadding(dcf_val)
+            file_hint = inst_short_name + str(dcf_val).zfill(zero_padding)
             try:
-                file_name = FileFinder.findRuns(file_hint)[0]
-#pylint: disable=bare-except
+                file_name = mantid.FileFinder.findRuns(file_hint)[0]
+            # pylint: disable=bare-except
             except:
-                return (False,"Can not find run file corresponding to run N: {0}".format(file_hint))
+                return (False, "Can not find run file corresponding to run N: {0}".format(file_hint))
             self._det_cal_file = file_name
-            return (True,file_name)
+            return (True, file_name)
 
-         # string can be a run number or a file name:
+            # string can be a run number or a file name:
         file_name = prop_helpers.findFile(self._det_cal_file)
-        if len(file_name) == 0: # it still can be a run number as string
+        if len(file_name) == 0:  # it still can be a run number as string
             try:
-                file_name = FileFinder.findRuns(self._det_cal_file)[0]
-#pylint: disable=bare-except
+                file_name = mantid.FileFinder.findRuns(self._det_cal_file)[0]
+            # pylint: disable=bare-except
             except:
-                return (False,"Can not find file or run file corresponding to name : {0}".format(self._det_cal_file))
+                return (False, "Can not find file or run file corresponding to name : {0}".format(self._det_cal_file))
         else:
             pass
         self._det_cal_file = file_name
-        return (True,file_name)
-#end DetCalFile
-#-----------------------------------------------------------------------------------------
+        return (True, file_name)
+
+
+# end DetCalFile
+# -----------------------------------------------------------------------------------------
 
 
 class MapMaskFile(PropDescriptor):
     """common method to wrap around an auxiliary file name"""
 
-    def __init__(self,prop_name,file_ext,doc_string=None):
+    def __init__(self, prop_name, file_ext, doc_string=None):
         self._file_name = None
         self._file_ext = file_ext
         self._prop_name = prop_name
@@ -812,37 +845,40 @@ class MapMaskFile(PropDescriptor):
         if doc_string is not None:
             self.__doc__ = doc_string
 
-    def __get__(self,instance,class_type=None):
+    def __get__(self, instance, class_type=None):
         if instance is None:
             return self
 
         return self._file_name
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
         if value is not None:
-#pylint: disable=unused-variable
+            # pylint: disable=unused-variable
             fileName, fileExtension = os.path.splitext(value)
             if not fileExtension:
                 value = value + self._file_ext
         self._file_name = value
-#pylint: disable=unused-argument
 
-    def find_file(self,instance,**kwargs):
+    # pylint: disable=unused-argument
+
+    def find_file(self, instance, **kwargs):
         """ Method to find file, correspondent to
            current MapMaskFile file hint
        """
         if self._file_name is None:
-            return (True,'No file for {0} is defined'.format(self._prop_name))
+            return (True, 'No file for {0} is defined'.format(self._prop_name))
 
         file_name = prop_helpers.findFile(self._file_name)
-        if len(file_name) == 0: # it still can be a run number as string
-            return (False,'No file for {0} corresponding to guess: {1} found'.format(self._prop_name,self._file_name))
+        if len(file_name) == 0:  # it still can be a run number as string
+            return (False, 'No file for {0} corresponding to guess: {1} found'.format(self._prop_name, self._file_name))
         else:
             self._file_name = file_name
-            return (True,file_name)
-#end MapMaskFile
+            return (True, file_name)
+
+
+# end MapMaskFile
 
-#-----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
 
 
 class HardMaskPlus(prop_helpers.ComplexProperty):
@@ -856,32 +892,33 @@ class HardMaskPlus(prop_helpers.ComplexProperty):
     """
 
     def __init__(self):
-        prop_helpers.ComplexProperty.__init__(self,['use_hard_mask_only','run_diagnostics'])
+        prop_helpers.ComplexProperty.__init__(self, ['use_hard_mask_only', 'run_diagnostics'])
 
-    def __get__(self,instance,class_type=None):
+    def __get__(self, instance, class_type=None):
         if instance is None:
             return self
 
         return instance.hard_mask_file
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
         if value is not None:
-#pylint: disable=unused-variable
+            # pylint: disable=unused-variable
             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])
+            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:
-#pylint: disable=protected-access
+            # pylint: disable=protected-access
             del instance.__changed_properties['hardmaskOnly']
-#pylint: disable=bare-except
+        # pylint: disable=bare-except
         except:
             pass
 
-#-----------------------------------------------------------------------------------------
+
+# -----------------------------------------------------------------------------------------
 
 
 class HardMaskOnly(prop_helpers.ComplexProperty):
@@ -893,32 +930,32 @@ class HardMaskOnly(prop_helpers.ComplexProperty):
     """
 
     def __init__(self):
-        prop_helpers.ComplexProperty.__init__(self,['use_hard_mask_only','run_diagnostics'])
+        prop_helpers.ComplexProperty.__init__(self, ['use_hard_mask_only', 'run_diagnostics'])
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         if instance is None:
             return self
 
-        return prop_helpers.gen_getter(instance.__dict__,'use_hard_mask_only')
+        return prop_helpers.gen_getter(instance.__dict__, 'use_hard_mask_only')
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
         if value is None:
             use_hard_mask_only = False
             instance.hard_mask_file = None
             hard_mask_file = None
-        elif isinstance(value,bool) or isinstance(value,int):
+        elif isinstance(value, bool) or isinstance(value, int):
             use_hard_mask_only = bool(value)
             hard_mask_file = instance.hard_mask_file
-        elif isinstance(value,str):
-            if value.lower() in ['true','yes']:
+        elif isinstance(value, str):
+            if value.lower() in ['true', 'yes']:
                 use_hard_mask_only = True
-            elif value.lower() in ['false','no']:
+            elif value.lower() in ['false', 'no']:
                 use_hard_mask_only = False
-            else: # it is probably a hard mask file provided:
+            else:  # it is probably a hard mask file provided:
                 instance.hard_mask_file = value
                 use_hard_mask_only = True
             hard_mask_file = instance.hard_mask_file
-        #end
+        # end
 
         # if no hard mask file is there and use_hard_mask_only is True,
         # diagnostics should not run
@@ -926,15 +963,17 @@ class HardMaskOnly(prop_helpers.ComplexProperty):
             run_diagnostics = False
         else:
             run_diagnostics = True
-        prop_helpers.ComplexProperty.__set__(self,instance.__dict__,[use_hard_mask_only,run_diagnostics])
+        prop_helpers.ComplexProperty.__set__(self, instance.__dict__, [use_hard_mask_only, run_diagnostics])
         try:
-#pylint: disable=protected-access
+            # pylint: disable=protected-access
             del instance.__changed_properties['hardmaskPlus']
-#pylint: disable=bare-except
+        # pylint: disable=bare-except
         except:
             pass
-#end HardMaskOnly
-#-----------------------------------------------------------------------------------------
+
+
+# end HardMaskOnly
+# -----------------------------------------------------------------------------------------
 
 
 class MonovanIntegrationRange(prop_helpers.ComplexProperty):
@@ -959,75 +998,80 @@ class MonovanIntegrationRange(prop_helpers.ComplexProperty):
        integration_range = [monovan_lo_value,monovan_hi_value].
     """
 
-    def __init__(self,DepType=None):
+    def __init__(self, DepType=None):
         if DepType:
             self._rel_range = False
-            prop_helpers.ComplexProperty.__init__(self,['monovan_lo_value','monovan_hi_value'])
+            prop_helpers.ComplexProperty.__init__(self, ['monovan_lo_value', 'monovan_hi_value'])
         else:
             self._rel_range = True
-            prop_helpers.ComplexProperty.__init__(self,['monovan_lo_frac','monovan_hi_frac'])
+            prop_helpers.ComplexProperty.__init__(self, ['monovan_lo_frac', 'monovan_hi_frac'])
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
 
         if instance is None:
             return self
 
-        if isinstance(instance,dict):
+        if isinstance(instance, dict):
             ei = 1
             tDict = instance
         else:
             ei = owner.incident_energy.get_current()
             tDict = instance.__dict__
 
-        if self._rel_range: # relative range
+        if self._rel_range:  # relative range
             if ei is None:
-                raise AttributeError('Attempted to obtain relative to ei monovan integration range, but incident energy has not been set')
-            rel_range = prop_helpers.ComplexProperty.__get__(self,tDict)
-            the_range = [rel_range[0] * ei,rel_range[1] * ei]
+                raise AttributeError(
+                    'Attempted to obtain relative to ei monovan integration range, but incident energy has not been set')
+            rel_range = prop_helpers.ComplexProperty.__get__(self, tDict)
+            the_range = [rel_range[0] * ei, rel_range[1] * ei]
             return the_range
-        else: # absolute range
-            return prop_helpers.ComplexProperty.__get__(self,tDict)
+        else:  # absolute range
+            return prop_helpers.ComplexProperty.__get__(self, tDict)
 
-    def __set__(self,instance,value):
-        if isinstance(instance,dict):
+    def __set__(self, instance, value):
+        if isinstance(instance, dict):
             tDict = instance
         else:
             tDict = instance.__dict__
         if value is None:
             if not self._rel_range:
                 self._rel_range = True
-                self._other_prop = ['monovan_lo_frac','monovan_hi_frac']
+                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._other_prop = ['monovan_lo_value', 'monovan_hi_value']
 
-            if isinstance(value,str):
+            if isinstance(value, str):
                 values = value.split(',')
                 result = []
-                for val in values :
+                for val in values:
                     result.append(int(val))
                 value = result
             if len(value) != 2:
                 raise KeyError("monovan_integr_range has to be list of two values, "
-                               "defining min/max values of integration range or None to use relative to incident energy limits")
-            prop_helpers.ComplexProperty.__set__(self,tDict,value)
+                               "defining min/max values of integration range or None "
+                               "to use relative to incident energy limits")
+
+            prop_helpers.ComplexProperty.__set__(self, tDict, value)
 
-    def validate(self,instance, owner):
+    def validate(self, instance, owner):
         """ check if monovan integration range has reasonable value """
 
         if instance.monovan_run is None:
-            return (True,0,'')
+            return (True, 0, '')
 
-        the_range = sepf.__get__(instance,owner)
+        the_range = self.__get__(instance, owner)
         ei = instance.incident_energy
         if the_range[0] >= the_range[1]:
-            return (False,2,'monovan integration range limits = [{0}:{1}] are wrong'.format(the_range[0],the_range[1]))
+            return False, 2, 'monovan integration range limits = [{0}:{1}] are wrong'.format(the_range[0], the_range[1])
         if the_range[0] < -100 * ei or the_range[0] > 100 * ei:
-            return (False,1,'monovan integration is suspiciously wide: [{0}:{1}]. This may be incorrect'
-                    .format(the_range[0],the_range[1]))
-        return (True,0,'')
-#end MonovanIntegrationRange
+            return False, 1, 'monovan integration is suspiciously wide: [{0}:{1}]. ' \
+                             'This may be incorrect'.format(the_range[0], the_range[1])
+        return True, 0, ''
+
+
+# end MonovanIntegrationRange
 
 
 class EiMonSpectra(prop_helpers.ComplexProperty):
@@ -1039,44 +1083,44 @@ class EiMonSpectra(prop_helpers.ComplexProperty):
 
     def __init__(self):
         """ Ei mon spectra is defined as function of two other complex properties"""
-        prop_helpers.ComplexProperty.__init__(self,['ei-mon1-spec','ei-mon2-spec'])
+        prop_helpers.ComplexProperty.__init__(self, ['ei-mon1-spec', 'ei-mon2-spec'])
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         if instance is None:
             return self
 
-        if isinstance(instance,dict):
+        if isinstance(instance, dict):
             tDict = instance
         else:
             tDict = instance.__dict__
 
-        mon_range = prop_helpers.ComplexProperty.__get__(self,tDict)
+        mon_range = prop_helpers.ComplexProperty.__get__(self, tDict)
 
         # Return monitors range, converted into the standard form.
         # namely tuple of two monitors or monitors list
-        monitors = [0,0]
-        for index,mon_val in enumerate(mon_range):
-            monitors[index]=self._process_monitors_spectra(mon_val)
-        return (monitors[0],monitors[1])
+        monitors = [0, 0]
+        for index, mon_val in enumerate(mon_range):
+            monitors[index] = self._process_monitors_spectra(mon_val)
+        return (monitors[0], monitors[1])
 
-    def __set__(self,instance,value):
-        if value is None: # Do nothing
+    def __set__(self, instance, value):
+        if value is None:  # Do nothing
             return
 
-        if isinstance(instance,dict):
+        if isinstance(instance, dict):
             tDict = instance
         else:
             tDict = instance.__dict__
 
-        if isinstance(value,str):
-            val =  value.replace('[','').replace(']','').strip()
-            if val.find(':')>-1:
+        if isinstance(value, str):
+            val = value.replace('[', '').replace(']', '').strip()
+            if val.find(':') > -1:
                 val = val.split(':')
             else:
                 val = val.split(',')
         else:
             val = value
-        #end if
+        # end if
         if len(val) != 2:
             raise KeyError("ei_mon_spectra may be either tuple defining two spectra "
                            "lists or string, which can be transformed to such lists. Got {0}"
@@ -1088,25 +1132,25 @@ class EiMonSpectra(prop_helpers.ComplexProperty):
         if val[1] == 'ei-mon2-spec':
             val[1] = tDict['ei-mon2-spec']
         #
-        prop_helpers.ComplexProperty.__set__(self,tDict,val)
+        prop_helpers.ComplexProperty.__set__(self, tDict, val)
 
-    def need_to_sum_monitors(self,instance):
+    def need_to_sum_monitors(self, instance):
         """Returns True if some monitors are defined as range of spectra to sum
            False -- if all monitors are related to one spectra each.
         """
         tDict = instance.__dict__
-        mon_range = prop_helpers.ComplexProperty.__get__(self,tDict)
+        mon_range = prop_helpers.ComplexProperty.__get__(self, tDict)
         # Return monitors range, converted into the standard form.
-        need_to_sum =False
+        need_to_sum = False
         for mon_val in mon_range:
             mon_list = self._process_monitors_spectra(mon_val)
-            if isinstance(mon_list,Iterable):
-                need_to_sum  = True
+            if isinstance(mon_list, Iterable):
+                need_to_sum = True
                 break
         return need_to_sum
 
     #
-    def _process_monitors_spectra(self,mon_range):
+    def _process_monitors_spectra(self, mon_range):
         """A method to process any form of monitor spectra list
            representation
         Called on get rather then on set operation as monitor lists
@@ -1114,12 +1158,12 @@ class EiMonSpectra(prop_helpers.ComplexProperty):
         properties and these properties are currently standard properties
         """
 
-        if isinstance(mon_range,str):
+        if isinstance(mon_range, str):
             mon_val = mon_range.split(',')
         else:
             mon_val = mon_range
-        if isinstance(mon_val,list) or isinstance(mon_val,tuple):
-            rez_spectra=[]
+        if isinstance(mon_val, list) or isinstance(mon_val, tuple):
+            rez_spectra = []
             for mon in mon_val:
                 rez_spectra.append(int(mon))
             if len(rez_spectra) == 1:
@@ -1128,11 +1172,12 @@ class EiMonSpectra(prop_helpers.ComplexProperty):
             rez_spectra = int(mon_range)
         return rez_spectra
 
-#    def validate(self,instance, owner):
+
+# def validate(self,instance, owner):
 #        """ """
 #        return (True,0,'')
 
-#-----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
 
 
 class SpectraToMonitorsList(PropDescriptor):
@@ -1149,43 +1194,45 @@ class SpectraToMonitorsList(PropDescriptor):
     def __init__(self):
         self._spectra_to_monitors_list = None
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=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):
+    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:
                 spectra = spectra_list.split(',')
                 result = []
-                for spectum in spectra :
+                for spectum in spectra:
                     result.append(int(spectum))
 
         else:
-            if isinstance(spectra_list,list):
+            if isinstance(spectra_list, list):
                 if len(spectra_list) == 0:
                     result = None
                 else:
                     result = []
-                    for i in range(0,len(spectra_list)):
+                    for i in range(0, len(spectra_list)):
                         result.append(int(spectra_list[i]))
             else:
                 result = [int(spectra_list)]
         return result
-#end SpectraToMonitorsList
 
-#-----------------------------------------------------------------------------------------
+
+# end SpectraToMonitorsList
+
+# -----------------------------------------------------------------------------------------
 
 
 class SaveFormat(PropDescriptor):
@@ -1196,19 +1243,19 @@ class SaveFormat(PropDescriptor):
        See Mantid documentation for detailed description of the formats.
        If set to None, internal saving procedure is not used.
     """
-   # formats available for saving the data
-    save_formats = ['spe','nxspe','nxs']
+    # formats available for saving the data
+    save_formats = ['spe', 'nxspe', 'nxs']
 
     def __init__(self):
         self._save_format = set()
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         if instance is None:
             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"""
 
@@ -1218,40 +1265,44 @@ class SaveFormat(PropDescriptor):
             return
 
         # check string
-        if isinstance(value,str):
+        if isinstance(value, str):
             value = value.strip('[]().')
             subformats = value.split(',')
             if len(subformats) > 1:
-                self.__set__(instance,subformats)
+                self.__set__(instance, subformats)
                 return
             else:
                 value = subformats[0]
 
                 if value not in SaveFormat.save_formats:
-                    instance.log("Trying to set saving in unknown format: \"" + str(value) + "\" No saving will occur for this format")
+                    instance.log("Trying to set saving in unknown format: \"" + str(
+                        value) + "\" No saving will occur for this format")
                     return
         else:
             try:
-               # set single default save format recursively
+                # set single default save format recursively
                 for val in value:
-                    self.__set__(instance,val)
+                    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'
-                               .format(value,type(value)))
-        #end if different types
+                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)
 
-    def validate(self,instance, owner):
+    def validate(self, instance, owner):
 
         n_formats = len(self._save_format)
         if n_formats == 0:
-            return (False,1,'No internal save format is defined. Results may be lost')
+            return (False, 1, 'No internal save format is defined. Results may be lost')
         else:
-            return (True,0,'')
-#end SaveFormat
+            return (True, 0, '')
+
 
-#-----------------------------------------------------------------------------------------
+# end SaveFormat
+
+# -----------------------------------------------------------------------------------------
 
 
 class DiagSpectra(PropDescriptor):
@@ -1267,21 +1318,21 @@ class DiagSpectra(PropDescriptor):
     def __init__(self):
         self._diag_spectra = None
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         if instance is None:
             return self
 
         return self._diag_spectra
 
-    def __set__(self,instance,spectra_list):
+    def __set__(self, instance, spectra_list):
         self._diag_spectra = self._process_spectra_list(spectra_list)
 
-    def _process_spectra_list(self,specta_sring):
+    def _process_spectra_list(self, specta_sring):
         """ process IDF description of the spectra string """
         if specta_sring is None:
             return None
-        if isinstance(specta_sring,str):
-            if specta_sring.lower() in ['none','no']:
+        if isinstance(specta_sring, str):
+            if specta_sring.lower() in ['none', 'no']:
                 return None
             else:
                 banks = specta_sring.split(";")
@@ -1289,16 +1340,19 @@ class DiagSpectra(PropDescriptor):
                 for b in banks:
                     token = b.split(",")  # b = "(,)"
                     if len(token) != 2:
-                        raise ValueError("Invalid bank spectra specification in diagnostics properties %s" % specta_sring)
+                        raise ValueError(
+                            "Invalid bank spectra specification in diagnostics properties %s" % specta_sring)
                     start = int(token[0].lstrip('('))
                     end = int(token[1].rstrip(')'))
-                    bank_spectra.append((start,end))
+                    bank_spectra.append((start, end))
             return bank_spectra
         else:
             raise ValueError("Spectra For diagnostics can be a string inthe form (num1,num2);(num3,num4) etc. or None")
-#end class DiagSpectra
 
-#-----------------------------------------------------------------------------------------
+
+# end class DiagSpectra
+
+# -----------------------------------------------------------------------------------------
 
 
 class BackbgroundTestRange(PropDescriptor):
@@ -1311,7 +1365,7 @@ class BackbgroundTestRange(PropDescriptor):
     def __init__(self):
         self._background_test_range = None
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         if instance is None:
             return self
 
@@ -1320,31 +1374,34 @@ class BackbgroundTestRange(PropDescriptor):
         else:
             return instance.bkgd_range
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
         if value is None:
             self._background_test_range = None
             return
-        if isinstance(value,str):
-            value = str.split(value,',')
+        if isinstance(value, str):
+            value = str.split(value, ',')
         if len(value) != 2:
             raise ValueError("background test range can be only a 2 element list of floats")
-        self._background_test_range = (float(value[0]),float(value[1]))
+        self._background_test_range = (float(value[0]), float(value[1]))
 
-    def validate(self,instance, owner=None):
+    def validate(self, instance, owner=None):
         """ validate background test range """
-        test_range = self.__get__(instance,owner)
+        test_range = self.__get__(instance, owner)
         if test_range is None:
-            return (True,0,'')
+            return True, 0, ''
         if test_range[0] >= test_range[1]:
-            return (False,2,' Background test range: [{0}:{1}] is incorrect '.format(test_range[0],test_range[1]))
+            return False, 2, ' Background test range: [{0}:{1}] is incorrect '.format(test_range[0], test_range[1])
         if test_range[0] < 0:
-            return (False,2,' Background test range is TOF range, so it can not be negative={0}'.format(test_range[0]))
+            return False, 2, ' Background test range is TOF range, so it can not be negative={0}'.format(test_range[0])
         if test_range[1] > 20000:
-            return (False,1,' Background test range is TOF range, its max value looks suspiciously big={0}'.format(test_range[1]))
-        return (True,0,'')
-#end BackbgroundTestRange
+            return False, 1, ' Background test range is TOF range, its max value looks suspiciously big={0}'.format(
+                   test_range[1])
+        return True, 0, ''
+
 
-#-----------------------------------------------------------------------------------------
+# end BackbgroundTestRange
+
+# -----------------------------------------------------------------------------------------
 
 
 class MultirepTOFSpectraList(PropDescriptor):
@@ -1358,19 +1415,19 @@ class MultirepTOFSpectraList(PropDescriptor):
     def __init__(self):
         self._spectra_list = None
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         if instance is None:
             return self
 
         return self._spectra_list
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
         if value is None:
             self._spectra_list = None
             return
-        if isinstance(value,str):
-            value = str.split(value,',')
-            self.__set__(instance,value)
+        if isinstance(value, str):
+            value = str.split(value, ',')
+            self.__set__(instance, value)
             return
         if isinstance(value, list):
             rez = []
@@ -1379,7 +1436,9 @@ class MultirepTOFSpectraList(PropDescriptor):
         else:
             rez = [int(value)]
         self._spectra_list = rez
-#end MultirepTOFSpectraList
+
+
+# end MultirepTOFSpectraList
 
 
 class MonoCorrectionFactor(PropDescriptor):
@@ -1398,38 +1457,39 @@ class MonoCorrectionFactor(PropDescriptor):
           no changes to the values it depends on were identified.
     """
 
-    def __init__(self,ei_prop,monovan_run_prop):
+    def __init__(self, ei_prop, monovan_run_prop):
         self._cor_factor = None
         self._mono_run_number = None
         self._ei_prop = ei_prop
         self.cashed_values = {}
         self._mono_run_prop = monovan_run_prop
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         if instance is None:
             return self
 
         return self._cor_factor
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
         self._cor_factor = value
-    #
+        #
         if value is None:
-#pylint: disable=protected-access
-            self._mono_run_prop._in_cash = False # enable monovan run validation if any
+            # pylint: disable=protected-access
+            self._mono_run_prop._in_cash = False  # enable monovan run validation if any
+
     #
 
-    def set_val_to_cash(self,instance,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
-        cp = getattr(instance,'_PropertyManager__changed_properties')
+        cp = getattr(instance, '_PropertyManager__changed_properties')
         cp.add('mono_correction_factor')
 
-    def get_val_from_cash(self,instance):
+    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:
@@ -1437,7 +1497,7 @@ class MonoCorrectionFactor(PropDescriptor):
         else:
             return None
 
-    def set_cash_mono_run_number(self,new_value):
+    def set_cash_mono_run_number(self, new_value):
         if new_value is None:
             self.cashed_values = {}
             self._mono_run_number = None
@@ -1446,20 +1506,22 @@ class MonoCorrectionFactor(PropDescriptor):
             self.cashed_values = {}
             self._mono_run_number = int(new_value)
 
-    def _build_cash_val_id(self,mono_int_range):
+    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}".\
-            format(ei,mono_int_range[0],mono_int_range[1],self._mono_run_number)
+        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
 
-    def validate(self,instance, owner=None):
+    def validate(self, instance, owner=None):
 
         if self._cor_factor is None:
-            return (True,0,'')
+            return (True, 0, '')
         if self._cor_factor <= 0:
-            return (False,2,'Mono-correction factor has to be positive if specified: {0}'.format(self._cor_factor))
-        return (True,0,'')
-#end MonoCorrectionFactor
+            return (False, 2, 'Mono-correction factor has to be positive if specified: {0}'.format(self._cor_factor))
+        return (True, 0, '')
+
+
+# end MonoCorrectionFactor
 
 
 class MotorLogName(PropDescriptor):
@@ -1474,22 +1536,24 @@ class MotorLogName(PropDescriptor):
     def __init__(self):
         self._log_names = []
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         if instance is None:
             return self
         return self._log_names
 
-    def __set__(self,instance,value):
-        if isinstance(value,str):
+    def __set__(self, instance, value):
+        if isinstance(value, str):
             val_list = value.split(';')
-        elif isinstance(value,list):
+        elif isinstance(value, list):
             val_list = []
             for val in value:
                 val_list.append(str(val))
         else:
             val_list = [str(value)]
         self._log_names = val_list
-#end MotorLogName
+
+
+# end MotorLogName
 
 
 class MotorOffset(PropDescriptor):
@@ -1501,19 +1565,21 @@ class MotorOffset(PropDescriptor):
     def __init__(self):
         self._offset = None
 
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         if instance is None:
             return self
         return self._offset
 
-    def __set__(self,instance,value):
+    def __set__(self, instance, value):
         # we do not need to analyze for None or empty list
         # as all this is implemented within generic setter
         if value is None:
             self._offset = None
         else:
             self._offset = float(value)
-#end MotorOffset
+
+
+# end MotorOffset
 
 
 class RotationAngle(PropDescriptor):
@@ -1526,7 +1592,7 @@ class RotationAngle(PropDescriptor):
        the value specified is used and stored in NXSPE files.
     """
 
-    def __init__(self,MotorLogNamesClass,Motor_Offset):
+    def __init__(self, MotorLogNamesClass, Motor_Offset):
         self._mot_offset = Motor_Offset
         self._motor_log = MotorLogNamesClass
         # user may override value derived
@@ -1539,7 +1605,7 @@ class RotationAngle(PropDescriptor):
         self._log_ws_name = None
 
     #
-    def __get__(self,instance,owner=None):
+    def __get__(self, instance, owner=None):
         if instance is None:
             return self
 
@@ -1547,52 +1613,52 @@ class RotationAngle(PropDescriptor):
             return self._own_psi_value
         return self.read_psi_from_workspace(self._log_ws_name)
 
-    def __set__(self,instance,value):
-        if isinstance(value,str):
-            if value in mtd: ## its workspace
+    def __set__(self, instance, value):
+        if isinstance(value, str):
+            if value in mantid.mtd:  ## its workspace
                 self._log_ws_name = value
                 self._own_psi_value = None
-            else: # it is string representation of psi.  Should be
+            else:  # it is string representation of psi.  Should be
                 # convertible to number.
                 self._own_psi_value = float(value)
-        elif isinstance(value,api.Workspace):
+        elif isinstance(value, api.Workspace):
             self._log_ws_name = value.name()
             self._own_psi_value = None
-        elif value is None: # clear all
+        elif value is None:  # clear all
             self._own_psi_value = None
-        else: #own psi value
+        else:  # own psi value
             self._own_psi_value = float(value)
 
-    def _read_ws_logs(self,external_ws=None):
+    def _read_ws_logs(self, external_ws=None):
         """read specified workspace logs from workspace
            provided either internally or externally
         """
         working_ws = external_ws
         if working_ws is None:
-            working_ws = mtd[self._log_ws_name]
+            working_ws = mantid.mtd[self._log_ws_name]
         if working_ws is None:
             raise RuntimeError("No workspace provided. Can not read logs to identify psi")
         else:
-            if isinstance(external_ws,str):
-                working_ws = mtd[external_ws]
+            if isinstance(external_ws, str):
+                working_ws = mantid.mtd[external_ws]
 
         value = None
-#pylint: disable=protected-access
+        # pylint: disable=protected-access
         log_names = self._motor_log._log_names
         for name in log_names:
             try:
                 value = working_ws.getRun().getLogData(name).timeAverageValue()
                 break
-#pylint: disable=bare-except
+            # pylint: disable=bare-except
             except:
                 pass
         return value
 
-    def read_psi_from_workspace(self,workspace):
+    def read_psi_from_workspace(self, workspace):
         """Independent method to read rotation angle from workspace and
          previously set log and offset parameters
         """
-#pylint: disable=protected-access
+        # pylint: disable=protected-access
         offset = self._mot_offset._offset
         if offset is None:
             return np.NaN
@@ -1603,10 +1669,11 @@ class RotationAngle(PropDescriptor):
             return offset + log_val
 
     def dependencies(self):
-        return ['motor_log_names','motor_offset']
-#end RotationAngle
+        return ['motor_log_names', 'motor_offset']
+
+# end RotationAngle
 
 
-#-----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
 # END Descriptors for PropertyManager itself
-#-----------------------------------------------------------------------------------------
+# -----------------------------------------------------------------------------------------
diff --git a/scripts/Inelastic/Direct/PropertyManager.py b/scripts/Inelastic/Direct/PropertyManager.py
index 22fb7840ad2c49959c1bace7ecb5a6d40985f934..5eceaa888cf692874df451d9b14df2d3c37a229e 100644
--- a/scripts/Inelastic/Direct/PropertyManager.py
+++ b/scripts/Inelastic/Direct/PropertyManager.py
@@ -2,9 +2,9 @@
 from __future__ import (absolute_import, division, print_function)
 from Direct.NonIDF_Properties import *
 
-from collections import OrderedDict,Iterable
+from collections import OrderedDict, Iterable
 from six import iteritems
-
+from mantid.kernel import funcinspect
 
 class PropertyManager(NonIDF_Properties):
     """ Class defines the interface for Direct inelastic reduction with properties
@@ -302,15 +302,12 @@ class PropertyManager(NonIDF_Properties):
         """ Method returns list of monitors ID used during reduction """
 
         used_mon=set()
-        for case in common.switch(self.normalise_method):
-            if case('monitor-1'):
-                used_mon.add(self.mon1_norm_spec)
-                break
-            if case('monitor-2'):
-                used_mon.add(self.mon2_norm_spec)
-                break
-            if case(): # default, could also just omit condition or 'if True'
-                pass
+        if self.normalise_method == 'monitor-1':
+            used_mon.add(self.mon1_norm_spec)
+        elif self.normalise_method == 'monitor-2':
+            used_mon.add(self.mon2_norm_spec)
+        else: # default, could also just omit condition or 'if True'
+            pass
         #
 
         def add_ei_monitors(used_mon,ei_mon_list):
diff --git a/scripts/Inelastic/Direct/RunDescriptor.py b/scripts/Inelastic/Direct/RunDescriptor.py
index b3b30a06a1ff19084b0f0984e6447f11d139c62b..9dc9e8307295668dce80d37979f36cfd3a78de8c 100644
--- a/scripts/Inelastic/Direct/RunDescriptor.py
+++ b/scripts/Inelastic/Direct/RunDescriptor.py
@@ -5,6 +5,7 @@
 
 from __future__ import (absolute_import, division, print_function)
 from mantid.simpleapi import *
+from mantid.kernel import funcinspect
 from Direct.PropertiesDescriptors import *
 import re
 import collections
diff --git a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py
index 5591e7f647fc7b0bc9a89a6772faa41d33f2e20a..4c99c1074664996b7e0dd5b210a7a0c70738133b 100644
--- a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py
+++ b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py
@@ -100,10 +100,7 @@ class DgsReductionScripter(BaseReductionScripter):
                             options += subitem
 
         if '_spe' in output_workspace:
-            output_workspace_name = 'live_spe'
             output_workspace = 'OutputWorkspace="live_spe"'
-        else:
-            output_workspace_name = output_workspace.split('"')[1]
 
         script = """StartLiveData(UpdateEvery='10',Instrument='"""
         script += self.instrument_name
diff --git a/scripts/Interface/reduction_gui/reduction/output_script.py b/scripts/Interface/reduction_gui/reduction/output_script.py
index ce485383ee73da01f4dcc8ee4eddc9506cfcde2f..a1dc06f729158ae1d5ec5916f3020e5453647919 100644
--- a/scripts/Interface/reduction_gui/reduction/output_script.py
+++ b/scripts/Interface/reduction_gui/reduction/output_script.py
@@ -1,5 +1,6 @@
 #pylint: disable=invalid-name
 from scripter import BaseScriptElement
+import sys
 
 # Check whether we are running in MantidPlot
 IS_IN_MANTIDPLOT = False
diff --git a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py
index 2f6aa39f0c87a6090c653599e721b0d702f811ee..db262d8cd71e1e85380d3efd74f9b281e77cf1f4 100644
--- a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py
+++ b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py
@@ -156,7 +156,7 @@ class REFLSFCalculatorScripter(BaseReductionScripter):
 
         _script = self.create_script(script_part2)
         if _script == '':
-            print 'Please define a Scaling Factor File Name'
+            print('Please define a Scaling Factor File Name')
             raise RuntimeError
 
         script += _script
@@ -175,14 +175,14 @@ class REFLSFCalculatorScripter(BaseReductionScripter):
         if HAS_MANTID:
             script = self.to_script(None)
 
-            print script
+            print(script)
 
             try:
                 t0 = time.time()
-                exec script
+                exec(script)
                 delta_t = time.time()-t0
-                print REF_RED_OUTPUT_MESSAGE
-                print "SF calculation time: %5.2g sec" % delta_t
+                print("REF_RED_OUTPUT_MESSAGE")
+                print("SF calculation time: %5.2g sec" % delta_t)
                 # Update scripter
                 for item in self._observers:
                     if item.state() is not None:
@@ -196,6 +196,6 @@ class REFLSFCalculatorScripter(BaseReductionScripter):
                             item.state().update()
                         except:
                             pass
-                raise RuntimeError(sys.exc_value)
+                raise RuntimeError(sys.exc_info()[1])
         else:
             raise RuntimeError("SF calculation could not be executed: Mantid could not be imported")
diff --git a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_script.py b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_script.py
index 1d79a37982c377cb9182dddfd30a8bab1adda390..ea85b3fc56911cdce8851e3fd192150ebfa73446 100644
--- a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_script.py
+++ b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_script.py
@@ -89,9 +89,7 @@ class DataSets(BaseScriptElement):
         self.reset()
         dom = xml.dom.minidom.parseString(xml_str)
         self.from_xml_element(dom)
-        element_list = dom.getElementsByTagName("RefLSFCalculator")
-        if len(element_list)>0:
-            instrument_dom = element_list[0]
+        dom.getElementsByTagName("RefLSFCalculator")
 
     def from_xml_element(self, instrument_dom):
         """
diff --git a/scripts/Interface/reduction_gui/reduction/reflectometer/refm_data_script.py b/scripts/Interface/reduction_gui/reduction/reflectometer/refm_data_script.py
index 2e86224f60fb60818b47c2f0d8598db9ec2be596..30ece94dd30c7b10d75101ee91d635e083bb382c 100644
--- a/scripts/Interface/reduction_gui/reduction/reflectometer/refm_data_script.py
+++ b/scripts/Interface/reduction_gui/reduction/reflectometer/refm_data_script.py
@@ -234,9 +234,7 @@ class DataSets(BaseScriptElement):
         self.reset()
         dom = xml.dom.minidom.parseString(xml_str)
         self.from_xml_element(dom)
-        element_list = dom.getElementsByTagName("RefMData")
-        if len(element_list) > 0:
-            instrument_dom = element_list[0]
+        dom.getElementsByTagName("RefMData")
 
     def from_xml_element(self, instrument_dom):
         """
diff --git a/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py b/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py
index d06336dbf6016858ef24eb2876b315f68085f6ca..1116c5b1cd9289691de4c4abf961b0012794f6fc 100644
--- a/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py
+++ b/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py
@@ -2,11 +2,13 @@
 import math
 import time
 import sys
+import os
 from functools import partial
 import numpy as np
 from PyQt4 import QtGui, QtCore
 import reduction_gui.widgets.util as util
 from reduction_gui.widgets.base_widget import BaseWidget
+
 # from launch_peak_back_selection_1d import DesignerMainWindow
 
 IS_IN_MANTIDPLOT = False
@@ -14,12 +16,12 @@ try:
     # from MantidFramework import *
     # mtd.initialise(False)
     # from mantidsimple import *
-    from mantid.simpleapi import *
+    import mantid.simpleapi as mantid
     from reduction.instruments.reflectometer import data_manipulation
 
     IS_IN_MANTIDPLOT = True
-except ImportError, e:
-    logger.error(e.message())
+except ImportError as e:
+    mantid.logger.error(e)
 
 
 class BaseRefWidget(BaseWidget):
@@ -57,14 +59,16 @@ class BaseRefWidget(BaseWidget):
         # Validators
         self._summary.data_peak_from_pixel.setValidator(QtGui.QIntValidator(self._summary.data_peak_from_pixel))
         self._summary.data_peak_to_pixel.setValidator(QtGui.QIntValidator(self._summary.data_peak_to_pixel))
-        self._summary.data_background_from_pixel1.setValidator(QtGui.QIntValidator(self._summary.data_background_from_pixel1))
-        self._summary.data_background_to_pixel1.setValidator(QtGui.QIntValidator(self._summary.data_background_to_pixel1))
+        self._summary.data_background_from_pixel1.setValidator(
+            QtGui.QIntValidator(self._summary.data_background_from_pixel1))
+        self._summary.data_background_to_pixel1.setValidator(
+            QtGui.QIntValidator(self._summary.data_background_to_pixel1))
         self._summary.data_from_tof.setValidator(QtGui.QIntValidator(self._summary.data_from_tof))
         self._summary.data_to_tof.setValidator(QtGui.QIntValidator(self._summary.data_to_tof))
         self._summary.dq0.setValidator(QtGui.QDoubleValidator(self._summary.dq0))
         self._summary.dq_over_q.setValidator(QtGui.QDoubleValidator(self._summary.dq_over_q))
-#        self._summary.overlapValueMeanRadioButton(QtGui.setChecked(False)
-#        self._summary.overlapValueLowestErrorRadioButton.setChecked(True)
+        #        self._summary.overlapValueMeanRadioButton(QtGui.setChecked(False)
+        #        self._summary.overlapValueLowestErrorRadioButton.setChecked(True)
 
         self._summary.x_min_edit.setValidator(QtGui.QDoubleValidator(self._summary.x_min_edit))
         self._summary.x_max_edit.setValidator(QtGui.QDoubleValidator(self._summary.x_max_edit))
@@ -75,12 +79,15 @@ class BaseRefWidget(BaseWidget):
         self._summary.q_min_edit.setValidator(QtGui.QDoubleValidator(self._summary.q_min_edit))
 
         self._summary.angle_offset_edit.setValidator(QtGui.QDoubleValidator(self._summary.angle_offset_edit))
-        self._summary.angle_offset_error_edit.setValidator(QtGui.QDoubleValidator(self._summary.angle_offset_error_edit))
+        self._summary.angle_offset_error_edit.setValidator(
+            QtGui.QDoubleValidator(self._summary.angle_offset_error_edit))
 
         self._summary.norm_peak_from_pixel.setValidator(QtGui.QIntValidator(self._summary.norm_peak_from_pixel))
         self._summary.norm_peak_to_pixel.setValidator(QtGui.QIntValidator(self._summary.norm_peak_to_pixel))
-        self._summary.norm_background_from_pixel1.setValidator(QtGui.QIntValidator(self._summary.norm_background_from_pixel1))
-        self._summary.norm_background_to_pixel1.setValidator(QtGui.QIntValidator(self._summary.norm_background_to_pixel1))
+        self._summary.norm_background_from_pixel1.setValidator(
+            QtGui.QIntValidator(self._summary.norm_background_from_pixel1))
+        self._summary.norm_background_to_pixel1.setValidator(
+            QtGui.QIntValidator(self._summary.norm_background_to_pixel1))
 
         # Event connections
         self.connect(self._summary.data_run_number_edit, QtCore.SIGNAL("returnPressed()"),
@@ -225,7 +232,7 @@ class BaseRefWidget(BaseWidget):
         This retrieve the metadata from the data event NeXus filename
         """
         _full_file_name = filename
-        tmpWks = LoadEventNexus(Filename=_full_file_name,MetaDataOnly='1')
+        tmpWks = mantid.LoadEventNexus(Filename=_full_file_name, MetaDataOnly='1')
 
         isSi = False
 
@@ -257,7 +264,7 @@ class BaseRefWidget(BaseWidget):
         except:
             s2w = mt_run.getProperty('S2HWidth').value[0]
 
-        return [tthd,ths, lambda_requested, s1h, s2h, s1w, s2w, isSi]
+        return [tthd, ths, lambda_requested, s1h, s2h, s1w, s2w, isSi]
 
     def data_run_number_validated(self):
         """
@@ -265,30 +272,30 @@ class BaseRefWidget(BaseWidget):
         number and will retrieve some of the metadata and display them
         in the metadata box
         """
-#        self._summary.data_run_number_processing.show()
+        #        self._summary.data_run_number_processing.show()
         run_number = self._summary.data_run_number_edit.text()
 
         try:
-            _file = FileFinder.findRuns("REF_L%d"%int(run_number))[0]
+            _file = mantid.FileFinder.findRuns("REF_L%d" % int(run_number))[0]
 
-            metadata= self.getMetadata(_file)
+            metadata = self.getMetadata(_file)
 
-            #tthd
+            # tthd
             tthd_value = metadata[0]
             tthd_value_string = '{0:.2f}'.format(tthd_value)
             self._summary.tthd_value.setText(tthd_value_string)
 
-            #ths
+            # ths
             ths_value = metadata[1]
             ths_value_string = '{0:.2f}'.format(ths_value)
             self._summary.ths_value.setText(ths_value_string)
 
-            #lambda requested
+            # lambda requested
             lambda_value = metadata[2]
             lambda_value_string = '{0:.2f}'.format(lambda_value)
             self._summary.lambda_request.setText(lambda_value_string)
 
-            #s1h, s2h, s1w and s2w
+            # s1h, s2h, s1w and s2w
             s1h_value = metadata[3]
             s1h_value_string = '{0:.2f}'.format(s1h_value)
             self._summary.s1h.setText(s1h_value_string)
@@ -309,17 +316,17 @@ class BaseRefWidget(BaseWidget):
             self._summary.s2w.setText(s2w_value_string)
 
             isSi = metadata[7]
-            print isSi
+            print(isSi)
             if isSi:
                 self._summary.label_25.setText("Si height:")
                 self._summary.label_27.setText("Si width:")
             else:
                 self._summary.label25.setText("S2 height:")
                 self._summary.label27.setText("S2 width:")
-#            self._summary.data_run_number_processing.hide()
+            #            self._summary.data_run_number_processing.hide()
         except:
             pass
-#            self._summary.data_run_number_processing.hide()
+        #            self._summary.data_run_number_processing.hide()
 
     def _output_dir_browse(self):
         output_dir = QtGui.QFileDialog.getExistingDirectory(self, "Output Directory - Choose a directory",
@@ -334,22 +341,22 @@ class BaseRefWidget(BaseWidget):
         This method will do an weighted average of the value when
         their x-axis is within a given range (precision)
         """
-        _precision = 0.1/100.   #0.1%
+        _precision = 0.1 / 100.  # 0.1%
 
         new_x_axis = []
         new_y_axis = []
         new_e_axis = []
 
-#        if self.bDEBUG:
-#            print 'x_axis before _smooth_x_axis:'
-#            print x_axis
+        #        if self.bDEBUG:
+        #            print 'x_axis before _smooth_x_axis:'
+        #            print x_axis
 
         sz = len(x_axis)
-        i=0
-        while i < sz-1:
+        i = 0
+        while i < sz - 1:
 
             _left_x = x_axis[i]
-            _right_x = x_axis[i+1]
+            _right_x = x_axis[i + 1]
 
             bCalAverage = False
             if _left_x == _right_x:
@@ -367,26 +374,26 @@ class BaseRefWidget(BaseWidget):
 
             if bCalAverage:
 
-                #average the two values
-                _right_e = e_axis[i+1]
+                # average the two values
+                _right_e = e_axis[i + 1]
                 _right_e2 = _right_e * _right_e
-                _right_y = y_axis[i+1]
+                _right_y = y_axis[i + 1]
 
                 if _left_e2 == 0. or _right_e2 == 0.:
                     _y = 0.
                     _e = 0.
                 else:
 
-                    _error = 1./_left_e2 + 1./_right_e2
+                    _error = 1. / _left_e2 + 1. / _right_e2
                     _x = (_left_x + _right_x) / 2.
-                    _y = (_left_y/_left_e2 + _right_y/_right_e2) / _error
-                    _e = math.sqrt(1./_error)
+                    _y = (_left_y / _left_e2 + _right_y / _right_e2) / _error
+                    _e = math.sqrt(1. / _error)
 
                 new_x_axis.append(_x)
                 new_y_axis.append(_y)
                 new_e_axis.append(_e)
 
-                i+=1
+                i += 1
 
             else:
 
@@ -394,12 +401,12 @@ class BaseRefWidget(BaseWidget):
                 new_y_axis.append(y_axis[i])
                 new_e_axis.append(e_axis[i])
 
-            i+=1
+            i += 1
 
-#        if self.bDEBUG:
-#            print
-#            print 'x-axis after _smooth_x_axis:'
-#            print new_x_axis
+        #        if self.bDEBUG:
+        #            print
+        #            print 'x-axis after _smooth_x_axis:'
+        #            print new_x_axis
 
         self.x_axis = new_x_axis
         self.y_axis = new_y_axis
@@ -420,7 +427,7 @@ class BaseRefWidget(BaseWidget):
         dataDen = 0
         for i in range(sz):
             if error_array[i] != 0:
-                tmpFactor = 1./float((pow(error_array[i], 2)))
+                tmpFactor = 1. / float((pow(error_array[i], 2)))
                 dataDen += tmpFactor
 
         if dataDen == 0:
@@ -428,7 +435,7 @@ class BaseRefWidget(BaseWidget):
             mean_error = 0
         else:
             mean = float(dataNum) / float(dataDen)
-            mean_error = math.sqrt(1/dataDen)
+            mean_error = math.sqrt(1 / dataDen)
 
         return [mean, mean_error]
 
@@ -438,7 +445,7 @@ class BaseRefWidget(BaseWidget):
         the weighted mean
         """
 
-        ws_list = AnalysisDataService.getObjectNames()
+        ws_list = mantid.AnalysisDataService.getObjectNames()
         scaled_ws_list = []
 
         # Get the list of scaled histos
@@ -455,19 +462,19 @@ class BaseRefWidget(BaseWidget):
         # Convert each histo to histograms and rebin to final binning
         for ws in scaled_ws_list:
             new_name = "%s_histo" % ws
-            ConvertToHistogram(InputWorkspace=ws, OutputWorkspace=new_name)
-            Rebin(InputWorkspace=new_name, Params=binning_parameters,
-                  OutputWorkspace=new_name)
+            mantid.ConvertToHistogram(InputWorkspace=ws, OutputWorkspace=new_name)
+            mantid.Rebin(InputWorkspace=new_name, Params=binning_parameters,
+                         OutputWorkspace=new_name)
 
         # Take the first rebinned histo as our output
-        data_y = mtd[scaled_ws_list[0]+'_histo'].dataY(0)
-        data_e = mtd[scaled_ws_list[0]+'_histo'].dataE(0)
+        data_y = mantid.mtd[scaled_ws_list[0] + '_histo'].dataY(0)
+        data_e = mantid.mtd[scaled_ws_list[0] + '_histo'].dataE(0)
 
         # Add in the other histos, averaging the overlaps
         for scaled_ws in scaled_ws_list:
             y_val_index = 0
-            data_y_i = mtd[scaled_ws +'_histo'].dataY(0)
-            data_e_i = mtd[scaled_ws+'_histo'].dataE(0)
+            data_y_i = mantid.mtd[scaled_ws + '_histo'].dataY(0)
+            data_e_i = mantid.mtd[scaled_ws + '_histo'].dataE(0)
             for y_val in data_y_i:
                 y_val_index += 1
                 if data_y[y_val_index] > 0 and y_val > 0:
@@ -478,7 +485,7 @@ class BaseRefWidget(BaseWidget):
                     data_y[y_val_index] = y_val
                     data_e[y_val_index] = data_e_i[y_val_index]
 
-        return scaled_ws_list[0]+'_histo'
+        return scaled_ws_list[0] + '_histo'
 
     def _produce_y_of_same_x_(self, isUsingLessErrorValue):
         """
@@ -486,7 +493,7 @@ class BaseRefWidget(BaseWidget):
         the weighted mean
         """
 
-        ws_list = AnalysisDataService.getObjectNames()
+        ws_list = mantid.AnalysisDataService.getObjectNames()
         scaled_ws_list = []
 
         # Get the list of scaled histos
@@ -502,17 +509,13 @@ class BaseRefWidget(BaseWidget):
 
         # DEBUGGING ONLY
         _file_number = 0
-#        print '=========== BEFORE REBINING =========='
+        #        print '=========== BEFORE REBINING =========='
         for ws in scaled_ws_list:
             # print 'file_number: ' , file_number
-            data_y = mtd[ws].dataY(0)
+            data_y = mantid.mtd[ws].dataY(0)
 
             # cleanup data 0-> NAN
-            for y_val in data_y:
-                # print '-> data_y[j]: ' , data_y[j] , ' data_e[j]: ' , data_y[j]
-                if y_val < 1e-12:
-                    _y_val = np.nan
-
+            data_y = [np.nan if y_val < 1e-12 else y_val for y_val in data_y]
             _file_number += 1
 
         # END OF DEBUGGING ONLY
@@ -520,38 +523,38 @@ class BaseRefWidget(BaseWidget):
         # Convert each histo to histograms and rebin to final binning
         for ws in scaled_ws_list:
             new_name = "%s_histo" % ws
-            ConvertToHistogram(InputWorkspace=ws, OutputWorkspace=new_name)
-#            mtd[new_name].setDistribution(True)
-            Rebin(InputWorkspace=new_name, Params=binning_parameters,
-                  OutputWorkspace=new_name)
+            mantid.ConvertToHistogram(InputWorkspace=ws, OutputWorkspace=new_name)
+            #            mtd[new_name].setDistribution(True)
+            mantid.Rebin(InputWorkspace=new_name, Params=binning_parameters,
+                         OutputWorkspace=new_name)
 
         # Take the first rebinned histo as our output
-        data_y = mtd[scaled_ws_list[0]+'_histo'].dataY(0)
-        data_e = mtd[scaled_ws_list[0]+'_histo'].dataE(0)
+        data_y = mantid.mtd[scaled_ws_list[0] + '_histo'].dataY(0)
+        data_e = mantid.mtd[scaled_ws_list[0] + '_histo'].dataE(0)
 
         # skip first 3 points and last one
         skip_index = 0
         point_to_skip = 3
 
-#        print '============ AFTER REBINING ================' #DEBUGGING ONLY
+        #        print '============ AFTER REBINING ================' #DEBUGGING ONLY
 
         # Add in the other histos, averaging the overlaps
         for i in range(1, len(scaled_ws_list)):
 
-#            print 'i: ' , i
+            #            print 'i: ' , i
 
             skip_point = True
             can_skip_last_point = False
 
-            data_y_i = mtd[scaled_ws_list[i]+'_histo'].dataY(0)
-            data_e_i = mtd[scaled_ws_list[i]+'_histo'].dataE(0)
-            for j in range(len(data_y_i)-1):
+            data_y_i = mantid.mtd[scaled_ws_list[i] + '_histo'].dataY(0)
+            data_e_i = mantid.mtd[scaled_ws_list[i] + '_histo'].dataE(0)
+            for j in range(len(data_y_i) - 1):
 
-#                print '-> j: ' , j
+                #                print '-> j: ' , j
 
                 if data_y_i[j] > 0:
 
-#                    print '   data_y_i[j]: ', data_y_i[j], ' data_e_i[j]: ' , data_e_i[j]
+                    #                    print '   data_y_i[j]: ', data_y_i[j], ' data_e_i[j]: ' , data_e_i[j]
 
                     can_skip_last_point = True
                     if skip_point:
@@ -562,10 +565,10 @@ class BaseRefWidget(BaseWidget):
                         else:
                             continue
 
-                if can_skip_last_point and (data_y_i[j+1]==0):
+                if can_skip_last_point and (data_y_i[j + 1] == 0):
                     break
 
-                if data_y[j]>0 and data_y_i[j]>0:
+                if data_y[j] > 0 and data_y_i[j] > 0:
 
                     if isUsingLessErrorValue:
                         if data_e[j] > data_e_i[j]:
@@ -574,33 +577,33 @@ class BaseRefWidget(BaseWidget):
                     else:
                         [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):
+                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]
 
-        return scaled_ws_list[0]+'_histo'
+        return scaled_ws_list[0] + '_histo'
 
     def _create_ascii_clicked(self):
         """
         Reached by the 'Create ASCII' button
         """
 
-        #make sure there is the right output workspace called '
-#        if not mtd.workspaceExists('ref_combined'):
-#            print 'Workspace "ref_combined" does not exist !'
-#            return
+        # make sure there is the right output workspace called '
+        #        if not mtd.workspaceExists('ref_combined'):
+        #            print 'Workspace "ref_combined" does not exist !'
+        #            return
 
-        #get default output file name
+        # get default output file name
         run_number = self._summary.data_run_number_edit.text()
         default_file_name = 'REFL_' + run_number + '_combined_data.txt'
 
-        #retrieve name of the output file
+        # 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() == '':
             return
 
-        #check the status of the 4th column switch
+        # check the status of the 4th column switch
         _with_4th_flag = self._summary.fourth_column_switch.isChecked()
         text = []
         if _with_4th_flag:
@@ -613,36 +616,36 @@ class BaseRefWidget(BaseWidget):
         else:
             text = ['#Q(1/Angstrom) R delta_R']
 
-#        #rebinned using output factors
-#        q_min = float(self._summary.q_min_edit.text())
-#        q_bin = -float(self._summary.q_step_edit.text())
-#
-#        mt = mtd['ref_combined']
-#        x_axis = mt.readX(0)[:]
-#        q_max = float(x_axis[-1])
-#
-#        q_binning = [q_min, q_bin, q_max]
-#        Rebin(InputWorkspace='ref_combined',
-#              OutputWorkspace='ref_combined',
-#              Params=q_binning)
-
-        #using mean or value with less error
+        #        #rebinned using output factors
+        #        q_min = float(self._summary.q_min_edit.text())
+        #        q_bin = -float(self._summary.q_step_edit.text())
+        #
+        #        mt = mtd['ref_combined']
+        #        x_axis = mt.readX(0)[:]
+        #        q_max = float(x_axis[-1])
+        #
+        #        q_binning = [q_min, q_bin, q_max]
+        #        Rebin(InputWorkspace='ref_combined',
+        #              OutputWorkspace='ref_combined',
+        #              Params=q_binning)
+
+        # using mean or value with less error
         _overlap_less_error_flag = self._summary.overlapValueLowestErrorRadioButton.isChecked()
         wks_file_name = self._produce_y_of_same_x_(_overlap_less_error_flag)
-#        print 'wks_file_name: ' , wks_file_name
+        #        print 'wks_file_name: ' , wks_file_name
 
-#        mt = mtd['ref_combined']
-#        x_axis = mt.readX(0)[:]
-#        y_axis = mt.readY(0)[:]
-#        e_axis = mt.readE(0)[:]
-#
-#        self._smooth_x_axis(x_axis, y_axis, e_axis)
+        #        mt = mtd['ref_combined']
+        #        x_axis = mt.readX(0)[:]
+        #        y_axis = mt.readY(0)[:]
+        #        e_axis = mt.readE(0)[:]
+        #
+        #        self._smooth_x_axis(x_axis, y_axis, e_axis)
 
-        x_axis = mtd[wks_file_name].readX(0)[:]
-        y_axis = mtd[wks_file_name].readY(0)[:]
-        e_axis = mtd[wks_file_name].readE(0)[:]
+        x_axis = mantid.mtd[wks_file_name].readX(0)[:]
+        y_axis = mantid.mtd[wks_file_name].readY(0)[:]
+        e_axis = mantid.mtd[wks_file_name].readE(0)[:]
 
-        sz = len(x_axis)-1
+        sz = len(x_axis) - 1
         for i in range(sz):
             # do not display data where R=0
             if y_axis[i] > 1e-15:
@@ -654,7 +657,7 @@ class BaseRefWidget(BaseWidget):
                     _line += ' ' + _precision
                 text.append(_line)
 
-        f=open(file_name,'w')
+        f = open(file_name, 'w')
         for _line in text:
             f.write(_line + '\n')
 
@@ -669,7 +672,7 @@ class BaseRefWidget(BaseWidget):
                     self._summary.cfg_scaling_factor_file_name.setText(file_name)
                     self.retrieve_list_of_incident_medium(file_name)
         except:
-            print 'Invalid file format (' + file_name + ')'
+            print('Invalid file format (' + file_name + ')')
 
     def variable_value_splitter(self, variable_value):
         """
@@ -679,7 +682,7 @@ class BaseRefWidget(BaseWidget):
         _split = variable_value.split('=')
         variable = _split[0]
         value = _split[1]
-        return {'variable':variable, 'value':value}
+        return {'variable': variable, 'value': value}
 
     def retrieve_list_of_incident_medium(self, cfg_file_name):
         """
@@ -687,7 +690,7 @@ class BaseRefWidget(BaseWidget):
         populate the Incident Medium dropbox with the list of incident medium
         found
         """
-        f=open(cfg_file_name,'r')
+        f = open(cfg_file_name, 'r')
         text = f.readlines()
         list_incident_medium = []
         for _line in text:
@@ -761,7 +764,7 @@ class BaseRefWidget(BaseWidget):
         m.data_files = ["runNumber"]
         reduce_script = m.to_script(True)
 
-        content =  "# Script automatically generated by Mantid on %s\n" % time.ctime()
+        content = "# Script automatically generated by Mantid on %s\n" % time.ctime()
         content += "import sys\n"
         content += "import os\n"
         content += "if (os.environ.has_key(\"MANTIDPATH\")):\n"
@@ -794,7 +797,7 @@ class BaseRefWidget(BaseWidget):
         xml_str += "  <timestamp>%s</timestamp>\n" % time.ctime()
         xml_str += "  <python_version>%s</python_version>\n" % sys.version
         if IS_IN_MANTIDPLOT:
-            xml_str += "  <mantid_version>%s</mantid_version>\n" % mantid_build_version()
+            xml_str += "  <mantid_version>%s</mantid_version>\n" % mantid.mantid_build_version()
         xml_str += m.to_xml()
         xml_str += "</Reduction>\n"
 
@@ -817,7 +820,7 @@ class BaseRefWidget(BaseWidget):
         content += "          CommentIndicator='# ')\n"
 
         home_dir = os.path.expanduser('~')
-        f=open(os.path.join(home_dir,"reduce_%s.py" % self.instrument_name),'w')
+        f = open(os.path.join(home_dir, "reduce_%s.py" % self.instrument_name), 'w')
         f.write(content)
         f.close()
 
@@ -825,23 +828,23 @@ class BaseRefWidget(BaseWidget):
         def _report_error(error=None):
             message = ""
             if error is not None:
-                message += error+'\n\n'
+                message += error + '\n\n'
             else:
                 message += "The automated reduction script could not be saved.\n\n"
             message += "Your script has been saved in your home directory:\n"
-            message += os.path.join(home_dir,"reduce_%s.py" % self.instrument_name)
+            message += os.path.join(home_dir, "reduce_%s.py" % self.instrument_name)
             message += "\n\nTry copying it by hand in %s\n" % sns_path
             QtGui.QMessageBox.warning(self, "Error saving automated reduction script", message)
 
         sns_path = "/SNS/%s/shared/autoreduce" % self.instrument_name
         if os.path.isdir(sns_path):
             if os.access(sns_path, os.W_OK):
-                file_path = os.path.join(sns_path,"reduce_%s.py" % self.instrument_name)
+                file_path = os.path.join(sns_path, "reduce_%s.py" % self.instrument_name)
                 if os.path.isfile(file_path) and not os.access(file_path, os.W_OK):
                     _report_error("You do not have permissions to overwrite %s." % file_path)
                     return
                 try:
-                    f = open(file_path,'w')
+                    f = open(file_path, 'w')
                     f.write(content)
                     f.close()
                     QtGui.QMessageBox.information(self, "Automated reduction script saved",
@@ -865,12 +868,12 @@ class BaseRefWidget(BaseWidget):
             self._summary.auto_reduce_btn.hide()
 
     def _remove_item(self):
-        if self._summary.angle_list.count()==0:
+        if self._summary.angle_list.count() == 0:
             return
         self._summary.angle_list.setEnabled(False)
         self._summary.remove_btn.setEnabled(False)
         row = self._summary.angle_list.currentRow()
-        if row>=0:
+        if row >= 0:
             self._summary.angle_list.takeItem(row)
         self._summary.angle_list.setEnabled(True)
         self._summary.remove_btn.setEnabled(True)
@@ -981,7 +984,7 @@ class BaseRefWidget(BaseWidget):
         self._summary.tof_max_label.setEnabled(is_checked)
         self._summary.data_to_tof.setEnabled(is_checked)
         self._summary.tof_max_label2.setEnabled(is_checked)
-        #self._summary.plot_tof_btn.setEnabled(is_checked)
+        # self._summary.plot_tof_btn.setEnabled(is_checked)
 
         self._edit_event(None, self._summary.tof_range_switch)
 
@@ -1001,40 +1004,40 @@ class BaseRefWidget(BaseWidget):
             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]
-#
-#        #range_min = int(min_ctrl.text())
-#        #range_max = int(max_ctrl.text())
-#
-#        # For REFL, Y is high-res
-#        is_pixel_y = True
-#        is_high_res = True
-#        isPeak = True
-#        min, max = data_manipulation.counts_vs_pixel_distribution(f, is_pixel_y=is_pixel_y,
-#                                                                      high_res=is_high_res,
-#                                                                      instrument=self.short_name,
-#                                                                      isPeak=isPeak)
-#
-#        # for low res
-#        is_high_res = False
-#        is_pixel_y = False
-#        min, max = data_manipulation.counts_vs_pixel_distribution(f, is_pixel_y=is_pixel_y,
-#                                                                      high_res=is_high_res,
-#                                                                      instrument=self.short_name,
-#                                                                      isPeak=isPeak)
-#
-#
-#        basename = os.path.basename(f)
-#        wk1 = "Peak - " + basename + " - Y pixel "
-#        wk2 = "Peak - " + basename + " - X pixel "
-#        dmw = DesignerMainWindow(parent=self, wk1=wk1, wk2=wk2, type='data')
-#
-#        # show it
-#        dmw.show()
-#        # start the Qt main loop execution, existing from this script
-#        # with the same return code of Qt application
-##        sys.exit(app.exec_())
+        #        run_number = self._summary.data_run_number_edit.text()
+        #        f = FileFinder.findRuns("%s%s" % (self.instrument_name, str(run_number)))[0]
+        #
+        #        #range_min = int(min_ctrl.text())
+        #        #range_max = int(max_ctrl.text())
+        #
+        #        # For REFL, Y is high-res
+        #        is_pixel_y = True
+        #        is_high_res = True
+        #        isPeak = True
+        #        min, max = data_manipulation.counts_vs_pixel_distribution(f, is_pixel_y=is_pixel_y,
+        #                                                                      high_res=is_high_res,
+        #                                                                      instrument=self.short_name,
+        #                                                                      isPeak=isPeak)
+        #
+        #        # for low res
+        #        is_high_res = False
+        #        is_pixel_y = False
+        #        min, max = data_manipulation.counts_vs_pixel_distribution(f, is_pixel_y=is_pixel_y,
+        #                                                                      high_res=is_high_res,
+        #                                                                      instrument=self.short_name,
+        #                                                                      isPeak=isPeak)
+        #
+        #
+        #        basename = os.path.basename(f)
+        #        wk1 = "Peak - " + basename + " - Y pixel "
+        #        wk2 = "Peak - " + basename + " - X pixel "
+        #        dmw = DesignerMainWindow(parent=self, wk1=wk1, wk2=wk2, type='data')
+        #
+        #        # show it
+        #        dmw.show()
+        #        # start the Qt main loop execution, existing from this script
+        #        # with the same return code of Qt application
+        ##        sys.exit(app.exec_())
 
         _minimum, _maximum = self._integrated_plot(True,
                                                    self._summary.data_run_number_edit,
@@ -1080,73 +1083,73 @@ class BaseRefWidget(BaseWidget):
         """
 
         # retrieve name of workspace first
-        run_number =  self._summary.data_run_number_edit.text()
-        file_path = FileFinder.findRuns("%s%s" % (self.instrument_name, str(run_number)))[0]
+        run_number = self._summary.data_run_number_edit.text()
+        file_path = mantid.FileFinder.findRuns("%s%s" % (self.instrument_name, str(run_number)))[0]
 
         basename = os.path.basename(file_path)
 
-#         if self.instrument_name == 'REF_L':
-#             ws_output_base = "Pixel Y vs TOF" + " - " + basename
-#         else:
-#             ws_output_base = "Pixel X vs TOF" + " - " + basename
-
-#        if (self.instrument_name == 'REF_L'):
-#            if isPeak:
-#                type = 'Peak'
-#            else:
-#                type = 'Background'
-#            if is_pixel_y is False:
-#                x_title = "X pixel"
-#            else:
-#                x_title = "Y pixel"
-#            ws_output_base =  type + " - " + basename + " - " + x_title
-#        else:
-#            ws_output_base = "Counts vs TOF - %s" % basename
-#            x_title = "Y pixel"
-#            if is_pixel_y is False:
-#                ws_output_base = "Counts vs X pixel - %s" % basename
-#                x_title = "X pixel"
-
-#         range_min = int(self._summary.data_from_tof.text())
-#         range_max = int(self._summary.data_to_tof.text())
+        #         if self.instrument_name == 'REF_L':
+        #             ws_output_base = "Pixel Y vs TOF" + " - " + basename
+        #         else:
+        #             ws_output_base = "Pixel X vs TOF" + " - " + basename
+
+        #        if (self.instrument_name == 'REF_L'):
+        #            if isPeak:
+        #                type = 'Peak'
+        #            else:
+        #                type = 'Background'
+        #            if is_pixel_y is False:
+        #                x_title = "X pixel"
+        #            else:
+        #                x_title = "Y pixel"
+        #            ws_output_base =  type + " - " + basename + " - " + x_title
+        #        else:
+        #            ws_output_base = "Counts vs TOF - %s" % basename
+        #            x_title = "Y pixel"
+        #            if is_pixel_y is False:
+        #                ws_output_base = "Counts vs X pixel - %s" % basename
+        #                x_title = "X pixel"
+
+        #         range_min = int(self._summary.data_from_tof.text())
+        #         range_max = int(self._summary.data_to_tof.text())
 
         ws_output_base = "Peak - " + basename + " - Y pixel _2D"
-#        if mtd.workspaceExists(ws_output_base):
-#            mtd.deleteWorkspace(ws_output_base)
-#            ws_output_base_1 = "__" + self.instrument_name + "_" + str(run_number) + "_event.nxs"
-#            mtd.deleteWorkspace(ws_output_base_1)
-#            ws_output_base_2 = "__" + self.instrument_name + "_" + str(run_number) + "_event.nxs_all"
-#            mtd.deleteWorkspace(ws_output_base_2)
-#            ws_output_base_3 = "Peak - " + self.instrument_name + "_" + str(run_number) + "_event.nxs - Y pixel "
-#            mtd.deleteWorkspace(ws_output_base_3)
-
-        if mtd.doesExist(ws_output_base):
-            DeleteWorkspace(ws_output_base)
+        #        if mtd.workspaceExists(ws_output_base):
+        #            mtd.deleteWorkspace(ws_output_base)
+        #            ws_output_base_1 = "__" + self.instrument_name + "_" + str(run_number) + "_event.nxs"
+        #            mtd.deleteWorkspace(ws_output_base_1)
+        #            ws_output_base_2 = "__" + self.instrument_name + "_" + str(run_number) + "_event.nxs_all"
+        #            mtd.deleteWorkspace(ws_output_base_2)
+        #            ws_output_base_3 = "Peak - " + self.instrument_name + "_" + str(run_number) + "_event.nxs - Y pixel "
+        #            mtd.deleteWorkspace(ws_output_base_3)
+
+        if mantid.mtd.doesExist(ws_output_base):
+            mantid.DeleteWorkspace(ws_output_base)
             ws_output_base_1 = "__" + self.instrument_name + "_" + str(run_number) + "_event.nxs"
-            DeleteWorkspace(ws_output_base_1)
+            mantid.DeleteWorkspace(ws_output_base_1)
             ws_output_base_2 = "__" + self.instrument_name + "_" + str(run_number) + "_event.nxs_all"
-            DeleteWorkspace(ws_output_base_2)
+            mantid.DeleteWorkspace(ws_output_base_2)
             ws_output_base_3 = "Peak - " + self.instrument_name + "_" + str(run_number) + "_event.nxs - Y pixel "
-            DeleteWorkspace(ws_output_base_3)
+            mantid.DeleteWorkspace(ws_output_base_3)
 
         data_manipulation.counts_vs_pixel_distribution(file_path,
                                                        is_pixel_y=True,
                                                        callback=None,
                                                        instrument='REFL')
 
-#        def call_back(peakmin, peakmax, backmin, backmax, tofmin, tofmax):
-#            print 'Inside the call_back on the python side'
-#            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.x_min_edit.setText("%-d" % int(tofmin))
-#            self._summary.x_max_edit.setText("%-d" % int(tofmax))
+        #        def call_back(peakmin, peakmax, backmin, backmax, tofmin, tofmax):
+        #            print 'Inside the call_back on the python side'
+        #            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.x_min_edit.setText("%-d" % int(tofmin))
+        #            self._summary.x_max_edit.setText("%-d" % int(tofmax))
 
         # mantidplot.app should be used instead of _qti.app (it's just an alias)
-        #mantidplot.app.connect(mantidplot.app.mantidUI, QtCore.SIGNAL("python_peak_back_tof_range_update(double,double,
+        # 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
+        # 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())
@@ -1174,40 +1177,40 @@ class BaseRefWidget(BaseWidget):
 
     def _norm_count_vs_y(self):
 
-#        run_number = self._summary.norm_run_number_edit.text()
-#        f = FileFinder.findRuns("%s%s" % (self.instrument_name, str(run_number)))[0]
-#
-#        #range_min = int(min_ctrl.text())
-#        #range_max = int(max_ctrl.text())
-#
-#        # For REFL, Y is high-res
-#        is_pixel_y = True
-#        is_high_res = True
-#        isPeak = True
-#        min, max = data_manipulation.counts_vs_pixel_distribution(f, is_pixel_y=is_pixel_y,
-#                                                                      high_res=is_high_res,
-#                                                                      instrument=self.short_name,
-#                                                                      isPeak=isPeak)
-#
-#        # for low res
-#        is_high_res = False
-#        is_pixel_y = False
-#        min, max = data_manipulation.counts_vs_pixel_distribution(f, is_pixel_y=is_pixel_y,
-#                                                                      high_res=is_high_res,
-#                                                                      instrument=self.short_name,
-#                                                                      isPeak=isPeak)
-#
-#
-#        basename = os.path.basename(f)
-#        wk1 = "Peak - " + basename + " - Y pixel "
-#        wk2 = "Peak - " + basename + " - X pixel "
-#        dmw = DesignerMainWindow(parent=self, wk1=wk1, wk2=wk2, type='norm')
-#
-#        # show it
-#        dmw.show()
-
-#        dmw = DesignerMainWindow(self, 'norm')
-#        dmw.show()
+        #        run_number = self._summary.norm_run_number_edit.text()
+        #        f = FileFinder.findRuns("%s%s" % (self.instrument_name, str(run_number)))[0]
+        #
+        #        #range_min = int(min_ctrl.text())
+        #        #range_max = int(max_ctrl.text())
+        #
+        #        # For REFL, Y is high-res
+        #        is_pixel_y = True
+        #        is_high_res = True
+        #        isPeak = True
+        #        min, max = data_manipulation.counts_vs_pixel_distribution(f, is_pixel_y=is_pixel_y,
+        #                                                                      high_res=is_high_res,
+        #                                                                      instrument=self.short_name,
+        #                                                                      isPeak=isPeak)
+        #
+        #        # for low res
+        #        is_high_res = False
+        #        is_pixel_y = False
+        #        min, max = data_manipulation.counts_vs_pixel_distribution(f, is_pixel_y=is_pixel_y,
+        #                                                                      high_res=is_high_res,
+        #                                                                      instrument=self.short_name,
+        #                                                                      isPeak=isPeak)
+        #
+        #
+        #        basename = os.path.basename(f)
+        #        wk1 = "Peak - " + basename + " - Y pixel "
+        #        wk2 = "Peak - " + basename + " - X pixel "
+        #        dmw = DesignerMainWindow(parent=self, wk1=wk1, wk2=wk2, type='norm')
+        #
+        #        # show it
+        #        dmw.show()
+
+        #        dmw = DesignerMainWindow(self, 'norm')
+        #        dmw.show()
         _minimum, _maximum = self._integrated_plot(True,
                                                    self._summary.norm_run_number_edit,
                                                    self._summary.norm_peak_from_pixel,
@@ -1262,7 +1265,7 @@ class BaseRefWidget(BaseWidget):
             return None, None
 
         try:
-            f = FileFinder.findRuns("%s%s" % (self.instrument_name, str(file_ctrl.text())))[0]
+            f = mantid.FileFinder.findRuns("%s%s" % (self.instrument_name, str(file_ctrl.text())))[0]
 
             range_min = int(min_ctrl.text())
             range_max = int(max_ctrl.text())
@@ -1273,7 +1276,7 @@ class BaseRefWidget(BaseWidget):
 
             # For REFL, Y is high-res
 
-            is_pixel_y =  is_high_res
+            is_pixel_y = is_high_res
             # For REFM it's the other way around
             if self.short_name == "REFM":
                 is_pixel_y = not is_pixel_y
@@ -1287,15 +1290,16 @@ class BaseRefWidget(BaseWidget):
                                                                               isPeak=isPeak)
 
             return minimum, maximum
-        except IOError, e:
-            logger.error("Could not find file: " + e.filename())
+        except IOError as e:
+            mantid.logger.error("Could not find file: " + e)
 
     def _plot_tof(self):
         if not IS_IN_MANTIDPLOT:
             return
         try:
-            f = FileFinder.findRuns("%s%s" % (self.instrument_name, str(self._summary.norm_run_number_edit.text())))[0]
-#            print FileFinder.findRuns("%s%s" % (self.instrument_name, str(self._summary.norm_run_number_edit.text())))
+            f = mantid.FileFinder.findRuns("%s%s" %
+                                           (self.instrument_name, str(self._summary.norm_run_number_edit.text())))[0]
+            #            print FileFinder.findRuns("%s%s" % (self.instrument_name, str(self._summary.norm_run_number_edit.text())))
             range_min = int(self._summary.data_from_tof.text())
             range_max = int(self._summary.data_to_tof.text())
 
@@ -1315,14 +1319,14 @@ class BaseRefWidget(BaseWidget):
         # Check whether it's already in the list
         run_numbers = self._summary.data_run_number_edit.text()
         list_items = self._summary.angle_list.findItems(run_numbers, QtCore.Qt.MatchFixedString)
-        if len(list_items)>0:
+        if len(list_items) > 0:
             list_items[0].setData(QtCore.Qt.UserRole, state)
             in_list = True
 
-            #loop over all the already defined states and give all of them the
-            #same Qmin, Qsteps, Angle offset, scaling factor config file name
-            #and incident medium
-            i=0
+            # loop over all the already defined states and give all of them the
+            # same Qmin, Qsteps, Angle offset, scaling factor config file name
+            # and incident medium
+            i = 0
             while i < self._summary.angle_list.count():
 
                 current_item = self._summary.angle_list.item(i)
@@ -1345,7 +1349,7 @@ class BaseRefWidget(BaseWidget):
 
                 state.geometry_correction_switch = self._summary.geometry_correction_switch.isChecked()
 
-                #incident medium
+                # incident medium
                 _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()
@@ -1359,12 +1363,12 @@ class BaseRefWidget(BaseWidget):
                 state.overlap_lowest_error = self._summary.overlapValueLowestErrorRadioButton.isChecked()
                 state.overlap_mean_value = self._summary.overlapValueMeanRadioButton.isChecked()
 
-                #4th column (precision)
+                # 4th column (precision)
                 state.fourth_column_dq0 = self._summary.dq0.text()
                 state.fourth_column_dq_over_q = self._summary.dq_over_q.text()
 
                 current_item.setData(QtCore.Qt.UserRole, state)
-                i+=1
+                i += 1
 
         else:
             item_widget = QtGui.QListWidgetItem(run_numbers, self._summary.angle_list)
@@ -1377,7 +1381,7 @@ class BaseRefWidget(BaseWidget):
 
                 state.geometry_correction_switch = self._summary.geometry_correction_switch.isChecked()
 
-            #incident medium
+            # incident medium
             _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()
@@ -1400,11 +1404,11 @@ class BaseRefWidget(BaseWidget):
         self._reset_warnings()
 
     def _angle_changed(self):
-        if self._summary.angle_list.count()==0:
+        if self._summary.angle_list.count() == 0:
             return
         self._summary.angle_list.setEnabled(False)
         self._summary.remove_btn.setEnabled(False)
-        current_item =  self._summary.angle_list.currentItem()
+        current_item = self._summary.angle_list.currentItem()
         if current_item is not None:
             state = current_item.data(QtCore.Qt.UserRole)
             self.set_editing_state(state)
@@ -1418,22 +1422,22 @@ class BaseRefWidget(BaseWidget):
             @param state: data object
         """
         self._summary.angle_list.clear()
-        if len(state.data_sets)==1 and state.data_sets[0].data_files[0]==0:
+        if len(state.data_sets) == 1 and state.data_sets[0].data_files[0] == 0:
             pass
         else:
             for item in state.data_sets:
                 if item is not None:
-                    item_widget = QtGui.QListWidgetItem(unicode(str(','.join([str(i) for i in item.data_files]))),
+                    item_widget = QtGui.QListWidgetItem(str(str(','.join([str(i) for i in item.data_files]))),
                                                         self._summary.angle_list)
                     item_widget.setData(QtCore.Qt.UserRole, item)
 
-        if len(state.data_sets)>0:
+        if len(state.data_sets) > 0:
             self.set_editing_state(state.data_sets[0])
             self._summary.angle_list.setCurrentRow(0, QtGui.QItemSelectionModel.Select)
 
-#            # Common Q binning
-#            self._summary.q_min_edit.setText(str(state.data_sets[0].q_min))
-#            self._summary.log_scale_chk.setChecked(state.data_sets[0].q_step<0)
+            #            # Common Q binning
+            #            self._summary.q_min_edit.setText(str(state.data_sets[0].q_min))
+            #            self._summary.log_scale_chk.setChecked(state.data_sets[0].q_step<0)
 
             # Common angle offset
             if hasattr(state.data_sets[0], "angle_offset"):
@@ -1444,7 +1448,7 @@ class BaseRefWidget(BaseWidget):
 
     def set_editing_state(self, state):
         self._summary.q_min_edit.setText(str(state.q_min))
-        self._summary.log_scale_chk.setChecked(state.q_step<0)
+        self._summary.log_scale_chk.setChecked(state.q_step < 0)
 
         self._summary.incident_medium_combobox.clear()
         _incident_medium_str = str(state.incident_medium_list[0])
@@ -1453,35 +1457,35 @@ class BaseRefWidget(BaseWidget):
             self._summary.incident_medium_combobox.addItem(str(item))
         self._summary.incident_medium_combobox.setCurrentIndex(state.incident_medium_index_selected)
 
-        #Peak from/to pixels
+        # Peak from/to pixels
         self._summary.data_peak_from_pixel.setText(str(state.DataPeakPixels[0]))
         self._summary.data_peak_to_pixel.setText(str(state.DataPeakPixels[1]))
 
-        #data low resolution range
+        # data low resolution range
         self._summary.data_low_res_range_switch.setChecked(state.data_x_range_flag)
         self._summary.x_min_edit.setText(str(state.data_x_range[0]))
         self._summary.x_max_edit.setText(str(state.data_x_range[1]))
         self._data_low_res_clicked(state.data_x_range_flag)
 
-        #data metadata
+        # data metadata
         self._summary.tthd_value.setText(str(state.tthd_value))
         self._summary.ths_value.setText(str(state.ths_value))
 
-        #norm low resolution range
+        # norm low resolution range
         self._summary.norm_low_res_range_switch.setChecked(state.norm_x_range_flag)
         self._summary.norm_x_min_edit.setText(str(state.norm_x_range[0]))
         self._summary.norm_x_max_edit.setText(str(state.norm_x_range[1]))
         self._norm_low_res_clicked(state.data_x_range_flag)
 
-        #Background flag
+        # Background flag
         self._summary.data_background_switch.setChecked(state.DataBackgroundFlag)
         self._data_background_clicked(state.DataBackgroundFlag)
 
-        #Background from/to pixels
+        # Background from/to pixels
         self._summary.data_background_from_pixel1.setText(str(state.DataBackgroundRoi[0]))
         self._summary.data_background_to_pixel1.setText(str(state.DataBackgroundRoi[1]))
 
-        #from TOF and to TOF
+        # from TOF and to TOF
         self._summary.data_from_tof.setText(str(int(state.DataTofRange[0])))
         self._summary.data_to_tof.setText(str(int(state.DataTofRange[1])))
 
@@ -1496,13 +1500,13 @@ class BaseRefWidget(BaseWidget):
         self._summary.norm_background_from_pixel1.setText(str(state.NormBackgroundRoi[0]))
         self._summary.norm_background_to_pixel1.setText(str(state.NormBackgroundRoi[1]))
 
-        #normalization flag
+        # normalization flag
         self._summary.norm_switch.setChecked(state.NormFlag)
         self._norm_clicked(state.NormFlag)
 
         # Q binning
         self._summary.q_min_edit.setText(str(state.q_min))
-        self._summary.log_scale_chk.setChecked(state.q_step<0)
+        self._summary.log_scale_chk.setChecked(state.q_step < 0)
         self._summary.q_step_edit.setText(str(math.fabs(state.q_step)))
 
         # overlap ascii values
@@ -1511,10 +1515,10 @@ class BaseRefWidget(BaseWidget):
 
         # Output directory
         if hasattr(state, "output_dir"):
-            if len(str(state.output_dir).strip())>0:
+            if len(str(state.output_dir).strip()) > 0:
                 self._summary.outdir_edit.setText(str(state.output_dir))
 
-        #scaling factor file and options
+        # scaling factor file and options
         self._summary.use_sf_config_switch.setChecked(state.scaling_factor_file_flag)
         self._summary.cfg_scaling_factor_file_name.setText(str(state.scaling_factor_file))
         self._summary.slits_width_flag.setChecked(state.slits_width_flag)
@@ -1526,6 +1530,6 @@ class BaseRefWidget(BaseWidget):
         self._reset_warnings()
         self._summary.data_run_number_edit.setText(str(','.join([str(i) for i in state.data_files])))
 
-        #4th column (precision)
+        # 4th column (precision)
         self._summary.fourth_column_switch.setChecked(state.fourth_column_flag)
         self._fourth_column_clicked(state.fourth_column_flag)
diff --git a/scripts/Interface/ui/reflectometer/refl_gui.py b/scripts/Interface/ui/reflectometer/refl_gui.py
index 8de9d8c0aeeb0baf9c40641ffcb4dfa09f8eec92..99c39eb0152226ea27054ef8f9a509da977089b6 100644
--- a/scripts/Interface/ui/reflectometer/refl_gui.py
+++ b/scripts/Interface/ui/reflectometer/refl_gui.py
@@ -4,7 +4,7 @@
 try:
     from mantidplot import *
 except ImportError:
-    canMantidPlot = False #
+    canMantidPlot = False  #
 
 import ui_refl_window
 import refl_save
@@ -35,7 +35,6 @@ canMantidPlot = True
 
 
 class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
-
     current_instrument = None
     current_table = None
     current_polarisation_method = None
@@ -81,25 +80,27 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         self.__group_tof_workspaces_key = "group_tof_workspaces"
         self.__stitch_right_key = "stitch_right"
 
-        #Setup instrument with defaults assigned.
+        # Setup instrument with defaults assigned.
         self.instrument_list = ['INTER', 'SURF', 'CRISP', 'POLREF', 'OFFSPEC']
         self.polarisation_instruments = ['CRISP', 'POLREF']
         self.polarisation_options = {'None': PolarisationCorrection.NONE,
                                      '1-PNR': PolarisationCorrection.PNR,
                                      '2-PA': PolarisationCorrection.PA}
 
-        #Set the live data settings, use default if none have been set before
+        # Set the live data settings, use default if none have been set before
         settings = QtCore.QSettings()
         settings.beginGroup(self.__live_data_settings)
         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:
-            logger.information("No settings were found for Update frequency of loading live data, Loading default of 60 seconds")
+            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:
-            logger.information("No settings were found for Accumulation Method of loading live data, Loading default of \"Add\"")
+            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()
@@ -108,8 +109,8 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
 
         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.
+            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)
 
@@ -126,7 +127,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         settings.endGroup()
 
         del settings
-        #register startup
+        # register startup
         UsageService.registerFeatureUsage("Interface", "ISIS Reflectomety", False)
 
     def __del__(self):
@@ -194,16 +195,17 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         self.textRB.clear()
         self._populate_runs_list()
         self.current_instrument = self.instrument_list[instrument]
-        self.comboPolarCorrect.setEnabled(self.current_instrument in self.polarisation_instruments) # Enable as appropriate
-        self.comboPolarCorrect.setCurrentIndex(self.comboPolarCorrect.findText('None')) # Reset to None
+        self.comboPolarCorrect.setEnabled(
+            self.current_instrument in self.polarisation_instruments)  # Enable as appropriate
+        self.comboPolarCorrect.setCurrentIndex(self.comboPolarCorrect.findText('None'))  # Reset to None
 
     def _table_modified(self, row, column):
         """
         sets the modified flag when the table is altered
         """
 
-        #Sometimes users enter leading or trailing whitespace into a cell.
-        #Let's remove it for them automatically.
+        # Sometimes users enter leading or trailing whitespace into a cell.
+        # Let's remove it for them automatically.
         item = self.tableMain.item(row, column)
         item.setData(0, str.strip(str(item.data(0))))
 
@@ -248,7 +250,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
             config['default.instrument'] = 'INTER'
         self.current_instrument = config['default.instrument'].upper()
 
-        #Setup polarisation options with default assigned
+        # Setup polarisation options with default assigned
         self.comboPolarCorrect.clear()
         self.comboPolarCorrect.addItems(self.polarisation_options.keys())
         self.comboPolarCorrect.setCurrentIndex(self.comboPolarCorrect.findText('None'))
@@ -266,7 +268,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         """
         Reset the plot buttons and stitch checkboxes back to thier defualt state
         """
-        #switches from current to true, to false to make sure stateChanged fires
+        # switches from current to true, to false to make sure stateChanged fires
         self.checkTickAll.setCheckState(2)
         self.checkTickAll.setCheckState(0)
         for row in range(self.tableMain.rowCount()):
@@ -287,7 +289,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         """
         Initialise the table. Clearing all data and adding the checkboxes and plot buttons
         """
-        #first check if the table has been changed before clearing it
+        # first check if the table has been changed before clearing it
         if self.mod_flag:
             ret, _saved = self._save_check()
             if ret == QtGui.QMessageBox.RejectRole:
@@ -425,7 +427,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
 
             search_alg = AlgorithmManager.create('CatalogGetDataFiles')
             search_alg.initialize()
-            search_alg.setChild(True) # Keeps the results table out of the ADS
+            search_alg.setChild(True)  # Keeps the results table out of the ADS
             search_alg.setProperty('InvestigationId', str(self.textRB.text()))
             search_alg.setProperty('Session', active_session_id)
             search_alg.setPropertyValue('OutputWorkspace', '_dummy')
@@ -440,7 +442,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                 description = row['Description']
                 run_number = re.search(r'[1-9]\d+', file_name).group()
 
-                if bool(re.search('(raw)$', file_name, re.IGNORECASE)): # Filter to only display and map raw files.
+                if bool(re.search('(raw)$', file_name, re.IGNORECASE)):  # Filter to only display and map raw files.
                     title = (run_number + ': ' + description).strip()
                     self.icat_file_map[title] = (file_id, run_number, file_name)
                     self.listMain.addItem(title)
@@ -476,7 +478,8 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                                                "No target cells to autofill. Rows to be filled should contain a run number in their "
                                                "first cell, and start from directly below the selected line.")
             else:
-                QtGui.QMessageBox.critical(self.tableMain, 'Cannot perform Autofill', "Selected cells must all be in the same row.")
+                QtGui.QMessageBox.critical(self.tableMain, 'Cannot perform Autofill',
+                                           "Selected cells must all be in the same row.")
         else:
             QtGui.QMessageBox.critical(self.tableMain, 'Cannot perform Autofill', "There are no source cells selected.")
 
@@ -503,7 +506,8 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         """
         cells = self.tableMain.selectedItems()
         if not cells:
-            print 'nothing to copy'
+            print
+            'nothing to copy'
             return
         # first discover the size of the selection and initialise a list
         mincol = cells[0].column()
@@ -522,7 +526,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         colsize = maxcol - mincol + 1
         rowsize = maxrow - minrow + 1
         selection = [['' for x in range(colsize)] for y in range(rowsize)]
-        #now fill that list
+        # now fill that list
         for cell in cells:
             row = cell.row()
             col = cell.column()
@@ -557,20 +561,21 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         pastedcols = len(pastedcells[0])
         pastedrows = len(pastedcells)
         if len(selected) > 1:
-            #discover the size of the selection
+            # discover the size of the selection
             mincol = selected[0].column()
             if mincol > self.scale_col:
                 logger.error("Cannot copy, all cells out of range")
                 return
             minrow = selected[0].row()
-            #now fill that list
+            # now fill that list
             for cell in selected:
                 row = cell.row()
                 col = cell.column()
-                if col < self.stitch_col and (col - mincol) < pastedcols and (row - minrow) < pastedrows and len(pastedcells[row - minrow]):
+                if col < self.stitch_col and (col - mincol) < pastedcols and (row - minrow) < pastedrows and len(
+                        pastedcells[row - minrow]):
                     cell.setText(pastedcells[row - minrow][col - mincol])
         elif selected:
-            #when only a single cell is selected, paste all the copied item up until the table limits
+            # when only a single cell is selected, paste all the copied item up until the table limits
             cell = selected[0]
             currow = cell.row()
             homecol = cell.column()
@@ -585,11 +590,11 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                                 curcell.setText(col)
                                 curcol += 1
                             else:
-                                #the row has hit the end of the editable cells
+                                # the row has hit the end of the editable cells
                                 break
                         currow += 1
                     else:
-                        #it's dropped off the bottom of the table
+                        # it's dropped off the bottom of the table
                         break
         else:
             logger.warning("Cannot paste, no editable cells selected")
@@ -609,18 +614,18 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                     continue
                 else:
                     theta = 0
-                    split_title.append(theta) # Append a dummy theta value.
+                    split_title.append(theta)  # Append a dummy theta value.
             if len(split_title) < 4:
                 dqq = 0
-                split_title.append(dqq) # Append a dummy dq/q value.
-            tup = tup + (split_title,) # Tuple of lists containing (run number, title, theta, dq/q)
+                split_title.append(dqq)  # Append a dummy dq/q value.
+            tup = tup + (split_title,)  # Tuple of lists containing (run number, title, theta, dq/q)
 
         tupsort = sorted(tup, key=itemgetter(1, 2))  # now sorted by title then theta
         row = 0
-        for _key, group in itertools.groupby(tupsort, lambda x: x[1]): # now group by title
+        for _key, group in itertools.groupby(tupsort, lambda x: x[1]):  # now group by title
             col = 0
-            dqq = 0 # only one value of dqq per row
-            run_angle_pairs_of_title = list() # for storing run_angle pairs all with the same title
+            dqq = 0  # only one value of dqq per row
+            run_angle_pairs_of_title = list()  # for storing run_angle pairs all with the same title
             for object in group:  # loop over all with equal title
 
                 run_no = object[0]
@@ -668,7 +673,8 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
 
             save_location = config['defaultsave.directory']
 
-            CatalogDownloadDataFiles(file_id, FileNames=file_name, DownloadPath=save_location, Session=active_session_id)
+            CatalogDownloadDataFiles(file_id, FileNames=file_name, DownloadPath=save_location,
+                                     Session=active_session_id)
 
             current_search_dirs = config.getDataSearchDirs()
 
@@ -689,7 +695,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         """
         Process has been pressed, check what has been selected then pass the selection (or whole table) to quick
         """
-#--------- If "Process" button pressed, convert raw files to IvsLam and IvsQ and combine if checkbox ticked -------------
+        # --------- If "Process" button pressed, convert raw files to IvsLam and IvsQ and combine if checkbox ticked -------------
         _overallQMin = float("inf")
         _overallQMax = float("-inf")
         try:
@@ -731,7 +737,8 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                         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,
+                                loadedRun = load_live_runs.get_live_data(config['default.instrument'],
+                                                                         frequency=self.live_freq,
                                                                          accumulation=self.live_method)
                             else:
                                 Load(Filename=runno[0], OutputWorkspace="_run")
@@ -742,19 +749,19 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                                 if len(two_theta_str) > 0:
                                     two_theta = float(two_theta_str)
 
-                                #Make sure we only ever run calculate resolution on a non-group workspace.
-                                #If we're given a group workspace, we can just run it on the first member of the group instead
+                                # Make sure we only ever run calculate resolution on a non-group workspace.
+                                # 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]
                                 dqq, two_theta = CalculateResolution(Workspace=thetaRun, TwoTheta=two_theta)
 
-                                #Put the calculated resolution into the table
+                                # Put the calculated resolution into the table
                                 resItem = QtGui.QTableWidgetItem()
                                 resItem.setText(str(dqq))
                                 self.tableMain.setItem(row, 15, resItem)
 
-                                #Update the value for two_theta in the table
+                                # Update the value for two_theta in the table
                                 ttItem = QtGui.QTableWidgetItem()
                                 ttItem.setText(str(two_theta))
                                 self.tableMain.setItem(row, 1, ttItem)
@@ -762,8 +769,9 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                                 logger.notice("Calculated resolution: " + str(dqq))
                             except:
                                 self.statusMain.clearMessage()
-                                logger.error("Failed to calculate dq/q because we could not find theta in the workspace's sample log. "
-                                             "Try entering theta or dq/q manually.")
+                                logger.error(
+                                    "Failed to calculate dq/q because we could not find theta in the workspace's sample log. "
+                                    "Try entering theta or dq/q manually.")
                                 return
                         else:
                             dqq = float(self.tableMain.item(row, 15).text())
@@ -787,7 +795,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                             theta, qmin, qmax, _wlam, wqBinnedAndScaled, _wqUnBinnedAndUnScaled = \
                                 self._do_run(runno[i], row, i)
                             if not first_wq:
-                                first_wq = wqBinnedAndScaled # Cache the first Q workspace
+                                first_wq = wqBinnedAndScaled  # Cache the first Q workspace
                             theta = round(theta, 3)
                             qmin = round(qmin, 3)
                             qmax = round(qmax, 3)
@@ -833,9 +841,9 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                                     if Qmin < _overallQMin:
                                         _overallQMin = Qmin
 
-                                    _wcomb = combineDataMulti(wksp, outputwksp, overlapLow, overlapHigh,
-                                                              _overallQMin, _overallQMax, -dqq, 1, keep=True,
-                                                              scale_right=self.__scale_right)
+                                    combineDataMulti(wksp, outputwksp, overlapLow, overlapHigh,
+                                                     _overallQMin, _overallQMax, -dqq, 1, keep=True,
+                                                     scale_right=self.__scale_right)
 
                         # Enable the plot button
                         plotbutton = self.tableMain.cellWidget(row, self.plot_col).children()[1]
@@ -860,7 +868,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
             return
         import unicodedata
 
-        #make sure the required data can be retrieved properly
+        # make sure the required data can be retrieved properly
         try:
             runno_u = plotbutton.property('runno')
             runno = []
@@ -924,8 +932,8 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                 outputwksp = runno[0] + '_' + runno[2][3:]
             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, scale_right=self.__scale_right)
+                combineDataMulti(wkspBinned, outputwksp, overlapLow, overlapHigh, Qmin, Qmax, -dqq, 1,
+                                 keep=True, scale_right=self.__scale_right)
 
             Qmin = min(getWorkspace(outputwksp).readX(0))
             Qmax = max(getWorkspace(outputwksp).readX(0))
@@ -985,7 +993,8 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
 
         loadedRun = runno
         if load_live_runs.is_live_run(runno):
-            load_live_runs.get_live_data(config['default.instrument'], frequency=self.live_freq, accumulation=self.live_method)
+            load_live_runs.get_live_data(config['default.instrument'], frequency=self.live_freq,
+                                         accumulation=self.live_method)
         wlam, wq, th, wqBinned = None, None, None, None
 
         # Only make a transmission workspace if we need one.
@@ -996,12 +1005,15 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
             if size == 1:
                 trans1 = converter.get_workspace_from_list(0)
 
-                transmission_ws = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans1, OutputWorkspace=out_ws_name,
-                                                                  Params=0.02, StartOverlap=10.0, EndOverlap=12.0, Version=1)
+                transmission_ws = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans1,
+                                                                  OutputWorkspace=out_ws_name,
+                                                                  Params=0.02, StartOverlap=10.0, EndOverlap=12.0,
+                                                                  Version=1)
             elif size == 2:
                 trans1 = converter.get_workspace_from_list(0)
                 trans2 = converter.get_workspace_from_list(1)
-                transmission_ws = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans1, OutputWorkspace=out_ws_name,
+                transmission_ws = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans1,
+                                                                  OutputWorkspace=out_ws_name,
                                                                   SecondTransmissionRun=trans2, Params=0.02,
                                                                   StartOverlap=10.0, EndOverlap=12.0, Version=1)
             else:
@@ -1012,11 +1024,11 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
 
         if self.__alg_use:
             if self.tableMain.item(row, self.scale_col).text():
-                factor=float(self.tableMain.item(row, self.scale_col).text())
+                factor = float(self.tableMain.item(row, self.scale_col).text())
             else:
-                factor=1.0
+                factor = 1.0
             if self.tableMain.item(row, 15).text():
-                Qstep=float(self.tableMain.item(row, 15).text())
+                Qstep = float(self.tableMain.item(row, 15).text())
             else:
                 Qstep = None
             if len(self.tableMain.item(row, which * 5 + 3).text()) > 0:
@@ -1036,7 +1048,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                 thetaGroup = []
                 group_trans_ws = transmission_ws
                 for i in range(0, ws.size()):
-                    #If the transmission workspace is a group, we'll use it pair-wise with the tof workspace group
+                    # If the transmission workspace is a group, we'll use it pair-wise with the tof workspace group
                     if isinstance(transmission_ws, WorkspaceGroup):
                         group_trans_ws = transmission_ws[i]
 
@@ -1047,9 +1059,9 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                         alg.setProperty("FirstTransmissionRun", group_trans_ws)
                     if angle is not None:
                         alg.setProperty("ThetaIn", angle)
-                    alg.setProperty("OutputWorkspaceBinned", runno+'_IvsQ_binned_'+str(i+1))
-                    alg.setProperty("OutputWorkspace", runno+'_IvsQ_'+str(i+1))
-                    alg.setProperty("OutputWorkspaceWavelength", runno+'_IvsLam_'+str(i+1))
+                    alg.setProperty("OutputWorkspaceBinned", runno + '_IvsQ_binned_' + str(i + 1))
+                    alg.setProperty("OutputWorkspace", runno + '_IvsQ_' + str(i + 1))
+                    alg.setProperty("OutputWorkspaceWavelength", runno + '_IvsLam_' + str(i + 1))
                     alg.setProperty("ScaleFactor", factor)
                     if Qstep is not None:
                         alg.setProperty("MomentumTransferStep", Qstep)
@@ -1058,9 +1070,9 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                     if Qmax is not None:
                         alg.setProperty("MomentumTransferMax", Qmax)
                     alg.execute()
-                    wqBinned = mtd[runno+'_IvsQ_binned_'+str(i+1)]
-                    wq = mtd[runno+'_IvsQ_'+str(i+1)]
-                    wlam = mtd[runno+'_IvsLam_'+str(i+1)]
+                    wqBinned = mtd[runno + '_IvsQ_binned_' + str(i + 1)]
+                    wq = mtd[runno + '_IvsQ_' + str(i + 1)]
+                    wlam = mtd[runno + '_IvsLam_' + str(i + 1)]
                     th = alg.getProperty("ThetaIn").value
 
                     wqGroupBinned.append(wqBinned)
@@ -1068,9 +1080,9 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                     wlamGroup.append(wlam)
                     thetaGroup.append(th)
 
-                wqBinned = GroupWorkspaces(InputWorkspaces=wqGroupBinned, OutputWorkspace=runno+'_IvsQ_binned')
-                wq = GroupWorkspaces(InputWorkspaces=wqGroup, OutputWorkspace=runno+'_IvsQ')
-                wlam = GroupWorkspaces(InputWorkspaces=wlamGroup, OutputWorkspace=runno+'_IvsLam')
+                wqBinned = GroupWorkspaces(InputWorkspaces=wqGroupBinned, OutputWorkspace=runno + '_IvsQ_binned')
+                wq = GroupWorkspaces(InputWorkspaces=wqGroup, OutputWorkspace=runno + '_IvsQ')
+                wlam = GroupWorkspaces(InputWorkspaces=wlamGroup, OutputWorkspace=runno + '_IvsLam')
                 th = thetaGroup[0]
             else:
                 alg = AlgorithmManager.create("ReflectometryReductionOneAuto")
@@ -1080,9 +1092,9 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                     alg.setProperty("FirstTransmissionRun", transmission_ws)
                 if angle is not None:
                     alg.setProperty("ThetaIn", angle)
-                alg.setProperty("OutputWorkspaceBinned", runno+'_IvsQ_binned')
-                alg.setProperty("OutputWorkspace", runno+'_IvsQ')
-                alg.setProperty("OutputWorkspaceWavelength", runno+'_IvsLam')
+                alg.setProperty("OutputWorkspaceBinned", runno + '_IvsQ_binned')
+                alg.setProperty("OutputWorkspace", runno + '_IvsQ')
+                alg.setProperty("OutputWorkspaceWavelength", runno + '_IvsLam')
                 alg.setProperty("ScaleFactor", factor)
                 if Qstep is not None:
                     alg.setProperty("MomentumTransferStep", Qstep)
@@ -1091,9 +1103,9 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
                 if Qmax is not None:
                     alg.setProperty("MomentumTransferMax", Qmax)
                 alg.execute()
-                wqBinned = mtd[runno+'_IvsQ_binned']
-                wq = mtd[runno+'_IvsQ']
-                wlam = mtd[runno+'_IvsLam']
+                wqBinned = mtd[runno + '_IvsQ_binned']
+                wq = mtd[runno + '_IvsQ']
+                wlam = mtd[runno + '_IvsLam']
                 th = alg.getProperty("ThetaIn").value
 
             cleanup()
@@ -1150,11 +1162,13 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         """
         filename = ''
         if failsave:
-            #this is an emergency autosave as the program is failing
-            logger.error("The ISIS Reflectonomy GUI has encountered an error, it will now attempt to save a copy of your work.")
+            # this is an emergency autosave as the program is failing
+            logger.error(
+                "The ISIS Reflectonomy GUI has encountered an error, it will now attempt to save a copy of your work.")
             msgBox = QtGui.QMessageBox()
-            msgBox.setText("The ISIS Reflectonomy GUI has encountered an error, it will now attempt to save a copy of your work.\n"
-                           "Please check the log for details.")
+            msgBox.setText(
+                "The ISIS Reflectonomy GUI has encountered an error, it will now attempt to save a copy of your work.\n"
+                "Please check the log for details.")
             msgBox.setStandardButtons(QtGui.QMessageBox.Ok)
             msgBox.setIcon(QtGui.QMessageBox.Critical)
             msgBox.setDefaultButton(QtGui.QMessageBox.Ok)
@@ -1211,11 +1225,11 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         loadDialog.setNameFilter("Table Files (*.tbl);;All files (*)")
         if loadDialog.exec_():
             try:
-                #before loading make sure you give them a chance to save
+                # before loading make sure you give them a chance to save
                 if self.mod_flag:
                     ret, _saved = self._save_check()
                     if ret == QtGui.QMessageBox.RejectRole:
-                        #if they hit cancel abort the load
+                        # if they hit cancel abort the load
                         self.loading = False
                         return
                 self._reset_table()
@@ -1244,14 +1258,15 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         if filename:
             if self.mod_flag:
                 msgBox = QtGui.QMessageBox()
-                msgBox.setText("The table has been modified. Are you sure you want to reload the table and lose your changes?")
+                msgBox.setText(
+                    "The table has been modified. Are you sure you want to reload the table and lose your changes?")
                 msgBox.setStandardButtons(QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
                 msgBox.setIcon(QtGui.QMessageBox.Question)
                 msgBox.setDefaultButton(QtGui.QMessageBox.Yes)
                 msgBox.setEscapeButton(QtGui.QMessageBox.No)
                 ret = msgBox.exec_()
                 if ret == QtGui.QMessageBox.No:
-                    #if they hit No abort the reload
+                    # if they hit No abort the reload
                     self.loading = False
                     return
             try:
@@ -1291,12 +1306,12 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl):
         """
         try:
 
-            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,
+            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,
                                                          def_stitch_right=self.__scale_right)
             if dialog_controller.exec_():
-
                 # Fetch the settings back off the controller
                 self.live_freq = dialog_controller.frequency()
                 self.live_method = dialog_controller.method()
diff --git a/scripts/LargeScaleStructures/REF_L_geometry.py b/scripts/LargeScaleStructures/REF_L_geometry.py
index 8d180316e273c59f84844b8113cdb1cdace8ddfd..33e09c635349798f747f87c333e0c5bc7fd65c25 100644
--- a/scripts/LargeScaleStructures/REF_L_geometry.py
+++ b/scripts/LargeScaleStructures/REF_L_geometry.py
@@ -1,6 +1,7 @@
 #pylint: disable=invalid-name
 from __future__ import (absolute_import, division, print_function)
 from .geometry_writer import MantidGeom
+import mantid.simpleapi as mantid
 
 NUM_PIXELS_PER_TUBE = 304
 NUM_TUBES = 256
@@ -15,10 +16,10 @@ def create_grouping(workspace=None):
 
     ## Integrated over X
     if workspace is not None:
-        if mtd[workspace].getInstrument().hasParameter("number-of-x-pixels"):
-            npix_x = int(mtd[workspace].getInstrument().getNumberParameter("number-of-x-pixels")[0])
-        if mtd[workspace].getInstrument().hasParameter("number-of-y-pixels"):
-            npix_y = int(mtd[workspace].getInstrument().getNumberParameter("number-of-y-pixels")[0])
+        if mantid.mtd[workspace].getInstrument().hasParameter("number-of-x-pixels"):
+            npix_x = int(mantid.mtd[workspace].getInstrument().getNumberParameter("number-of-x-pixels")[0])
+        if mantid.mtd[workspace].getInstrument().hasParameter("number-of-y-pixels"):
+            npix_y = int(mantid.mtd[workspace].getInstrument().getNumberParameter("number-of-y-pixels")[0])
 
     f = open("REFL_Detector_Grouping_Sum_X_rot.xml",'w')
     f.write("<detector-grouping description=\"Integrated over X\">\n")
diff --git a/scripts/MantidIPython/__init__.py b/scripts/MantidIPython/__init__.py
index 4ede76d88d070c30442eb2eeda0ed3d9098acbde..831824e6114261387169bae1de844b987c996b0a 100644
--- a/scripts/MantidIPython/__init__.py
+++ b/scripts/MantidIPython/__init__.py
@@ -21,10 +21,8 @@
 Some tools for use in ipython notebooks generated by Mantid.
 """
 
-from MantidIPython.plot_functions import *
-import warnings
-import mantid.kernel
-
-# Check if the version of Mantid being used matches the version which created the notebook.
-if "3.5.20160108.1509" != mantid.kernel.version_str():
-    warnings.warn("Version of Mantid being used does not match version which created the notebook.")
+# Suppress warnings about unused import as these
+# imports are important for iPython
+from MantidIPython.plot_functions import *  # noqa: F401
+import warnings  # noqa: F401
+import mantid.kernel  # noqa: F401
diff --git a/scripts/SANS/ISISCommandInterface.py b/scripts/SANS/ISISCommandInterface.py
index de531bac0a104ea2445f42825e27e7920e9ef022..0a81425fa643b98485a6b37b13bf2b7d620f2b44 100644
--- a/scripts/SANS/ISISCommandInterface.py
+++ b/scripts/SANS/ISISCommandInterface.py
@@ -980,7 +980,6 @@ def DisplayMask(mask_worksp=None):
     """
     # this will be copied from a sample work space if one exists
     counts_data = None
-    _instrument = ReductionSingleton().instrument
 
     if not mask_worksp:
         mask_worksp = '__CurrentMask'
diff --git a/scripts/TemporaryREF_MScripts/testCenterREF_M.py b/scripts/TemporaryREF_MScripts/testCenterREF_M.py
index b29ff2c92b3cc3decc38fa289c298bf6a3d8e58b..65053f0c0e3f97849437c3c7d2625fb6a77ac2ce 100644
--- a/scripts/TemporaryREF_MScripts/testCenterREF_M.py
+++ b/scripts/TemporaryREF_MScripts/testCenterREF_M.py
@@ -30,12 +30,12 @@ atangle=mantid.simpleapi.LoadEventNexus('REF_M_22710',NXentryName='entry-Off_Off
 mantid.simpleapi.MoveInstrumentComponent(Workspace=atangle,ComponentName="DetectorArm",X=0,Y=translation,Z=1,RelativePosition=1)
 mantid.simpleapi.RotateInstrumentComponent(Workspace=atangle,ComponentName="DetectorArm",X=0,Y=1,Z=0,Angle=rotation,RelativeRotation=1)
 
-central=ConvertUnits(central,Target="Wavelength",EMode="Elastic")
-central=Rebin(central,"3.5,0.1,7")
+central=mantid.simpleapi.ConvertUnits(central,Target="Wavelength",EMode="Elastic")
+central=mantid.simpleapi.Rebin(central,"3.5,0.1,7")
 
-atangle=ConvertUnits(atangle,Target="Wavelength",EMode="Elastic")
-atangle=Rebin(atangle,"3.5,0.1,7")
+atangle=mantid.simpleapi.ConvertUnits(atangle,Target="Wavelength",EMode="Elastic")
+atangle=mantid.simpleapi.Rebin(atangle,"3.5,0.1,7")
 
-csum=SumSpectra(central)
-asum=SumSpectra(atangle)
+csum=mantid.simpleapi.SumSpectra(central)
+asum=mantid.simpleapi.SumSpectra(atangle)
 normalized=asum/csum
diff --git a/scripts/Vates/Diffraction_Workflow.py b/scripts/Vates/Diffraction_Workflow.py
index 4ce3ad2480457bffbd9d6c7a104e7890eeaabb54..e9114ebcd1d30c7338f87953b9f6ee4d44f125e4 100644
--- a/scripts/Vates/Diffraction_Workflow.py
+++ b/scripts/Vates/Diffraction_Workflow.py
@@ -1,84 +1,88 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 # Basic parameters  for  Triphylite Crystal
-#Name of the workspaces to create
+# Name of the workspaces to create
+import mantid.simpleapi as mantid
+
 ws_name = "TOPAZ_3132"
-filename = ws_name +"_event.nxs"
-ws = LoadEventNexus(Filename=filename,FilterByTofMin=3000, FilterByTofMax=16000)
+filename = ws_name + "_event.nxs"
+ws = mantid.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)
+ws = mantid.AnvredCorrection(InputWorkspace=ws, LinearScatteringCoef=0.451, LinearAbsorptionCoef=0.993, Radius=0.14)
 
 # Convert to Q space
-LabQ = ConvertToDiffractionMDWorkspace(InputWorkspace=ws, LorentzCorrection='0',
-                                       OutputDimensions='Q (lab frame)', SplitInto=2, SplitThreshold=150)
+LabQ = mantid.ConvertToDiffractionMDWorkspace(InputWorkspace=ws, LorentzCorrection='0',
+                                              OutputDimensions='Q (lab frame)', SplitInto=2, SplitThreshold=150)
 
 # Find peaks
-PeaksLattice = FindPeaksMD(InputWorkspace=LabQ,MaxPeaks=100)
+PeaksLattice = mantid.FindPeaksMD(InputWorkspace=LabQ, MaxPeaks=100)
 
 # 3d integration to centroid peaks
-PeaksLattice = CentroidPeaksMD(InputWorkspace=LabQ,
-                               PeakRadius=0.12, PeaksWorkspace=PeaksLattice)
+PeaksLattice = mantid.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,
-                             alpha=90, beta=90, gamma=90, NumInitial=20, Tolerance=0.12)
+mantid.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)
+mantid.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,
-                                           PeaksWorkspace=PeaksLattice)
+PeaksLattice_Integrated = mantid.IntegratePeaksMD(InputWorkspace=LabQ, PeakRadius=0.12,
+                                                  BackgroundOuterRadius=0.18, BackgroundInnerRadius=0.15,
+                                                  PeaksWorkspace=PeaksLattice)
 
 # Save for SHELX
-SaveHKL(InputWorkspace=PeaksLattice, Filename=ws_name + '.hkl')
+mantid.SaveHKL(InputWorkspace=PeaksLattice, Filename=ws_name + '.hkl')
 
 # ------------------------------------------------------------------------------------------------------------------------------------------
 # Part 2. Alternative/Advanced Processing Steps
 
 
 # Find peaks again for FFT
-PeaksLatticeFFT = FindPeaksMD(InputWorkspace=LabQ, MaxPeaks=100)
+PeaksLatticeFFT = mantid.FindPeaksMD(InputWorkspace=LabQ, MaxPeaks=100)
 
 # 3d integration to centroid peaks
-PeaksLatticeFFT = CentroidPeaksMD(InputWorkspace=LabQ,
-                                  PeakRadius=0.12, PeaksWorkspace=PeaksLatticeFFT)
+PeaksLatticeFFT = mantid.CentroidPeaksMD(InputWorkspace=LabQ,
+                                         PeakRadius=0.12, PeaksWorkspace=PeaksLatticeFFT)
 
 # Find the UB matrix using FFT
-FindUBUsingFFT(PeaksWorkspace=PeaksLatticeFFT, MinD=3.0, MaxD=14.0)
+mantid.FindUBUsingFFT(PeaksWorkspace=PeaksLatticeFFT, MinD=3.0, MaxD=14.0)
 
 # And index to HKL
-IndexPeaks(PeaksWorkspace=PeaksLatticeFFT, Tolerance=0.12)
+mantid.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,
-                                   PeaksWorkspace=PeaksLatticeFFT)
+PeaksLatticeFFT = mantid.IntegratePeaksMD(InputWorkspace=LabQ, PeakRadius=0.12,
+                                          BackgroundOuterRadius=0.18, BackgroundInnerRadius=0.15,
+                                          PeaksWorkspace=PeaksLatticeFFT)
 
 # Save for SHELX
-SaveHKL(InputWorkspace=PeaksLatticeFFT, Filename=ws_name + '.hkl')
+mantid.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,
-           CopyName='0',CopyMaterial='0',CopyEnvironment='0',CopyShape='0',  CopyLattice=1)
+mantid.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,
-                                      OutputDimensions='HKL',LorentzCorrection='0', SplitInto='2',SplitThreshold='150')
+HKL = mantid.ConvertToDiffractionMDWorkspace(InputWorkspace=ws,
+                                             OutputDimensions='HKL', LorentzCorrection='0', SplitInto='2',
+                                             SplitThreshold='150')
 
 # ------------------------------------------------------------------------------------------------------------------------------------------
 # Part 4. Displaying
 
 # Bin to a regular grid
-Binned = BinMD(InputWorkspace=HKL,AlignedDim0='[H,0,0], -15, 5, 150',AlignedDim1='[0,K,0], -0, 10, 50',AlignedDim2='[0,0,L], 0, 12,  150')
+Binned = mantid.BinMD(InputWorkspace=HKL, AlignedDim0='[H,0,0], -15, 5, 150', AlignedDim1='[0,K,0], -0, 10, 50',
+                      AlignedDim2='[0,0,L], 0, 12,  150')
 
 # Show in slice Viewer
-sv = plotSlice(Binned, xydim=('[H,0,0]','[0,0,L]'), slicepoint=[0, +9, 0], colorscalelog=True)
-sv.setColorMapBackground(0,0,0)
+sv = mantid.plotSlice(Binned, xydim=('[H,0,0]', '[0,0,L]'), slicepoint=[0, +9, 0], colorscalelog=True)
+sv.setColorMapBackground(0, 0, 0)
diff --git a/scripts/Vates/Inelastic_Workflow.py b/scripts/Vates/Inelastic_Workflow.py
index 4a3f6b9edff32c8e6a60ecce51625393d5e59491..3a501525d06274be34fae2b3467a010c975a4031 100644
--- a/scripts/Vates/Inelastic_Workflow.py
+++ b/scripts/Vates/Inelastic_Workflow.py
@@ -1,27 +1,29 @@
-#pylint: disable=invalid-name
-#Common names
+# pylint: disable=invalid-name
+# Common names
+import mantid.simpleapi as mantid
+
 filename = 'fe_demo_30.sqw'
-ws_in ='fe_demo_30'
+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)
+# Load an SQW file and internally convert to a Multidimensional event workspace (MDEW)
+if not mantid.mtd.doesExist(ws_in):
+    mantid.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',
-      AlignedDim3='E,0,150,30')
+# Bin the workspace in an axis aligned manner. Creates a Histogrammed MD workspace.
+mantid.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',
-      Origin='0,0,0,0')
+# Bin the workpace using a coordinate transformation to rotate the output.. Creates a Histogrammed MD workspace.
+mantid.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.
-SaveMD(ws_in, Filename='MDEW_fe_demo_30.nxs')
+# Save the MDEW workspace in the MDEW nexus format.
+mantid.SaveMD(ws_in, Filename='MDEW_fe_demo_30.nxs')
 
-#Could reload the MDEW at this point.
+# Could reload the MDEW at this point.
diff --git a/scripts/Vates/SXD_NaCl.py b/scripts/Vates/SXD_NaCl.py
index 9d418ba063867b2aa8fa6107b69467185bc684a0..3bfe353accddbca0769f58d17d01c383d836905f 100644
--- a/scripts/Vates/SXD_NaCl.py
+++ b/scripts/Vates/SXD_NaCl.py
@@ -1,4 +1,5 @@
 from __future__ import (absolute_import, division, print_function)
+import mantid.simpleapi as mantid
 
 
 def reportUnitCell(peaks_ws):
@@ -15,26 +16,27 @@ def reportUnitCell(peaks_ws):
 #
 # Exclude the monitors when loading the raw SXD file.  This avoids
 #
-Load(Filename='SXD23767.raw',OutputWorkspace='SXD23767',LoadMonitors='Exclude')
+mantid.Load(Filename='SXD23767.raw', OutputWorkspace='SXD23767', LoadMonitors='Exclude')
 
 #
 # A lower SplitThreshold, with a reasonable bound on the recursion depth, helps find weaker peaks at higher Q.
 #
-QLab = ConvertToDiffractionMDWorkspace(InputWorkspace='SXD23767', OutputDimensions='Q (lab frame)',
-                                       SplitThreshold=50, LorentzCorrection='1',
-                                       MaxRecursionDepth='13',Extents='-15,15,-15,15,-15,15')
+QLab = mantid.ConvertToDiffractionMDWorkspace(InputWorkspace='SXD23767', OutputDimensions='Q (lab frame)',
+                                              SplitThreshold=50, LorentzCorrection='1',
+                                              MaxRecursionDepth='13', Extents='-15,15,-15,15,-15,15')
 
 #
 #  NaCl has a relatively small unit cell, so the distance between peaks is relatively large.  Setting the PeakDistanceThreshold
 #  higher avoids finding high count regions on the sides of strong peaks as separate peaks.
 #
-peaks_qLab = FindPeaksMD(InputWorkspace='QLab', MaxPeaks=300, DensityThresholdFactor=10,PeakDistanceThreshold=1.0)
+peaks_qLab = mantid.FindPeaksMD(InputWorkspace='QLab', MaxPeaks=300, DensityThresholdFactor=10,
+                                PeakDistanceThreshold=1.0)
 
 #
 #  Fewer peaks index if Centroiding is used.  This indicates that there may be an error in the centroiding algorithm,
 #  since the peaks seem to be less accurate.
 #
-#peaks_qLab = CentroidPeaksMD(InputWorkspace='QLab',PeaksWorkspace=peaks_qLab)
+# peaks_qLab = CentroidPeaksMD(InputWorkspace='QLab',PeaksWorkspace=peaks_qLab)
 
 use_fft = True
 use_cubic_lat_par = False
@@ -44,32 +46,33 @@ use_Niggli_lat_par = False
 # Note: Reduced tolerance on  FindUBUsingFFT will omit peaks not near the lattice.  This seems to help
 # 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)
+if use_fft:
+    mantid.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)
+    mantid.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)
+    mantid.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)
+mantid.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)
+    mantid.ShowPossibleCells(PeaksWorkspace=peaks_qLab, MaxScalarError='0.5')
+    mantid.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)
+peaks_qLab_Integrated = mantid.IntegratePeaksMD(InputWorkspace=QLab, PeaksWorkspace=peaks_qLab, PeakRadius=0.2,
+                                                BackgroundInnerRadius=0.3, BackgroundOuterRadius=0.4)
 
-binned=BinMD(InputWorkspace=QLab,AlignedDim0='Q_lab_x,-15,15,200',AlignedDim1='Q_lab_y,-15,15,200',AlignedDim2='Q_lab_z,-15,15,200')
+binned = mantid.BinMD(InputWorkspace=QLab, AlignedDim0='Q_lab_x,-15,15,200', AlignedDim1='Q_lab_y,-15,15,200',
+                      AlignedDim2='Q_lab_z,-15,15,200')
 
 print('The final result is:')
 reportUnitCell(peaks_qLab)
diff --git a/scripts/reducer_singleton.py b/scripts/reducer_singleton.py
index c22114225429a55453059a77de500a956ae799e9..b0fdb5d7bc21e06a069041a3246466f3fe7cc738 100644
--- a/scripts/reducer_singleton.py
+++ b/scripts/reducer_singleton.py
@@ -1,8 +1,9 @@
-#pylint: disable=invalid-name
+# pylint: disable=invalid-name
 import random
 import string
 import os
 import mantid
+import time
 
 from isis_instrument import BaseInstrument
 
@@ -11,6 +12,7 @@ class ReductionStep(object):
     """
         Base class for reduction steps
     """
+
     @classmethod
     def delete_workspaces(cls, workspace):
         """
@@ -25,8 +27,9 @@ class ReductionStep(object):
         """
             Generate a unique name for an internal workspace
         """
-        random_str = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for x in range(5))
-        return "__"+descriptor+"_"+extract_workspace_name(filepath)+"_"+random_str
+        random_str = ''.join(
+            random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for x in range(5))
+        return "__" + descriptor + "_" + os.path.basename(filepath) + "_" + random_str
 
     def execute(self, reducer, inputworkspace=None, outputworkspace=None):
         """
@@ -64,14 +67,16 @@ class Reducer(object):
     output_workspaces = []
 
     def __init__(self):
-        self.UID = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for x in range(5))
+        self.UID = ''.join(
+            random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for x in range(5))
         self._reduction_steps = []
 
     def set_instrument(self, configuration):
         if issubclass(configuration.__class__, BaseInstrument):
             self.instrument = configuration
         else:
-            raise RuntimeError("Reducer.set_instrument expects an %s object, found %s" % (Instrument, configuration.__class__))
+            raise RuntimeError(
+                "Reducer.set_instrument expects an %s object, found %s" % (BaseInstrument, configuration.__class__))
 
     def set_data_path(self, path):
         """
@@ -131,7 +136,7 @@ class Reducer(object):
         self.pre_process()
 
         # Go through the list of files to be reduced
-        #for file_ws in self._data_files:
+        # for file_ws in self._data_files:
         #    for item in self._reduction_steps:
         #        try:
         #            result = item.execute(self, file_ws)
@@ -141,7 +146,7 @@ class Reducer(object):
         #            self.log_text += "\n%s\n" % sys.exc_value
         #            raise
 
-        #any clean up, possibly removing workspaces
+        # any clean up, possibly removing workspaces
         self.post_process()
 
         # Determine which directory to use
@@ -152,8 +157,8 @@ class Reducer(object):
             else:
                 output_dir = os.path.expanduser('~')
 
-        self.log_text += "Reduction completed in %g sec\n" % (time.time()-t_0)
-        log_path = os.path.join(output_dir,"%s_reduction.log" % instrument_name)
+        self.log_text += "Reduction completed in %g sec\n" % (time.time() - t_0)
+        log_path = os.path.join(output_dir, "%s_reduction.log" % instrument_name)
         self.log_text += "Log saved to %s" % log_path
 
         # Write the log to file
diff --git a/scripts/reduction/reducer.py b/scripts/reduction/reducer.py
index 383d3763fb79450591d1f73830240f50479aa017..0854667337f60305e66c3d5a3275ab5abea4e606 100644
--- a/scripts/reduction/reducer.py
+++ b/scripts/reduction/reducer.py
@@ -24,12 +24,11 @@ import os
 import sys
 import time
 import types
+import uuid
 from reduction.instrument import Instrument
-import mantid
-from mantid import simpleapi
+import mantid.simpleapi as mantid
 import warnings
 import inspect
-import random
 from reduction.find_data import find_data
 
 
@@ -79,7 +78,7 @@ def validate_loader(func):
                             if data_file is None:
                                 return
                         else:
-                            raise RuntimeError("SANSReductionSteps.LoadRun doesn't recognize workspace handle %s" % workspace)
+                            raise RuntimeError("SANSReductionSteps.LoadRun doesn't recognize workspace handle %s" % inputworkspace)
                     else:
                         data_file = self._data_file
 
@@ -107,7 +106,7 @@ def validate_loader(func):
                         kwargs[kwargs["AlternateName"]] = data_file
 
                     self.algorithm = alg
-                    simpleapi.set_properties(alg, *(), **kwargs)
+                    mantid.set_properties(alg, *(), **kwargs)
                     alg.execute()
                     if "OutputMessage" in propertyOrder:
                         return alg.getPropertyValue("OutputMessage")
@@ -146,7 +145,7 @@ def validate_loader(func):
                             if data_file is None:
                                 return
                         else:
-                            raise RuntimeError("SANSReductionSteps.LoadRun doesn't recognize workspace handle %s" % workspace)
+                            raise RuntimeError("SANSReductionSteps.LoadRun doesn't recognize workspace handle %s" % inputworkspace)
                     else:
                         data_file = self._data_file
 
@@ -255,7 +254,7 @@ def validate_step(func):
                         kwargs["OutputWorkspace"] = outputworkspace
 
                     self.algorithm = alg
-                    simpleapi.set_properties(alg, *(), **kwargs)
+                    mantid.set_properties(alg, *(), **kwargs)
                     alg.execute()
                     if "OutputMessage" in propertyOrder:
                         return alg.getPropertyValue("OutputMessage")
@@ -335,8 +334,8 @@ class Reducer(object):
     output_workspaces = []
 
     def __init__(self):
-        self.UID = ''.join(
-            random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for x in range(5))
+        # Generate UUID and trim to 5 chars
+        self.UID = str(uuid.uuid1())[:5]
         self.property_manager = "__reduction_parameters_" + self.UID
         self._data_files = {}
         self._reduction_steps = []
@@ -366,8 +365,8 @@ class Reducer(object):
             Removes all workspace flagged as dirty, use when a reduction aborts with errors
         """
         for bad_data in self._dirty:
-            if bad_data in mtd:
-                simpleapi.DeleteWorkspace(Workspace=bad_data)
+            if bad_data in mantid.mtd:
+                mantid.DeleteWorkspace(Workspace=bad_data)
             else:
                 mantid.logger.notice('reducer: Could not access tainted workspace ' + bad_data)
 
@@ -454,7 +453,7 @@ class Reducer(object):
             TODO: this needs to be an ordered list
         """
         if data_file is None:
-            if workspace in mtd:
+            if workspace in mantid.mtd:
                 self._data_files[workspace] = None
                 return
             else:
@@ -555,8 +554,7 @@ class ReductionStep(object):
         """
             Generate a unique name for an internal workspace
         """
-        random_str = ''.join(
-            random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for x in range(5))
+        random_str = str(uuid.uuid1())[:5]
         return "__" + descriptor + "_" + extract_workspace_name(filepath) + "_" + random_str
 
     def execute(self, reducer, inputworkspace=None, outputworkspace=None):
diff --git a/scripts/reduction_workflow/command_interface.py b/scripts/reduction_workflow/command_interface.py
index c75684cba6d4036d55f89bcff1ddd3bcd5471621..490fe35491c5f6fc1e1abeb0d30b4e3f78540c40 100644
--- a/scripts/reduction_workflow/command_interface.py
+++ b/scripts/reduction_workflow/command_interface.py
@@ -8,8 +8,7 @@ from reduction_workflow.reducer import Reducer
 
 class ReductionSingleton(object):
     """ Singleton reduction class """
-
-    ## storage for the instance reference
+    # storage for the instance reference
     __instance = None
 
     def __init__(self):
@@ -66,7 +65,8 @@ class ReductionSingleton(object):
 
 
 def get_property_manager(name):
-    prop_mng = PropertyManagerDataService.retrieve(name)
+    # prop_mng = mantid.PropertyManagerDataService.retrieve(name)
+    pass
 
 ## List of user commands ######################################################
 
diff --git a/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py b/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py
index a00031304af16f927baa590a57cff84c0e74fc85..8a5a5326a2acded2a3014fd45971abae9853c9cd 100644
--- a/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py
+++ b/scripts/reduction_workflow/instruments/sans/hfir_command_interface.py
@@ -8,13 +8,17 @@ List of common user commands for HFIR SANS
 import os.path
 import mantid
 
-from reduction_workflow.command_interface import ReductionSingleton, Clear, OutputPath, Reduce1D, Reduce, AppendDataFile, ClearDataFiles
+from reduction_workflow.command_interface import ReductionSingleton, Clear
 from reduction_workflow.find_data import find_data
 from reduction_workflow.instruments.sans import hfir_instrument
 
 from mantid.kernel import Logger
 from mantid.simpleapi import Load
 
+# The following imports allow users to import this file and have all functionality automatically imported
+# Do not remove these imports as it will break user scripts which rely on them
+from reduction_workflow.command_interface import OutputPath, Reduce1D, Reduce, \
+                                                 AppendDataFile, ClearDataFiles  # noqa: F401
 
 def BIOSANS():
     Clear()
diff --git a/scripts/reduction_workflow/instruments/sans/sns_command_interface.py b/scripts/reduction_workflow/instruments/sans/sns_command_interface.py
index 5adfdacd89f0fe096406df999f7433f1ec0c2a1b..ae30908e0f8ab998ef21285833a77f75bd2210c3 100644
--- a/scripts/reduction_workflow/instruments/sans/sns_command_interface.py
+++ b/scripts/reduction_workflow/instruments/sans/sns_command_interface.py
@@ -5,38 +5,37 @@
 # Import the specific commands that we need - some of these are used in systemtests
 from reduction_workflow.command_interface import *
 
-from hfir_command_interface import DarkCurrent, NoDarkCurrent, NoNormalization
-from hfir_command_interface import SolidAngle, NoSolidAngle
-from hfir_command_interface import DirectBeamCenter, ScatteringBeamCenter
+from hfir_command_interface import SolidAngle
 from hfir_command_interface import SetBeamCenter as BaseSetBeamCenter
 
-from hfir_command_interface import SensitivityCorrection, SetSensitivityBeamCenter
-from hfir_command_interface import SensitivityDirectBeamCenter, SensitivityScatteringBeamCenter
-from hfir_command_interface import NoSensitivityCorrection, DivideByThickness
+# The following imports allow users to import this file and have all functionality automatically imported
+# Do not remove these imports as it will break user scripts which rely on them
 
-from hfir_command_interface import IQxQy, NoIQxQy, SaveIq, NoSaveIq, SaveIqAscii
+from hfir_command_interface import DarkCurrent, NoDarkCurrent, NoNormalization, NoSolidAngle  # noqa: F401
+from hfir_command_interface import DirectBeamCenter, ScatteringBeamCenter  # noqa: F401
+from hfir_command_interface import SensitivityCorrection, SetSensitivityBeamCenter  # noqa: F401
+from hfir_command_interface import SensitivityDirectBeamCenter, SensitivityScatteringBeamCenter  # noqa: F401
+from hfir_command_interface import NoSensitivityCorrection, DivideByThickness  # noqa: F401
 
-from hfir_command_interface import DirectBeamTransmission, TransmissionDarkCurrent
-from hfir_command_interface import ThetaDependentTransmission
-from hfir_command_interface import SetTransmissionBeamCenter, TransmissionDirectBeamCenter
-from hfir_command_interface import SetTransmission, NoTransmission
+from hfir_command_interface import IQxQy, NoIQxQy, SaveIq, NoSaveIq, SaveIqAscii  # noqa: F401
 
-from hfir_command_interface import Background, NoBackground, NoBckTransmission
-from hfir_command_interface import SetBckTransmission, BckDirectBeamTransmission
-from hfir_command_interface import SetBckTransmissionBeamCenter, BckThetaDependentTransmission
-from hfir_command_interface import BckTransmissionDirectBeamCenter, BckTransmissionDarkCurrent
+from hfir_command_interface import DirectBeamTransmission, TransmissionDarkCurrent  # noqa: F401
+from hfir_command_interface import ThetaDependentTransmission  # noqa: F401
+from hfir_command_interface import SetTransmissionBeamCenter, TransmissionDirectBeamCenter  # noqa: F401
+from hfir_command_interface import SetTransmission, NoTransmission  # noqa: F401
 
-from hfir_command_interface import SetSampleDetectorOffset, SetSampleDetectorDistance
-from hfir_command_interface import Mask, MaskRectangle, MaskDetectors, MaskDetectorSide
-from hfir_command_interface import SetAbsoluteScale, SetDirectBeamAbsoluteScale
+from hfir_command_interface import Background, NoBackground, NoBckTransmission  # noqa: F401
+from hfir_command_interface import SetBckTransmission, BckDirectBeamTransmission  # noqa: F401
+from hfir_command_interface import SetBckTransmissionBeamCenter, BckThetaDependentTransmission  # noqa: F401
+from hfir_command_interface import BckTransmissionDirectBeamCenter, BckTransmissionDarkCurrent  # noqa: F401
+
+from hfir_command_interface import SetSampleDetectorOffset, SetSampleDetectorDistance  # noqa: F401
+from hfir_command_interface import Mask, MaskRectangle, MaskDetectors, MaskDetectorSide  # noqa: F401
+from hfir_command_interface import SetAbsoluteScale, SetDirectBeamAbsoluteScale  # noqa: F401
 from hfir_command_interface import Stitch
 
-#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):
     Clear()
     ReductionSingleton().set_instrument("EQSANS",