From 16b61e4925f27a4daed93123c3ec64cf5b484691 Mon Sep 17 00:00:00 2001 From: Pete Peterson Date: Wed, 20 Aug 2014 15:47:26 -0400 Subject: [PATCH] Re #10137. Fixing python whitespace in Code/Mantid/Framework tree --- .../Algorithms/test/NormaliseToUnityTest.py | 8 +- .../Framework/MDEvents/scripts/analysis.py | 42 +- .../src/generate_mdevent_declarations.py | 34 +- .../Framework/MPIAlgorithms/scripts/NOM1.py | 2 +- .../scripts/NOMAD_mpi_example.py | 2 +- .../PythonInterface/mantid/__init__.py | 22 +- .../PythonInterface/mantid/api/__init__.py | 6 +- .../PythonInterface/mantid/api/_adsimports.py | 18 +- .../PythonInterface/mantid/api/_aliases.py | 4 +- .../mantid/api/_workspaceops.py | 16 +- .../PythonInterface/mantid/kernel/__init__.py | 2 +- .../PythonInterface/mantid/kernel/dlopen.py | 22 +- .../mantid/kernel/environment.py | 12 +- .../mantid/kernel/funcreturns.py | 90 +- .../PythonInterface/mantid/kernel/plugins.py | 34 +- .../PythonInterface/mantid/simpleapi.py | 152 +-- .../plugins/algorithms/BASISReduction.py | 176 +-- .../CalibrateRectangularDetectors.py | 112 +- .../plugins/algorithms/CheckForSampleLogs.py | 46 +- .../plugins/algorithms/ConjoinFiles.py | 4 +- .../plugins/algorithms/ConjoinSpectra.py | 20 +- .../algorithms/ConvertSnsRoiFileToMask.py | 34 +- .../plugins/algorithms/CorrectLogTimes.py | 26 +- .../algorithms/CreateEmptyTableWorkspace.py | 4 +- .../algorithms/CreateLeBailFitInput.py | 42 +- .../plugins/algorithms/DSFinterp.py | 2 +- .../plugins/algorithms/DakotaChiSquared.py | 106 +- .../plugins/algorithms/EnginXCalibrate.py | 108 +- .../plugins/algorithms/EnginXCalibrateFull.py | 252 ++-- .../plugins/algorithms/EnginXFitPeaks.py | 354 +++--- .../plugins/algorithms/EnginXFocus.py | 240 ++-- .../algorithms/ExaminePowderDiffProfile.py | 124 +- .../plugins/algorithms/Examples/Squares.py | 8 +- .../plugins/algorithms/ExportExperimentLog.py | 134 +- .../algorithms/ExportSampleLogsToCSVFile.py | 576 ++++----- .../plugins/algorithms/FilterLogByTime.py | 14 +- .../algorithms/FindReflectometryLines.py | 186 +-- .../GenerateGroupingSNSInelastic.py | 18 +- .../plugins/algorithms/GetEiMonDet.py | 62 +- .../plugins/algorithms/GetEiT0atSNS.py | 22 +- .../plugins/algorithms/LoadFullprofFile.py | 250 ++-- .../algorithms/LoadLogPropertyTable.py | 22 +- .../plugins/algorithms/LoadMultipleGSS.py | 4 +- .../plugins/algorithms/LoadSINQFile.py | 4 +- .../plugins/algorithms/LoadVesuvio.py | 118 +- .../plugins/algorithms/MaskAngle.py | 4 +- .../plugins/algorithms/MaskBTP.py | 46 +- .../algorithms/MaskWorkspaceToCalFile.py | 134 +- .../plugins/algorithms/Mean.py | 10 +- .../plugins/algorithms/MergeCalFiles.py | 40 +- .../PDDetermineCharacterizations.py | 16 +- .../plugins/algorithms/PearlMCAbsorption.py | 12 +- .../plugins/algorithms/PoldiMerge.py | 4 +- .../plugins/algorithms/PoldiProjectAddDir.py | 82 +- .../plugins/algorithms/PoldiProjectAddFile.py | 44 +- .../plugins/algorithms/PoldiProjectRun.py | 142 +-- .../plugins/algorithms/RefLReduction.py | 152 +-- .../algorithms/RefinePowderDiffProfileSeq.py | 328 ++--- .../plugins/algorithms/RetrieveRunInfo.py | 54 +- .../plugins/algorithms/SANSSubtract.py | 74 +- .../algorithms/SANSWideAngleCorrection.py | 20 +- .../plugins/algorithms/SNSPowderReduction.py | 140 +-- .../algorithms/SelectPowderDiffPeaks.py | 100 +- .../plugins/algorithms/SortByQVectors.py | 18 +- .../plugins/algorithms/SortDetectors.py | 18 +- .../plugins/algorithms/SortXAxis.py | 6 +- .../plugins/algorithms/Stitch1DMany.py | 90 +- .../plugins/algorithms/SuggestTibCNCS.py | 46 +- .../plugins/algorithms/SuggestTibHYSPEC.py | 20 +- .../algorithms/TestWorkspaceGroupProperty.py | 8 +- .../plugins/algorithms/USANSSimulation.py | 44 +- .../UpdatePeakParameterTableValue.py | 32 +- .../WorkflowAlgorithms/DensityOfStates.py | 1092 ++++++++--------- .../EQSANSAzimuthalAverage1D.py | 126 +- .../EQSANSDirectBeamTransmission.py | 66 +- .../WorkflowAlgorithms/EQSANSNormalise.py | 42 +- .../WorkflowAlgorithms/FuryFitMultiple.py | 6 +- .../WorkflowAlgorithms/HFIRSANSReduction.py | 124 +- .../IndirectILLReduction.py | 2 +- .../IndirectTransmission.py | 172 +-- .../WorkflowAlgorithms/MuscatData.py | 128 +- .../WorkflowAlgorithms/MuscatFunc.py | 168 +-- .../NormaliseByThickness.py | 14 +- .../OSIRISDiffractionReduction.py | 82 +- .../algorithms/WorkflowAlgorithms/QLines.py | 202 +-- .../algorithms/WorkflowAlgorithms/Quest.py | 184 +-- .../WorkflowAlgorithms/REFLReprocess.py | 42 +- .../ReactorSANSResolution.py | 30 +- .../algorithms/WorkflowAlgorithms/ResNorm.py | 6 +- .../WorkflowAlgorithms/SANSAbsoluteScale.py | 58 +- .../SANSAzimuthalAverage1D.py | 56 +- .../SANSBeamSpreaderTransmission.py | 90 +- .../SANSDirectBeamTransmission.py | 50 +- .../algorithms/WorkflowAlgorithms/SANSMask.py | 28 +- .../WorkflowAlgorithms/SANSReduction.py | 108 +- .../WorkflowAlgorithms/SavePlot1D.py | 46 +- .../WorkflowAlgorithms/SofQWMoments.py | 238 ++-- .../WorkflowAlgorithms/Symmetrise.py | 64 +- .../WorkflowAlgorithms/TransmissionUtils.py | 66 +- .../WorkflowAlgorithms/USANSReduction.py | 64 +- .../plugins/algorithms/sfCalculator.py | 534 ++++---- .../plugins/functions/ChudleyElliot.py | 6 +- .../plugins/functions/DSFinterp1DFit.py | 2 +- .../functions/Examples/Example1DFunction.py | 8 +- .../functions/Examples/ExamplePeakFunction.py | 12 +- .../plugins/functions/FickDiffusion.py | 6 +- .../plugins/functions/HallRoss.py | 6 +- .../plugins/functions/StretchedExpFT.py | 18 +- .../plugins/functions/TeixeiraWater.py | 6 +- .../test/python/mantid/ImportModuleTest.py | 8 +- .../test/python/mantid/SimpleAPIFitTest.py | 24 +- .../test/python/mantid/SimpleAPILoadTest.py | 22 +- .../test/python/mantid/SimpleAPITest.py | 62 +- .../python/mantid/api/AlgorithmFactoryTest.py | 4 +- .../python/mantid/api/AlgorithmHistoryTest.py | 12 +- .../python/mantid/api/AlgorithmManagerTest.py | 18 +- .../mantid/api/AlgorithmPropertyTest.py | 4 +- .../test/python/mantid/api/AlgorithmTest.py | 26 +- .../mantid/api/AnalysisDataServiceTest.py | 26 +- .../test/python/mantid/api/AxisTest.py | 14 +- .../python/mantid/api/CatalogManagerTest.py | 6 +- .../api/DeprecatedAlgorithmCheckerTest.py | 2 +- .../python/mantid/api/ExperimentInfoTest.py | 24 +- .../test/python/mantid/api/FileFinderTest.py | 4 +- .../python/mantid/api/FilePropertyTest.py | 6 +- .../python/mantid/api/FrameworkManagerTest.py | 2 +- .../python/mantid/api/FunctionFactoryTest.py | 10 +- .../python/mantid/api/FunctionPropertyTest.py | 4 +- .../python/mantid/api/IEventWorkspaceTest.py | 12 +- .../test/python/mantid/api/IFunction1DTest.py | 14 +- .../python/mantid/api/IPeakFunctionTest.py | 4 +- .../python/mantid/api/IPeaksWorkspaceTest.py | 22 +- .../python/mantid/api/ITableWorkspaceTest.py | 30 +- .../python/mantid/api/MDHistoWorkspaceTest.py | 92 +- .../python/mantid/api/MatrixWorkspaceTest.py | 70 +- .../mantid/api/MultipleFilePropertyTest.py | 2 +- .../test/python/mantid/api/ProgressTest.py | 6 +- .../api/PythonAlgorithmChildAlgCallTest.py | 12 +- .../api/PythonAlgorithmPropertiesTest.py | 36 +- .../mantid/api/PythonAlgorithmTraitsTest.py | 42 +- .../PythonAlgorithmWorkspacePropertyTest.py | 15 +- .../python/mantid/api/RunPythonScriptTest.py | 14 +- .../test/python/mantid/api/RunTest.py | 12 +- .../python/mantid/api/WorkspaceFactoryTest.py | 12 +- .../python/mantid/api/WorkspaceGroupTest.py | 14 +- .../mantid/api/WorkspacePropertiesTest.py | 18 +- .../test/python/mantid/api/WorkspaceTest.py | 2 +- .../mantid/api/WorkspaceValidatorsTest.py | 26 +- .../python/mantid/geometry/IComponentTest.py | 4 +- .../python/mantid/geometry/InstrumentTest.py | 12 +- .../test/python/mantid/geometry/ObjectTest.py | 4 +- .../mantid/geometry/OrientedLatticeTest.py | 28 +- .../geometry/RectangularDetectorTest.py | 8 +- .../mantid/geometry/ReferenceFrameTest.py | 2 +- .../python/mantid/geometry/UnitCellTest.py | 18 +- .../kernel/ArrayBoundedValidatorTest.py | 12 +- .../mantid/kernel/ArrayLengthValidatorTest.py | 20 +- .../python/mantid/kernel/ArrayPropertyTest.py | 38 +- .../mantid/kernel/BoundedValidatorTest.py | 8 +- .../mantid/kernel/CompositeValidatorTest.py | 8 +- .../python/mantid/kernel/ConfigServiceTest.py | 22 +- .../python/mantid/kernel/DateAndTimeTest.py | 4 +- .../python/mantid/kernel/DeltaEModeTest.py | 6 +- .../mantid/kernel/EnabledWhenPropertyTest.py | 2 +- .../python/mantid/kernel/FacilityInfoTest.py | 4 +- .../kernel/FilteredTimeSeriesPropertyTest.py | 8 +- .../mantid/kernel/InstrumentInfoTest.py | 2 +- .../python/mantid/kernel/ListValidatorTest.py | 12 +- .../test/python/mantid/kernel/LoggerTest.py | 4 +- .../mantid/kernel/MandatoryValidatorTest.py | 10 +- .../mantid/kernel/PropertyWithValueTest.py | 38 +- .../python/mantid/kernel/PythonPluginsTest.py | 10 +- .../test/python/mantid/kernel/QuatTest.py | 8 +- .../python/mantid/kernel/StatisticsTest.py | 8 +- .../mantid/kernel/TimeSeriesPropertyTest.py | 10 +- .../mantid/kernel/UnitConversionTest.py | 4 +- .../python/mantid/kernel/UnitFactoryTest.py | 6 +- .../test/python/mantid/kernel/V3DTest.py | 22 +- .../test/python/mantid/kernel/VMDTest.py | 12 +- .../mantid/kernel/VisibleWhenPropertyTest.py | 2 +- .../algorithms/CheckForSampleLogsTest.py | 18 +- .../plugins/algorithms/ConjoinSpectraTest.py | 18 +- .../plugins/algorithms/CorrectLogTimesTest.py | 10 +- .../algorithms/CreateLeBailFitInputTest.py | 8 +- .../plugins/algorithms/CreateWorkspaceTest.py | 18 +- .../plugins/algorithms/DSFinterpTest.py | 2 +- .../algorithms/DakotaChiSquaredTest.py | 166 +-- .../algorithms/ExportExperimentLogTest.py | 118 +- .../ExportSampleLogsToCSVFileTest.py | 96 +- .../plugins/algorithms/FilterLogByTimeTest.py | 42 +- .../algorithms/FindReflectometryLinesTest.py | 46 +- .../plugins/algorithms/GetEiT0atSNSTest.py | 6 +- .../algorithms/LoadFullprofFileTest.py | 130 +- .../plugins/algorithms/LoadLiveDataTest.py | 40 +- .../algorithms/LoadLogPropertyTableTest.py | 44 +- .../plugins/algorithms/LoadMultipleGSSTest.py | 2 +- .../plugins/algorithms/MaskAngleTest.py | 12 +- .../python/plugins/algorithms/MaskBTPTest.py | 18 +- .../algorithms/MaskWorkspaceToCalFileTest.py | 18 +- .../python/plugins/algorithms/MeanTest.py | 12 +- .../plugins/algorithms/MergeCalFilesTest.py | 112 +- .../PDDetermineCharacterizationsTest.py | 4 +- .../plugins/algorithms/RetrieveRunInfoTest.py | 38 +- .../plugins/algorithms/SANSSubtractTest.py | 12 +- .../algorithms/SANSWideAngleCorrectionTest.py | 16 +- .../plugins/algorithms/SavePlot1DTest.py | 10 +- .../plugins/algorithms/SortByQVectorsTest.py | 20 +- .../plugins/algorithms/SortDetectorsTest.py | 4 +- .../plugins/algorithms/SortXAxisTest.py | 26 +- .../plugins/algorithms/Stitch1DManyTest.py | 64 +- .../plugins/algorithms/SuggestTibCNCSTest.py | 16 +- .../algorithms/SuggestTibHYSPECTest.py | 16 +- .../UpdatePeakParameterTableValueTest.py | 2 +- .../plugins/functions/DSFinterp1DFitTest.py | 6 +- .../functions/Example1DFunctionTest.py | 14 +- .../functions/ExamplePeakFunctionTest.py | 12 +- .../plugins/functions/StretchedExpFTTest.py | 6 +- .../test/testhelpers/__init__.py | 8 +- .../test/testhelpers/algorithm_decorator.py | 28 +- .../Framework/UserAlgorithms/createAlg.py | 2 +- .../WorkflowAlgorithms/test/EQSANSQ2DTest.py | 8 +- .../test/SANSBeamFluxCorrectionTest.py | 12 +- 222 files changed, 5759 insertions(+), 5760 deletions(-) diff --git a/Code/Mantid/Framework/Algorithms/test/NormaliseToUnityTest.py b/Code/Mantid/Framework/Algorithms/test/NormaliseToUnityTest.py index a116014e3272..c4f34c3c574b 100644 --- a/Code/Mantid/Framework/Algorithms/test/NormaliseToUnityTest.py +++ b/Code/Mantid/Framework/Algorithms/test/NormaliseToUnityTest.py @@ -5,14 +5,14 @@ class NormaliseToUnityTest(unittest.TestCase): """ Simple test to check the numpy integration """ - + def setUp(self): CreateWorkspace([1,2,3,4,5,6,1,2,3,4,5,6], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], 2, OutputWorkspace="normalise_to_unity_test") def tearDown(self): if mtd.doesExist("normalise_to_unity_test"): DeleteWorkspace("normalise_to_unity_test") - + def test_whole_ws(self): """ Check that we can normalize to the sum of all bins @@ -25,7 +25,7 @@ def test_whole_ws(self): def test_x_range(self): """ Check that we can specify a range in X and normalize to the sum in that range only - """ + """ output_ws = NormaliseToUnity("normalise_to_unity_test", RangeLower=2, RangeUpper=4) self.assertEqual(output_ws.readY(0)[0],0.25) if output_ws: @@ -40,6 +40,6 @@ def test_x_range_and_spectra(self): self.assertEqual(output_ws.readY(0)[0],0.5) if output_ws: DeleteWorkspace(output_ws) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/MDEvents/scripts/analysis.py b/Code/Mantid/Framework/MDEvents/scripts/analysis.py index 1b7fc900ede4..e8cd56a3e454 100644 --- a/Code/Mantid/Framework/MDEvents/scripts/analysis.py +++ b/Code/Mantid/Framework/MDEvents/scripts/analysis.py @@ -37,22 +37,22 @@ def plot_results_vs_other(results, x_field, y_field, other_field, extra_title="" others.add( eval('par.%s' % other_field) ) others = list(others) others.sort() - + figure() - + for other in others: data = [] - for par in results: + for par in results: this_other = eval('par.%s' % other_field) - if this_other == other: - x = eval('par.%s' % x_field) + if this_other == other: + x = eval('par.%s' % x_field) y = eval('par.%s' % y_field) - data.append( (x,y) ) + data.append( (x,y) ) data.sort() xs = [x for (x,y) in data] ys = [y for (x,y) in data] p = plot(xs,ys, marker='.', label="%s = %f" % (other_field, other)) - + if extra_title != "": extra_title = "\n" + extra_title title("%s vs %s%s" % (y_field, x_field, extra_title) ); xlabel(x_field) @@ -67,25 +67,25 @@ def plot_results_vs_other(results, x_field, y_field, other_field, extra_title="" def plot_results_with_slope(results, x_field, y_field, x_scale=1): """ Function to plot Y vs X of anything. It accesses the members of "results" to plot them. other_field is used to separate by another field, and make separate line plots for each - + @param x_scale :: multiply x by this amount """ figure() - + data = [] - for par in results: - x = eval('par.%s' % x_field) + for par in results: + x = eval('par.%s' % x_field) y = eval('par.%s' % y_field) - data.append( (x,y) ) + data.append( (x,y) ) data.sort() xs = [x*x_scale for (x,y) in data] ys = [y for (x,y) in data] - - # Now get the slope + + # Now get the slope gradient, intercept, r_value, p_value, std_err = stats.linregress(xs,ys) - + p = plot(xs,ys, marker='.', label="y = %.3gx + %.3g" % (gradient, intercept)) - + title("%s vs %s" % (y_field, x_field)); xlabel("%s x %s" % (x_field, x_scale) ) ylabel(y_field) @@ -98,21 +98,21 @@ def plot_results_with_slope(results, x_field, y_field, x_scale=1): #======================================================================================================== def do_analysis(file_list, type): # Load back the results - + results = [] for filename in file_list: f = open(filename, 'r') these_results = pickle.load(f) results += these_results f.close() - + if type == 1: plot_results_vs_other(results, "SplitInto", "MakeTime", "SplitThresholdBase") plot_results_vs_other(results, "SplitInto", "MemoryUsed", "SplitThresholdBase") plot_results_vs_other(results, "SplitInto", "CoarseBinTime", "SplitThresholdBase") plot_results_vs_other(results, "SplitInto", "MediumBinTime", "SplitThresholdBase") plot_results_vs_other(results, "SplitInto", "FineBinTime", "SplitThresholdBase") - + elif type == 2: plot_results_with_slope(results, "NumberEvents", "MakeTime", x_scale=1e-9) plot_results_with_slope(results, "NumberEvents", "MemoryUsed", x_scale=1e-9) @@ -128,7 +128,7 @@ def do_analysis(file_list, type): plot_results_vs_other(results, "SplitThreshold", "MediumBinTime", "SplitInto", extra_title) plot_results_vs_other(results, "SplitThreshold", "FineBinTime", "SplitInto", extra_title) show() - + #======================================================================================================== @@ -143,5 +143,5 @@ def do_analysis(file_list, type): file_list = ["optimize_results1.dat"] do_analysis(file_list, 1) - + diff --git a/Code/Mantid/Framework/MDEvents/src/generate_mdevent_declarations.py b/Code/Mantid/Framework/MDEvents/src/generate_mdevent_declarations.py index 636de1ed9a1c..cd091712a875 100644 --- a/Code/Mantid/Framework/MDEvents/src/generate_mdevent_declarations.py +++ b/Code/Mantid/Framework/MDEvents/src/generate_mdevent_declarations.py @@ -9,21 +9,21 @@ # List of every possible MDEvent or MDLeanEvent types. mdevent_types = ["MDEvent", "MDLeanEvent"] -header = """/* Code below Auto-generated by '%s' +header = """/* Code below Auto-generated by '%s' * on %s * * DO NOT EDIT! - */ + */ """ % (os.path.basename(__file__), datetime.datetime.now()) - + footer = """ -/* CODE ABOWE WAS AUTO-GENERATED BY %s - DO NOT EDIT! */ +/* CODE ABOWE WAS AUTO-GENERATED BY %s - DO NOT EDIT! */ """ % (os.path.basename(__file__)) - + #============================================================================================================ #============================================================================================================ #============================================================================================================ @@ -45,7 +45,7 @@ def build_macro(padding,min_dimension=1, max_dimensions=4,const=""): * @param funcname :: name of the function that will be called. * @param workspace :: IMDEventWorkspace_sptr input workspace. */ - + #define %sCALL_MDEVENT_FUNCTION%s(funcname, workspace) \\ { \\ """ @@ -61,7 +61,7 @@ def build_macro(padding,min_dimension=1, max_dimensions=4,const=""): if (min_dimension > 1): suffix = "%d" % min_dimension if const != "": prefix = "CONST_" s = macro_top % (prefix, suffix); - + for mdevent_type in mdevent_types: for nd in xrange(1,max_dimensions+1): if (nd >= min_dimension): @@ -69,7 +69,7 @@ def build_macro(padding,min_dimension=1, max_dimensions=4,const=""): varname = "MDEW_%s_%d" % (mdevent_type.upper(),nd) if const != "": varname = "CONST_" + varname - s += macro % (padding,const, eventType,nd, varname, const, eventType,nd, varname, eventType,nd, varname) + s += macro % (padding,const, eventType,nd, varname, const, eventType,nd, varname, eventType,nd, varname) s += "} \n \n \n" return s.split("\n") @@ -110,16 +110,16 @@ def find_num_dim(lines): for i in xrange(len(lines)) : found = searcher.search(lines[i]); if found : - rez = found.group() + rez = found.group() return re.search('\d',rez).group() - + raise IOError," can not find the string which defines the number of dimensions to process " def parse_file(file_name,start_marker,end_marker) : - """Read the file and separate it into three parts with the part between input markers to be generated and two others left unchanged. + """Read the file and separate it into three parts with the part between input markers to be generated and two others left unchanged. @param -- file_name -- full file name to open @param -- start_marker -- the marker which indicate first line of autogenerated file @@ -174,7 +174,7 @@ def generate(): lines +=header_lines; - + # ========== Start the header file ============= # Make the macro then pad it into the list of lines @@ -197,12 +197,12 @@ def generate(): for nd in dimensions: lines.append("%s/// Typedef for a %s with %d dimension%s " % (padding,c, nd, ['','s'][nd>1]) ) lines.append("%s typedef %s<%s<%d>, %d> %s%dLean;" % (padding,c, mdevent_type, nd, nd, c, nd) ) - + lines.append("\n"); - + lines += footer_lines + lines_after - + f = open("../inc/MantidMDEvents/MDEventFactory.h", 'w') for line in lines: f.write(line + "\n") @@ -233,9 +233,9 @@ def generate(): for nd in dimensions: lines.append("%s template DLLExport class %s<%s<%d>, %d>;" % (padding,c, mdevent_type, nd, nd) ) lines.append("\n ") - - lines += footer_lines+lines_after + + lines += footer_lines+lines_after f = open("./MDEventFactory.cpp", 'w') for line in lines: f.write(line+"\n") diff --git a/Code/Mantid/Framework/MPIAlgorithms/scripts/NOM1.py b/Code/Mantid/Framework/MPIAlgorithms/scripts/NOM1.py index eaa884beaa72..9219da9278e8 100644 --- a/Code/Mantid/Framework/MPIAlgorithms/scripts/NOM1.py +++ b/Code/Mantid/Framework/MPIAlgorithms/scripts/NOM1.py @@ -22,7 +22,7 @@ SNSPowderReduction(Instrument="NOM", RunNumber=runNumber, Extension="_event.nxs", PreserveEvents=False, PushDataPositive='AddMinimum', CalibrationFile=cal_file, CharacterizationRunsFile=char_file, - BackgroundNumber=sam_back, VanadiumNumber=van, + BackgroundNumber=sam_back, VanadiumNumber=van, VanadiumBackgroundNumber=van_back, RemovePromptPulseWidth=50, Binning=binning, BinInDspace=False, FilterBadPulses=True, SaveAs="gsas and NeXus", OutputDirectory=outputDir, diff --git a/Code/Mantid/Framework/MPIAlgorithms/scripts/NOMAD_mpi_example.py b/Code/Mantid/Framework/MPIAlgorithms/scripts/NOMAD_mpi_example.py index 84838faab72c..be1beb2a67fe 100644 --- a/Code/Mantid/Framework/MPIAlgorithms/scripts/NOMAD_mpi_example.py +++ b/Code/Mantid/Framework/MPIAlgorithms/scripts/NOMAD_mpi_example.py @@ -43,7 +43,7 @@ def focus(filename): DiffractionFocussing(InputWorkspace=wksp, OutputWorkspace=wksp, GroupingWorkspace="grouping", PreserveEvents=False) return mtd[wksp] - + CreateGroupingWorkspace(InstrumentName='NOMAD', GroupNames='NOMAD', OutputWorkspace="grouping") ##CreateGroupingWorkspace(InstrumentName='NOMAD', OldCalFilename=calib, OutputWorkspace="grouping") diff --git a/Code/Mantid/Framework/PythonInterface/mantid/__init__.py b/Code/Mantid/Framework/PythonInterface/mantid/__init__.py index ba2cedcdd5d1..cb9e7b413cf1 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/__init__.py +++ b/Code/Mantid/Framework/PythonInterface/mantid/__init__.py @@ -4,16 +4,16 @@ http://www.mantidproject.org -The Mantid project provides a platform that supports high-performance computing -on neutron and muon data. The framework provides a set of common services, +The Mantid project provides a platform that supports high-performance computing +on neutron and muon data. The framework provides a set of common services, algorithms and data objects that are: - Instrument or technique independent; - Supported on multiple target platforms (Windows, Linux, Mac OS X); - Easily extensible by Instruments Scientists/Users; - Open source and freely redistributable to visiting scientists; - - Provides functionalities for Scripting, Visualization, Data transformation, - Implementing Algorithms, Virtual Instrument Geometry. + - Provides functionalities for Scripting, Visualization, Data transformation, + Implementing Algorithms, Virtual Instrument Geometry. """ ############################################################################### @@ -33,7 +33,7 @@ def apiVersion(): ############################################################################### # GUI - Do this as early as possible ############################################################################### -# Flag indicating whether the GUI layer is loaded. +# Flag indicating whether the GUI layer is loaded. try: import _qti __gui__ = True @@ -63,7 +63,7 @@ def apiVersion(): ############################################################################### import kernel import geometry -import api +import api ############################################################################### # Make the aliases form each module accessible in a the mantid namspace @@ -80,14 +80,14 @@ def apiVersion(): # Load the Python plugins now everything has started. # # Before the plugins are loaded the simpleapi module is called to create -# fake error-raising functions for all of the plugins. After the plugins have been +# fake error-raising functions for all of the plugins. After the plugins have been # loaded the correction translation is applied to create the "real" simple # API functions. # -# Although this seems odd it is necessary so that any PythonAlgorithm -# can call any other PythonAlgorithm through the simple API mechanism. If left +# Although this seems odd it is necessary so that any PythonAlgorithm +# can call any other PythonAlgorithm through the simple API mechanism. If left # to the simple import mechanism then plugins that are loaded later cannot -# be seen by the earlier ones (chicken & the egg essentially). +# be seen by the earlier ones (chicken & the egg essentially). ################################################################################ import simpleapi as _simpleapi from kernel import plugins as _plugins @@ -116,7 +116,7 @@ def apiVersion(): plugin_modules = _plugins.load(plugin_files) # Create the proper algorithm definitions in the module new_attrs = _simpleapi._translate() -# Finally, overwrite the mocked function definitions in the loaded modules with the real ones +# Finally, overwrite the mocked function definitions in the loaded modules with the real ones _plugins.sync_attrs(_simpleapi, new_attrs, plugin_modules) ################################################################################ diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/__init__.py b/Code/Mantid/Framework/PythonInterface/mantid/api/__init__.py index 1a84ae50ebe9..c67e4df668c7 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/__init__.py +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/__init__.py @@ -25,15 +25,15 @@ ############################################################################### FrameworkManagerImpl.Instance() # Declare any additional C++ algorithms defined in this package -_api._declareCPPAlgorithms() +_api._declareCPPAlgorithms() ############################################################################### # Make aliases accessible in this namespace ############################################################################### -from _aliases import * +from _aliases import * ############################################################################### -# Add importAll member to ADS +# Add importAll member to ADS ############################################################################### import _adsimports diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/_adsimports.py b/Code/Mantid/Framework/PythonInterface/mantid/api/_adsimports.py index 80f52ec26fa8..d523173bc0b2 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/_adsimports.py +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/_adsimports.py @@ -2,11 +2,11 @@ This modules provides a function, importAllFromADS, that creates a python variable in the globals dict of the current frame for each name in the analysis data service. - + If the name is not a valid variable then no variable is created. - + The function is also attached to the AnalysisDataService and named importAll. - + """ from mantid.api import AnalysisDataServiceImpl import inspect as _inspect @@ -24,16 +24,16 @@ def _importAll(mtd): """ Creates a named variable in the globals dictionary of the current frame (inspect.currentframe). - + For example, if the ADS contains a workspace with the name "deltax" then - + mtd.importAll() - + will create a python variable for that workspace as if the user had typed mtd['deltax']. - + @param mtd The Analysis Data Service Object - """ + """ def clean(name): """ Returns a name cleaned up so that it is a valid @@ -49,7 +49,7 @@ def clean(name): if LEADING_NUMS_REGEX.match(varname) is not None: varname = "_" + varname return varname - + stack = _inspect.stack() try: # stack[1][0] is the frame object of the caller to this function diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/_aliases.py b/Code/Mantid/Framework/PythonInterface/mantid/api/_aliases.py index 6cfef533ace0..0baba181dc65 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/_aliases.py +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/_aliases.py @@ -1,10 +1,10 @@ """ Defines a set of aliases to make accessing certain objects easier """ -from _api import (FrameworkManagerImpl, AnalysisDataServiceImpl, +from _api import (FrameworkManagerImpl, AnalysisDataServiceImpl, AlgorithmFactoryImpl, AlgorithmManagerImpl, FileFinderImpl, FunctionFactoryImpl, - WorkspaceFactoryImpl, + WorkspaceFactoryImpl, PropertyManagerDataServiceImpl, CatalogManagerImpl) ############################################################################### diff --git a/Code/Mantid/Framework/PythonInterface/mantid/api/_workspaceops.py b/Code/Mantid/Framework/PythonInterface/mantid/api/_workspaceops.py index 7c9876a659e9..7d18371993de 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/api/_workspaceops.py +++ b/Code/Mantid/Framework/PythonInterface/mantid/api/_workspaceops.py @@ -1,7 +1,7 @@ """ This module adds functions to the Workspace classes so that Python operators, i.e +-*/, can be used on them - + It is intended for internal use. """ from mantid.kernel.funcreturns import lhs_info @@ -23,7 +23,7 @@ def op_wrapper(self, other): # Get the result variable to know what to call the output result_info = lhs_info() # Pass off to helper - return _do_binary_operation(algorithm, self, other, result_info, + return _do_binary_operation(algorithm, self, other, result_info, inplace, reverse) op_wrapper.__name__ = attr setattr(_api.Workspace, attr, op_wrapper) @@ -60,7 +60,7 @@ def _do_binary_operation(op, self, rhs, lhs_vars, inplace, reverse): :param lhs_vars: A tuple containing details of the lhs of the assignment, i.e a = b + c, lhs_vars = (1, 'a') :param inplace: True if the operation should be performed inplace :param reverse: True if the reverse operator was called, i.e. 3 + a calls __radd__ - + """ global _workspace_op_tmps # @@ -79,7 +79,7 @@ def _do_binary_operation(op, self, rhs, lhs_vars, inplace, reverse): # Do the operation resultws = _api.performBinaryOp(self,rhs, op, output_name, inplace, reverse) - + # Do we need to clean up if clear_tmps: ads = _api.AnalysisDataServiceImpl.Instance() @@ -88,7 +88,7 @@ def _do_binary_operation(op, self, rhs, lhs_vars, inplace, reverse): del ads[name] _workspace_op_tmps = [] else: - if type(resultws) == _api.WorkspaceGroup: + if type(resultws) == _api.WorkspaceGroup: # Ensure the members are removed aswell members = resultws.getNames() for member in members: @@ -163,7 +163,7 @@ def _do_unary_operation(op, self, lhs_vars): if name in ads and output_name != name: ads.remove(name) _workspace_op_tmps = [] - + return resultws #------------------------------------------------------------------------------ @@ -193,7 +193,7 @@ def attach_func_as_method(name, func_obj, self_param_name, workspace_types=None) """ Adds a method to the given type that calls an algorithm using the calling object as the input workspace - + :param name: The name of the new method as it should appear on the type :param func_obj: A free function object that defines the implementation of the call :param self_param_name: The name of the parameter in the free function that the method's self maps to @@ -219,7 +219,7 @@ def _method_impl(self, *args, **kwargs): tuple(signature), f.co_filename, f.co_name, f.co_firstlineno, f.co_lnotab, f.co_freevars) # Replace the code object of the wrapper function _method_impl.func_code = c - + if workspace_types or len(workspace_types) > 0: for typename in workspace_types: cls = getattr(_api, typename) diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/__init__.py b/Code/Mantid/Framework/PythonInterface/mantid/kernel/__init__.py index ec209fa3ac39..4ec4e4897bb5 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/__init__.py +++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/__init__.py @@ -12,7 +12,7 @@ import dlopen as _pydlopen import os as _os clib = _os.path.join(_os.path.dirname(__file__), '_kernel.so') -flags = _pydlopen.setup_dlopen(clib, ['libMantidKernel']) +flags = _pydlopen.setup_dlopen(clib, ['libMantidKernel']) from _kernel import * _pydlopen.restore_flags(flags) ############################################################################### diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/dlopen.py b/Code/Mantid/Framework/PythonInterface/mantid/kernel/dlopen.py index 03247acf6f82..4905fc072d2f 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/dlopen.py +++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/dlopen.py @@ -30,28 +30,28 @@ except: _oldpath = '' _sep = '' -os.environ[_var] = os.environ['MANTIDPATH'] + _sep + _oldpath +os.environ[_var] = os.environ['MANTIDPATH'] + _sep + _oldpath ####################################################################### # Public api ####################################################################### - + def setup_dlopen(library, depends=[]): """Set the flags for a call to import a shared library such that all symbols are imported. - - On Linux this sets the flags for dlopen so that + + On Linux this sets the flags for dlopen so that all symbols from the library are imported in to the global symbol table. - + Without this each shared library gets its own copy of any singleton, which is not the correct behaviour - + Args: library - The path to the library we are opening depends - A list of dependents to open (default=[]) - + Returns the original flags """ if environment.is_windows(): @@ -63,7 +63,7 @@ def setup_dlopen(library, depends=[]): import subprocess _bin = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../../') - + def get_libpath(mainlib, dependency): if environment.is_linux(): cmd = 'ldd %s | grep %s' % (mainlib, dependency) @@ -86,7 +86,7 @@ def get_libpath(mainlib, dependency): pythonlib = library if environment.is_linux(): - # stdc++ has to be loaded first or exceptions don't get translated + # stdc++ has to be loaded first or exceptions don't get translated # properly across bounadries # NeXus has to be loaded as well as there seems to be an issue with # the thread-local storage not being initialized properly unles @@ -107,9 +107,9 @@ def get_libpath(mainlib, dependency): RTLD_LOCAL = 0x4 RTLD_NOW = 0x2 sys.setdlopenflags(RTLD_LOCAL|RTLD_NOW) - + return old_flags - + def restore_flags(flags): """Restores the dlopen flags to those provided, usually with the results from a call to setup_dlopen diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/environment.py b/Code/Mantid/Framework/PythonInterface/mantid/kernel/environment.py index ca5f87c3c420..eb027e62100a 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/environment.py +++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/environment.py @@ -1,7 +1,7 @@ """ Defines a set functions for interrogating the current enviroment. - - The standard platform module doesn't have simple things like is_windows(), + + The standard platform module doesn't have simple things like is_windows(), is_linux(). The set of functions defined here should make it clearer what is going on when they are used. """ @@ -19,14 +19,14 @@ def is_mac(): Returns True if the current platform is Mac (regardless of version/32- or 64-bit etc) """ return _sys.platform == "darwin" - + def is_linux(): """ Returns True if the current platform is OS X (regardless of version/32- or 64-bit etc) - Variant on is_apple + Variant on is_apple """ return _sys.platform.startswith("linux") - + def is_32bit(): """ Returns True if the current platform is 32-bit @@ -37,7 +37,7 @@ def is_32bit(): else: bits = _platform.architecture()[0] return bits == '32bit' - + def is_64bit(): """ Returns True if the current platform is 64-bit diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/funcreturns.py b/Code/Mantid/Framework/PythonInterface/mantid/kernel/funcreturns.py index 7149e7173684..d57b6257ebec 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/funcreturns.py +++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/funcreturns.py @@ -1,9 +1,9 @@ """ - Defines functions that can be used to inspect the properties of a + Defines functions that can be used to inspect the properties of a function call. For example - + lhs_info() can be used to get retrieve the names and number of - arguments that are being assigned to a function + arguments that are being assigned to a function return """ import opcode @@ -12,31 +12,31 @@ #------------------------------------------------------------------------------- def decompile(code_object): """ - Taken from + Taken from http://thermalnoise.wordpress.com/2007/12/30/exploring-python-bytecode/ - Extracts dissasembly information from the byte code and stores it in + Extracts dissasembly information from the byte code and stores it in a list for further use. - + Call signature(s): instructions=decompile(f.f_code) Required arguments: ========= ===================================================================== code_object A bytecode object extracted with inspect.currentframe() - or any other mechanism that returns byte code. - - Optional keyword arguments: NONE + or any other mechanism that returns byte code. + + Optional keyword arguments: NONE Outputs: ========= ===================================================================== - instructions a list of offsets, op_codes, names, arguments, argument_type, + instructions a list of offsets, op_codes, names, arguments, argument_type, argument_value which can be deconstructed to find out various things about a function call. Example: # Two frames back so that we get the callers' caller - f = inspect.currentframe().f_back.f_back + f = inspect.currentframe().f_back.f_back i = f.f_lasti # index of the last attempted instruction in byte code ins = decompile(f.f_code) """ @@ -89,24 +89,24 @@ def decompile(code_object): # A must list all of the operators that behave like a function calls in byte-code # This is for the lhs functionality -__operator_names = set(['CALL_FUNCTION', 'CALL_FUNCTION_VAR', 'CALL_FUNCTION_KW', +__operator_names = set(['CALL_FUNCTION', 'CALL_FUNCTION_VAR', 'CALL_FUNCTION_KW', 'CALL_FUNCTION_VAR_KW','UNARY_POSITIVE', 'UNARY_NEGATIVE','UNARY_NOT', 'UNARY_CONVERT','UNARY_INVERT', - 'GET_ITER', 'BINARY_POWER', 'BINARY_MULTIPLY','BINARY_DIVIDE', + 'GET_ITER', 'BINARY_POWER', 'BINARY_MULTIPLY','BINARY_DIVIDE', 'BINARY_FLOOR_DIVIDE', 'BINARY_TRUE_DIVIDE', 'BINARY_MODULO', 'BINARY_ADD','BINARY_SUBTRACT', 'BINARY_SUBSCR','BINARY_LSHIFT', - 'BINARY_RSHIFT','BINARY_AND', 'BINARY_XOR','BINARY_OR', - 'INPLACE_POWER', 'INPLACE_MULTIPLY', 'INPLACE_DIVIDE', + 'BINARY_RSHIFT','BINARY_AND', 'BINARY_XOR','BINARY_OR', + 'INPLACE_POWER', 'INPLACE_MULTIPLY', 'INPLACE_DIVIDE', 'INPLACE_TRUE_DIVIDE','INPLACE_FLOOR_DIVIDE', - 'INPLACE_MODULO', 'INPLACE_ADD', 'INPLACE_SUBTRACT', + 'INPLACE_MODULO', 'INPLACE_ADD', 'INPLACE_SUBTRACT', 'INPLACE_LSHIFT','INPLACE_RSHIFT','INPLACE_AND', 'INPLACE_XOR', 'INPLACE_OR', 'COMPARE_OP']) #-------------------------------------------------------------------------------------- def process_frame(frame): - """Returns the number of arguments on the left of assignment along + """Returns the number of arguments on the left of assignment along with the names of the variables for the given frame. - + Call signature(s):: Required arguments: @@ -114,17 +114,17 @@ def process_frame(frame): frame The code frame to analyse Outputs: - ========= + ========= Returns the a tuple with the number of arguments and their names """ # Index of the last attempted instruction in byte code - last_i = frame.f_lasti + last_i = frame.f_lasti ins_stack = decompile(frame.f_code) call_function_locs = {} - start_index = 0 + start_index = 0 start_offset = 0 - + for index, instruction in enumerate(ins_stack): (offset, op, name, argument, argtype, argvalue) = instruction if name in __operator_names: @@ -134,32 +134,32 @@ def process_frame(frame): (offset, op, name, argument, argtype, argvalue) = ins_stack[-1] # Append the index of the last entry to form the last boundary - call_function_locs[start_offset] = (start_index, len(ins_stack)-1) + call_function_locs[start_offset] = (start_index, len(ins_stack)-1) - # last_i should be the offset of a call_function_locs instruction. + # last_i should be the offset of a call_function_locs instruction. # We use this to bracket the bit which we are interested in. # Bug: # Some types of call, eg # def foo(callableObj, *args, **kwargs): # x = callableObj(*args, **kwargs) - # + # # foo(FuncUsingLHS, 'Args') # # have the incorrect index at last_i due to the call being passed through - # an intermediate reference. Currently this method does not provide the + # an intermediate reference. Currently this method does not provide the # correct answer and throws a KeyError. Ticket #4186 - + output_var_names = [] max_returns = [] last_func_offset = call_function_locs[last_i][0] - (offset, op, name, argument, argtype, argvalue) = ins_stack[last_func_offset + 1] + (offset, op, name, argument, argtype, argvalue) = ins_stack[last_func_offset + 1] if name == 'POP_TOP': # no return values pass - if name == 'STORE_FAST' or name == 'STORE_NAME': # one return value + if name == 'STORE_FAST' or name == 'STORE_NAME': # one return value output_var_names.append(argvalue) - if name == 'UNPACK_SEQUENCE': # Many Return Values, One equal sign + if name == 'UNPACK_SEQUENCE': # Many Return Values, One equal sign for index in range(argvalue): - (offset_, op_, name_, argument_, argtype_, argvalue_) = ins_stack[last_func_offset + 2 +index] + (offset_, op_, name_, argument_, argtype_, argvalue_) = ins_stack[last_func_offset + 2 +index] output_var_names.append(argvalue_) max_returns = len(output_var_names) if name == 'DUP_TOP': # Many Return Values, Many equal signs @@ -171,53 +171,53 @@ def process_frame(frame): count = 0 max_returns = 0 # Must count the max_returns ourselves in this case while count < len(ins_stack[call_function_locs[i][0]:call_function_locs[i][1]]): - (offset_, op_, name_, argument_, argtype_, argvalue_) = ins[call_function_locs[i][0]+count] - if name_ == 'UNPACK_SEQUENCE': # Many Return Values, One equal sign + (offset_, op_, name_, argument_, argtype_, argvalue_) = ins[call_function_locs[i][0]+count] + if name_ == 'UNPACK_SEQUENCE': # Many Return Values, One equal sign hold = [] if argvalue_ > max_returns: max_returns = argvalue_ for index in range(argvalue_): - (_offset_, _op_, _name_, _argument_, _argtype_, _argvalue_) = ins[call_function_locs[i][0] + count+1+index] + (_offset_, _op_, _name_, _argument_, _argtype_, _argvalue_) = ins[call_function_locs[i][0] + count+1+index] hold.append(_argvalue_) count = count + argvalue_ output_var_names.append(hold) # Need to now skip the entries we just appended with the for loop. - if name_ == 'STORE_FAST' or name_ == 'STORE_NAME': # One Return Value + if name_ == 'STORE_FAST' or name_ == 'STORE_NAME': # One Return Value if 1 > max_returns: max_returns = 1 output_var_names.append(argvalue_) count = count + 1 - + return (max_returns, tuple(output_var_names)) #------------------------------------------------------------------------------- def lhs_info(output_type='both', frame=None): - """Returns the number of arguments on the left of assignment along + """Returns the number of arguments on the left of assignment along with the names of the variables. - Acknowledgements: - Thanks to Tim Charlton and Jon Taylor of the ISIS facility for + Acknowledgements: + Thanks to Tim Charlton and Jon Taylor of the ISIS facility for figuring this out. - + Call signature(s):: Required arguments: NONE - + Optional keyword arguments Meaning: =========================== ========== output_type A string enumerating the type of output, one of output_type = 'nreturns' : The number of return values expected from the call - output_type = 'names' : Just return a list of - variable names + output_type = 'names' : Just return a list of + variable names output_type = 'both' : A tuple containing both of the above frame A frame object that points to the frame containing a variable assignment. Default = inspect.currentframe().f_back.f_back Outputs: - ========= + ========= Depends on the value of the argument. See above. """ @@ -235,7 +235,7 @@ def lhs_info(output_type='both', frame=None): ret_vals = process_frame(frame) finally: del frame - + if output_type == 'nreturns': ret_vals = ret_vals[0] elif output_type == 'names': diff --git a/Code/Mantid/Framework/PythonInterface/mantid/kernel/plugins.py b/Code/Mantid/Framework/PythonInterface/mantid/kernel/plugins.py index 41e5d2b2413f..1bc5b0dff605 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/kernel/plugins.py +++ b/Code/Mantid/Framework/PythonInterface/mantid/kernel/plugins.py @@ -1,8 +1,8 @@ """ Defines functions to dynamically load Python modules. -These modules may define extensions to C++ types, e.g. -algorithms, fit functions etc. +These modules may define extensions to C++ types, e.g. +algorithms, fit functions etc. """ import os as _os import imp as _imp @@ -27,7 +27,7 @@ def run(self): """ Try and load the module we are pointing at and return the module object. - + Any ImportErrors raised are not caught and are passed on to the caller """ @@ -45,7 +45,7 @@ def get_plugin_paths_as_set(key): """ Returns the value of the given key in the config service as a set. Raises an KeyError if the key is not defined - + @param key The name of the key @returns A set containing defined plugins paths """ @@ -57,7 +57,7 @@ def get_plugin_paths_as_set(key): def check_for_plugins(top_dir): """ Runs a quick check to see if any plugin files exist in the given directory - + @returns True if any plugins are found, false otherwise """ if not _os.path.isdir(top_dir): @@ -86,22 +86,22 @@ def find_plugins(top_dir): all_plugins.append(filename) if contains_newapi_algorithm(filename): algs.append(filename) - + return all_plugins, algs #====================================================================================================================== def load(path): """ - High-level function to import the module(s) on the given path. + High-level function to import the module(s) on the given path. The module is imported using __import__ so any code not defined inside an if __name__ == '__main__' block is executed. @param path :: If the path is a filename load the file; if the - path points to a directory load all files in the directory + path points to a directory load all files in the directory recursively; if the path contains a list of directories then all files in each are loaded in turn - + @return A list of the loaded modules. Note this will not included modules that will have attempted to be reloaded but had not been changed @@ -118,7 +118,7 @@ def load(path): loaded += load_from_dir(path) else: raise RuntimeError("Unknown type of path found when trying to load plugins: '%s'" % str(path)) - + return loaded #====================================================================================================================== @@ -126,7 +126,7 @@ def load(path): def load_from_list(paths): """ Load all modules in the given list - + @param paths :: A list of filenames to load """ loaded = [] @@ -143,7 +143,7 @@ def load_from_list(paths): def load_from_dir(directory): """ Load all modules in the given directory - + @param directory :: A path that must point to a directory """ plugins = find_plugins(directory) @@ -176,10 +176,10 @@ def load_from_file(filepath): def load_plugin(plugin_path): """ Load a plugin and return the name & module object - + @param plugin_path :: A path that must should point to a .py file that will be loaded. A ValueError is raised if - path is not a valid plugin path. Any exceptions raised by the + path is not a valid plugin path. Any exceptions raised by the import are passed to the caller """ loader = PluginLoader(plugin_path) @@ -190,11 +190,11 @@ def load_plugin(plugin_path): def sync_attrs(source_module, attrs, clients): """ - Syncs the attribute definitions between the + Syncs the attribute definitions between the given list from the source module & list of client modules such that the function defintions point to the same one - + @param source_module :: The module containing the "correct" definitions @param attrs :: The list of attributes to change in the client modules @@ -215,7 +215,7 @@ def contains_newapi_algorithm(filename): it contains an algorithm written with this API. The check is simple. If registerPyAlgorithm is discovered then it will not be considered a new API algorithm - + @param filename :: A full file path pointing to a python file @returns True if a python algorithm written with the new API has been found. diff --git a/Code/Mantid/Framework/PythonInterface/mantid/simpleapi.py b/Code/Mantid/Framework/PythonInterface/mantid/simpleapi.py index c5c3d74ce655..5fe8e17b739c 100644 --- a/Code/Mantid/Framework/PythonInterface/mantid/simpleapi.py +++ b/Code/Mantid/Framework/PythonInterface/mantid/simpleapi.py @@ -3,21 +3,21 @@ algorithms. Each algorithm within Mantid is mapped to a Python function of the same name with the parameters of the algorithm becoming arguments to the function. - + For example: - + The Rebin algorithm is mapped to this Python function: Rebin(InputWorkspace, OutputWorkspace, Params, PreserveEvents=None, Version=1) - + It returns the output workspace and this workspace has the same name as the variable it is assigned to, i.e. - + rebinned = Rebin(input, Params = '0.1,0.05,10') - + would call Rebin with the given parameters and create a workspace called 'rebinned' and assign it to the rebinned variable - + """ import api as _api import kernel as _kernel @@ -43,7 +43,7 @@ def specialization_exists(name): """ Returns true if a specialization for the given name already exists, false otherwise - + :param name: The name of a possible new function """ return name in __SPECIALIZED_FUNCTIONS__ @@ -54,37 +54,37 @@ def Load(*args, **kwargs): It's aim is to discover the correct loading algorithm for a given file. This flexibility comes at the expense of knowing the properties out right before the file is specified. - + The argument list for the Load function has to be more flexible to allow this searching to occur. Two arguments must be specified: - + - Filename :: The name of the file, - OutputWorkspace :: The name of the workspace, - + either as the first two arguments in the list or as keywords. Any other properties that the Load algorithm has can be specified by keyword only. - + Some common keywords are: - SpectrumMin, - SpectrumMax, - SpectrumList, - EntryNumber - + Example: # Simple usage, ISIS NeXus file run_ws = Load('INSTR00001000.nxs') - + # Histogram NeXus with SpectrumMin and SpectrumMax = 1 run_ws = Load('INSTR00001000.nxs', SpectrumMin=1,SpectrumMax=1) - + # Event NeXus with precount on event_ws = Load('INSTR_1000_event.nxs', Precount=True) - + # The output workspace name is picked up from the LHS unless overridden Load('INSTR00001000.nxs',OutputWorkspace='run_ws') """ filename, = _get_mandatory_args('Load', ["Filename"], *args, **kwargs) - + # Create and execute algm = _create_algorithm_object('Load') _set_logging_option(algm, kwargs) @@ -99,8 +99,8 @@ def Load(*args, **kwargs): # then raise a more helpful error than what we would get from an algorithm if lhs[0] == 0 and 'OutputWorkspace' not in kwargs: raise RuntimeError("Unable to set output workspace name. Please either assign the output of " - "Load to a variable or use the OutputWorkspace keyword.") - + "Load to a variable or use the OutputWorkspace keyword.") + lhs_args = _get_args_from_lhs(lhs, algm) final_keywords = _merge_keywords_with_lhs(kwargs, lhs_args) # Check for any properties that aren't known and warn they will not be used @@ -110,7 +110,7 @@ def Load(*args, **kwargs): del final_keywords[key] _set_properties(algm, **final_keywords) algm.execute() - + # If a WorkspaceGroup was loaded then there will be a set of properties that have an underscore in the name # and users will simply expect the groups to be returned NOT the groups + workspaces. return _gather_returns('Load', lhs, algm, ignore_regex=['LoaderName','LoaderVersion','.*_.*']) @@ -156,7 +156,7 @@ def LoadDialog(*args, **kwargs): if 'Enable' not in arguments: arguments['Enable']='' if 'Disable' not in arguments: arguments['Disable']='' if 'Message' not in arguments: arguments['Message']='' - + algm = _create_algorithm_object('Load') _set_properties_dialog(algm,**arguments) algm.execute() @@ -169,11 +169,11 @@ def Fit(*args, **kwargs): Fit defines the interface to the fitting framework within Mantid. It can work with arbitrary data sources and therefore some options are only available when the function & workspace type are known. - + This simple wrapper takes the Function (as a string) & the InputWorkspace - as the first two arguments. The remaining arguments must be + as the first two arguments. The remaining arguments must be specified by keyword. - + Example: Fit(Function='name=LinearBackground,A0=0.3', InputWorkspace=dataWS', StartX='0.05',EndX='1.0',Output="Z1") @@ -199,7 +199,7 @@ def Fit(*args, **kwargs): if key.startswith('InputWorkspace_'): algm.setProperty(key, kwargs[key]) del kwargs[key] - + lhs = _funcreturns.lhs_info() # Check for any properties that aren't known and warn they will not be used for key in kwargs.keys(): @@ -208,7 +208,7 @@ def Fit(*args, **kwargs): del kwargs[key] _set_properties(algm, **kwargs) algm.execute() - + return _gather_returns('Fit', lhs, algm) # Have a better load signature for autocomplete @@ -243,7 +243,7 @@ def FitDialog(*args, **kwargs): if 'Enable' not in arguments: arguments['Enable']='' if 'Disable' not in arguments: arguments['Disable']='' if 'Message' not in arguments: arguments['Message']='' - + algm = _create_algorithm_object('Fit') _set_properties_dialog(algm,**arguments) algm.execute() @@ -253,7 +253,7 @@ def FitDialog(*args, **kwargs): def _get_function_spec(func): """Get the python function signature for the given function object - + :param func: A Python function object """ import inspect @@ -315,7 +315,7 @@ def _get_mandatory_args(func_name, required_args ,*args, **kwargs): """Given a list of required arguments, parse them from the given args & kwargs and raise an error if they are not provided - + :param func_name: The name of the function call :type str. :param required_args: A list of names of required arguments @@ -334,7 +334,7 @@ def get_argument_value(key, kwargs): raise RuntimeError('%s argument not supplied to %s function' % (str(key), func_name)) nrequired = len(required_args) npositional = len(args) - + if npositional == 0: mandatory_args = [] for arg in required_args: @@ -359,10 +359,10 @@ def get_argument_value(key, kwargs): def _is_workspace_property(prop): """ Returns true if the property is a workspace property. - + Currently several properties , i.e WorspaceProperty cannot be recognised by Python so we have to resort to a name test - + :param prop: A property object :type Property :returns: True if the property is considered to be of type workspace @@ -378,13 +378,13 @@ def _is_workspace_property(prop): def _get_args_from_lhs(lhs, algm_obj): """ Return the extra arguments that are to be passed to the algorithm - from the information in the lhs tuple. These are basically the names + from the information in the lhs tuple. These are basically the names of output workspaces. The algorithm properties are iterated over in the same order they were created within the wrapper and for each output workspace property an entry is added to the returned dictionary that contains {PropertyName:lhs_name}. - + :param lhs: A 2-tuple that contains the number of variables supplied on the lhs of the function call and the names of these variables :param algm_obj: An initialised algorithm object :returns: A dictionary mapping property names to the values extracted from the lhs variables @@ -409,20 +409,20 @@ def _merge_keywords_with_lhs(keywords, lhs_args): by the keywords passed to a function and the lhs arguments that have been parsed. Any value in keywords overrides on in lhs_args. - + :param keywords: A dictionary of keywords that has been passed to the function call :param lhs_args: A dictionary of arguments retrieved from the lhs of the function call """ final_keywords = lhs_args final_keywords.update(keywords) return final_keywords - + def _gather_returns(func_name, lhs, algm_obj, ignore_regex=[]): """Gather the return values and ensure they are in the correct order as defined by the output properties and return them as a tuple. If their is a single return value it is returned on its own - + :param func_name: The name of the calling function. :param lhs: A 2-tuple that contains the number of variables supplied on the lhs of the function call and the names of these variables. :param algm_obj: An executed algorithm object. @@ -435,8 +435,8 @@ def ignore_property(name, ignore_regex): return True # Matched nothing return False - - if type(ignore_regex) is str: + + if type(ignore_regex) is str: ignore_regex = [ignore_regex] # Compile regexes for index, expr in enumerate(ignore_regex): @@ -448,7 +448,7 @@ def ignore_property(name, ignore_regex): continue prop = algm_obj.getProperty(name) # Parent algorithms store their workspaces in the ADS - # Child algorithms should store their workspaces in the property + # Child algorithms should store their workspaces in the property # but they don't at the moment while the issues with history recording Python Child Algs # is resolved: ticket #5157 if _is_workspace_property(prop): @@ -465,7 +465,7 @@ def ignore_property(name, ignore_regex): else: raise RuntimeError('Internal error. Unknown property type encountered. "%s" on algorithm "%s" is not understood by ' 'Python. Please contact development team' % (name, algm_obj.name())) - + nvals = len(retvals) nlhs = lhs[0] @@ -484,7 +484,7 @@ def ignore_property(name, ignore_regex): def _set_logging_option(algm_obj, kwargs): """ Checks the keyword arguments for the _LOGGING keyword, sets the state of the - algorithm logging accordingly and removes the value from the dictionary. If the keyword + algorithm logging accordingly and removes the value from the dictionary. If the keyword does not exist then it does nothing. :param alg_object: An initialised algorithm object @@ -499,7 +499,7 @@ def _set_properties(alg_object, *args, **kwargs): Set all of the properties of the algorithm :param alg_object: An initialised algorithm object :param *args: Positional arguments - :param **kwargs: Keyword arguments + :param **kwargs: Keyword arguments """ if len(args) > 0: mandatory_props = alg_object.mandatoryProperties() @@ -525,7 +525,7 @@ def _set_properties(alg_object, *args, **kwargs): # The correct parent/child relationship is not quite set up yet: #5157 # ChildAlgorithms in Python are marked as children but their output is in the # ADS meaning we cannot just set DataItem properties by value. At the moment - # they are just set with strings + # they are just set with strings if isinstance(value, _kernel.DataItem): alg_object.setPropertyValue(key, value.name()) else: @@ -538,7 +538,7 @@ def _create_algorithm_function(algorithm, version, _algm_object): :param algorithm: name of the algorithm :param _algm_object: the created algorithm object. """ - + def algorithm_wrapper(*args, **kwargs): """ Note that if the Version parameter is passed, we will create @@ -554,13 +554,13 @@ def algorithm_wrapper(*args, **kwargs): # Temporary removal of unneeded parameter from user's python scripts if "CoordinatesToUse" in kwargs and algorithm in __MDCOORD_FUNCTIONS__: del kwargs["CoordinatesToUse"] - + try: frame = kwargs["__LHS_FRAME_OBJECT__"] del kwargs["__LHS_FRAME_OBJECT__"] except KeyError: frame = None - + lhs = _funcreturns.lhs_info(frame=frame) lhs_args = _get_args_from_lhs(lhs, algm) final_keywords = _merge_keywords_with_lhs(kwargs, lhs_args) @@ -568,15 +568,15 @@ def algorithm_wrapper(*args, **kwargs): _set_properties(algm, *args, **final_keywords) algm.execute() return _gather_returns(algorithm, lhs, algm) - - + + algorithm_wrapper.__name__ = algorithm - + # Construct the algorithm documentation algorithm_wrapper.__doc__ = _algm_object.docString() - + # Dark magic to get the correct function signature - # Calling help(...) on the wrapper function will produce a function + # Calling help(...) on the wrapper function will produce a function # signature along the lines of AlgorithmName(*args, **kwargs). # We will replace the name "args" by the list of properties, and # the name "kwargs" by "Version=1". @@ -584,7 +584,7 @@ def algorithm_wrapper(*args, **kwargs): # taking care of giving no default values to mandatory parameters # 2 - All output properties will be removed from the function # argument list - + arg_list = [] for p in _algm_object.mandatoryProperties(): prop = _algm_object.getProperty(p) @@ -596,11 +596,11 @@ def algorithm_wrapper(*args, **kwargs): if len(valid_str) > 0: arg_list.append(p) else: - # None is not quite accurate here, but we are reproducing the + # None is not quite accurate here, but we are reproducing the # behavior found in the C++ code for SimpleAPI. arg_list.append("%s=None" % p) - # Build the function argument string from the tokens we found + # Build the function argument string from the tokens we found arg_str = ','.join(arg_list) # Calling help(...) will put a * in front of the first parameter name, so we use \b signature = "\b%s" % arg_str @@ -611,10 +611,10 @@ def algorithm_wrapper(*args, **kwargs): c = f.__new__(f.__class__, f.co_argcount, f.co_nlocals, f.co_stacksize, f.co_flags, f.co_code, f.co_consts, f.co_names,\ (signature, "\b\bVersion=%d" % version), f.co_filename, f.co_name, f.co_firstlineno, f.co_lnotab, f.co_freevars) # Replace the code object of the wrapper function - algorithm_wrapper.func_code = c + algorithm_wrapper.func_code = c globals()[algorithm] = algorithm_wrapper - + # Register aliases for alias in _algm_object.alias().strip().split(' '): alias = alias.strip() @@ -688,9 +688,9 @@ def get_self(frame): def _set_properties_dialog(algm_object, *args, **kwargs): """ Set the properties all in one go assuming that you are preparing for a - dialog box call. If the dialog is cancelled raise a runtime error, otherwise + dialog box call. If the dialog is cancelled raise a runtime error, otherwise return the algorithm ready to execute. - + :param algm_object An initialized algorithm object """ if not __gui__: @@ -704,13 +704,13 @@ def _set_properties_dialog(algm_object, *args, **kwargs): message = kwargs.get("Message", "") del kwargs["Message"] presets = '|' - + #------------------------------------------------------------------------------- def make_str(value): """Make a string out of a value such that the Mantid properties can understand it """ import numpy - + if isinstance(value, numpy.ndarray): value = list(value) # Temp until more complete solution available (#2340) if isinstance(value, list) or \ @@ -733,7 +733,7 @@ def make_str(value): for index, value in enumerate(args): propname = ordered_props[index] kwargs[propname] = args[index] - + # configure everything for the dialog for name in kwargs.keys(): value = kwargs[name] @@ -763,12 +763,12 @@ def algorithm_wrapper(*args, **kwargs): for item in ["Message", "Enable", "Disable"]: if item not in kwargs: kwargs[item] = "" - + algm = _create_algorithm_object(algorithm, _version) _set_properties_dialog(algm, *args, **kwargs) # throws if input cancelled algm.execute() return algm - + algorithm_wrapper.__name__ = "%sDialog" % algorithm algorithm_wrapper.__doc__ = "\n\n%s dialog" % algorithm @@ -782,10 +782,10 @@ def algorithm_wrapper(*args, **kwargs): c = f.__new__(f.__class__, f.co_argcount, f.co_nlocals, f.co_stacksize, f.co_flags, f.co_code, f.co_consts, f.co_names,\ (signature, "\b\bMessage=\"\", Enable=\"\", Disable=\"\", Version=%d" % version), \ f.co_filename, f.co_name, f.co_firstlineno, f.co_lnotab, f.co_freevars) - algorithm_wrapper.func_code = c - + algorithm_wrapper.func_code = c + globals()["%sDialog" % algorithm] = algorithm_wrapper - + # Register aliases for alias in _algm_object.alias().strip().split(' '): alias = alias.strip() @@ -797,10 +797,10 @@ def algorithm_wrapper(*args, **kwargs): def _mockup(plugins): """ Creates fake, error-raising functions for all loaded algorithms plus - any plugins given. - The function name for the Python algorithms are taken from the filename + any plugins given. + The function name for the Python algorithms are taken from the filename so this mechanism requires the algorithm name to match the filename. - + This mechanism solves the "chicken-and-egg" problem with Python algorithms trying to use other Python algorithms through the simple API functions. The issue occurs when a python algorithm tries to import the simple API function of another @@ -809,7 +809,7 @@ def _mockup(plugins): is not yet known. By having a pre-loading step all of the necessary functions on this module can be created and after the plugins are loaded the correct function definitions can overwrite the "fake" ones. - + :param plugins: A list of modules that have been loaded """ #-------------------------------------------------------------------------------------------------------- @@ -845,7 +845,7 @@ def create_fake_functions(alg_names): import os cppalgs = AlgorithmFactory.getRegisteredAlgorithms(True) create_fake_functions(cppalgs.keys()) - + # Now the plugins for plugin in plugins: name = os.path.basename(plugin) @@ -856,17 +856,17 @@ def create_fake_functions(alg_names): def _translate(): """ - Loop through the algorithms and register a function call + Loop through the algorithms and register a function call for each of them - + :returns: a list of new function calls """ from api import AlgorithmFactory, AlgorithmManager - + new_functions = [] # Names of new functions added to the global namespace new_methods = {} # Method names mapped to their algorithm names. Used to detect multiple copies of same method name # on different algorithms, which is an error - + algs = AlgorithmFactory.getRegisteredAlgorithms(True) algorithm_mgr = AlgorithmManager for name, versions in algs.iteritems(): @@ -894,7 +894,7 @@ def _translate(): # Dialog variant _create_algorithm_dialog(name, max(versions), algm_object) new_functions.append(name) - + return new_functions #------------------------------------------------------------------------------------------------------------- diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py index 0ae72a8d6730..900047b0e3de 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/BASISReduction.py @@ -24,31 +24,31 @@ def PyInit(self): self._short_inst = "BSS" self._long_inst = "BASIS" self._extension = "_event.nxs" - + self.declareProperty("RunNumbers", "", "Sample run numbers") self.declareProperty("DoIndividual", False, "Do each run individually") - self.declareProperty("NoMonitorNorm", False, + self.declareProperty("NoMonitorNorm", False, "Stop monitor normalization") - self.declareProperty("NormRunNumbers", "", "Normalization run numbers") - arrVal = FloatArrayLengthValidator(2) - self.declareProperty(FloatArrayProperty("NormWavelengthRange", DEFAULT_RANGE, - arrVal, direction=Direction.Input), - "Wavelength range for normalization. default:(6.24A, 6.30A)") - self.declareProperty(FloatArrayProperty("EnergyBins", DEFAULT_BINS, - direction=Direction.Input), + self.declareProperty("NormRunNumbers", "", "Normalization run numbers") + arrVal = FloatArrayLengthValidator(2) + self.declareProperty(FloatArrayProperty("NormWavelengthRange", DEFAULT_RANGE, + arrVal, direction=Direction.Input), + "Wavelength range for normalization. default:(6.24A, 6.30A)") + self.declareProperty(FloatArrayProperty("EnergyBins", DEFAULT_BINS, + direction=Direction.Input), "Energy transfer binning scheme (in ueV)") - self.declareProperty(FloatArrayProperty("MomentumTransferBins", - DEFAULT_BINS, - direction=Direction.Input), + self.declareProperty(FloatArrayProperty("MomentumTransferBins", + DEFAULT_BINS, + direction=Direction.Input), "Momentum transfer binning scheme") self.declareProperty(FileProperty(name="MaskFile", defaultValue="", action=FileAction.OptionalLoad, extensions=['.xml']), "Directory location for standard masking and grouping files.") grouping_type = ["None", "Low-Resolution", "By-Tube"] - self.declareProperty("GroupDetectors", "None", - StringListValidator(grouping_type), + self.declareProperty("GroupDetectors", "None", + StringListValidator(grouping_type), "Switch for grouping detectors") - + def PyExec(self): config['default.facility'] = "SNS" config['default.instrument'] = self._long_inst @@ -69,65 +69,65 @@ def PyExec(self): config.appendDataSearchDir(DEFAULT_MASK_GROUP_DIR) self._maskFile = DEFAULT_MASK_FILE - api.LoadMask(Instrument='BASIS', OutputWorkspace='BASIS_MASK', + api.LoadMask(Instrument='BASIS', OutputWorkspace='BASIS_MASK', InputFile=self._maskFile) - + # Work around length issue _dMask = api.ExtractMask('BASIS_MASK') self._dMask = _dMask[1] api.DeleteWorkspace(_dMask[0]) - - # Do normalization if run numbers are present - norm_runs = self.getProperty("NormRunNumbers").value - self._doNorm = bool(norm_runs) - self.log().information("Do Norm: " + str(self._doNorm)) - if self._doNorm: - if ";" in norm_runs: - raise SyntaxError("Normalization does not support run groups") - # Setup the integration (rebin) parameters - normRange = self.getProperty("NormWavelengthRange").value - self._normRange = [normRange[0], normRange[1]-normRange[0], normRange[1]] - - # Process normalization runs - self._norm_run_list = self._getRuns(norm_runs) - for norm_set in self._norm_run_list: + + # Do normalization if run numbers are present + norm_runs = self.getProperty("NormRunNumbers").value + self._doNorm = bool(norm_runs) + self.log().information("Do Norm: " + str(self._doNorm)) + if self._doNorm: + if ";" in norm_runs: + raise SyntaxError("Normalization does not support run groups") + # Setup the integration (rebin) parameters + normRange = self.getProperty("NormWavelengthRange").value + self._normRange = [normRange[0], normRange[1]-normRange[0], normRange[1]] + + # Process normalization runs + self._norm_run_list = self._getRuns(norm_runs) + for norm_set in self._norm_run_list: extra_extension = "_norm" self._normWs = self._makeRunName(norm_set[0]) self._normWs += extra_extension - self._normMonWs = self._normWs + "_monitors" + self._normMonWs = self._normWs + "_monitors" self._sumRuns(norm_set, self._normWs, self._normMonWs, extra_extension) - self._calibData(self._normWs, self._normMonWs) - - api.Rebin(InputWorkspace=self._normWs, OutputWorkspace=self._normWs, - Params=self._normRange) - api.FindDetectorsOutsideLimits(InputWorkspace=self._normWs, - OutputWorkspace="BASIS_NORM_MASK") + self._calibData(self._normWs, self._normMonWs) + + api.Rebin(InputWorkspace=self._normWs, OutputWorkspace=self._normWs, + Params=self._normRange) + api.FindDetectorsOutsideLimits(InputWorkspace=self._normWs, + OutputWorkspace="BASIS_NORM_MASK") self._run_list = self._getRuns(self.getProperty("RunNumbers").value) for run_set in self._run_list: self._samWs = self._makeRunName(run_set[0]) self._samMonWs = self._samWs + "_monitors" self._samWsRun = str(run_set[0]) - - self._sumRuns(run_set, self._samWs, self._samMonWs) + + self._sumRuns(run_set, self._samWs, self._samMonWs) # After files are all added, run the reduction - self._calibData(self._samWs, self._samMonWs) - - if self._doNorm: - api.MaskDetectors(Workspace=self._samWs, - MaskedWorkspace='BASIS_NORM_MASK') - api.Divide(LHSWorkspace=self._samWs, RHSWorkspace=self._normWs, - OutputWorkspace=self._samWs) - - api.ConvertUnits(InputWorkspace=self._samWs, - OutputWorkspace=self._samWs, + self._calibData(self._samWs, self._samMonWs) + + if self._doNorm: + api.MaskDetectors(Workspace=self._samWs, + MaskedWorkspace='BASIS_NORM_MASK') + api.Divide(LHSWorkspace=self._samWs, RHSWorkspace=self._normWs, + OutputWorkspace=self._samWs) + + api.ConvertUnits(InputWorkspace=self._samWs, + OutputWorkspace=self._samWs, Target='DeltaE', EMode='Indirect') - api.CorrectKiKf(InputWorkspace=self._samWs, - OutputWorkspace=self._samWs, + api.CorrectKiKf(InputWorkspace=self._samWs, + OutputWorkspace=self._samWs, EMode='Indirect') - - api.Rebin(InputWorkspace=self._samWs, - OutputWorkspace=self._samWs, + + api.Rebin(InputWorkspace=self._samWs, + OutputWorkspace=self._samWs, Params=self._etBins) if self._groupDetOpt != "None": if self._groupDetOpt == "Low-Resolution": @@ -139,29 +139,29 @@ def PyExec(self): if self._overrideMask: config.appendDataSearchDir(DEFAULT_MASK_GROUP_DIR) - api.GroupDetectors(InputWorkspace=self._samWs, + api.GroupDetectors(InputWorkspace=self._samWs, OutputWorkspace=self._samWs, MapFile=grp_file, Behaviour="Sum") - + self._samSqwWs = self._samWs+'_sqw' - api.SofQW3(InputWorkspace=self._samWs, + api.SofQW3(InputWorkspace=self._samWs, OutputWorkspace=self._samSqwWs, - QAxisBinning=self._qBins, EMode='Indirect', + QAxisBinning=self._qBins, EMode='Indirect', EFixed='2.0826') - - dave_grp_filename = self._makeRunName(self._samWsRun, + + dave_grp_filename = self._makeRunName(self._samWsRun, False) + ".dat" - api.SaveDaveGrp(Filename=dave_grp_filename, + api.SaveDaveGrp(Filename=dave_grp_filename, InputWorkspace=self._samSqwWs, ToMicroEV=True) - processed_filename = self._makeRunName(self._samWsRun, + processed_filename = self._makeRunName(self._samWsRun, False) + "_sqw.nxs" - api.SaveNexus(Filename=processed_filename, - InputWorkspace=self._samSqwWs) + api.SaveNexus(Filename=processed_filename, + InputWorkspace=self._samSqwWs) def _getRuns(self, rlist): """ - Create sets of run numbers for analysis. A semicolon indicates a + Create sets of run numbers for analysis. A semicolon indicates a separate group of runs to be processed together. """ run_list = [] @@ -170,7 +170,7 @@ def _getRuns(self, rlist): iap = IntArrayProperty("", rlval) if self._doIndiv: run_list.extend([[x] for x in iap.value]) - else: + else: run_list.append(iap.value) return run_list @@ -182,12 +182,12 @@ def _makeRunName(self, run, useShort=True): return self._short_inst + "_" + str(run) else: return self._long_inst + "_" + str(run) - + def _makeRunFile(self, run): """ Make name like BSS24234 """ - return self._short_inst + str(run) + return self._short_inst + str(run) def _sumRuns(self, run_set, sam_ws, mon_ws, extra_ext=None): for run in run_set: @@ -196,54 +196,54 @@ def _sumRuns(self, run_set, sam_ws, mon_ws, extra_ext=None): ws_name += extra_ext mon_ws_name = ws_name + "_monitors" run_file = self._makeRunFile(run) - + api.Load(Filename=run_file, OutputWorkspace=ws_name) if not self._noMonNorm: - api.LoadNexusMonitors(Filename=run_file, + api.LoadNexusMonitors(Filename=run_file, OutputWorkspace=mon_ws_name) if sam_ws != ws_name: api.Plus(LHSWorkspace=sam_ws, RHSWorkspace=ws_name, OutputWorkspace=sam_ws) api.DeleteWorkspace(ws_name) if mon_ws != mon_ws_name and not self._noMonNorm: - api.Plus(LHSWorkspace=mon_ws, + api.Plus(LHSWorkspace=mon_ws, RHSWorkspace=mon_ws_name, OutputWorkspace=mon_ws) api.DeleteWorkspace(mon_ws_name) def _calibData(self, sam_ws, mon_ws): - api.MaskDetectors(Workspace=sam_ws, + api.MaskDetectors(Workspace=sam_ws, DetectorList=self._dMask) #MaskedWorkspace='BASIS_MASK') - api.ModeratorTzeroLinear(InputWorkspace=sam_ws, + api.ModeratorTzeroLinear(InputWorkspace=sam_ws, OutputWorkspace=sam_ws) - api.LoadParameterFile(Workspace=sam_ws, + api.LoadParameterFile(Workspace=sam_ws, Filename=config.getInstrumentDirectory() + 'BASIS_silicon_111_Parameters.xml') - api.ConvertUnits(InputWorkspace=sam_ws, + api.ConvertUnits(InputWorkspace=sam_ws, OutputWorkspace=sam_ws, Target='Wavelength', EMode='Indirect') - + if not self._noMonNorm: - api.ModeratorTzeroLinear(InputWorkspace=mon_ws, + api.ModeratorTzeroLinear(InputWorkspace=mon_ws, OutputWorkspace=mon_ws) - api.Rebin(InputWorkspace=mon_ws, + api.Rebin(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Params='10') - api.ConvertUnits(InputWorkspace=mon_ws, - OutputWorkspace=mon_ws, + api.ConvertUnits(InputWorkspace=mon_ws, + OutputWorkspace=mon_ws, Target='Wavelength') api.OneMinusExponentialCor(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, - C='0.20749999999999999', + C='0.20749999999999999', C1='0.001276') - api.Scale(InputWorkspace=mon_ws, + api.Scale(InputWorkspace=mon_ws, OutputWorkspace=mon_ws, Factor='9.9999999999999995e-07') - api.RebinToWorkspace(WorkspaceToRebin=sam_ws, + api.RebinToWorkspace(WorkspaceToRebin=sam_ws, WorkspaceToMatch=mon_ws, OutputWorkspace=sam_ws) - api.Divide(LHSWorkspace=sam_ws, - RHSWorkspace=mon_ws, + api.Divide(LHSWorkspace=sam_ws, + RHSWorkspace=mon_ws, OutputWorkspace=sam_ws) - + # Register algorithm with Mantid. AlgorithmFactory.subscribe(BASISReduction) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py index 5842e460e1a5..5b911dc0137c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py @@ -20,9 +20,9 @@ def name(self): def summary(self): return "Calibrate the detector pixels and write a calibration file" - def PyInit(self): + def PyInit(self): sns = ConfigService.Instance().getFacility("SNS") - + instruments = [] for instr in sns.instruments(): for tech in instr.techniques(): @@ -33,11 +33,11 @@ def PyInit(self): StringListValidator(instruments)) validator = IntArrayBoundedValidator() validator.setLower(0) - self.declareProperty(IntArrayProperty("RunNumber", values=[0], direction=Direction.Input, + self.declareProperty(IntArrayProperty("RunNumber", values=[0], direction=Direction.Input, validator=validator)) validator = IntArrayBoundedValidator() validator.setLower(0) - self.declareProperty(IntArrayProperty("Background", values=[0], direction=Direction.Input, + self.declareProperty(IntArrayProperty("Background", values=[0], direction=Direction.Input, validator=validator)) extensions = [ "_event.nxs", "_runinfo.xml"] self.declareProperty("Extension", "_event.nxs", @@ -50,7 +50,7 @@ def PyInit(self): "Sum detector pixels in Y direction. Must be a factor of Y total pixels. Default is 1.") self.declareProperty("SmoothSummedOffsets", False, "If the data was summed for calibration, smooth the resulting offsets workspace.") - self.declareProperty("SmoothGroups", "", + self.declareProperty("SmoothGroups", "", "Comma delimited number of points for smoothing pixels in each group. Default is no Smoothing.") self.declareProperty("UnwrapRef", 0., "Reference total flight path for frame unwrapping. Zero skips the correction") @@ -60,7 +60,7 @@ def PyInit(self): "Maximum absolute value of offsets; default is 1") self.declareProperty("CrossCorrelation", True, "CrossCorrelation if True; minimize using many peaks if False.") - self.declareProperty("PeakPositions", "", + self.declareProperty("PeakPositions", "", "Comma delimited d-space positions of reference peaks. Use 1-3 for Cross Correlation. Unlimited for many peaks option.") self.declareProperty("PeakWindowMax", 0., "Maximum window around a peak to search for it. Optional.") @@ -97,9 +97,9 @@ def PyInit(self): outfiletypes = ['dspacemap', 'calibration', 'dspacemap and calibration'] self.declareProperty("SaveAs", "calibration", StringListValidator(outfiletypes)) self.declareProperty(FileProperty("OutputDirectory", "", FileAction.Directory)) - + self.declareProperty("OutputFilename", "", Direction.Output) - + return def validateInputs(self): @@ -130,7 +130,7 @@ def _loadPreNeXusData(self, runnumber, extension, **kwargs): """ Load PreNexus data @param runnumer: run number (integer) - @param extension: file extension + @param extension: file extension """ Logger("CalibrateRectangularDetector").warning("Loading PreNexus for run %s" % runnumber) mykwargs = {} @@ -155,7 +155,7 @@ def _loadEventNeXusData(self, runnumber, extension, **kwargs): """ Load event Nexus data @param runnumer: run number (integer) - @param extension: file extension + @param extension: file extension """ kwargs["Precount"] = False if self.getProperty("CompressOnRead").value: @@ -167,7 +167,7 @@ def _loadEventNeXusData(self, runnumber, extension, **kwargs): # For NOMAD data before Aug 2012, use the updated geometry if str(wksp.getInstrument().getValidFromDate()) == "1900-01-31T23:59:59" and str(self._instrument) == "NOMAD": path=config["instrumentDefinition.directory"] - LoadInstrument(Workspace=wksp, Filename=path+'/'+"NOMAD_Definition_20120701-20120731.xml", + LoadInstrument(Workspace=wksp, Filename=path+'/'+"NOMAD_Definition_20120701-20120731.xml", RewriteSpectraMap=False) return wksp @@ -196,7 +196,7 @@ def _loadData(self, runnumber, extension, filterWall=None): wksp = FilterBadPulses(InputWorkspace=wksp, OutputWorkspace=wksp.name()) if not self.getProperty("CompressOnRead").value: - wksp = CompressEvents(wksp, OutputWorkspace=wksp.name(), + wksp = CompressEvents(wksp, OutputWorkspace=wksp.name(), Tolerance=COMPRESS_TOL_TOF) # 100ns return wksp @@ -209,20 +209,20 @@ def _cccalibrate(self, wksp, calib): if LRef > 0: wksp = UnwrapSNS(InputWorkspace=wksp, OutputWorkspace=wksp.name(), LRef=LRef) if DIFCref > 0: - wksp = RemoveLowResTOF(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = RemoveLowResTOF(InputWorkspace=wksp, OutputWorkspace=wksp.name(), ReferenceDIFC=DIFCref) if not self.getProperty("CompressOnRead").value: - wksp = CompressEvents(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = CompressEvents(InputWorkspace=wksp, OutputWorkspace=wksp.name(), Tolerance=COMPRESS_TOL_TOF) # 100ns wksp = ConvertUnits(InputWorkspace=wksp, OutputWorkspace=wksp.name(), Target="dSpacing") SortEvents(InputWorkspace=wksp, SortBy="X Value") # Sum pixelbin X pixelbin blocks of pixels if self._xpixelbin*self._ypixelbin>1: - wksp = SumNeighbours(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = SumNeighbours(InputWorkspace=wksp, OutputWorkspace=wksp.name(), SumX=self._xpixelbin, SumY=self._ypixelbin) # Bin events in d-Spacing - wksp = Rebin(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = Rebin(InputWorkspace=wksp, OutputWorkspace=wksp.name(), Params=str(self._peakmin)+","+str(abs(self._binning[1]))+","+str(self._peakmax)) #Find good peak for reference ymax = 0 @@ -241,14 +241,14 @@ def _cccalibrate(self, wksp, calib): self._lastpixel = wksp.getNumberHistograms()-1 else: self._lastpixel = wksp.getNumberHistograms()*self._lastpixel/self._lastpixel3-1 - CrossCorrelate(InputWorkspace=wksp, OutputWorkspace=str(wksp)+"cc", - ReferenceSpectra=refpixel, WorkspaceIndexMin=0, - WorkspaceIndexMax=self._lastpixel, + CrossCorrelate(InputWorkspace=wksp, OutputWorkspace=str(wksp)+"cc", + ReferenceSpectra=refpixel, WorkspaceIndexMin=0, + WorkspaceIndexMax=self._lastpixel, XMin=self._peakmin, XMax=self._peakmax) # Get offsets for pixels using interval around cross correlations center and peak at peakpos (d-Spacing) - GetDetectorOffsets(InputWorkspace=str(wksp)+"cc", OutputWorkspace=str(wksp)+"offset", - Step=abs(self._binning[1]), DReference=self._peakpos1, - XMin=-self._ccnumber, XMax=self._ccnumber, + GetDetectorOffsets(InputWorkspace=str(wksp)+"cc", OutputWorkspace=str(wksp)+"offset", + Step=abs(self._binning[1]), DReference=self._peakpos1, + XMin=-self._ccnumber, XMax=self._ccnumber, MaxOffset=self._maxoffset, MaskWorkspace=str(wksp)+"mask") if AnalysisDataService.doesExist(str(wksp)+"cc"): AnalysisDataService.remove(str(wksp)+"cc") @@ -266,14 +266,14 @@ def _cccalibrate(self, wksp, calib): msg = "Reference spectra = %s, lastpixel_3 = %s" % (refpixel, self._lastpixel3) self.log().information(msg) self._lastpixel2 = wksp.getNumberHistograms()*self._lastpixel2/self._lastpixel3-1 - CrossCorrelate(InputWorkspace=wksp, OutputWorkspace=str(wksp)+"cc2", - ReferenceSpectra=refpixel, WorkspaceIndexMin=self._lastpixel+1, - WorkspaceIndexMax=self._lastpixel2, + CrossCorrelate(InputWorkspace=wksp, OutputWorkspace=str(wksp)+"cc2", + ReferenceSpectra=refpixel, WorkspaceIndexMin=self._lastpixel+1, + WorkspaceIndexMax=self._lastpixel2, XMin=self._peakmin2, XMax=self._peakmax2) # Get offsets for pixels using interval around cross correlations center and peak at peakpos (d-Spacing) - GetDetectorOffsets(InputWorkspace=str(wksp)+"cc2", OutputWorkspace=str(wksp)+"offset2", - Step=abs(self._binning[1]), DReference=self._peakpos2, - XMin=-self._ccnumber, XMax=self._ccnumber, + GetDetectorOffsets(InputWorkspace=str(wksp)+"cc2", OutputWorkspace=str(wksp)+"offset2", + Step=abs(self._binning[1]), DReference=self._peakpos2, + XMin=-self._ccnumber, XMax=self._ccnumber, MaxOffset=self._maxoffset, MaskWorkspace=str(wksp)+"mask2") Plus(LHSWorkspace=str(wksp)+"offset", RHSWorkspace=str(wksp)+"offset2", OutputWorkspace=str(wksp)+"offset") @@ -295,15 +295,15 @@ def _cccalibrate(self, wksp, calib): refpixel = s ymax = y_s[midBin] self.log().information("Reference spectra=%s" % refpixel) - CrossCorrelate(InputWorkspace=wksp, OutputWorkspace=str(wksp)+"cc3", + CrossCorrelate(InputWorkspace=wksp, OutputWorkspace=str(wksp)+"cc3", ReferenceSpectra=refpixel, - WorkspaceIndexMin=self._lastpixel2+1, - WorkspaceIndexMax=wksp.getNumberHistograms()-1, + WorkspaceIndexMin=self._lastpixel2+1, + WorkspaceIndexMax=wksp.getNumberHistograms()-1, XMin=self._peakmin3, XMax=self._peakmax3) # Get offsets for pixels using interval around cross correlations center and peak at peakpos (d-Spacing) - GetDetectorOffsets(InputWorkspace=str(wksp)+"cc3", OutputWorkspace=str(wksp)+"offset3", - Step=abs(self._binning[1]), DReference=self._peakpos3, - XMin=-self._ccnumber, XMax=self._ccnumber, + GetDetectorOffsets(InputWorkspace=str(wksp)+"cc3", OutputWorkspace=str(wksp)+"offset3", + Step=abs(self._binning[1]), DReference=self._peakpos3, + XMin=-self._ccnumber, XMax=self._ccnumber, MaxOffset=self._maxoffset, MaskWorkspace=str(wksp)+"mask3") Plus(LHSWorkspace=str(wksp)+"offset", RHSWorkspace=str(wksp)+"offset3", OutputWorkspace=str(wksp)+"offset") @@ -312,12 +312,12 @@ def _cccalibrate(self, wksp, calib): for ws in [str(wksp)+"cc3", str(wksp)+"offset3", str(wksp)+"mask3"]: if AnalysisDataService.doesExist(ws): AnalysisDataService.remove(ws) - (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping, + (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping, OutputWorkspace=str(wksp)+"group") if (numGroupedSpectra==0) or (numGroups==0): raise RuntimeError("%d spectra will be in %d groups" % (numGroupedSpectra, numGroups)) lcinst = str(self._instrument) - + outfilename = None if "dspacemap" in self._outTypes: #write Dspacemap file @@ -329,10 +329,10 @@ def _cccalibrate(self, wksp, calib): SaveCalFile(OffsetsWorkspace=str(wksp)+"offset", GroupingWorkspace=str(wksp)+"group", MaskWorkspace=str(wksp)+"mask",Filename=calib) - + if outfilename is not None: self.setProperty("OutputFilename", outfilename) - + return wksp def _multicalibrate(self, wksp, calib): @@ -344,10 +344,10 @@ def _multicalibrate(self, wksp, calib): if LRef > 0: wksp = UnwrapSNS(InputWorkspace=wksp, OutputWorkspace=wksp.name(), LRef=LRef) if DIFCref > 0: - wksp = RemoveLowResTOF(InputWorkspace=wksp, OutputWorkspace=wksp.name(), - ReferenceDIFC=DIFCref) + wksp = RemoveLowResTOF(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + ReferenceDIFC=DIFCref) if not self.getProperty("CompressOnRead").value and not "histo" in self.getProperty("Extension").value: - wksp = CompressEvents(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = CompressEvents(InputWorkspace=wksp, OutputWorkspace=wksp.name(), Tolerance=COMPRESS_TOL_TOF) # 100ns wksp = ConvertUnits(InputWorkspace=wksp, OutputWorkspace=wksp.name(), Target="dSpacing") @@ -355,18 +355,18 @@ def _multicalibrate(self, wksp, calib): SortEvents(InputWorkspace=wksp, SortBy="X Value") # Sum pixelbin X pixelbin blocks of pixels if self._xpixelbin*self._ypixelbin>1: - wksp = SumNeighbours(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = SumNeighbours(InputWorkspace=wksp, OutputWorkspace=wksp.name(), SumX=self._xpixelbin, SumY=self._ypixelbin) # Bin events in d-Spacing if not "histo" in self.getProperty("Extension").value: wksp = Rebin(InputWorkspace=wksp, OutputWorkspace=wksp.name(), Params=str(self._binning[0])+","+str((self._binning[1]))+","+str(self._binning[2])) - (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping, + (temp, numGroupedSpectra, numGroups) = CreateGroupingWorkspace(InputWorkspace=wksp, GroupDetectorsBy=self._grouping, OutputWorkspace=str(wksp)+"group") if (numGroupedSpectra==0) or (numGroups==0): raise RuntimeError("%d spectra will be in %d groups" % (numGroupedSpectra, numGroups)) if len(self._smoothGroups) > 0: - wksp = SmoothData(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = SmoothData(InputWorkspace=wksp, OutputWorkspace=wksp.name(), NPoints=self._smoothGroups, GroupingWorkspace=str(wksp)+"group") # Remove old calibration files cmd = "rm "+calib @@ -392,12 +392,12 @@ def _multicalibrate(self, wksp, calib): # Get offsets for pixels using interval around cross correlations center and peak at peakpos (d-Spacing) GetDetOffsetsMultiPeaks(InputWorkspace=str(wksp), OutputWorkspace=str(wksp)+"offset", - DReference=self._peakpos, - FitWindowMaxWidth=self.getProperty("PeakWindowMax").value, + DReference=self._peakpos, + FitWindowMaxWidth=self.getProperty("PeakWindowMax").value, MinimumPeakHeight=self.getProperty("MinimumPeakHeight").value, BackgroundType=self.getProperty("BackgroundType").value, - MaxOffset=self._maxoffset, NumberPeaksWorkspace=str(wksp)+"peaks", - MaskWorkspace=str(wksp)+"mask", + MaxOffset=self._maxoffset, NumberPeaksWorkspace=str(wksp)+"peaks", + MaskWorkspace=str(wksp)+"mask", FitwindowTableWorkspace = fitwinws, InputResolutionWorkspace=resws, MinimumResolutionFactor = reslowf, @@ -405,13 +405,13 @@ def _multicalibrate(self, wksp, calib): #Fixed SmoothNeighbours for non-rectangular and rectangular if self._smoothoffsets and self._xpixelbin*self._ypixelbin>1: # Smooth data if it was summed - SmoothNeighbours(InputWorkspace=str(wksp)+"offset", OutputWorkspace=str(wksp)+"offset", + SmoothNeighbours(InputWorkspace=str(wksp)+"offset", OutputWorkspace=str(wksp)+"offset", WeightedSum="Flat", AdjX=self._xpixelbin, AdjY=self._ypixelbin) wksp = Rebin(InputWorkspace=wksp, OutputWorkspace=wksp.name(), Params=str(self._binning[0])+","+str((self._binning[1]))+","+str(self._binning[2])) lcinst = str(self._instrument) - + outfilename = None if "dspacemap" in self._outTypes: #write Dspacemap file @@ -423,17 +423,17 @@ def _multicalibrate(self, wksp, calib): GroupingWorkspace=str(wksp)+"group", MaskWorkspace=str(wksp)+"mask", Filename=calib) outfilename = calib - + if outfilename is not None: self.setProperty("OutputFilename", outfilename) - + return wksp def _focus(self, wksp, calib): if wksp is None: return None MaskDetectors(Workspace=wksp, MaskedWorkspace=str(wksp)+"mask") - wksp = AlignDetectors(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = AlignDetectors(InputWorkspace=wksp, OutputWorkspace=wksp.name(), OffsetsWorkspace=str(wksp)+"offset") # Diffraction focusing using new calibration file with offsets if self._diffractionfocus: @@ -516,7 +516,7 @@ def PyExec(self): backRun = self._loadData(backNum, SUFFIX, filterWall) samRun -= backRun DeleteWorkspace(backRun) - samRun = CompressEvents(samRun, OutputWorkspace=samRun.name(), + samRun = CompressEvents(samRun, OutputWorkspace=samRun.name(), Tolerance=COMPRESS_TOL_TOF) # 100ns if self.getProperty("CrossCorrelation").value: samRun = self._cccalibrate(samRun, calib) @@ -530,10 +530,10 @@ def PyExec(self): DIFCref = self.getProperty("LowResRef").value if (LRef > 0.) or (DIFCref > 0.): # super special Jason stuff if LRef > 0: - wksp = UnwrapSNS(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = UnwrapSNS(InputWorkspace=wksp, OutputWorkspace=wksp.name(), LRef=LRef) if DIFCref > 0: - wksp = RemoveLowResTOF(InputWorkspace=wksp, OutputWorkspace=wksp.name(), + wksp = RemoveLowResTOF(InputWorkspace=wksp, OutputWorkspace=wksp.name(), ReferenceDIFC=DIFCref) else: samRun = ConvertUnits(InputWorkspace=samRun, OutputWorkspace=samRun.name(), diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py index b5bf9c608e32..9240f3fda25d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CheckForSampleLogs.py @@ -1,5 +1,5 @@ from mantid.api import PythonAlgorithm, AlgorithmFactory, WorkspaceProperty -import mantid.simpleapi +import mantid.simpleapi from mantid.kernel import Direction, logger from string import * @@ -10,7 +10,7 @@ def category(self): """ Return category """ return "PythonAlgorithms;Utility\\Workspaces" - + def name(self): """ Return name """ @@ -22,29 +22,29 @@ def summary(self): def PyInit(self): """ Declare properties """ - self.declareProperty(WorkspaceProperty("Workspace", "",Direction.Input), "The workspace to check.") - self.declareProperty("LogNames","","Names of the logs to look for") - self.declareProperty("Result","A string that will be empty if all the logs are found, otherwise will contain an error message",Direction.Output) + self.declareProperty(WorkspaceProperty("Workspace", "",Direction.Input), "The workspace to check.") + self.declareProperty("LogNames","","Names of the logs to look for") + self.declareProperty("Result","A string that will be empty if all the logs are found, otherwise will contain an error message",Direction.Output) return - + def PyExec(self): """ Main execution body """ - #get parameters - w = self.getProperty("Workspace").value - logNames = self.getProperty("LogNames").value - resultString='' - #check for parameters and build the result string - for value in logNames.split(','): - value=value.strip() - if len(value)>0: - if not w.run().hasProperty(value): - resultString+='Property '+value+' not found\n' - - #return the result - logger.notice(resultString) - self.setProperty("Result",resultString) - return - - + #get parameters + w = self.getProperty("Workspace").value + logNames = self.getProperty("LogNames").value + resultString='' + #check for parameters and build the result string + for value in logNames.split(','): + value=value.strip() + if len(value)>0: + if not w.run().hasProperty(value): + resultString+='Property '+value+' not found\n' + + #return the result + logger.notice(resultString) + self.setProperty("Result",resultString) + return + + AlgorithmFactory.subscribe(CheckForSampleLogs) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py index 03248eb07c83..78fa1e54ff87 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinFiles.py @@ -28,7 +28,7 @@ def __load(self, directory, instr, run, loader, exts, wksp): except Exception, e: logger.information(str(e)) pass - raise RuntimeError("Failed to load run %s from file %s" % (str(run), filename)) + raise RuntimeError("Failed to load run %s from file %s" % (str(run), filename)) def PyInit(self): greaterThanZero = IntArrayBoundedValidator() @@ -43,7 +43,7 @@ def PyExec(self): runs = self.getProperty("RunNumbers") instr = config.getInstrument().shortName() directory = self.getPropertyValue("Directory").strip() - + # change here if you want something other than gsas files exts = ['.txt', '.gsa'] loader = LoadGSS diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py index 897eaee623e5..f22e38a75532 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConjoinSpectra.py @@ -6,10 +6,10 @@ class ConjoinSpectra(PythonAlgorithm): """ Conjoins spectra from several workspaces into a single workspace - - Spectra to be conjoined must be equally binned in order for ConjoinSpectra to work. If necessary use RebinToWorkspace first. + + Spectra to be conjoined must be equally binned in order for ConjoinSpectra to work. If necessary use RebinToWorkspace first. """ - + def category(self): return "Transforms\\Merging;PythonAlgorithms" @@ -18,7 +18,7 @@ def name(self): def summmary(self): return "Joins individual spectra from a range of workspaces into a single workspace for plotting or further analysis." - + def PyInit(self): self.declareProperty("InputWorkspaces","", validator=StringMandatoryValidator(), doc="Comma seperated list of workspaces to use, group workspaces will automatically include all members.") self.declareProperty(WorkspaceProperty("OutputWorkspace", "", direction=Direction.Output), doc="Name the workspace that will contain the result") @@ -26,8 +26,8 @@ def PyInit(self): self.declareProperty("LabelUsing", "", doc="The name of a log value used to label the resulting spectra. Default: The source workspace name") labelValueOptions = ["Mean","Median","Maximum","Minimum","First Value"] self.declareProperty("LabelValue", "Mean", validator=StringListValidator(labelValueOptions), doc="How to derive the value from a time series property") - - + + def PyExec(self): # get parameter values wsOutput = self.getPropertyValue("OutputWorkspace") @@ -39,7 +39,7 @@ def PyExec(self): #internal values wsTemp = "__ConjoinSpectra_temp" loopIndex=0 - + #get the wokspace list wsNames = [] for wsName in wsString.split(","): @@ -59,7 +59,7 @@ def PyExec(self): for wsName in wsNames: #extract the spectrum ExtractSingleSpectrum(InputWorkspace=wsName,OutputWorkspace=wsTemp,WorkspaceIndex=wsIndex) - + labelString ="" if (labelUsing != ""): labelString = self.GetLogValue(mtd[wsName.strip()],labelUsing,labelValue) @@ -80,7 +80,7 @@ def PyExec(self): self.setProperty("OutputWorkspace",wsOut) - + def GetLogValue(self,ws,labelUsing,labelValue): labelString = "" run=ws.getRun() @@ -106,5 +106,5 @@ def GetLogValue(self,ws,labelUsing,labelValue): #log and pass out an empty string logger.information("Could not find log " + labelUsing + " in workspace " + str(ws) + " using workspace label instead.") return labelString - + AlgorithmFactory.subscribe(ConjoinSpectra) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py index e54df907acfd..93301070c0de 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ConvertSnsRoiFileToMask.py @@ -29,7 +29,7 @@ def name(self): def summary(self): return "This algorithm reads in an old SNS reduction ROI file and converts it into a Mantid mask workspace." - + def PyInit(self): """ Set the algorithm properties. @@ -40,10 +40,10 @@ def PyInit(self): extensions=EXTENSIONS), "SNS reduction ROI file to load.") allowedInstruments = kernel.StringListValidator(INSTRUMENTS) - self.declareProperty("Instrument", "", + self.declareProperty("Instrument", "", validator=allowedInstruments, doc="One of the following instruments: "+" ".join(INSTRUMENTS)) - self.declareProperty("OutputFilePrefix", "", + self.declareProperty("OutputFilePrefix", "", "Overrides the default filename for the output "\ +"file (Optional). Default is _Mask.") self.declareProperty(api.FileProperty(name="OutputDirectory", @@ -51,7 +51,7 @@ def PyInit(self): action=api.FileAction.Directory), "Directory to save mask file."\ +" Default is current Mantid save directory.") - + def PyExec(self): """ Execute the algorithm. @@ -60,8 +60,8 @@ def PyExec(self): self._instName = self.getProperty("Instrument").value self._filePrefix = self.getProperty("OutputFilePrefix").value self._outputDir = self.getProperty("OutputDirectory").value - - # Read in ROI file + + # Read in ROI file roi_file = open(self._roiFile) id_list = [] for line in roi_file: @@ -69,7 +69,7 @@ def PyExec(self): continue id_list.append(self._get_id(line)) roi_file.close() - + # Make XML DOM for "mask" import xml.dom.minidom doc = xml.dom.minidom.Document() @@ -81,28 +81,28 @@ def PyExec(self): detids = doc.createTextNode(",".join([str(x) for x in id_list])) det_node.appendChild(detids) grp_node.appendChild(det_node) - + # Create temporary "mask" file temp_file = "temp.xml" fh = open(temp_file, 'w') fh.write(doc.toprettyxml()) - fh.close() - + fh.close() + # Load and invert mask - mask_ws = msapi.LoadMask(InputFile=temp_file, + mask_ws = msapi.LoadMask(InputFile=temp_file, Instrument=self._instName) mask_ws = msapi.InvertMask(mask_ws) - + # Clean up temporary file os.remove(temp_file) - + # Save mask to a file if self._filePrefix == "": self._filePrefix = self._instName + "_Mask" - + output_file = os.path.join(self._outputDir, self._filePrefix) msapi.SaveMask(mask_ws, OutputFile=output_file+".xml") - + def _get_id(self, idx): """ Convert the old bankN_x_y pixel ID into a Mantid index. @@ -112,10 +112,10 @@ def _get_id(self, idx): det_size = TYPE2 else: det_size = TYPE1 - + parts = idx.split('_') bankid = int(parts[0].split('bank')[-1]) return int(parts[2]) + det_size[1] * (int(parts[1]) + det_size[0] * (bankid-1)) - + # Register algorithm with Mantid. api.AlgorithmFactory.subscribe(ConvertSnsRoiFileToMask) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py index d5450e62db11..2f2478c27b9a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CorrectLogTimes.py @@ -1,4 +1,4 @@ -import mantid.simpleapi +import mantid.simpleapi import mantid.api import mantid.kernel import numpy @@ -19,17 +19,17 @@ def name(self): def summary(self): return "This algorithm attempts to make the time series property logs start at the same time as the first time in the proton charge log." - + def PyInit(self): self.declareProperty(mantid.api.WorkspaceProperty("Workspace", "",direction=mantid.kernel.Direction.InOut), "Input workspace") - self.declareProperty("LogNames","",doc="Experimental log values to be shifted. If empty, will attempt to shift all logs") + self.declareProperty("LogNames","",doc="Experimental log values to be shifted. If empty, will attempt to shift all logs") def PyExec(self): self.ws = self.getProperty("Workspace").value logNames = self.getProperty("LogNames").value - + logList=[] - + #check for parameters and build the result string for value in logNames.split(','): value=value.strip() @@ -39,8 +39,8 @@ def PyExec(self): raise ValueError(err) else: logList.append(value) - - + + if len(logList)==0: logList=self.ws.getRun().keys() @@ -49,10 +49,10 @@ def PyExec(self): try: self.ShiftTime(x) except: - pass - - - def ShiftTime(self, logName): + pass + + + def ShiftTime(self, logName): """ shift the time in a given log to match the time in the proton charge log" """ @@ -61,6 +61,6 @@ def ShiftTime(self, logName): Tdiff = PC-P Tdiff_num = Tdiff.total_milliseconds()*1E-3 mantid.simpleapi.ChangeLogTime(InputWorkspace=self.ws, OutputWorkspace = self.ws, LogName = logName, TimeOffset = Tdiff_num) - - + + mantid.api.AlgorithmFactory.subscribe(CorrectLogTimes) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py index 9327afbc692c..162f572d05da 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateEmptyTableWorkspace.py @@ -10,11 +10,11 @@ def summary(self): def PyInit(self): # Declare properties self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), "The name of the table workspace that will be created.") - + def PyExec(self): tableWS = WorkspaceFactory.createTable() self.setProperty("OutputWorkspace", tableWS) - + # Register algorithm with Mantid AlgorithmFactory.subscribe(CreateEmptyTableWorkspace) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py index da5d0068f2f7..029a0c8ada2b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/CreateLeBailFitInput.py @@ -26,7 +26,7 @@ def summary(self): def PyInit(self): """ Declare properties - """ + """ #instruments=["POWGEN", "NOMAD", "VULCAN"] #self.declareProperty("Instrument", "POWGEN", StringListValidator(instruments), "Powder diffractometer's name") @@ -36,26 +36,26 @@ def PyInit(self): self.declareProperty(FileProperty("FullprofParameterFile", "", FileAction.Load, ['.irf']), "Fullprof's .irf file containing the peak parameters.") - self.declareProperty("GenerateBraggReflections", False, + self.declareProperty("GenerateBraggReflections", False, "Generate Bragg reflections other than reading a Fullprof .irf file. ") - + arrvalidator = IntArrayBoundedValidator() arrvalidator.setLower(0) - self.declareProperty(IntArrayProperty("MaxHKL", values=[12, 12, 12], validator=arrvalidator, + self.declareProperty(IntArrayProperty("MaxHKL", values=[12, 12, 12], validator=arrvalidator, direction=Direction.Input), "Maximum reflection (HKL) to generate") self.declareProperty("Bank", 1, "Bank ID for output if there are more than one bank in .irf file.") self.declareProperty("LatticeConstant", -0.0, validator=FloatBoundedValidator(lower=1.0E-9), doc="Lattice constant for cubic crystal.") - self.declareProperty(ITableWorkspaceProperty("InstrumentParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("InstrumentParameterWorkspace", "", Direction.Output), "Name of Table Workspace Containing Peak Parameters From .irf File.") - - self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Output), + + self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Output), "Name of Table Workspace Containing Peaks' Miller Indices From .prf File.") return - + def PyExec(self): """ Main Execution Body """ @@ -78,7 +78,7 @@ def PyExec(self): if len(hklmax) != 3: raise NotImplementedError("MaxHKL must have 3 integers") hklws = self.generateBraggReflections(hklmax) - else: + else: hklwsname = self.getProperty("BraggPeakParameterWorkspace").value hklws = self.importFullProfHKLFile(reflectionfilename, hklwsname) self.setProperty("BraggPeakParameterWorkspace", hklws) @@ -112,11 +112,11 @@ def importFullProfHKLFile(self, hklfilename, hklwsname): # api.DeleteWorkspace(Workspace=dummyws) # api.DeleteWorkspace(Workspace="TempXXX") - api.LoadFullprofFile( + api.LoadFullprofFile( Filename=hklfilename, PeakParameterWorkspace = hklwsname, OutputWorkspace = dummywsname) - + hklws = AnalysisDataService.retrieve(hklwsname) if hklws is None: raise NotImplementedError("Unable to retrieve LoadFullprofFile's output TempXXX from analysis data service.") @@ -132,10 +132,10 @@ def createPeakParameterWorkspace(self, irffilename): Note: 1. Sig-0, Sig-1 and Sig-2 in .irf file are actually the square of sig0, sig1 and sig2 defined in the manual - + Input: - irffilename: Resolution file (.irf) Can be single bank or multiple bank - + Output: - tableworkspace """ @@ -145,7 +145,7 @@ def createPeakParameterWorkspace(self, irffilename): # 2. Create an empty workspace tablews = WorkspaceFactory.createTable() - + tablews.addColumn("str", "Name") tablews.addColumn("double", "Value") tablews.addColumn("str", "FitOrTie") @@ -155,7 +155,7 @@ def createPeakParameterWorkspace(self, irffilename): numrows = irfws.rowCount() for ir in xrange(numrows): - tablews.addRow(["Parameter", 0.0, "tie", -1.0E200, 1.0E200, 1.0]) + tablews.addRow(["Parameter", 0.0, "tie", -1.0E200, 1.0E200, 1.0]) # 3. Copy between 2 workspace for ir in xrange(numrows): @@ -164,11 +164,11 @@ def createPeakParameterWorkspace(self, irffilename): # 4. Extra Lattice parameter latticepar = float(self.getPropertyValue("LatticeConstant")) - tablews.addRow(["LatticeConstant", latticepar, "tie", -1.0E200, 1.0E200, 1.0]) + tablews.addRow(["LatticeConstant", latticepar, "tie", -1.0E200, 1.0E200, 1.0]) # 5. Clean api.DeleteWorkspace(Workspace=irfwsname) - + return tablews @@ -188,9 +188,9 @@ def generateBraggReflections(self, hklmax): for h in xrange(0, max_m): for k in xrange(h, max_m): for l in xrange(k, max_m): - dsq = h*h + k*k + l*l + dsq = h*h + k*k + l*l if dsq <= max_hkl_sq: - if hkldict.has_key(dsq) is False: + if hkldict.has_key(dsq) is False: hkldict[dsq] = [] hkldict[dsq].append([h, k, l]) # ENDIF @@ -200,7 +200,7 @@ def generateBraggReflections(self, hklmax): # Create table workspace tablews = WorkspaceFactory.createTable() - + tablews.addColumn("int", "H") tablews.addColumn("int", "K") tablews.addColumn("int", "L") @@ -212,7 +212,7 @@ def generateBraggReflections(self, hklmax): tablews.addRow(hkl) return tablews - + # Register algorithm with Mantid AlgorithmFactory.subscribe(CreateLeBailFitInput) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py index 84dcec900ff2..e7720a121e5a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DSFinterp.py @@ -45,7 +45,7 @@ def PyInit(self): self.channelgroup = None def areWorkspacesCompatible(self, a, b): - sizeA = a.blocksize() * a.getNumberHistograms() + sizeA = a.blocksize() * a.getNumberHistograms() sizeB = b.blocksize() * b.getNumberHistograms() return sizeA == sizeB diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py index 7a671ccb7066..078934b4098a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/DakotaChiSquared.py @@ -1,6 +1,6 @@ from mantid.api import PythonAlgorithm, AlgorithmFactory,MatrixWorkspaceProperty,PropertyMode from mantid.kernel import Direction,IntBoundedValidator,FloatBoundedValidator -import mantid.simpleapi +import mantid.simpleapi import mantid import numpy from string import * @@ -12,7 +12,7 @@ def category(self): """ Return category """ return "PythonAlgorithms;Utility\\Workspaces" - + def name(self): """ Return name """ @@ -24,67 +24,67 @@ def summmary(self): def PyInit(self): """ Declare properties """ - f1=mantid.api.FileProperty("DataFile","",mantid.api.FileAction.Load,".nxs") - self.declareProperty(f1,"Input Nexus file containing data.") - f2=mantid.api.FileProperty("CalculatedFile","",mantid.api.FileAction.Load,".nxs") + f1=mantid.api.FileProperty("DataFile","",mantid.api.FileAction.Load,".nxs") + self.declareProperty(f1,"Input Nexus file containing data.") + f2=mantid.api.FileProperty("CalculatedFile","",mantid.api.FileAction.Load,".nxs") self.declareProperty(f2,"Input Nexus file containing calculated data.") - fout=mantid.api.FileProperty("OutputFile","",mantid.api.FileAction.Save,".xml") + fout=mantid.api.FileProperty("OutputFile","",mantid.api.FileAction.Save,".xml") self.declareProperty(fout,"Output filename containing chi^2.") - self.declareProperty("ChiSquared",0.0,Direction.Output) - self.declareProperty(MatrixWorkspaceProperty("ResidualsWorkspace", "",Direction.Output,PropertyMode.Optional), "The name of the workspace that will contain residuals.") - + self.declareProperty("ChiSquared",0.0,Direction.Output) + self.declareProperty(MatrixWorkspaceProperty("ResidualsWorkspace", "",Direction.Output,PropertyMode.Optional), "The name of the workspace that will contain residuals.") + return - + def PyExec(self): """ Main execution body """ - #get parameters - f1 = self.getProperty("DataFile").value - f2 = self.getProperty("CalculatedFile").value - fout = self.getProperty("OutputFile").value - - #load files + #get parameters + f1 = self.getProperty("DataFile").value + f2 = self.getProperty("CalculatedFile").value + fout = self.getProperty("OutputFile").value + + #load files __w1=mantid.simpleapi.Load(f1) - __w2=mantid.simpleapi.Load(f2) + __w2=mantid.simpleapi.Load(f2) - #validate inputs - if (type(__w1)!= mantid.api._api.MatrixWorkspace): - mantid.kernel.logger.error('Wrong workspace type for data file') - raise ValueError( 'Wrong workspace type for data file') - if (type(__w2)!= mantid.api._api.MatrixWorkspace): - mantid.kernel.logger.error('Wrong workspace type for calculated file') - raise ValueError( 'Wrong workspace type for calculated file') - if((__w1.blocksize()!=__w2.blocksize()) or (__w1.getNumberHistograms()!=__w2.getNumberHistograms())): - mantid.kernel.logger.error('The file sizes are different') - raise ValueError( 'The file sizes are different') - - #calculate chi^2 - soeName = self.getPropertyValue("ResidualsWorkspace") - if (len(soeName)>0): - mantid.simpleapi.SignalOverError(__w1-__w2,OutputWorkspace=soeName) - self.setProperty("ResidualsWorkspace",soeName) - __soe=mantid.mtd[soeName] - else: - __soe=mantid.simpleapi.SignalOverError(__w1-__w2) - __soe2=__soe*__soe - __soe2=mantid.simpleapi.ReplaceSpecialValues(__soe2,0,0,0,0) - - data=__soe2.extractY() - chisquared=numpy.sum(data) + #validate inputs + if (type(__w1)!= mantid.api._api.MatrixWorkspace): + mantid.kernel.logger.error('Wrong workspace type for data file') + raise ValueError( 'Wrong workspace type for data file') + if (type(__w2)!= mantid.api._api.MatrixWorkspace): + mantid.kernel.logger.error('Wrong workspace type for calculated file') + raise ValueError( 'Wrong workspace type for calculated file') + if((__w1.blocksize()!=__w2.blocksize()) or (__w1.getNumberHistograms()!=__w2.getNumberHistograms())): + mantid.kernel.logger.error('The file sizes are different') + raise ValueError( 'The file sizes are different') - #write out the Dakota chi squared file - f = open(fout,'w') - f.write(str(chisquared)+' obj_fn\n') - f.close() + #calculate chi^2 + soeName = self.getPropertyValue("ResidualsWorkspace") + if (len(soeName)>0): + mantid.simpleapi.SignalOverError(__w1-__w2,OutputWorkspace=soeName) + self.setProperty("ResidualsWorkspace",soeName) + __soe=mantid.mtd[soeName] + else: + __soe=mantid.simpleapi.SignalOverError(__w1-__w2) + __soe2=__soe*__soe + __soe2=mantid.simpleapi.ReplaceSpecialValues(__soe2,0,0,0,0) + + data=__soe2.extractY() + chisquared=numpy.sum(data) + + #write out the Dakota chi squared file + f = open(fout,'w') + f.write(str(chisquared)+' obj_fn\n') + f.close() self.setProperty("ChiSquared",chisquared) - - #cleanup - mantid.simpleapi.DeleteWorkspace(__w1.getName()) - mantid.simpleapi.DeleteWorkspace(__w2.getName()) - mantid.simpleapi.DeleteWorkspace(__soe2.getName()) - if (len(soeName)==0): - mantid.simpleapi.DeleteWorkspace(__soe.getName()) - + + #cleanup + mantid.simpleapi.DeleteWorkspace(__w1.getName()) + mantid.simpleapi.DeleteWorkspace(__w2.getName()) + mantid.simpleapi.DeleteWorkspace(__soe2.getName()) + if (len(soeName)==0): + mantid.simpleapi.DeleteWorkspace(__soe.getName()) + AlgorithmFactory.subscribe(DakotaChiSquared) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py index 38e6b1c5e21b..b7dcc6e08a22 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrate.py @@ -6,58 +6,58 @@ import math class EnginXCalibrate(PythonAlgorithm): - def category(self): - return "Diffraction\Engineering;PythonAlgorithms" - - def name(self): - return "EnginXCalibrate" - - def summary(self): - return "Calibrates a detector bank by performing a single peak fitting." - - def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), - "Calibration run to use") - - self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), - "A list of dSpacing values where peaks are expected.") - - self.declareProperty("Bank", 1, "Which bank to calibrate") - - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), - "Calibrated detector positions. If not specified, default ones are used.") - - self.declareProperty("Difc", 0.0, direction = Direction.Output, - doc = "Calibrated Difc value for the bank") - - self.declareProperty("Zero", 0.0, direction = Direction.Output, - doc = "Calibrated Zero value for the bank") - - def PyExec(self): - - ws = self._focusRun() - - fitPeaksAlg = self.createChildAlgorithm('EnginXFitPeaks') - fitPeaksAlg.setProperty('InputWorkspace', ws) - fitPeaksAlg.setProperty('WorkspaceIndex', 0) # There should be only one index anyway - fitPeaksAlg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) - fitPeaksAlg.execute() - - self.setProperty('Difc', fitPeaksAlg.getProperty('Difc').value) - self.setProperty('Zero', fitPeaksAlg.getProperty('Zero').value) - - def _focusRun(self): - alg = self.createChildAlgorithm('EnginXFocus') - alg.setProperty('Filename', self.getProperty('Filename').value) - alg.setProperty('Bank', self.getProperty('Bank').value) - - detPos = self.getProperty('DetectorPositions').value - if detPos: - alg.setProperty('DetectorPositions', detPos) - - alg.execute() - - return alg.getProperty('OutputWorkspace').value - - + def category(self): + return "Diffraction\Engineering;PythonAlgorithms" + + def name(self): + return "EnginXCalibrate" + + def summary(self): + return "Calibrates a detector bank by performing a single peak fitting." + + def PyInit(self): + self.declareProperty(FileProperty("Filename", "", FileAction.Load), + "Calibration run to use") + + self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), + "A list of dSpacing values where peaks are expected.") + + self.declareProperty("Bank", 1, "Which bank to calibrate") + + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), + "Calibrated detector positions. If not specified, default ones are used.") + + self.declareProperty("Difc", 0.0, direction = Direction.Output, + doc = "Calibrated Difc value for the bank") + + self.declareProperty("Zero", 0.0, direction = Direction.Output, + doc = "Calibrated Zero value for the bank") + + def PyExec(self): + + ws = self._focusRun() + + fitPeaksAlg = self.createChildAlgorithm('EnginXFitPeaks') + fitPeaksAlg.setProperty('InputWorkspace', ws) + fitPeaksAlg.setProperty('WorkspaceIndex', 0) # There should be only one index anyway + fitPeaksAlg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) + fitPeaksAlg.execute() + + self.setProperty('Difc', fitPeaksAlg.getProperty('Difc').value) + self.setProperty('Zero', fitPeaksAlg.getProperty('Zero').value) + + def _focusRun(self): + alg = self.createChildAlgorithm('EnginXFocus') + alg.setProperty('Filename', self.getProperty('Filename').value) + alg.setProperty('Bank', self.getProperty('Bank').value) + + detPos = self.getProperty('DetectorPositions').value + if detPos: + alg.setProperty('DetectorPositions', detPos) + + alg.execute() + + return alg.getProperty('OutputWorkspace').value + + AlgorithmFactory.subscribe(EnginXCalibrate) \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py index 3f3c15610fa4..8d359e41fe2a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXCalibrateFull.py @@ -3,132 +3,132 @@ import math class EnginXCalibrateFull(PythonAlgorithm): - def category(self): - return "Diffraction\Engineering;PythonAlgorithms" - - def name(self): - return "EnginXCalibrateFull" - - def summary(self): - return "Calibrates every pixel position by performing single peak fitting." - - def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), - "Calibration run to use") - - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Output), - "A table with calibrated detector positions as accepted by ApplyCalibration algorithm.") - - self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), - "A list of dSpacing values where peaks are expected.") - - self.declareProperty("Bank", 1, "Which bank to calibrate") - - def PyExec(self): - - import EnginXUtils - - ws = self._loadCalibrationRun() - - ws = self._prepareWsForFitting(ws) - - positionTable = self._createPositionsTable() - - indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) - - prog = Progress(self, 0, 1, len(indices)) - - for i in indices: - - _, difc = self._fitPeaks(ws, i) - - det = ws.getDetector(i) - - newPos = self._getCalibratedDetPos(difc, det, ws) - - positionTable.addRow([det.getID(), newPos]) - - prog.report() - - self.setProperty("DetectorPositions", positionTable) - - def _loadCalibrationRun(self): - """ Loads specified calibration run - """ - alg = self.createChildAlgorithm('Load') - alg.setProperty('Filename', self.getProperty('Filename').value) - alg.execute() - return alg.getProperty('OutputWorkspace').value - - def _prepareWsForFitting(self, ws): - """ Rebins the workspace and converts it to distribution - """ - rebinAlg = self.createChildAlgorithm('Rebin') - rebinAlg.setProperty('InputWorkspace', ws) - rebinAlg.setProperty('Params', '-0.0005') # The value is borrowed from OG routines - rebinAlg.execute() - result = rebinAlg.getProperty('OutputWorkspace').value + def category(self): + return "Diffraction\Engineering;PythonAlgorithms" + + def name(self): + return "EnginXCalibrateFull" + + def summary(self): + return "Calibrates every pixel position by performing single peak fitting." + + def PyInit(self): + self.declareProperty(FileProperty("Filename", "", FileAction.Load), + "Calibration run to use") + + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Output), + "A table with calibrated detector positions as accepted by ApplyCalibration algorithm.") + + self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), + "A list of dSpacing values where peaks are expected.") + + self.declareProperty("Bank", 1, "Which bank to calibrate") + + def PyExec(self): + + import EnginXUtils + + ws = self._loadCalibrationRun() + + ws = self._prepareWsForFitting(ws) + + positionTable = self._createPositionsTable() + + indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) + + prog = Progress(self, 0, 1, len(indices)) + + for i in indices: + + _, difc = self._fitPeaks(ws, i) + + det = ws.getDetector(i) + + newPos = self._getCalibratedDetPos(difc, det, ws) + + positionTable.addRow([det.getID(), newPos]) + + prog.report() + + self.setProperty("DetectorPositions", positionTable) + + def _loadCalibrationRun(self): + """ Loads specified calibration run + """ + alg = self.createChildAlgorithm('Load') + alg.setProperty('Filename', self.getProperty('Filename').value) + alg.execute() + return alg.getProperty('OutputWorkspace').value + + def _prepareWsForFitting(self, ws): + """ Rebins the workspace and converts it to distribution + """ + rebinAlg = self.createChildAlgorithm('Rebin') + rebinAlg.setProperty('InputWorkspace', ws) + rebinAlg.setProperty('Params', '-0.0005') # The value is borrowed from OG routines + rebinAlg.execute() + result = rebinAlg.getProperty('OutputWorkspace').value if result.isDistribution()==False: - convertAlg = self.createChildAlgorithm('ConvertToDistribution') - convertAlg.setProperty('Workspace', result) - convertAlg.execute() - - return result - - def _createPositionsTable(self): - """ Creates an empty table for storing detector positions - """ - alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') - alg.execute() - table = alg.getProperty('OutputWorkspace').value - - table.addColumn('int', 'Detector ID') - table.addColumn('V3D', 'Detector Position') - - return table - - def _fitPeaks(self, ws, wsIndex): - """ Fits expected peaks to the spectrum, and returns calibrated zero and difc values. - """ - alg = self.createChildAlgorithm('EnginXFitPeaks') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('WorkspaceIndex', wsIndex) # There should be only one index anyway - alg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) - alg.execute() - - difc = alg.getProperty('Difc').value - zero = alg.getProperty('Zero').value - - return (zero, difc) - - def _getCalibratedDetPos(self, newDifc, det, ws): - """ Returns a detector position which corresponds to the newDifc value. - - The two_theta and phi of the detector are preserved, L2 is changed. - """ - detL2 = det.getDistance(ws.getInstrument().getSample()) - detTwoTheta = ws.detectorTwoTheta(det) - detPhi = det.getPhi() - - newL2 = (newDifc / (252.816 * 2 * math.sin(detTwoTheta / 2.0))) - 50 - - newPos = self._V3DFromSpherical(newL2, detTwoTheta, detPhi) - - return newPos - - def _V3DFromSpherical(self, R, polar, azimuth): - """ Returns a cartesian 3D vector for the given spherical coordinates. - - Borrowed from V3D::spherical (C++). - """ - z = R*math.cos(polar) - ct=R*math.sin(polar) - x=ct*math.cos(azimuth) - y=ct*math.sin(azimuth) - - return V3D(x,y,z) - - - + convertAlg = self.createChildAlgorithm('ConvertToDistribution') + convertAlg.setProperty('Workspace', result) + convertAlg.execute() + + return result + + def _createPositionsTable(self): + """ Creates an empty table for storing detector positions + """ + alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') + alg.execute() + table = alg.getProperty('OutputWorkspace').value + + table.addColumn('int', 'Detector ID') + table.addColumn('V3D', 'Detector Position') + + return table + + def _fitPeaks(self, ws, wsIndex): + """ Fits expected peaks to the spectrum, and returns calibrated zero and difc values. + """ + alg = self.createChildAlgorithm('EnginXFitPeaks') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('WorkspaceIndex', wsIndex) # There should be only one index anyway + alg.setProperty('ExpectedPeaks', self.getProperty('ExpectedPeaks').value) + alg.execute() + + difc = alg.getProperty('Difc').value + zero = alg.getProperty('Zero').value + + return (zero, difc) + + def _getCalibratedDetPos(self, newDifc, det, ws): + """ Returns a detector position which corresponds to the newDifc value. + + The two_theta and phi of the detector are preserved, L2 is changed. + """ + detL2 = det.getDistance(ws.getInstrument().getSample()) + detTwoTheta = ws.detectorTwoTheta(det) + detPhi = det.getPhi() + + newL2 = (newDifc / (252.816 * 2 * math.sin(detTwoTheta / 2.0))) - 50 + + newPos = self._V3DFromSpherical(newL2, detTwoTheta, detPhi) + + return newPos + + def _V3DFromSpherical(self, R, polar, azimuth): + """ Returns a cartesian 3D vector for the given spherical coordinates. + + Borrowed from V3D::spherical (C++). + """ + z = R*math.cos(polar) + ct=R*math.sin(polar) + x=ct*math.cos(azimuth) + y=ct*math.sin(azimuth) + + return V3D(x,y,z) + + + AlgorithmFactory.subscribe(EnginXCalibrateFull) \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py index f452d490a6c9..bd80e9350b76 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFitPeaks.py @@ -5,183 +5,183 @@ import numpy as np class EnginXFitPeaks(PythonAlgorithm): - def category(self): - return "Diffraction\Engineering;PythonAlgorithms" - - def name(self): - return "EnginXFitPeaks" - - def summary(self): - return "The algorithm fits an expected diffraction pattern to a workpace spectrum by performing single peak fits." - - def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), - "Workspace to fit peaks in. ToF is expected X unit.") - - self.declareProperty("WorkspaceIndex", 0, - "Index of the spectra to fit peaks in") - - self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), - "A list of dSpacing values where peaks are expected.") - - self.declareProperty("Difc", 0.0, direction = Direction.Output, - doc = "Fitted Difc value") - - self.declareProperty("Zero", 0.0, direction = Direction.Output, - doc = "Fitted Zero value") - - def PyExec(self): - # Get expected peaks in TOF for the detector - expectedPeaksTof = self._expectedPeaksInTOF() - - # FindPeaks will returned a list of peaks sorted by the centre found. Sort the peaks as well, - # so we can match them with fitted centres later. - expectedPeaksTof = sorted(expectedPeaksTof) - expectedPeaksD = sorted(self.getProperty('ExpectedPeaks').value) - - # Find approximate peak positions, asumming Gaussian shapes - findPeaksAlg = self.createChildAlgorithm('FindPeaks') - findPeaksAlg.setProperty('InputWorkspace', self.getProperty("InputWorkspace").value) - findPeaksAlg.setProperty('PeakPositions', expectedPeaksTof) - findPeaksAlg.setProperty('PeakFunction', 'Gaussian') - findPeaksAlg.setProperty('WorkspaceIndex', self.getProperty("WorkspaceIndex").value) - findPeaksAlg.execute() - foundPeaks = findPeaksAlg.getProperty('PeaksList').value - - if (foundPeaks.rowCount() < len(expectedPeaksTof)): - raise Exception("Some peaks were not found") - - fittedPeaks = self._createFittedPeaksTable() - - for i in range(foundPeaks.rowCount()): - - row = foundPeaks.row(i) - - # Peak parameters estimated by FindPeaks - centre = row['centre'] - width = row['width'] - height = row['height'] - - # Sigma value of the peak, assuming Gaussian shape - sigma = width / (2 * math.sqrt(2 * math.log(2))) - - # Approximate peak intensity, assuming Gaussian shape - intensity = height * sigma * math.sqrt(2 * math.pi) - - peak = FunctionFactory.createFunction("BackToBackExponential") - peak.setParameter('X0', centre) - peak.setParameter('S', sigma) - peak.setParameter('I', intensity) - - # Magic numbers - COEF_LEFT = 2 - COEF_RIGHT = 3 - - # Try to predict a fit window for the peak - xMin = centre - (width * COEF_LEFT) - xMax = centre + (width * COEF_RIGHT) - - # Fit using predicted window and a proper function with approximated initital values - fitAlg = self.createChildAlgorithm('Fit') - fitAlg.setProperty('Function', 'name=LinearBackground;' + str(peak)) - fitAlg.setProperty('InputWorkspace', self.getProperty("InputWorkspace").value) - fitAlg.setProperty('WorkspaceIndex', self.getProperty("WorkspaceIndex").value) - fitAlg.setProperty('StartX', xMin) - fitAlg.setProperty('EndX', xMax) - fitAlg.setProperty('CreateOutput', True) - fitAlg.execute() - paramTable = fitAlg.getProperty('OutputParameters').value - - fittedParams = {} - fittedParams['dSpacing'] = expectedPeaksD[i] - fittedParams['Chi'] = fitAlg.getProperty('OutputChi2overDoF').value - self._addParametersToMap(fittedParams, paramTable) - - fittedPeaks.addRow(fittedParams) - - (difc, zero) = self._fitDSpacingToTOF(fittedPeaks) - - self.setProperty('Difc', difc) - self.setProperty('Zero', zero) - - def _fitDSpacingToTOF(self, fittedPeaksTable): - """ Fits a linear background to the dSpacing <-> TOF relationship and returns fitted difc - and zero values. - """ - convertTableAlg = self.createChildAlgorithm('ConvertTableToMatrixWorkspace') - convertTableAlg.setProperty('InputWorkspace', fittedPeaksTable) - convertTableAlg.setProperty('ColumnX', 'dSpacing') - convertTableAlg.setProperty('ColumnY', 'X0') - convertTableAlg.execute() - dSpacingVsTof = convertTableAlg.getProperty('OutputWorkspace').value - - # Fit the curve to get linear coefficients of TOF <-> dSpacing relationship for the detector - fitAlg = self.createChildAlgorithm('Fit') - fitAlg.setProperty('Function', 'name=LinearBackground') - fitAlg.setProperty('InputWorkspace', dSpacingVsTof) - fitAlg.setProperty('WorkspaceIndex', 0) - fitAlg.setProperty('CreateOutput', True) - fitAlg.execute() - paramTable = fitAlg.getProperty('OutputParameters').value - - zero = paramTable.cell('Value', 0) # A0 - difc = paramTable.cell('Value', 1) # A1 - - return (difc, zero) - - - def _expectedPeaksInTOF(self): - """ Converts expected peak dSpacing values to TOF values for the detector - """ - ws = self.getProperty("InputWorkspace").value - wsIndex = self.getProperty("WorkspaceIndex").value - - # Detector for specified spectrum - det = ws.getDetector(wsIndex) - - # Current detector parameters - detL2 = det.getDistance(ws.getInstrument().getSample()) - detTwoTheta = ws.detectorTwoTheta(det) - - # Function for converting dSpacing -> TOF for the detector - dSpacingToTof = lambda d: 252.816 * 2 * (50 + detL2) * math.sin(detTwoTheta / 2.0) * d - - expectedPeaks = self.getProperty("ExpectedPeaks").value - - # Expected peak positions in TOF for the detector - expectedPeaksTof = map(dSpacingToTof, expectedPeaks) - - return expectedPeaksTof - - - def _createFittedPeaksTable(self): - """ Creates a table where to put peak fitting results to - """ - alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') - alg.execute() - table = alg.getProperty('OutputWorkspace').value - - table.addColumn('double', 'dSpacing') - - for name in ['A0', 'A1', 'X0', 'A', 'B', 'S', 'I']: - table.addColumn('double', name) - table.addColumn('double', name + '_Err') - - table.addColumn('double', 'Chi') - - return table - - def _addParametersToMap(self, paramMap, paramTable): - """ Reads parameters from the Fit Parameter table, and add their values and errors to the map - """ - for i in range(paramTable.rowCount() - 1): # Skip the last (fit goodness) row - row = paramTable.row(i) - - # Get local func. param name. E.g., not f1.A0, but just A0 - name = (row['Name'].rpartition('.'))[2] - - paramMap[name] = row['Value'] - paramMap[name + '_Err'] = row['Error'] + def category(self): + return "Diffraction\Engineering;PythonAlgorithms" + + def name(self): + return "EnginXFitPeaks" + + def summary(self): + return "The algorithm fits an expected diffraction pattern to a workpace spectrum by performing single peak fits." + + def PyInit(self): + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), + "Workspace to fit peaks in. ToF is expected X unit.") + + self.declareProperty("WorkspaceIndex", 0, + "Index of the spectra to fit peaks in") + + self.declareProperty(FloatArrayProperty("ExpectedPeaks", ""), + "A list of dSpacing values where peaks are expected.") + + self.declareProperty("Difc", 0.0, direction = Direction.Output, + doc = "Fitted Difc value") + + self.declareProperty("Zero", 0.0, direction = Direction.Output, + doc = "Fitted Zero value") + + def PyExec(self): + # Get expected peaks in TOF for the detector + expectedPeaksTof = self._expectedPeaksInTOF() + + # FindPeaks will returned a list of peaks sorted by the centre found. Sort the peaks as well, + # so we can match them with fitted centres later. + expectedPeaksTof = sorted(expectedPeaksTof) + expectedPeaksD = sorted(self.getProperty('ExpectedPeaks').value) + + # Find approximate peak positions, asumming Gaussian shapes + findPeaksAlg = self.createChildAlgorithm('FindPeaks') + findPeaksAlg.setProperty('InputWorkspace', self.getProperty("InputWorkspace").value) + findPeaksAlg.setProperty('PeakPositions', expectedPeaksTof) + findPeaksAlg.setProperty('PeakFunction', 'Gaussian') + findPeaksAlg.setProperty('WorkspaceIndex', self.getProperty("WorkspaceIndex").value) + findPeaksAlg.execute() + foundPeaks = findPeaksAlg.getProperty('PeaksList').value + + if (foundPeaks.rowCount() < len(expectedPeaksTof)): + raise Exception("Some peaks were not found") + + fittedPeaks = self._createFittedPeaksTable() + + for i in range(foundPeaks.rowCount()): + + row = foundPeaks.row(i) + + # Peak parameters estimated by FindPeaks + centre = row['centre'] + width = row['width'] + height = row['height'] + + # Sigma value of the peak, assuming Gaussian shape + sigma = width / (2 * math.sqrt(2 * math.log(2))) + + # Approximate peak intensity, assuming Gaussian shape + intensity = height * sigma * math.sqrt(2 * math.pi) + + peak = FunctionFactory.createFunction("BackToBackExponential") + peak.setParameter('X0', centre) + peak.setParameter('S', sigma) + peak.setParameter('I', intensity) + + # Magic numbers + COEF_LEFT = 2 + COEF_RIGHT = 3 + + # Try to predict a fit window for the peak + xMin = centre - (width * COEF_LEFT) + xMax = centre + (width * COEF_RIGHT) + + # Fit using predicted window and a proper function with approximated initital values + fitAlg = self.createChildAlgorithm('Fit') + fitAlg.setProperty('Function', 'name=LinearBackground;' + str(peak)) + fitAlg.setProperty('InputWorkspace', self.getProperty("InputWorkspace").value) + fitAlg.setProperty('WorkspaceIndex', self.getProperty("WorkspaceIndex").value) + fitAlg.setProperty('StartX', xMin) + fitAlg.setProperty('EndX', xMax) + fitAlg.setProperty('CreateOutput', True) + fitAlg.execute() + paramTable = fitAlg.getProperty('OutputParameters').value + + fittedParams = {} + fittedParams['dSpacing'] = expectedPeaksD[i] + fittedParams['Chi'] = fitAlg.getProperty('OutputChi2overDoF').value + self._addParametersToMap(fittedParams, paramTable) + + fittedPeaks.addRow(fittedParams) + + (difc, zero) = self._fitDSpacingToTOF(fittedPeaks) + + self.setProperty('Difc', difc) + self.setProperty('Zero', zero) + + def _fitDSpacingToTOF(self, fittedPeaksTable): + """ Fits a linear background to the dSpacing <-> TOF relationship and returns fitted difc + and zero values. + """ + convertTableAlg = self.createChildAlgorithm('ConvertTableToMatrixWorkspace') + convertTableAlg.setProperty('InputWorkspace', fittedPeaksTable) + convertTableAlg.setProperty('ColumnX', 'dSpacing') + convertTableAlg.setProperty('ColumnY', 'X0') + convertTableAlg.execute() + dSpacingVsTof = convertTableAlg.getProperty('OutputWorkspace').value + + # Fit the curve to get linear coefficients of TOF <-> dSpacing relationship for the detector + fitAlg = self.createChildAlgorithm('Fit') + fitAlg.setProperty('Function', 'name=LinearBackground') + fitAlg.setProperty('InputWorkspace', dSpacingVsTof) + fitAlg.setProperty('WorkspaceIndex', 0) + fitAlg.setProperty('CreateOutput', True) + fitAlg.execute() + paramTable = fitAlg.getProperty('OutputParameters').value + + zero = paramTable.cell('Value', 0) # A0 + difc = paramTable.cell('Value', 1) # A1 + + return (difc, zero) + + + def _expectedPeaksInTOF(self): + """ Converts expected peak dSpacing values to TOF values for the detector + """ + ws = self.getProperty("InputWorkspace").value + wsIndex = self.getProperty("WorkspaceIndex").value + + # Detector for specified spectrum + det = ws.getDetector(wsIndex) + + # Current detector parameters + detL2 = det.getDistance(ws.getInstrument().getSample()) + detTwoTheta = ws.detectorTwoTheta(det) + + # Function for converting dSpacing -> TOF for the detector + dSpacingToTof = lambda d: 252.816 * 2 * (50 + detL2) * math.sin(detTwoTheta / 2.0) * d + + expectedPeaks = self.getProperty("ExpectedPeaks").value + + # Expected peak positions in TOF for the detector + expectedPeaksTof = map(dSpacingToTof, expectedPeaks) + + return expectedPeaksTof + + + def _createFittedPeaksTable(self): + """ Creates a table where to put peak fitting results to + """ + alg = self.createChildAlgorithm('CreateEmptyTableWorkspace') + alg.execute() + table = alg.getProperty('OutputWorkspace').value + + table.addColumn('double', 'dSpacing') + + for name in ['A0', 'A1', 'X0', 'A', 'B', 'S', 'I']: + table.addColumn('double', name) + table.addColumn('double', name + '_Err') + + table.addColumn('double', 'Chi') + + return table + + def _addParametersToMap(self, paramMap, paramTable): + """ Reads parameters from the Fit Parameter table, and add their values and errors to the map + """ + for i in range(paramTable.rowCount() - 1): # Skip the last (fit goodness) row + row = paramTable.row(i) + + # Get local func. param name. E.g., not f1.A0, but just A0 + name = (row['Name'].rpartition('.'))[2] + + paramMap[name] = row['Value'] + paramMap[name + '_Err'] = row['Error'] AlgorithmFactory.subscribe(EnginXFitPeaks) \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py index 5b76f375731a..7086f19c4b11 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/EnginXFocus.py @@ -2,124 +2,124 @@ from mantid.api import * class EnginXFocus(PythonAlgorithm): - def category(self): - return "Diffraction\Engineering;PythonAlgorithms" - - def name(self): - return "EnginXFocus" - - def summary(self): - return "Focuses a run." - - def PyInit(self): - self.declareProperty(FileProperty("Filename", "", FileAction.Load), - "Run to focus") - - self.declareProperty(WorkspaceProperty("OutputWorkspace", "", Direction.Output), - "A workspace with focussed data") - - self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), - "Calibrated detector positions. If not specified, default ones are used.") - - self.declareProperty("Bank", 1, "Which bank to focus") - - - - def PyExec(self): - # Load the run file - ws = self._loadRun() - - # Leave the data for the bank we are interested in only - ws = self._cropData(ws) - - # Apply calibration - self._applyCalibration(ws) - - # Convert to dSpacing - ws = self._convertToDSpacing(ws) - - # Sum the values - ws = self._sumSpectra(ws) - - # Convert back to time of flight - ws = self._convertToTOF(ws) - - # OpenGenie displays distributions instead of pure counts (this is done implicitly when - # converting units), so I guess that's what users will expect - self._convertToDistr(ws) - - self.setProperty("OutputWorkspace", ws) - - def _loadRun(self): - """ Loads the specified run - """ - alg = self.createChildAlgorithm('Load') - alg.setProperty('Filename', self.getProperty("Filename").value) - alg.execute() - return alg.getProperty('OutputWorkspace').value - - def _applyCalibration(self, ws): - """ Refines the detector positions using the result of calibration (if one is specified) - """ - detPos = self.getProperty("DetectorPositions").value - - if detPos: - alg = self.createChildAlgorithm('ApplyCalibration') - alg.setProperty('Workspace', ws) - alg.setProperty('PositionTable', detPos) - alg.execute() - - def _convertToDSpacing(self, ws): - """ Converts workspace to dSpacing - """ - alg = self.createChildAlgorithm('ConvertUnits') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('Target', 'dSpacing') - alg.setProperty('AlignBins', True) - alg.execute() - return alg.getProperty('OutputWorkspace').value - - def _convertToTOF(self, ws): - """ Converts workspace to TOF - """ - alg = self.createChildAlgorithm('ConvertUnits') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('Target', 'TOF') - alg.execute() - return alg.getProperty('OutputWorkspace').value - - def _convertToDistr(self, ws): - """ Convert workspace to distribution - """ - alg = self.createChildAlgorithm('ConvertToDistribution') - alg.setProperty('Workspace', ws) - alg.execute() - - def _cropData(self, ws): - """ Crops the workspace so that only data for the specified bank is left. - - NB: This assumes spectra for a bank are consequent. - """ - - import EnginXUtils - - indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) - - # Leave only spectra between min and max - alg = self.createChildAlgorithm('CropWorkspace') - alg.setProperty('InputWorkspace', ws) - alg.setProperty('StartWorkspaceIndex', min(indices)) - alg.setProperty('EndWorkspaceIndex', max(indices)) - alg.execute() - - return alg.getProperty('OutputWorkspace').value - - def _sumSpectra(self, ws): - """ Calls the SumSpectra algorithm - """ - alg = self.createChildAlgorithm('SumSpectra') - alg.setProperty('InputWorkspace', ws) - alg.execute() - return alg.getProperty('OutputWorkspace').value - + def category(self): + return "Diffraction\Engineering;PythonAlgorithms" + + def name(self): + return "EnginXFocus" + + def summary(self): + return "Focuses a run." + + def PyInit(self): + self.declareProperty(FileProperty("Filename", "", FileAction.Load), + "Run to focus") + + self.declareProperty(WorkspaceProperty("OutputWorkspace", "", Direction.Output), + "A workspace with focussed data") + + self.declareProperty(ITableWorkspaceProperty("DetectorPositions", "", Direction.Input, PropertyMode.Optional), + "Calibrated detector positions. If not specified, default ones are used.") + + self.declareProperty("Bank", 1, "Which bank to focus") + + + + def PyExec(self): + # Load the run file + ws = self._loadRun() + + # Leave the data for the bank we are interested in only + ws = self._cropData(ws) + + # Apply calibration + self._applyCalibration(ws) + + # Convert to dSpacing + ws = self._convertToDSpacing(ws) + + # Sum the values + ws = self._sumSpectra(ws) + + # Convert back to time of flight + ws = self._convertToTOF(ws) + + # OpenGenie displays distributions instead of pure counts (this is done implicitly when + # converting units), so I guess that's what users will expect + self._convertToDistr(ws) + + self.setProperty("OutputWorkspace", ws) + + def _loadRun(self): + """ Loads the specified run + """ + alg = self.createChildAlgorithm('Load') + alg.setProperty('Filename', self.getProperty("Filename").value) + alg.execute() + return alg.getProperty('OutputWorkspace').value + + def _applyCalibration(self, ws): + """ Refines the detector positions using the result of calibration (if one is specified) + """ + detPos = self.getProperty("DetectorPositions").value + + if detPos: + alg = self.createChildAlgorithm('ApplyCalibration') + alg.setProperty('Workspace', ws) + alg.setProperty('PositionTable', detPos) + alg.execute() + + def _convertToDSpacing(self, ws): + """ Converts workspace to dSpacing + """ + alg = self.createChildAlgorithm('ConvertUnits') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('Target', 'dSpacing') + alg.setProperty('AlignBins', True) + alg.execute() + return alg.getProperty('OutputWorkspace').value + + def _convertToTOF(self, ws): + """ Converts workspace to TOF + """ + alg = self.createChildAlgorithm('ConvertUnits') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('Target', 'TOF') + alg.execute() + return alg.getProperty('OutputWorkspace').value + + def _convertToDistr(self, ws): + """ Convert workspace to distribution + """ + alg = self.createChildAlgorithm('ConvertToDistribution') + alg.setProperty('Workspace', ws) + alg.execute() + + def _cropData(self, ws): + """ Crops the workspace so that only data for the specified bank is left. + + NB: This assumes spectra for a bank are consequent. + """ + + import EnginXUtils + + indices = EnginXUtils.getWsIndicesForBank(self.getProperty('Bank').value, ws) + + # Leave only spectra between min and max + alg = self.createChildAlgorithm('CropWorkspace') + alg.setProperty('InputWorkspace', ws) + alg.setProperty('StartWorkspaceIndex', min(indices)) + alg.setProperty('EndWorkspaceIndex', max(indices)) + alg.execute() + + return alg.getProperty('OutputWorkspace').value + + def _sumSpectra(self, ws): + """ Calls the SumSpectra algorithm + """ + alg = self.createChildAlgorithm('SumSpectra') + alg.setProperty('InputWorkspace', ws) + alg.execute() + return alg.getProperty('OutputWorkspace').value + AlgorithmFactory.subscribe(EnginXFocus) \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py index adae35841742..38539930d03c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExaminePowderDiffProfile.py @@ -27,60 +27,60 @@ def PyInit(self): """ Declare properties """ # Data file - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional), "Name of data workspace containing the diffraction pattern in .prf file. ") self.declareProperty(FileProperty("DataFilename","", FileAction.OptionalLoad, ['.dat']), "Name of input data file.") self.declareProperty("LoadData", False, "Option to load data other than reading from an existing data workspace.") - self.declareProperty("StartX", -0.0, "Minimum x value (TOF) to do the pattern calculation.") - self.declareProperty("EndX", -0.0, "Maximum x value (TOF) to do the pattern calculation.") + self.declareProperty("StartX", -0.0, "Minimum x value (TOF) to do the pattern calculation.") + self.declareProperty("EndX", -0.0, "Maximum x value (TOF) to do the pattern calculation.") # Peak profile type profiletypes = ["Back-to-back exponential convoluted with PseudoVoigt", "Thermal Neutron Back-to-back exponential convoluted with PseudoVoigt"] self.declareProperty("ProfileType", "Back-to-back exponential convoluted with PseudoVoigt", StringListValidator(profiletypes), "Type of peak profile.") - # Table workspaces - self.declareProperty(ITableWorkspaceProperty("ProfileWorkspace", "", Direction.InOut), + # Table workspaces + self.declareProperty(ITableWorkspaceProperty("ProfileWorkspace", "", Direction.InOut), "Name of table workspace containing peak parameters as input.") - self.declareProperty(ITableWorkspaceProperty("BraggPeakWorkspace", "", Direction.InOut), + self.declareProperty(ITableWorkspaceProperty("BraggPeakWorkspace", "", Direction.InOut), "Name of table workspace containing reflections (bragg peaks) in form of Miller index.") self.declareProperty(FileProperty("ProfileFilename","", FileAction.OptionalLoad, ['.irf']), "Name of input data file.") - self.declareProperty("GenerateInformationWS", False, "Optional to genearte profile table workspace and Bragg peak table. ") + self.declareProperty("GenerateInformationWS", False, "Optional to genearte profile table workspace and Bragg peak table. ") - # Background + # Background self.declareProperty(ITableWorkspaceProperty("BackgroundParameterWorkspace", "", Direction.InOut), "Name of table workspace containing background parameters.") - self.declareProperty("ProcessBackground", False, "Option to process background from input data file.") + self.declareProperty("ProcessBackground", False, "Option to process background from input data file.") backgroundtypes = ["Polynomial", "Chebyshev", "FullprofPolynomial"] - self.declareProperty("BackgroundType", "Polynomial", StringListValidator(backgroundtypes), "Type of background.") + self.declareProperty("BackgroundType", "Polynomial", StringListValidator(backgroundtypes), "Type of background.") arrvalidator = FloatArrayBoundedValidator() arrvalidator.setLower(0.) - self.declareProperty(FloatArrayProperty("BackgroundPoints", values=[], validator=arrvalidator, direction=Direction.Input), + self.declareProperty(FloatArrayProperty("BackgroundPoints", values=[], validator=arrvalidator, direction=Direction.Input), "User specified X/TOF values of the data points to calculate background.") - self.declareProperty(MatrixWorkspaceProperty("BackgroundWorkspace", "", Direction.Output, PropertyMode.Optional), + self.declareProperty(MatrixWorkspaceProperty("BackgroundWorkspace", "", Direction.Output, PropertyMode.Optional), "Name of data workspace containing the background data. ") # Output - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Name of data workspace containing the diffraction pattern in .prf file. ") return - + def PyExec(self): """ Main Execution Body """ # Process properties self.loaddata = self.getProperty("LoadData").value - if self.loaddata is False: - self.dataws = self.getProperty("InputWorkspace").value - self.datafilename = "" - else: - self.dataws = None - self.datafilename = self.getProperty("DataFilename") + if self.loaddata is False: + self.dataws = self.getProperty("InputWorkspace").value + self.datafilename = "" + else: + self.dataws = None + self.datafilename = self.getProperty("DataFilename") profiletype = self.getProperty("ProfileType").value if profiletype == "Back-to-back exponential convoluted with PseudoVoigt": @@ -88,27 +88,27 @@ def PyExec(self): else: self.profiletype = "ThermalNeutronBk2BkExpConvPVoigt" - self.loadinfofile = self.getProperty("GenerateInformationWS").value - if self.loadinfofile is True: - self.irffilename = self.getProperty("ProfileFilename").value - self.inputparamws = None - self.inputbraggws = None - else: - self.irffilename = "" - self.inputparamws = self.getProperty("ProfileWorkspace").value - self.inputbraggws = self.getProperty("BraggPeakWorkspace").value - - self.process_bkgd = self.getProperty("ProcessBackground").value - if self.process_bkgd is True: - self.backgroundtype = self.getProperty("BackgroundType").value - self.usrbkgdpoints = self.getProperty("BackgroundPoints").value - self.bkgdwsname = self.getProperty("BackgroundWorkspace").value - else: - self.bkgdtablews = self.getProperty("BackgroundParameterWorkspace").value - self.backgroundtype = self.getProperty("BackgroundType").value - - self.startx = self.getProperty("StartX").value - self.endx = self.getProperty("EndX").value + self.loadinfofile = self.getProperty("GenerateInformationWS").value + if self.loadinfofile is True: + self.irffilename = self.getProperty("ProfileFilename").value + self.inputparamws = None + self.inputbraggws = None + else: + self.irffilename = "" + self.inputparamws = self.getProperty("ProfileWorkspace").value + self.inputbraggws = self.getProperty("BraggPeakWorkspace").value + + self.process_bkgd = self.getProperty("ProcessBackground").value + if self.process_bkgd is True: + self.backgroundtype = self.getProperty("BackgroundType").value + self.usrbkgdpoints = self.getProperty("BackgroundPoints").value + self.bkgdwsname = self.getProperty("BackgroundWorkspace").value + else: + self.bkgdtablews = self.getProperty("BackgroundParameterWorkspace").value + self.backgroundtype = self.getProperty("BackgroundType").value + + self.startx = self.getProperty("StartX").value + self.endx = self.getProperty("EndX").value self.outwsname = self.getPropertyValue("OutputWorkspace") @@ -126,41 +126,41 @@ def PyExec(self): def mainExec(self): """ Main execution body """ - # Load data optionally - if self.loaddata is True: - # Load data file + # Load data optionally + if self.loaddata is True: + # Load data file api.LoadAscii( - Filename = self.datafilename, - OutputWorkspace = self.datawsname, + Filename = self.datafilename, + OutputWorkspace = self.datawsname, Unit = 'TOF' - ) - + ) + # Load .irf file and .hkl file optionally - if self.loadinfofile is True: - api.CreateLeBailFitInput( - FullprofParameterFile = self.irffilename, + if self.loadinfofile is True: + api.CreateLeBailFitInput( + FullprofParameterFile = self.irffilename, MaxHKL = [13, 13, 13], - LatticeConstant = float(self.latticesize), + LatticeConstant = float(self.latticesize), Bank = self.bankid, GenerateBraggReflections = True, InstrumentParameterWorkspace = str(self.inputparamws), BraggPeakParameterWorkspace = str(self.inputbraggws) ) - # Process background optionally + # Process background optionally if self.process_bkgd is True: # [Background] # Remove peaks and get pure background (hopefully) api.ProcessBackground( Options = 'SelectBackgroundPoints', - InputWorkspace = self.dataws, - OutputWorkspace = self.bkgdwsname, - LowerBound = self.startx, - UpperBound = self.endx, + InputWorkspace = self.dataws, + OutputWorkspace = self.bkgdwsname, + LowerBound = self.startx, + UpperBound = self.endx, BackgroundType = self.backgroundtype, BackgroundPoints= self.usrbkgdpoints, NoiseTolerance = '0.10000000000000001') - + # Fit background points functionstr = "name=%s,n=%d" % (self.backgroundtype, self.backgroundorder) for iborder in xrange(self.backgroundorder+1): @@ -174,20 +174,20 @@ def mainExec(self): CreateOutput = '1', StartX = self.startx, EndX = self.endx) - + # [Le Bail calculation] self.log().debug("Fit range: %f , %f, Outputworkspace = %s" % (self.startx, self.endx, self.outwsname)) api.LeBailFit( Function = 'Calculation', - InputWorkspace = self.dataws, + InputWorkspace = self.dataws, OutputWorkspace = self.outwsname, InputParameterWorkspace = self.inputparamws, OutputParameterWorkspace= str(self.inputparamws), InputHKLWorkspace = self.inputbraggws, OutputPeaksWorkspace = str(self.inputbraggws), - FitRegion = '%f, %f' % (self.startx, self.endx), + FitRegion = '%f, %f' % (self.startx, self.endx), BackgroundType = self.backgroundtype, - UseInputPeakHeights = False, + UseInputPeakHeights = False, PeakRadius = '7', BackgroundParametersWorkspace = self.bkgdtablews, PeakType = self.profiletype, diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py index 62242a5c74db..76cc78dc8a9d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py @@ -3,7 +3,7 @@ # # The following points are recommendations for writing Python algorithms: -# - The class name should match the file name; +# - The class name should match the file name; # - Each file should contain exactly one algorithm. # class Squares(PythonAlgorithm): @@ -11,12 +11,12 @@ class Squares(PythonAlgorithm): def PyInit(self): # Integer property. IntBoundedValidator restricts values to be greater than 0 self.declareProperty("MaxRange", -1, validator = IntBoundedValidator(lower=0), doc = "A value for the end of the range(inclusive)") - # String property. StringMandatoryValidator requires that the value not be empty + # String property. StringMandatoryValidator requires that the value not be empty self.declareProperty("Preamble", "", validator = StringMandatoryValidator(), doc = "Required preamble") self.declareProperty("Sum", False, doc = "If True, sum the squared values") self.declareProperty(FileProperty("OutputFile","", action=FileAction.Save, extensions=['txt'])) self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output), "A workspace containing the squares") - + def PyExec(self): msg = self.getProperty("Preamble").value # Convert to string endrange = self.getProperty("MaxRange").value # Convert to int @@ -49,7 +49,7 @@ def PyExec(self): sumfile = open(filename,'w') sumfile.write('The sum of the squares of numbers up to ' + str(endrange) + ' is: ' + str(sum) + '\n') sumfile.close() - + ############################################################################################# AlgorithmFactory.subscribe(Squares) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py index 687bdfcf1036..078391f5afce 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py @@ -7,60 +7,60 @@ import datetime class ExportExperimentLog(PythonAlgorithm): - + """ Algorithm to export experiment log """ - + def summmary(self): return "Exports experimental log." def PyInit(self): """ Declaration of properties - """ + """ # wsprop = mantid.api.MatrixWorkspaceProperty("InputWorkspace", "", mantid.kernel.Direction.Input) wsprop = MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input) self.declareProperty(wsprop, "Input workspace containing the sample log information. ") - + self.declareProperty(FileProperty("OutputFilename","", FileAction.Save, ['.txt, .csv']), "Output file of the experiment log.") - + filemodes = ["append", "fastappend", "new"] self.declareProperty("FileMode", "append", mantid.kernel.StringListValidator(filemodes), "Optional to create a new file or append to an existing file.") - + lognameprop = StringArrayProperty("SampleLogNames", values=[], direction=Direction.Input) self.declareProperty(lognameprop, "Sample log names.") - + logtitleprop = StringArrayProperty("SampleLogTitles", values=[], direction=Direction.Input) self.declareProperty(logtitleprop, "Log sample titles as file header.") logoperprop = StringArrayProperty("SampleLogOperation", values=[], direction=Direction.Input) self.declareProperty(logoperprop, "Operation on each log, including None (as no operation), min, max, average, sum and \"0\". ") - + fileformates = ["tab", "comma (csv)"] des = "Output file format. 'tab' format will insert a tab between 2 adjacent values; 'comma' will put a , instead. " + \ "With this option, the posfix of the output file is .csv automatically. " self.declareProperty("FileFormat", "tab", mantid.kernel.StringListValidator(fileformates), des) - # Time zone - timezones = ["UTC", "America/New_York"] + # Time zone + timezones = ["UTC", "America/New_York"] self.declareProperty("TimeZone", "America/New_York", StringListValidator(timezones)) - - + + return - - + + def PyExec(self): """ Main execution body """ # Process inputs self._processInputs() - + # Get sample log's value valuedict = self._getSampleLogsValue() if valuedict is None: return - + # Load input if self._filemode == "append": same = self._examineLogFile() @@ -72,32 +72,32 @@ def PyExec(self): # ENDIFELSE # ENDIF (same) # ENDIF (filemode) - + # Write file if self._filemode == "new": # Create log file and write header self._createLogFile() - - # Append the new experiment log + + # Append the new experiment log self._appendExpLog(valuedict) - + return - + def _processInputs(self): """ Process input properties """ import os import os.path - + self._wksp = self.getProperty("InputWorkspace").value - + self._logfilename = self.getProperty("OutputFilename").value - + # Field and keys self._headerTitles = self.getProperty("SampleLogTitles").value self._sampleLogNames = self.getProperty("SampleLogNames").value ops = self.getProperty("SampleLogOperation").value - + if len(self._sampleLogNames) != len(ops): raise NotImplementedError("Size of sample log names and sample operations are unequal!") self._sampleLogOperations = {} @@ -106,35 +106,35 @@ def _processInputs(self): value = ops[i] self._sampleLogOperations[key] = value # ENDFOR - + if len(self._headerTitles) > 0 and len(self._headerTitles) != len(self._sampleLogNames): raise NotImplementedError("Input header titles have a different length to sample log names") - - # Determine file mode + + # Determine file mode if os.path.exists(self._logfilename) is False: self._filemode = "new" if len(self._headerTitles) == 0: raise NotImplementedError("Without specifying header title, unable to new a file.") else: self._filemode = self.getProperty("FileMode").value - + # Examine the file mode if self._filemode == "new" or self._filemode == "append": if len(self._headerTitles) != len(self._sampleLogNames): raise NotImplementedError("In mode new or append, there must be same number of sample titles and names") - + self.log().notice("File mode is %s. " % (self._filemode)) - # This is left for a feature that might be needed in future. + # This is left for a feature that might be needed in future. self._reorderOld = False - + # Output file format self._fileformat = self.getProperty("FileFormat").value if self._fileformat == "tab": self._valuesep = "\t" else: self._valuesep = "," - + # Output file's postfix if self._fileformat == "comma (csv)": fileName, fileExtension = os.path.splitext(self._logfilename) @@ -142,23 +142,23 @@ def _processInputs(self): # Force the extension of the output file to be .csv self._logfilename = "%s.csv" % (fileName) - self._timezone = self.getProperty("TimeZone").value - + self._timezone = self.getProperty("TimeZone").value + return - + def _createLogFile(self): """ Create a log file """ if len(self._headerTitles) == 0: raise NotImplementedError("No header title specified. Unable to write a new file.") - + wbuf = "" for ititle in xrange(len(self._headerTitles)): title = self._headerTitles[ititle] wbuf += "%s" % (title) if ititle < len(self._headerTitles)-1: wbuf += self._valuesep - + try: ofile = open(self._logfilename, "w") ofile.write(wbuf) @@ -166,14 +166,14 @@ def _createLogFile(self): except OSError as err: raise NotImplementedError("Unable to write file %s. Check permission. Error message %s." % ( self._logfilename, str(err))) - + return - + def _examineLogFile(self): - """ Examine existing log file. + """ Examine existing log file. If the titles in the existing log file are different from the inputs, then the old file will be saved - """ + """ # Parse old file try: logfile = open(self._logfilename, "r") @@ -182,16 +182,16 @@ def _examineLogFile(self): except OSError as err: raise NotImplementedError("Unable to read existing log file %s. Error: %s." % ( self._logfilename, str(err))) - + # Find the title line: first none-empty line for line in lines: titleline = line.strip() if len(titleline) > 0: break - + # Examine titles = titleline.split() - + same = True if len(titles) != len(self._headerTitles): same = False @@ -203,31 +203,31 @@ def _examineLogFile(self): break # ENDIF # ENDFOR - + return same - - + + def _startNewFile(self): """ Start a new file is user wants and save the older one to a different name """ import datetime import time import os - + # Rename old file and reset the file mode - + # Rename the old one: split path from file, new name, and rename fileName, fileExtension = os.path.splitext(self._logfilename) - + now = datetime.datetime.now() nowstr = time.strftime("%Y_%B_%d_%H_%M") newfilename = fileName + "_" + nowstr + fileExtension os.rename(self._logfilename, newfilename) - + # Reset the file mode self._filemode = "new" - + return @@ -248,16 +248,16 @@ def _appendExpLog(self, logvaluedict): lfile = open(self._logfilename, "a") lfile.write("\n%s" %(wbuf)) lfile.close() - + return - + def _reorderExistingFile(self): - """ Re-order the columns of the existing experimental log file + """ Re-order the columns of the existing experimental log file """ raise NotImplementedError("Too complicated") - + return - + def _getSampleLogsValue(self): """ From the workspace to get the value """ @@ -269,11 +269,11 @@ def _getSampleLogsValue(self): self.log().error("There is no Run object associated with workspace %s. " % ( str(self._wksp))) return None - + for logname in self._sampleLogNames: isexist = run.hasProperty(logname) - - # check whether this property does exist. + + # check whether this property does exist. if isexist is False: # If not exist, use 0.00 as default self.log().warning("Sample log %s does not exist in given workspace %s. " % (logname, str(self._wksp))) @@ -281,7 +281,7 @@ def _getSampleLogsValue(self): continue logproperty = run.getProperty(logname) - logclass = logproperty.__class__.__name__ + logclass = logproperty.__class__.__name__ # Get log value according to type if logclass == "StringPropertyWithValue": @@ -307,10 +307,10 @@ def _getSampleLogsValue(self): raise NotImplementedError("Operation %s for FloatTimeSeriesProperty %s is not supported." % (operationtype, logname)) else: raise NotImplementedError("Class type %d is not supported." % (logclass)) - + valuedict[logname] = propertyvalue # ENDFOR - + return valuedict @@ -327,11 +327,11 @@ def _convertLocalTimeString(self, utctimestr): from_zone = tz.gettz('UTC') to_zone = tz.gettz(self._timezone) - try: + try: if utctimestr.count(".") == 1: tail = utctimestr.split(".")[1] extralen = len(tail)-6 - extra = utctimestr[-extralen:] + extra = utctimestr[-extralen:] utctimestr = utctimestr[0:-extralen] utctime = datetime.strptime(utctimestr, '%Y-%m-%dT%H:%M:%S.%f') except ValueError as err: @@ -344,6 +344,6 @@ def _convertLocalTimeString(self, utctimestr): localtimestr = localtime.strftime("%Y-%m-%d %H:%M:%S.%f") + extra return localtimestr - + # Register algorithm with Mantid AlgorithmFactory.subscribe(ExportExperimentLog) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py index 5a9e4f301229..4a5bfc85f8d4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/ExportSampleLogsToCSVFile.py @@ -5,169 +5,169 @@ import datetime class ExportSampleLogsToCSVFile(PythonAlgorithm): - """ Python algorithm to export sample logs to spread sheet file + """ Python algorithm to export sample logs to spread sheet file for VULCAN """ def category(self): - """ Category - """ + """ Category + """ return "Utility;PythonAlgorithms" def name(self): - """ Algorithm name - """ + """ Algorithm name + """ return "ExportSampleLogsToCSVFile" def summary(self): return "Exports sample logs to spreadsheet file." def PyInit(self): - """ Declare properties - """ - # Input workspace - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), - "Name of data workspace containing sample logs to be exported. ") - - # Output file name - self.declareProperty(FileProperty("OutputFilename", "", FileAction.Save, [".txt"]), - "Name of the output sample environment log file name.") - - # Sample log names - self.declareProperty(StringArrayProperty("SampleLogNames", values=[], direction=Direction.Input), + """ Declare properties + """ + # Input workspace + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), + "Name of data workspace containing sample logs to be exported. ") + + # Output file name + self.declareProperty(FileProperty("OutputFilename", "", FileAction.Save, [".txt"]), + "Name of the output sample environment log file name.") + + # Sample log names + self.declareProperty(StringArrayProperty("SampleLogNames", values=[], direction=Direction.Input), "Names of sample logs to be exported in a same file.") - # Header - self.declareProperty("WriteHeaderFile", False, "Flag to generate a sample log header file.") + # Header + self.declareProperty("WriteHeaderFile", False, "Flag to generate a sample log header file.") - self.declareProperty("Header", "", "String in the header file.") + self.declareProperty("Header", "", "String in the header file.") - # Time zone - timezones = ["America/New_York"] + # Time zone + timezones = ["America/New_York"] self.declareProperty("TimeZone", "America/New_York", StringListValidator(timezones)) - # Log time tolerance - self.declareProperty("TimeTolerance", 0.01, - "If any 2 log entries with log times within the time tolerance, they will be recorded in one line. Unit is second. ") + # Log time tolerance + self.declareProperty("TimeTolerance", 0.01, + "If any 2 log entries with log times within the time tolerance, they will be recorded in one line. Unit is second. ") - return + return def PyExec(self): - """ Main executor - """ - # Read inputs - self._getProperties() - - # Read in logs - logtimesdict, logvaluedict, loglength = self._readSampleLogs() - - # Local time difference - localtimediff = self._calLocalTimeDiff(logtimesdict, loglength) - - # Write log file - # self._writeLogFile(logtimesdict, logvaluedict, loglength, localtimediff) - logtimeslist = [] - logvaluelist = [] - for logname in self._sampleloglist: - logtimeslist.append(logtimesdict[logname]) - logvaluelist.append(logvaluedict[logname]) - self._writeAscynLogFile(logtimeslist, logvaluelist, localtimediff, self._timeTolerance) - - # Write header file - if self._writeheader is True: - testdatetime = self._wksp.getRun().getProperty("run_start").value - description = "Type your description here" - self._writeHeaderFile(testdatetime, description) - - return - - + """ Main executor + """ + # Read inputs + self._getProperties() + + # Read in logs + logtimesdict, logvaluedict, loglength = self._readSampleLogs() + + # Local time difference + localtimediff = self._calLocalTimeDiff(logtimesdict, loglength) + + # Write log file + # self._writeLogFile(logtimesdict, logvaluedict, loglength, localtimediff) + logtimeslist = [] + logvaluelist = [] + for logname in self._sampleloglist: + logtimeslist.append(logtimesdict[logname]) + logvaluelist.append(logvaluedict[logname]) + self._writeAscynLogFile(logtimeslist, logvaluelist, localtimediff, self._timeTolerance) + + # Write header file + if self._writeheader is True: + testdatetime = self._wksp.getRun().getProperty("run_start").value + description = "Type your description here" + self._writeHeaderFile(testdatetime, description) + + return + + def _getProperties(self): - """ Get and process properties - """ - self._wksp = self.getProperty("InputWorkspace").value + """ Get and process properties + """ + self._wksp = self.getProperty("InputWorkspace").value + + self._outputfilename = self.getProperty("OutputFilename").value + filedir = os.path.split(self._outputfilename)[0] + if os.path.exists(filedir) is False: + raise NotImplementedError("Directory %s does not exist. File cannot be written." % (filedir)) - self._outputfilename = self.getProperty("OutputFilename").value - filedir = os.path.split(self._outputfilename)[0] - if os.path.exists(filedir) is False: - raise NotImplementedError("Directory %s does not exist. File cannot be written." % (filedir)) + self._sampleloglist = self.getProperty("SampleLogNames").value + if len(self._sampleloglist) == 0: + raise NotImplementedError("Sample logs names cannot be empty.") - self._sampleloglist = self.getProperty("SampleLogNames").value - if len(self._sampleloglist) == 0: - raise NotImplementedError("Sample logs names cannot be empty.") + self._writeheader = self.getProperty("WriteHeaderFile").value + self._headercontent = self.getProperty("Header").value + if self._writeheader is True and len(self._headercontent.strip()) == 0: + self.log().warning("Header is empty. Thus WriteHeaderFile is forced to be False.") + self._writeheader = False - self._writeheader = self.getProperty("WriteHeaderFile").value - self._headercontent = self.getProperty("Header").value - if self._writeheader is True and len(self._headercontent.strip()) == 0: - self.log().warning("Header is empty. Thus WriteHeaderFile is forced to be False.") - self._writeheader = False + self._timezone = self.getProperty("TimeZone").value - self._timezone = self.getProperty("TimeZone").value + self._timeTolerance = self.getProperty("TimeTolerance").value + if (self._timeTolerance) <= 0.: + raise NotImplementedError("TimeTolerance must be larger than zero.") - self._timeTolerance = self.getProperty("TimeTolerance").value - if (self._timeTolerance) <= 0.: - raise NotImplementedError("TimeTolerance must be larger than zero.") + return - return - def _calLocalTimeDiff(self, logtimesdict, loglength): - """ Calcualte the time difference between local time and UTC in seconds - """ - # Find out local time - if loglength > 0: - # Locate time0 - for key in logtimesdict.keys(): - times = logtimesdict[key] - if times is not None: - time0 = logtimesdict[key][0] - break - # Local time difference - localtimediff = getLocalTimeShiftInSecond(time0, self._timezone, self.log()) - else: - localtimediff = 0 - - return localtimediff + """ Calcualte the time difference between local time and UTC in seconds + """ + # Find out local time + if loglength > 0: + # Locate time0 + for key in logtimesdict.keys(): + times = logtimesdict[key] + if times is not None: + time0 = logtimesdict[key][0] + break + # Local time difference + localtimediff = getLocalTimeShiftInSecond(time0, self._timezone, self.log()) + else: + localtimediff = 0 + + return localtimediff def _writeLogFile(self, logtimesdict, logvaluedict, loglength, localtimediff): - """ Write the logs to file - """ - wbuf = "" - - # Init time - if loglength > 0: - for log in logtimesdict.keys(): - if logtimesdict[log] is not None: - time0 = logtimesdict[log][0] - abstime_init = time0.totalNanoseconds() * 1.E-9 - localtimediff - times = logtimesdict[log] - break - - # Loop - for i in xrange(loglength): - abstime = times[i].totalNanoseconds() * 1.E-9 - localtimediff - reltime = abstime - abstime_init - # Write absoute time and relative time - wbuf += "%.6f\t%.6f\t" % (abstime, reltime) - # Write each log value + """ Write the logs to file + """ + wbuf = "" + + # Init time + if loglength > 0: + for log in logtimesdict.keys(): + if logtimesdict[log] is not None: + time0 = logtimesdict[log][0] + abstime_init = time0.totalNanoseconds() * 1.E-9 - localtimediff + times = logtimesdict[log] + break + + # Loop + for i in xrange(loglength): + abstime = times[i].totalNanoseconds() * 1.E-9 - localtimediff + reltime = abstime - abstime_init + # Write absoute time and relative time + wbuf += "%.6f\t%.6f\t" % (abstime, reltime) + # Write each log value for samplelog in self._sampleloglist: - if logvaluedict[samplelog] is not None: - logvalue = logvaluedict[samplelog][i] - else: - logvalue = 0. - wbuf += "%.6f\t" % (logvalue) - wbuf += "\n" - # ENDFOR - - try: - ofile = open(self._outputfilename, "w") - ofile.write(wbuf) - ofile.close() - except IOError as err: - raise NotImplementedError("Unable to write file %s. Check permission." % (self._outputfilename)) - - return + if logvaluedict[samplelog] is not None: + logvalue = logvaluedict[samplelog][i] + else: + logvalue = 0. + wbuf += "%.6f\t" % (logvalue) + wbuf += "\n" + # ENDFOR + + try: + ofile = open(self._outputfilename, "w") + ofile.write(wbuf) + ofile.close() + except IOError as err: + raise NotImplementedError("Unable to write file %s. Check permission." % (self._outputfilename)) + + return def _getLogsInfo(self, logtimeslist): """ Get maximum number of lines, staring time and ending time in the output log file @@ -175,14 +175,14 @@ def _getLogsInfo(self, logtimeslist): maxnumlines = 0 first = True for logtimes in logtimeslist: - # skip NONE + # skip NONE if logtimes is None: continue # count on lines tmplines = len(logtimes) maxnumlines += tmplines - + # start and max time tmpstarttime = logtimes[0] tmpmaxtime = logtimes[-1] @@ -191,7 +191,7 @@ def _getLogsInfo(self, logtimeslist): maxtime = tmpmaxtime first = False else: - if tmpmaxtime > maxtime: + if tmpmaxtime > maxtime: maxtime = tmpmaxtime if tmpstarttime < starttime: starttime = tmpstarttime @@ -201,234 +201,234 @@ def _getLogsInfo(self, logtimeslist): def _writeAscynLogFile(self, logtimeslist, logvaluelist, localtimediff, timetol): - """ Logs are recorded upon the change of the data - time tolerance : two log entries within time tolerance will be recorded as one - Arguments - - timetol : tolerance of time (in second) - """ + """ Logs are recorded upon the change of the data + time tolerance : two log entries within time tolerance will be recorded as one + Arguments + - timetol : tolerance of time (in second) + """ # Check input if logtimeslist.__class__.__name__ != "list": raise NotImplementedError("Input log times is not list") if logvaluelist.__class__.__name__ != "list": raise NotImplementedError("Input log value is not list") - wbuf = "" - currtimeindexes = [] + wbuf = "" + currtimeindexes = [] for i in xrange(len(logtimeslist)): currtimeindexes.append(0) nextlogindexes = [] - continuewrite = True - linecount = 0 - maxcount, mintime, maxtime = self._getLogsInfo(logtimeslist) - self._maxtimestamp = maxcount + continuewrite = True + linecount = 0 + maxcount, mintime, maxtime = self._getLogsInfo(logtimeslist) + self._maxtimestamp = maxcount self._maxtime = maxtime self._starttime = mintime self._localtimediff = localtimediff - while continuewrite: - self._findNextTimeStamps(logtimeslist, currtimeindexes, timetol, nextlogindexes) + while continuewrite: + self._findNextTimeStamps(logtimeslist, currtimeindexes, timetol, nextlogindexes) self.log().debug("Next time stamp log indexes: %s" % (str(nextlogindexes))) - if len(nextlogindexes) == 0: - # No new indexes that can be found - continuewrite = False - else: - # - templine = self._writeNewLine(logtimeslist, logvaluelist, currtimeindexes, nextlogindexes) + if len(nextlogindexes) == 0: + # No new indexes that can be found + continuewrite = False + else: + # + templine = self._writeNewLine(logtimeslist, logvaluelist, currtimeindexes, nextlogindexes) self.log().debug("Write new line %d: %s" % (linecount, templine)) - self._progressTimeIndexes(currtimeindexes, nextlogindexes) - wbuf += templine + "\n" - linecount += 1 - # ENDIF + self._progressTimeIndexes(currtimeindexes, nextlogindexes) + wbuf += templine + "\n" + linecount += 1 + # ENDIF - if linecount > maxcount: - raise NotImplementedError("Logic error.") - # ENDWHILE + if linecount > maxcount: + raise NotImplementedError("Logic error.") + # ENDWHILE # Remove last "\n" - if wbuf[-1] == "\n": + if wbuf[-1] == "\n": wbuf = wbuf[:-1] - try: - ofile = open(self._outputfilename, "w") - ofile.write(wbuf) - ofile.close() - except IOError as err: - raise NotImplementedError("Unable to write file %s. Check permission." % (self._outputfilename)) + try: + ofile = open(self._outputfilename, "w") + ofile.write(wbuf) + ofile.close() + except IOError as err: + raise NotImplementedError("Unable to write file %s. Check permission." % (self._outputfilename)) - return + return def _findNextTimeStamps(self, logtimeslist, currtimeindexes, timetol, nexttimelogindexes): - """ + """ Arguments: - nexttimelogindexes : (output) indexes of logs for next time stamp - """ + """ # clear output nexttimelogindexes[:] = [] - # Initialize - nexttime = self._maxtime + # Initialize + nexttime = self._maxtime - for i in xrange(0, len(logtimeslist)): + for i in xrange(0, len(logtimeslist)): # skip the None log if logtimeslist[i] is None: continue - timeindex = currtimeindexes[i] - if timeindex >= len(logtimeslist[i]): - # skip as out of boundary of log - continue - tmptime = logtimeslist[i][timeindex] + timeindex = currtimeindexes[i] + if timeindex >= len(logtimeslist[i]): + # skip as out of boundary of log + continue + tmptime = logtimeslist[i][timeindex] self.log().debug("tmptime type = %s " % ( type(tmptime))) - # difftime = calTimeDiff(tmptime, nexttime) + # difftime = calTimeDiff(tmptime, nexttime) difftime = (tmptime.totalNanoseconds() - nexttime.totalNanoseconds())*1.0E-9 - - if abs(difftime) < timetol: - # same ... - nexttimelogindexes.append(i) - elif difftime < 0: - # new smaller time - nexttime = tmptime + + if abs(difftime) < timetol: + # same ... + nexttimelogindexes.append(i) + elif difftime < 0: + # new smaller time + nexttime = tmptime nexttimelogindexes[:] = [] - nexttimelogindexes.append(i) - # ENDIF - # ENDIF + nexttimelogindexes.append(i) + # ENDIF + # ENDIF - return + return def _writeNewLine(self, logtimeslist, logvaluelist, currtimeindexes, nexttimelogindexes): - """ Write a new line - """ - # Check - if len(nexttimelogindexes) == 0: - raise NotImplementedError("Logic error") + """ Write a new line + """ + # Check + if len(nexttimelogindexes) == 0: + raise NotImplementedError("Logic error") - # Log time + # Log time # self.log().information("logtimelist of type %s." % (type(logtimeslist))) - #logtime = logtimeslist[currtimeindexes[nexttimelogindexes[0]]] + #logtime = logtimeslist[currtimeindexes[nexttimelogindexes[0]]] logindex = nexttimelogindexes[0] logtimes = logtimeslist[logindex] thislogtime = logtimes[currtimeindexes[logindex]] # FIXME : refactor the following to increase efficiency - abstime = thislogtime.totalNanoseconds() * 1.E-9 - self._localtimediff - reltime = thislogtime.totalNanoseconds() * 1.E-9 - self._starttime.totalNanoseconds() * 1.0E-9 - wbuf = "%.6f\t%.6f\t" % (abstime, reltime) - - # Log valuess - tmplogvalues = [] - for i in xrange(len(logvaluelist)): - timeindex = currtimeindexes[i] - if not i in nexttimelogindexes: - timeindex -= 1 - if timeindex < 0: - timeindex = 0 + abstime = thislogtime.totalNanoseconds() * 1.E-9 - self._localtimediff + reltime = thislogtime.totalNanoseconds() * 1.E-9 - self._starttime.totalNanoseconds() * 1.0E-9 + wbuf = "%.6f\t%.6f\t" % (abstime, reltime) + + # Log valuess + tmplogvalues = [] + for i in xrange(len(logvaluelist)): + timeindex = currtimeindexes[i] + if not i in nexttimelogindexes: + timeindex -= 1 + if timeindex < 0: + timeindex = 0 if logvaluelist[i] is None: logvalue = 0. else: - logvalue = logvaluelist[i][timeindex] + logvalue = logvaluelist[i][timeindex] - # FIXME - This case is not considered yet - # if logvaluedict[samplelog] is not None: - # logvalue = logvaluedict[samplelog][i] - # else: - # logvalue = 0. - wbuf += "%.6f\t" % (logvalue) - # ENDFOR + # FIXME - This case is not considered yet + # if logvaluedict[samplelog] is not None: + # logvalue = logvaluedict[samplelog][i] + # else: + # logvalue = 0. + wbuf += "%.6f\t" % (logvalue) + # ENDFOR - return wbuf + return wbuf def _progressTimeIndexes(self, currtimeindexes, nexttimelogindexes): - """ Progress index - """ - for i in xrange(len(currtimeindexes)): - if i in nexttimelogindexes: - currtimeindexes[i] += 1 + """ Progress index + """ + for i in xrange(len(currtimeindexes)): + if i in nexttimelogindexes: + currtimeindexes[i] += 1 - return + return def _readSampleLogs(self): - """ Read sample logs - """ + """ Read sample logs + """ import sys - # Get all properties' times and value and check whether all the logs are in workspaces - samplerun = self._wksp.getRun() + # Get all properties' times and value and check whether all the logs are in workspaces + samplerun = self._wksp.getRun() - logtimesdict = {} - logvaluedict = {} + logtimesdict = {} + logvaluedict = {} for samplename in self._sampleloglist: - # Check existence - logexist = samplerun.hasProperty(samplename) - - if logexist is True: - # Get hold of sample values - p = samplerun.getProperty(samplename) - logtimesdict[samplename] = p.times - logvaluedict[samplename] = p.value - - else: - # Add None - self.log().warning("Sample log %s does not exist. " % (samplename)) - logtimesdict[samplename] = None - logvaluedict[samplename] = None - - # ENDIF - # ENDFOR - - # Check properties' size - loglength = sys.maxint - for i in xrange(len(self._sampleloglist)): - if logtimesdict[self._sampleloglist[i]] is not None: - tmplength = len(logtimesdict[self._sampleloglist[i]]) - if loglength != tmplength: - if loglength != sys.maxint: - self.log().warning("Log %s has different length from previous ones. " % (self._sampleloglist[i])) - loglength = min(loglength, tmplength) - # ENDIF - # ENDIF - # ENDFOR - - if loglength == sys.maxint: - self.log().warning("None of given log names is found in workspace. ") - loglength = 0 - else: - self.log().information("Final Log length = %d" % (loglength)) - - return (logtimesdict, logvaluedict, loglength) - - + # Check existence + logexist = samplerun.hasProperty(samplename) + + if logexist is True: + # Get hold of sample values + p = samplerun.getProperty(samplename) + logtimesdict[samplename] = p.times + logvaluedict[samplename] = p.value + + else: + # Add None + self.log().warning("Sample log %s does not exist. " % (samplename)) + logtimesdict[samplename] = None + logvaluedict[samplename] = None + + # ENDIF + # ENDFOR + + # Check properties' size + loglength = sys.maxint + for i in xrange(len(self._sampleloglist)): + if logtimesdict[self._sampleloglist[i]] is not None: + tmplength = len(logtimesdict[self._sampleloglist[i]]) + if loglength != tmplength: + if loglength != sys.maxint: + self.log().warning("Log %s has different length from previous ones. " % (self._sampleloglist[i])) + loglength = min(loglength, tmplength) + # ENDIF + # ENDIF + # ENDFOR + + if loglength == sys.maxint: + self.log().warning("None of given log names is found in workspace. ") + loglength = 0 + else: + self.log().information("Final Log length = %d" % (loglength)) + + return (logtimesdict, logvaluedict, loglength) + + def _writeHeaderFile(self, testdatetime, description): - """ Write the header file for a LoadFrame - """ - # Construct 3 lines of the header file - line0 = "Test date: %s" % (str(testdatetime)) - line1 = "Test description: %s" % (description) - line2 = self._headercontent - - # Write file - wbuf = line0 + "\n" + line1 + "\n" + line2 + "\n" - # headerfilename = self._outputfilename.split(".")[0] + "_header.txt" + """ Write the header file for a LoadFrame + """ + # Construct 3 lines of the header file + line0 = "Test date: %s" % (str(testdatetime)) + line1 = "Test description: %s" % (description) + line2 = self._headercontent + + # Write file + wbuf = line0 + "\n" + line1 + "\n" + line2 + "\n" + # headerfilename = self._outputfilename.split(".")[0] + "_header.txt" filepath = os.path.dirname(self._outputfilename) basename = os.path.basename(self._outputfilename) baseheadername = basename.split(".txt")[0] + "_header.txt" headerfilename = os.path.join(filepath, baseheadername) - self.log().information("Writing header file %s ... " % (headerfilename)) - - try: - ofile = open(headerfilename, "w") - ofile.write(wbuf) - ofile.close() - except OSError as err: - self.log().error(str(err)) + self.log().information("Writing header file %s ... " % (headerfilename)) + + try: + ofile = open(headerfilename, "w") + ofile.write(wbuf) + ofile.close() + except OSError as err: + self.log().error(str(err)) return - + def getLocalTimeShiftInSecond(utctime, localtimezone, logger = None): - """ Calculate the difference between UTC time and local time of given + """ Calculate the difference between UTC time and local time of given DataAndTime """ from datetime import datetime @@ -443,7 +443,7 @@ def getLocalTimeShiftInSecond(utctime, localtimezone, logger = None): t1str = (str(utctime)).split('.')[0].strip() if logger: logger.information("About to convert time string: %s" % t1str) - try: + try: utc = datetime.strptime(t1str, '%Y-%m-%dT%H:%M:%S') except ValueError as err: raise err diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py index f57a3d889bf1..df8108481e11 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FilterLogByTime.py @@ -15,16 +15,16 @@ def name(self): def summary(self): return "Filters a log between time intervals and applies a user defined operation to the result." - def PyInit(self): + def PyInit(self): self.declareProperty(WorkspaceProperty("InputWorkspace", "", direction=Direction.Input), "Input workspace") - log_validator = StringMandatoryValidator() + log_validator = StringMandatoryValidator() self.declareProperty(name="LogName", defaultValue="", direction=Direction.Input, validator=log_validator, doc="Log name to filter by") self.declareProperty(name="StartTime", defaultValue=-sys.float_info.max, validator=FloatBoundedValidator(), direction=Direction.Input, doc="Start time for filtering. Seconds after run start") self.declareProperty(name="EndTime", defaultValue=sys.float_info.max, validator=FloatBoundedValidator(), direction=Direction.Input, doc="End time for filtering. Seconds after run start") self.declareProperty(name="Method",defaultValue="mean", validator=StringListValidator(["mean","min", "max", "median"]), doc="Statistical method to use to generate ResultStatistic output") self.declareProperty(FloatArrayProperty(name="FilteredResult", direction=Direction.Output), doc="Filtered values between specified times.") self.declareProperty(name="ResultStatistic", defaultValue=0.0, direction=Direction.Output, doc="Requested statistic") - + def PyExec(self): in_ws = self.getProperty("InputWorkspace").value log_name = self.getProperty("LogName").value @@ -37,7 +37,7 @@ def PyExec(self): end_time = None if start_time and end_time and (start_time > end_time): raise ValueError("StartTime > EndTime, %s > %s" % (str(start_time), str(end_time))) - + values = self.__filter(in_ws, log_name, start_time, end_time) stats = self.__statistics(values, method) self.setProperty("FilteredResult", values) @@ -60,14 +60,14 @@ def __filter(self, ws, logname, starttime=None, endtime=None): raise ValueError("log called %s is not a FloatTimeSeries log" % logname) times = numpy.array(map(lambda t: t.total_nanoseconds(), log.times)) - + values = numpy.array(log.value) mask = (tstart <= times) & (times <= tend) # Get times between filter start and end. filteredvalues = values[mask] return filteredvalues - + def __statistics(self, values, operation): op = getattr(numpy, operation) return op(values) - + AlgorithmFactory.subscribe(FilterLogByTime) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py index 47697c5f49b2..22b471b12566 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/FindReflectometryLines.py @@ -3,100 +3,100 @@ import numpy as np class PeakFindingException(Exception): - pass + pass class FindReflectometryLines(PythonAlgorithm): - - # Determine if a given signal identifies a peak or not. - def __is_peak(self, before, current, after): - # A peak is defined to be any signal that is preceeded by a lower signal value and followed by a lower signal value. - if before < current and current > after: - return True - return False - - # Find a list of spectra numbers corresponding to peaks in the data. - def __find_peak_spectrum_numbers(self, y_data, ws): - peak_index_list = [] - for index, current in enumerate(y_data.flat): - if (index > 0) and (index < (y_data.size - 1)): - before = y_data[index-1] - after = y_data[index+1] - if self.__is_peak(before, current, after): - spec_number = ws.getSpectrum(index).getSpectrumNo() - peak_index_list.append(spec_number) - return peak_index_list - - # Zero-out any data considered to be background. - def __remove_background(self, y_data): - y_average = np.sum(y_data) / y_data.size - y_max = np.max(y_data) - #The thresholding criteria is hard-coded to be above the average as follows. - threshold = (y_max - y_average)/10 + y_average - y_data[y_data < threshold] = 0 - return y_data - - def category(self): - return "PythonAlgorithms;Reflectometry\\ISIS" - - def name(self): - return "FindReflectometryLines" - - def summary(self): - return "Finds spectrum numbers corresponding to reflected and transmission lines in a line detector Reflectometry dataset." - - def PyInit(self): - - workspace_validator = CompositeValidator() - workspace_validator.add(WorkspaceUnitValidator("Wavelength")) - workspace_validator.add(SpectraAxisValidator()) - - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, workspace_validator), "Input Reflectometry Workspace") - self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Output Spectrum Numbers") - self.declareProperty(name="StartWavelength", defaultValue=0.0, validator=FloatBoundedValidator(lower=0.0), doc="Start wavelength to use for x-axis cropping") - self.declareProperty(name="KeepIntermediateWorkspaces", defaultValue=False, doc="Keeps cropped and integrated workspaces in memory after usage.") - - def PyExec(self): - from mantid.simpleapi import CropWorkspace, Integration, DeleteWorkspace - - in_ws = self.getPropertyValue("InputWorkspace") - min_wavelength = self.getPropertyValue("StartWavelength") - keep_workspaces = self.getPropertyValue("KeepIntermediateWorkspaces") - - # Crop off lower wavelengths where the signal is also lower. - cropped_ws = CropWorkspace(InputWorkspace=in_ws,XMin=float(min_wavelength)) - # Integrate over the higher wavelengths after cropping. - summed_ws = Integration(InputWorkspace=cropped_ws) - # Loop through each histogram, and fetch out each intensity value from the single bin to generate a list of all values. - n_histograms = summed_ws.getNumberHistograms() - y_data = np.empty([n_histograms]) - for i in range(0, n_histograms): - intensity = summed_ws.readY(i)[0] - y_data[i] = intensity - #Remove the background - y_data = self.__remove_background(y_data) - #Find the peaks - peak_index_list = self.__find_peak_spectrum_numbers(y_data, summed_ws) + + # Determine if a given signal identifies a peak or not. + def __is_peak(self, before, current, after): + # A peak is defined to be any signal that is preceeded by a lower signal value and followed by a lower signal value. + if before < current and current > after: + return True + return False + + # Find a list of spectra numbers corresponding to peaks in the data. + def __find_peak_spectrum_numbers(self, y_data, ws): + peak_index_list = [] + for index, current in enumerate(y_data.flat): + if (index > 0) and (index < (y_data.size - 1)): + before = y_data[index-1] + after = y_data[index+1] + if self.__is_peak(before, current, after): + spec_number = ws.getSpectrum(index).getSpectrumNo() + peak_index_list.append(spec_number) + return peak_index_list + + # Zero-out any data considered to be background. + def __remove_background(self, y_data): + y_average = np.sum(y_data) / y_data.size + y_max = np.max(y_data) + #The thresholding criteria is hard-coded to be above the average as follows. + threshold = (y_max - y_average)/10 + y_average + y_data[y_data < threshold] = 0 + return y_data + + def category(self): + return "PythonAlgorithms;Reflectometry\\ISIS" + + def name(self): + return "FindReflectometryLines" + + def summary(self): + return "Finds spectrum numbers corresponding to reflected and transmission lines in a line detector Reflectometry dataset." + + def PyInit(self): + + workspace_validator = CompositeValidator() + workspace_validator.add(WorkspaceUnitValidator("Wavelength")) + workspace_validator.add(SpectraAxisValidator()) + + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, workspace_validator), "Input Reflectometry Workspace") + self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Output Spectrum Numbers") + self.declareProperty(name="StartWavelength", defaultValue=0.0, validator=FloatBoundedValidator(lower=0.0), doc="Start wavelength to use for x-axis cropping") + self.declareProperty(name="KeepIntermediateWorkspaces", defaultValue=False, doc="Keeps cropped and integrated workspaces in memory after usage.") + + def PyExec(self): + from mantid.simpleapi import CropWorkspace, Integration, DeleteWorkspace + + in_ws = self.getPropertyValue("InputWorkspace") + min_wavelength = self.getPropertyValue("StartWavelength") + keep_workspaces = self.getPropertyValue("KeepIntermediateWorkspaces") + + # Crop off lower wavelengths where the signal is also lower. + cropped_ws = CropWorkspace(InputWorkspace=in_ws,XMin=float(min_wavelength)) + # Integrate over the higher wavelengths after cropping. + summed_ws = Integration(InputWorkspace=cropped_ws) + # Loop through each histogram, and fetch out each intensity value from the single bin to generate a list of all values. + n_histograms = summed_ws.getNumberHistograms() + y_data = np.empty([n_histograms]) + for i in range(0, n_histograms): + intensity = summed_ws.readY(i)[0] + y_data[i] = intensity + #Remove the background + y_data = self.__remove_background(y_data) + #Find the peaks + peak_index_list = self.__find_peak_spectrum_numbers(y_data, summed_ws) #Reverse the order so that it goes from high spec number to low spec number - peak_index_list.reverse() - n_peaks_found = len(peak_index_list) - - output_ws = WorkspaceFactory.createTable("TableWorkspace") - output_ws.addColumn("int", "Reflected Spectrum Number") - - if n_peaks_found > 2: - raise PeakFindingException("Found more than two peaks.") - elif n_peaks_found == 0: - raise PeakFindingException("No peaks found") - elif n_peaks_found == 1: - output_ws.addRow(peak_index_list) - elif n_peaks_found == 2: - output_ws.addColumn("int", "Transmission Spectrum Number") - output_ws.addRow(peak_index_list) - - if int(keep_workspaces) == 0: - DeleteWorkspace(Workspace=cropped_ws) - DeleteWorkspace(Workspace=summed_ws) - - self.setProperty("OutputWorkspace", output_ws) - + peak_index_list.reverse() + n_peaks_found = len(peak_index_list) + + output_ws = WorkspaceFactory.createTable("TableWorkspace") + output_ws.addColumn("int", "Reflected Spectrum Number") + + if n_peaks_found > 2: + raise PeakFindingException("Found more than two peaks.") + elif n_peaks_found == 0: + raise PeakFindingException("No peaks found") + elif n_peaks_found == 1: + output_ws.addRow(peak_index_list) + elif n_peaks_found == 2: + output_ws.addColumn("int", "Transmission Spectrum Number") + output_ws.addRow(peak_index_list) + + if int(keep_workspaces) == 0: + DeleteWorkspace(Workspace=cropped_ws) + DeleteWorkspace(Workspace=summed_ws) + + self.setProperty("OutputWorkspace", output_ws) + AlgorithmFactory.subscribe(FindReflectometryLines()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py index 5aaaec332e00..fd44cde703f6 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GenerateGroupingSNSInelastic.py @@ -1,10 +1,10 @@ import mantid import mantid.api -import mantid.simpleapi +import mantid.simpleapi import mantid.kernel from numpy import arange - + class GenerateGroupingSNSInelastic(mantid.api.PythonAlgorithm): """ Class to generate grouping file """ @@ -31,7 +31,7 @@ def PyInit(self): py = ["1", "2", "4","8","16","32","64","128"] px = ["1", "2", "4","8"] instrument = ["ARCS","CNCS","HYSPEC","SEQUOIA"] - + self.declareProperty("AlongTubes", "1",mantid.kernel.StringListValidator(py), "Number of pixels across tubes to be grouped") self.declareProperty("AcrossTubes", "1", mantid.kernel.StringListValidator(px), "Number of pixels across tubes to be grouped") self.declareProperty("Instrument", instrument[0], mantid.kernel.StringListValidator(instrument), "The instrument for wich to create grouping") @@ -49,7 +49,7 @@ def PyExec(self): pixelsx = int(self.getProperty("AcrossTubes").value) instrument = self.getProperty("Instrument").value filename = self.getProperty("Filename").value - + IDF=mantid.api.ExperimentInfo.getInstrumentFilename(instrument) __w = mantid.simpleapi.LoadEmptyInstrument(Filename=IDF) @@ -59,8 +59,8 @@ def PyExec(self): #i is the index of the first true detector #now, crop the workspace of the monitors __w = mantid.simpleapi.CropWorkspace(__w,StartWorkspaceIndex=i) - - #get number of detectors (not including monitors) + + #get number of detectors (not including monitors) y=__w.extractY() numdet=(y[y==1]).size @@ -68,7 +68,7 @@ def PyExec(self): banks = numdet/8/128 - + f = open(filename,'w') f.write('\n\n') @@ -80,7 +80,7 @@ def PyExec(self): for k in arange(128/pixelsy)*pixelsy: groupname = str(groupnum) - ids = spectra[i, j:j+pixelsx, k:k+pixelsy].reshape(-1) + ids = spectra[i, j:j+pixelsx, k:k+pixelsy].reshape(-1) detids = [] for l in ids: detids.append(__w.getDetector(int(l)).getID()) @@ -93,5 +93,5 @@ def PyExec(self): f.close() mantid.simpleapi.DeleteWorkspace(__w.getName()) return - + mantid.api.AlgorithmFactory.subscribe(GenerateGroupingSNSInelastic) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py index d665ea3afb62..1d8d55dab696 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/GetEiMonDet.py @@ -1,6 +1,6 @@ from mantid.api import PythonAlgorithm, AlgorithmFactory,WorkspaceProperty from mantid.kernel import Direction,IntBoundedValidator,FloatBoundedValidator -import mantid.simpleapi +import mantid.simpleapi import mantid from numpy import array,where @@ -11,7 +11,7 @@ def category(self): """ Return category """ return "PythonAlgorithms;Inelastic" - + def name(self): """ Return name """ @@ -35,27 +35,27 @@ def PyInit(self): self.declareProperty("FirstMonitorIndex",0,Direction.Output) self.declareProperty("Tzero",0.0,Direction.Output) return - + def PyExec(self): """ Main execution body """ __w=self.getProperty("DetectorWorkspace").value - __w_mon=self.getProperty("MonitorWorkspace").value + __w_mon=self.getProperty("MonitorWorkspace").value mon1spec=self.getProperty("MonitorSpectrumNumber").value - Eguess=self.getProperty("EnergyGuess").value - + Eguess=self.getProperty("EnergyGuess").value + #find the minimum distance, then select only detector that are at d10meV so=i.getSource().getPos() m1=wm.getDetector(sp1).getPos() @@ -70,8 +70,8 @@ def PyExec(self): t2f=int(t2*60e-6) #frame number for monitor 2 wtemp=mantid.simpleapi.ChangeBinOffset(wm,t1f*16667,sp1,sp1) wtemp=mantid.simpleapi.ChangeBinOffset(wtemp,t2f*16667,sp2,sp2) - wtemp=mantid.simpleapi.Rebin(InputWorkspace=wtemp,Params="1",PreserveEvents=True) - + wtemp=mantid.simpleapi.Rebin(InputWorkspace=wtemp,Params="1",PreserveEvents=True) + alg=mantid.simpleapi.GetEi(InputWorkspace=wtemp,Monitor1Spec=sp1+1,Monitor2Spec=sp2+1,EnergyEstimate=EGuess) #Run GetEi algorithm Ei=alg[0] Tzero=alg[3] #Extract incident energy and T0 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py index 2a39f9a01703..a1826bcaa51a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadFullprofFile.py @@ -25,20 +25,20 @@ def summary(self): def PyInit(self): """ Declare properties - """ + """ self.declareProperty(FileProperty("Filename","", FileAction.Load, ['.hkl', '.prf', '.dat']), "Name of [http://www.ill.eu/sites/fullprof/ Fullprof] .hkl or .prf file.") #self.declareProperty("Bank", 1, "Bank ID for output if there are more than one bank in .irf file.") - self.declareProperty(ITableWorkspaceProperty("PeakParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("PeakParameterWorkspace", "", Direction.Output), "Name of table workspace containing peak parameters from .hkl file.") - - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), + + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Name of data workspace containing the diffraction pattern in .prf file. ") return - + def PyExec(self): """ Main Execution Body """ @@ -46,16 +46,16 @@ def PyExec(self): fpfilename = self.getPropertyValue("Filename") # 2. Import - if fpfilename.lower().endswith(".hkl") is True: + if fpfilename.lower().endswith(".hkl") is True: # (.hkl) file self._tableWS = self._loadFPHKLFile(fpfilename) self._dataWS = self._makeEmptyDataWorkspace() elif fpfilename.lower().endswith(".prf") is True: - # (.prf) file + # (.prf) file self._tableWS, self._dataWS= self._loadFullprofPrfFile(fpfilename) - elif fpfilename.lower().endswith(".dat") is True: - # (.dat) file: Fullprof data file - self._tableWS, self._dataWS = self._loadFullprofDataFile(fpfilename) + elif fpfilename.lower().endswith(".dat") is True: + # (.dat) file: Fullprof data file + self._tableWS, self._dataWS = self._loadFullprofDataFile(fpfilename) else: raise NotImplementedError("File %s is neither .hkl nor .prf. It is not supported." % (fpfilename)) @@ -131,13 +131,13 @@ def _importFullprofHKLFile(self, hklfilename): dkey = (h, k, l) if hkldict.has_key(dkey): - if _OUTPUTLEVEL == "INFORMATION": + if _OUTPUTLEVEL == "INFORMATION": self.warning("Warning! Duplicate HKL %d, %d, %d" (h, k, l)) continue if fwhm < 1.0E-5: # Peak width is too small/annihilated peak - if _OUTPUTLEVEL == "INFORMATION": + if _OUTPUTLEVEL == "INFORMATION": self.log.information("Peak (%d, %d, %d) has an unreasonable small FWHM. Peak does not exist. " % (h, k, l)) continue @@ -156,20 +156,20 @@ def _importFullprofHKLFile(self, hklfilename): return hkldict def _createReflectionWorkspace(self, hkldict): - """ Create TableWorkspace containing reflections and etc. + """ Create TableWorkspace containing reflections and etc. """ # 1. Set up columns tablews = WorkspaceFactory.createTable() - + tablews.addColumn("int", "H"); tablews.addColumn("int", "K"); - tablews.addColumn("int", "L"); - tablews.addColumn("double", "Alpha"); - tablews.addColumn("double", "Beta"); - tablews.addColumn("double", "Sigma2"); - tablews.addColumn("double", "Gamma"); - tablews.addColumn("double", "FWHM"); - tablews.addColumn("double", "PeakHeight"); + tablews.addColumn("int", "L"); + tablews.addColumn("double", "Alpha"); + tablews.addColumn("double", "Beta"); + tablews.addColumn("double", "Sigma2"); + tablews.addColumn("double", "Gamma"); + tablews.addColumn("double", "FWHM"); + tablews.addColumn("double", "PeakHeight"); # 2. Add rows for hkl in sorted(hkldict.keys()): @@ -210,7 +210,7 @@ def _loadFullprofPrfFile(self, prffilename): def _parseFullprofPrfFile(self, filename): """ Parse Fullprof .prf file to a information dictionary and a data set (list of list) """ - import re + import re # Import .prf file try: @@ -229,7 +229,7 @@ def _parseFullprofPrfFile(self, filename): dataset = [] # Parse information lines - # Line 0: header + # Line 0: header infoline = lines[0] if infoline.count("CELL:") == 1: terms = infoline.split("CELL:")[1].split() @@ -250,12 +250,12 @@ def _parseFullprofPrfFile(self, filename): # spacegroup = terms[1].strip() # infodict["SpaceGroup"] = spacegroup - # Find data line header + # Find data line header firstline = -1 for i in xrange(1, len(lines)): if lines[i].count("Yobs-Ycal") > 0: firstline = i+1 - dataheader = lines[i].strip() + dataheader = lines[i].strip() break if firstline < 0: @@ -263,25 +263,25 @@ def _parseFullprofPrfFile(self, filename): # Parse header line: T.O.F. Yobs Ycal Yobs-Ycal Backg Bragg ... # to determine how the data line look alike (==5 or >= 5) - headerterms = dataheader.split() - dataperline = 5 - # TOF., ... h k l ... - reflectionperline = len(headerterms)-5+3 + headerterms = dataheader.split() + dataperline = 5 + # TOF., ... h k l ... + reflectionperline = len(headerterms)-5+3 - # Parse data + # Parse data count = 0 for i in xrange(firstline, len(lines)): - line = lines[i].strip() - if len(line) == 0: # empty line - continue + line = lines[i].strip() + if len(line) == 0: # empty line + continue - if line.count(")") == 0 and line.count("(") == 0: + if line.count(")") == 0 and line.count("(") == 0: # A regular data line - terms = line.split() - if len(terms) != 5: - self.log().warning("Pure data line %d (%s) has irregular number of data points" % (i, line)) - continue + terms = line.split() + if len(terms) != 5: + self.log().warning("Pure data line %d (%s) has irregular number of data points" % (i, line)) + continue x = float(terms[0]) yobs = float(terms[1]) @@ -292,38 +292,38 @@ def _parseFullprofPrfFile(self, filename): dataset.append([x, yobs, ycal, ydif, ybak]) count += 1 - elif line.count(")") == 1 and line.count("(") == 1: - # A line can be either pure reflection line or a combined data/reflection line - # remove '(' and ')' - newline = re.sub('[()]', ' ', line) + elif line.count(")") == 1 and line.count("(") == 1: + # A line can be either pure reflection line or a combined data/reflection line + # remove '(' and ')' + newline = re.sub('[()]', ' ', line) - terms = newline.strip().split() + terms = newline.strip().split() if len(terms) < 9: - # Pure reflection line - tofh = float(terms[0]) - hklstr = line.split(")")[1].split(")")[0].strip() - infodict[hklstr] = tofh + # Pure reflection line + tofh = float(terms[0]) + hklstr = line.split(")")[1].split(")")[0].strip() + infodict[hklstr] = tofh - else: - # Mixed line: least number of items: data(5) + TOF+hkl = 9 + else: + # Mixed line: least number of items: data(5) + TOF+hkl = 9 - x = float(terms[0]) + x = float(terms[0]) yobs = float(terms[1]) ycal = float(terms[2]) ydif = float(terms[3]) ybak = float(terms[4]) - - dataset.append([x, yobs, ycal, ydif, ybak]) - count += 1 - - raise NotImplementedError("Need a sample line of this use case.") - hklstr = line.split(")")[1].split(")")[0].strip() - infodict[hklstr] = tofh - # ENDIFELSE (terms) - else: - self.log().warning("%d-th line (%s) is not well-defined." % (i, line)) - - # ENDIF-ELIF-ELSE (line.count) + + dataset.append([x, yobs, ycal, ydif, ybak]) + count += 1 + + raise NotImplementedError("Need a sample line of this use case.") + hklstr = line.split(")")[1].split(")")[0].strip() + infodict[hklstr] = tofh + # ENDIFELSE (terms) + else: + self.log().warning("%d-th line (%s) is not well-defined." % (i, line)) + + # ENDIF-ELIF-ELSE (line.count) # ENDFOR print "Data set counter = ", count @@ -339,70 +339,70 @@ def _makeEmptyDataWorkspace(self): return dataws def _loadFullprofDataFile(self, datafilename): - """ Parse a Fullprof (multiple) column file - """ - # Import file - datafile = open(datafilename, "r") - rawlines = datafile.readlines() - datafile.close() - - # Parse head - iline = 0 - parseheader = True - title = "" - while iline < len(rawlines) and parseheader is True: - line = rawlines[iline].strip() - if len(line) > 0: - if line.count("BANK") == 0: - # header - title += line + ", " + """ Parse a Fullprof (multiple) column file + """ + # Import file + datafile = open(datafilename, "r") + rawlines = datafile.readlines() + datafile.close() + + # Parse head + iline = 0 + parseheader = True + title = "" + while iline < len(rawlines) and parseheader is True: + line = rawlines[iline].strip() + if len(line) > 0: + if line.count("BANK") == 0: + # header + title += line + ", " else: - # line information - terms = line.split() - if terms[0] != 'BANK': - raise NotImplementedError("First word must be 'BANK', but not %s" % (terms[0])) - bankid = int(terms[1]) - numdata = int(terms[2]) - numlines = int(terms[3]) - - parseheader = False - # ENDIF - # ENDIF - iline += 1 - # ENDWHILE (iline) - - # Data vectors - vecx = [] - vecy = [] - vece = [] - - for i in xrange(iline, len(rawlines)): - line = rawlines[i].strip() - if len(line) == 0: - continue - - terms = line.split() - numitems = len(terms) - if numitems % 3 != 0: - print "%d-th line '%s' is not a data line" % (i, line) - continue - - numpts = numitems/3 - for j in xrange(numpts): - x = float(terms[j*3]) - y = float(terms[j*3+1]) - e = float(terms[j*3+2]) - - vecx.append(x) - vecy.append(y) - vece.append(e) - # ENDFOR - # ENDFOR (i) - - # Check - self.log().notice("Expected to read %d data points; Exactly read %d data points. " % (numdata*numlines, len(vecx))) - - # Create output workspaces + # line information + terms = line.split() + if terms[0] != 'BANK': + raise NotImplementedError("First word must be 'BANK', but not %s" % (terms[0])) + bankid = int(terms[1]) + numdata = int(terms[2]) + numlines = int(terms[3]) + + parseheader = False + # ENDIF + # ENDIF + iline += 1 + # ENDWHILE (iline) + + # Data vectors + vecx = [] + vecy = [] + vece = [] + + for i in xrange(iline, len(rawlines)): + line = rawlines[i].strip() + if len(line) == 0: + continue + + terms = line.split() + numitems = len(terms) + if numitems % 3 != 0: + print "%d-th line '%s' is not a data line" % (i, line) + continue + + numpts = numitems/3 + for j in xrange(numpts): + x = float(terms[j*3]) + y = float(terms[j*3+1]) + e = float(terms[j*3+2]) + + vecx.append(x) + vecy.append(y) + vece.append(e) + # ENDFOR + # ENDFOR (i) + + # Check + self.log().notice("Expected to read %d data points; Exactly read %d data points. " % (numdata*numlines, len(vecx))) + + # Create output workspaces tablews = WorkspaceFactory.createTable() # Create the data workspace diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py index d2715346fd58..eaaf9bdbb5cc 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadLogPropertyTable.py @@ -31,14 +31,14 @@ def PyInit(self): def category(self): return "Utility;Muon" - + def getGeneralLogValue(self,ws,name,begin): # get log value # average time series over run # for beamlog, etc return flag=true and value to push into previous run if(name=="comment"): return (ws.getComment(),False,0) - + try: v=ws.getRun().getProperty(name) except: @@ -58,7 +58,7 @@ def getGeneralLogValue(self,ws,name,begin): if(name[0:8]=="Beamlog_" and (name.find("Counts")>0 or name.find("Frames")>0)): i=bisect.bisect_right(times2,2) # allowance for "slow" clearing of DAE - #print "returning max beam log, list cut 0:",i,":",len(times2) + #print "returning max beam log, list cut 0:",i,":",len(times2) return (numpy.amax(v.value[i:]),True,numpy.amax(v.value[:i])) if(v.__class__.__name__ =="TimeSeriesProperty_dbl" or v.__class__.__name__ =="FloatTimeSeriesProperty"): i=bisect.bisect_left(times2,0) @@ -66,7 +66,7 @@ def getGeneralLogValue(self,ws,name,begin): return (v.value,False,0) def PyExec(self): - + file1=self.getProperty("FirstFile").value file9=self.getProperty("LastFile").value i1=file1.rindex('.') @@ -87,7 +87,7 @@ def PyExec(self): raise Exception("File numbering error") if(lastnum < firstnum): raise Exception("Run numbers must increase") - + # table. Rows=runs, columns=logs (col 0 = run number) collist=self.getProperty("LogNames").value ows=WorkspaceFactory.createTable() @@ -96,23 +96,23 @@ def PyExec(self): # loop and load files. Absolute numbers for now. for ff in range(firstnum,lastnum+1): thispath=file1[:j1]+str(ff).zfill(i1-j1)+file1[i1:] - returnTuple=None + returnTuple=None try: returnTuple=Load(Filename=thispath,OutputWorkspace="__CopyLogsTmp",SpectrumMin=1, SpectrumMax=1) except: continue - + #check if the return type is atuple if (type(returnTuple) == tuple): loadedWs=returnTuple[0] else: loadedWs = returnTuple - + #check if the ws is a group ws = loadedWs if (ws.id() == 'WorkspaceGroup'): ws=ws[0] - + begin=datetime.datetime(*(time.strptime(ws.getRun().getProperty("run_start").value,"%Y-%m-%dT%H:%M:%S")[0:6])) # start of day vallist=[ff] for cc in collist: @@ -133,8 +133,8 @@ def PyExec(self): ows.setCell(cc,ff-firstnum-1,lval) ows.addRow(vallist) DeleteWorkspace(loadedWs) - - + + self.setProperty("OutputWorkspace",ows) AlgorithmFactory.subscribe(LoadLogPropertyTable()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py index 525e22c57bbb..c31c0e8aaae7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadMultipleGSS.py @@ -26,7 +26,7 @@ def __load(self, directory, prefix): return except Exception, e: pass - raise RuntimeError("Failed to load run %s" % prefix) + raise RuntimeError("Failed to load run %s" % prefix) def PyInit(self): self.declareProperty("FilePrefix","") @@ -50,6 +50,6 @@ def PyExec(self): for run in runs: wksp = "%s_%d" % (prefix,run) self.__load(directory, wksp) - ConvertUnits(InputWorkspace=wksp, OutputWorkspace=wksp, Target="dSpacing") + ConvertUnits(InputWorkspace=wksp, OutputWorkspace=wksp, Target="dSpacing") AlgorithmFactory.subscribe(LoadMultipleGSS) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py index 5f04d72add65..734f5e6d7489 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadSINQFile.py @@ -1,6 +1,6 @@ #-------------------------------------------------------------- -# Algorithm which loads a SINQ file. It matches the instrument -# and the right dictionary file and then goes away and calls +# Algorithm which loads a SINQ file. It matches the instrument +# and the right dictionary file and then goes away and calls # LoadFlexiNexus and others to load the file. # # Mark Koennecke, November 2012 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py index a826ca6de1fa..3451ac631629 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/LoadVesuvio.py @@ -1,6 +1,6 @@ from mantid.kernel import * from mantid.api import * -from mantid.simpleapi import (CropWorkspace, LoadEmptyInstrument, LoadRaw, Plus, +from mantid.simpleapi import (CropWorkspace, LoadEmptyInstrument, LoadRaw, Plus, DeleteWorkspace) import copy @@ -32,7 +32,7 @@ _LOGGING_ = False class LoadVesuvio(PythonAlgorithm): - + def summary(self): return "Loads raw data produced by the Vesuvio instrument at ISIS." @@ -42,21 +42,21 @@ def PyInit(self): "14188 - for single run" "14188-14195 - for summed consecutive runs" "14188,14195 - for summed non-consecutive runs") - - self.declareProperty(WorkspaceProperty(WKSP_PROP, "", Direction.Output), + + self.declareProperty(WorkspaceProperty(WKSP_PROP, "", Direction.Output), doc="The name of the output workspace.") - + self.declareProperty(IntArrayProperty(SPECTRA_PROP, IntArrayMandatoryValidator(), - Direction.Input), + Direction.Input), doc="The spectrum numbers to load") self.declareProperty(MODE_PROP, "DoubleDifference", StringListValidator(MODES), doc="The difference option. Valid values: %s" % str(MODES)) self.declareProperty(FileProperty(INST_PAR_PROP,"",action=FileAction.OptionalLoad, - extensions=["dat"]), + extensions=["dat"]), doc="An optional IP file. If provided the values are used to correct " - "the default instrument values and attach the t0 values to each detector") + "the default instrument values and attach the t0 values to each detector") self.declareProperty(SUM_PROP, False, doc="If true then the final output is a single spectrum containing the sum " @@ -66,7 +66,7 @@ def PyInit(self): def PyExec(self): self._load_inst_parameters() self._retrieve_input() - + if "Difference" in self._diff_opt: self._exec_difference_mode() else: @@ -99,7 +99,7 @@ def _exec_difference_mode(self): self._load_ip_file(ip_file) if self._sumspectra: self._sum_all_spectra() - + self._store_results() finally: # Ensures it happens whether there was an error or not self._cleanup_raw() @@ -116,7 +116,7 @@ def _exec_single_foil_state_mode(self): isis = config.getFacility("ISIS") inst_prefix = isis.instrument("VESUVIO").shortName() - + try: run = int(runs[0]) run_str = inst_prefix + runs[0] @@ -147,7 +147,7 @@ def _exec_single_foil_state_mode(self): raw_grp_indices = range(0, self._nperiods) else: raise RuntimeError("Unknown single foil mode: %s." % (self._diff_opt)) - + dataY = foil_out.dataY(ws_index) dataE = foil_out.dataE(ws_index) for group_index in raw_grp_indices: @@ -163,8 +163,8 @@ def _exec_single_foil_state_mode(self): def _load_inst_parameters(self): """ - Loads an empty VESUVIO instrument and attaches the necessary - parameters as attributes + Loads an empty VESUVIO instrument and attaches the necessary + parameters as attributes """ isis = config.getFacility("ISIS") inst_name = "VESUVIO" @@ -172,12 +172,12 @@ def _load_inst_parameters(self): inst_file = os.path.join(inst_dir, inst_name + "_Definition.xml") __empty_vesuvio_ws = LoadEmptyInstrument(Filename=inst_file, EnableLogging=_LOGGING_) empty_vesuvio = __empty_vesuvio_ws.getInstrument() - + def to_int_list(str_param): """Return the list of numbers described by the string range""" elements = str_param.split("-") return range(int(elements[0]),int(elements[1]) + 1) # range goes x_l,x_h-1 - + # Attach parameters as attributes self._inst_prefix = isis.instrument(inst_name).shortName() parnames = empty_vesuvio.getParameterNames(False) @@ -199,13 +199,13 @@ def to_int_list(str_param): self._beta = self.double_diff_mixing self._tof_max = self.tof_max self._mon_tof_max = self.monitor_tof_max - + # Normalisation ranges def to_range_tuple(str_range): """Return a list of 2 floats giving the lower,upper range""" elements = str_range.split("-") return (float(elements[0]),float(elements[1])) - + self._back_mon_norm = to_range_tuple(self.backward_monitor_norm) self._back_period_sum1 = to_range_tuple(self.backward_period_sum1) self._back_period_sum2 = to_range_tuple(self.backward_period_sum2) @@ -235,7 +235,7 @@ def _setup_raw(self, spectra): first_ws = self._raw_grp[0] self._nperiods = nperiods self._goodframes = first_ws.getRun().getLogData("goodfrm").value - + # Cache delta_t values raw_t = first_ws.readX(0) delay = raw_t[2] - raw_t[1] @@ -260,7 +260,7 @@ def _load_and_sum_runs(self, spectra): inst_prefix = isis.instrument("VESUVIO").shortName() runs = self._get_runs() - + self.summed_ws, self.summed_mon = "__loadraw_evs", "__loadraw_evs_monitors" for index, run in enumerate(runs): run = inst_prefix + str(run) @@ -269,9 +269,9 @@ def _load_and_sum_runs(self, spectra): else: out_name, out_mon = SUMMED_WS+'tmp', SUMMED_MON + 'tmp' # Load data - LoadRaw(Filename=run, SpectrumList=spectra, + LoadRaw(Filename=run, SpectrumList=spectra, OutputWorkspace=out_name, LoadMonitors='Exclude',EnableLogging=_LOGGING_) - LoadRaw(Filename=run,SpectrumList=self._mon_spectra, + LoadRaw(Filename=run,SpectrumList=self._mon_spectra, OutputWorkspace=out_mon,EnableLogging=_LOGGING_) if index > 0: # sum Plus(LHSWorkspace=SUMMED_WS, RHSWorkspace=out_name, @@ -298,12 +298,12 @@ def _get_runs(self): if "-" in run_str: lower,upper = run_str.split("-") runs = range(int(lower),int(upper)+1) #range goes lower to up-1 but we want to include the last number - + elif "," in run_str: runs = run_str.split(",") else: runs = [run_str] - + return runs #---------------------------------------------------------------------------------------- @@ -311,7 +311,7 @@ def _set_spectra_type(self, spectrum_no): """ Set whether this spectrum no is forward/backward scattering and set the normalization range appropriately - @param spectrum_no The current spectrum no + @param spectrum_no The current spectrum no """ if spectrum_no >= self._backward_spectra_list[0] and spectrum_no <= self._backward_spectra_list[-1]: self._spectra_type=BACKWARD @@ -333,10 +333,10 @@ def _set_spectra_type(self, spectrum_no): #---------------------------------------------------------------------------------------- def _integrate_periods(self): """ - Calculates 2 arrays of sums, 1 per period, of the Y values from + Calculates 2 arrays of sums, 1 per period, of the Y values from the raw data between: - (a) period_sum1_start & period_sum1_end - (b) period_sum2_start & period_sum2_end. + (a) period_sum1_start & period_sum1_end + (b) period_sum2_start & period_sum2_end. It also creates a 3rd blank array that will be filled by calculate_foil_counts_per_us. Operates on the current workspace index """ @@ -348,7 +348,7 @@ def _integrate_periods(self): xvalues = self.pt_times sum1_indices = np.where((xvalues > sum1_start) & (xvalues < sum1_end)) sum2_indices = np.where((xvalues > sum2_start) & (xvalues < sum2_end)) - + wsindex = self._ws_index for i in range(self._nperiods): yvalues = self._raw_grp[i].readY(wsindex) @@ -371,7 +371,7 @@ def _create_foil_workspaces(self): ndata_bins = first_ws.blocksize() nhists = first_ws.getNumberHistograms() data_kwargs = {'NVectors':nhists,'XLength':ndata_bins,'YLength':ndata_bins} - + self.foil_out = WorkspaceFactory.create(first_ws, **data_kwargs) # This will be used as the result workspace self.foil_out.setDistribution(True) self.foil_thin = WorkspaceFactory.create(first_ws, **data_kwargs) @@ -394,15 +394,15 @@ def _create_foil_workspaces(self): self.mon_thick = WorkspaceFactory.create(first_monws, **monitor_kwargs) #---------------------------------------------------------------------------------------- - + def _sum_foil_periods(self): """ Sums the counts in the different periods to get the total counts - for the foil out, thin foil & thick foil states for the back scattering detectors for the + for the foil out, thin foil & thick foil states for the back scattering detectors for the current workspace index & spectrum number """ foil_out_periods, foil_thin_periods, foil_thick_periods = self._get_foil_periods() - + if self._nperiods == 6 and self._spectra_type == FORWARD: mon_out_periods = (5,6) mon_thin_periods = (3,4) @@ -411,7 +411,7 @@ def _sum_foil_periods(self): # None indicates same as standard foil mon_out_periods, mon_thin_periods, mon_thick_periods = (None,None,None) # - # Foil out + # Foil out self._sum_foils(self.foil_out, self.mon_out, IOUT, foil_out_periods, mon_out_periods) # Thin foil self._sum_foils(self.foil_thin, self.mon_thin, ITHIN, foil_thin_periods, mon_thin_periods) @@ -422,7 +422,7 @@ def _sum_foil_periods(self): #---------------------------------------------------------------------------------------- def _get_foil_periods(self): """ - Return the period numbers (starting from 1) that contribute to the + Return the period numbers (starting from 1) that contribute to the respective foil states """ if self._nperiods == 2: @@ -457,9 +457,9 @@ def _sum_foils(self, foil_ws, mon_ws, sum_index, foil_periods, mon_periods=None) Sums the counts from the given foil periods in the raw data group @param foil_ws :: The workspace that will receive the summed counts @param mon_ws :: The monitor workspace that will receive the summed monitor counts - @param sum_index :: An index into the sum3 array where the integrated counts will be accumulated + @param sum_index :: An index into the sum3 array where the integrated counts will be accumulated @param foil_periods :: The period numbers that contribute to this sum - @param mon_periods :: The period numbers of the monitors that contribute to this monitor sum + @param mon_periods :: The period numbers of the monitors that contribute to this monitor sum (if None then uses the foil_periods) """ raw_grp_indices = self.foil_map.get_indices(self._spectrum_no, foil_periods) @@ -484,7 +484,7 @@ def _sum_foils(self, foil_ws, mon_ws, sum_index, foil_periods, mon_periods=None) for grp_index in raw_grp_indices: raw_ws = self._raw_monitors[grp_index] outY += raw_ws.readY(self._mon_index) - + outY /= self.delta_tmon #---------------------------------------------------------------------------------------- @@ -494,7 +494,7 @@ def _normalise_by_monitor(self): instrument parameters for the current workspace index """ indices_in_range = np.where((self.mon_pt_times >= self._mon_norm_start) & (self.mon_pt_times < self._mon_norm_end)) - + wsindex = self._ws_index # inner function to apply normalization def monitor_normalization(foil_ws, mon_ws): @@ -515,7 +515,7 @@ def monitor_normalization(foil_ws, mon_ws): def _normalise_to_foil_out(self): """ - Normalises the thin/thick foil counts to the + Normalises the thin/thick foil counts to the foil out counts between (foil_out_norm_start,foil_out_norm_end) for the current workspace index """ @@ -535,7 +535,7 @@ def normalise_to_out(foil_ws, foil_type): values *= norm_factor errors = foil_ws.dataE(wsindex) errors *= norm_factor - + normalise_to_out(self.foil_thin, "thin") if self._nperiods != 2: normalise_to_out(self.foil_thick, "thick") @@ -573,12 +573,12 @@ def _calculate_thin_difference(self, ws_index): else: cout *= -1.0 cout += self.foil_thin.readY(ws_index) - + # Errors eout = self.foil_out.dataE(ws_index) ethin = self.foil_thin.readE(ws_index) np.sqrt((eout**2 + ethin**2), eout) # The second argument makes it happen in place - + #---------------------------------------------------------------------------------------- def _calculate_double_difference(self, ws_index): """ @@ -593,7 +593,7 @@ def _calculate_double_difference(self, ws_index): cout *= one_min_beta cout -= self.foil_thin.readY(ws_index) cout += self._beta*self.foil_thick.readY(ws_index) - + # Errors eout = self.foil_out.dataE(ws_index) ethin = self.foil_thin.readE(ws_index) @@ -610,7 +610,7 @@ def _calculate_thick_difference(self, ws_index): # Counts cout = self.foil_out.dataY(ws_index) cout -= self.foil_thick.readY(ws_index) - + # Errors eout = self.foil_out.dataE(ws_index) ethick = self.foil_thick.readE(ws_index) @@ -627,7 +627,7 @@ def _load_ip_file(self, ip_file): raise ValueError("Empty filename string for IP file") ip_header = self._get_header_format(ip_file) - + # More verbose until the child algorithm stuff is sorted update_inst = self.createChildAlgorithm("UpdateInstrumentFromFile") update_inst.setLogging(_LOGGING_) @@ -637,7 +637,7 @@ def _load_ip_file(self, ip_file): update_inst.setProperty("IgnorePhi", True) update_inst.setProperty("AsciiHeader", ip_header) update_inst.execute() - + self.foil_out = update_inst.getProperty("Workspace").value #---------------------------------------------------------------------------------------- @@ -653,7 +653,7 @@ def _sum_all_spectra(self): sum_spectra.setProperty("InputWorkspace", self.foil_out) sum_spectra.setProperty("OutputWorkspace", self.foil_out) sum_spectra.execute() - + self.foil_out = sum_spectra.getProperty("OutputWorkspace").value #---------------------------------------------------------------------------------------- @@ -662,7 +662,7 @@ def _get_header_format(self, ip_filename): Returns the header format to be used for the given IP file. Currently supports 5/6 column files. Raises ValueError if anything other than a 5/6 column - file is found. + file is found. @filename ip_filename :: Full path to the IP file. @returns The header format string for use with UpdateInstrumentFromFile """ @@ -696,7 +696,7 @@ class SpectraToFoilPeriodMap(object): """Defines the mapping between a spectrum number & the period index into a WorkspaceGroup for a foil state. """ - + def __init__(self, nperiods=6): """Constructor. For nperiods seet up the mappings""" if nperiods == 2: @@ -723,7 +723,7 @@ def reorder(self, arr): """ Orders the given array by increasing value. At the same time it reorders the 1:1 map to match this order - numpy + numpy """ vals = np.array(self._one_to_one.values()) sorted_indices = arr.argsort() @@ -754,11 +754,11 @@ def get_foil_periods(self, spectrum_no, state): """Returns a list of the periods for the given spectrum number & foil state. Note that these start from 1 not zero @param spectrum_no :: A spectrum number (1->nspectra) - @param state :: 0 = foil out, 1 = foil in. + @param state :: 0 = foil out, 1 = foil in. @returns A list of period numbers for foil out state """ self._validate_spectrum_number(spectrum_no) - + foil_out = (state==0) if spectrum_no < 135: @@ -783,7 +783,7 @@ def get_indices(self, spectrum_no, foil_state_numbers): for state in foil_state_numbers: indices.append(self.get_index(spectrum_no, state)) return tuple(indices) - + def get_index(self, spectrum_no, foil_state_no): """Returns an index that can be used to access the Workspace within a WorkspaceGroup that corresponds to the foil state given @@ -794,7 +794,7 @@ def get_index(self, spectrum_no, foil_state_no): """ self._validate_foil_number(foil_state_no) self._validate_spectrum_number(spectrum_no) - + # For the back scattering banks or foil states > 6 then there is a 1:1 map if foil_state_no > 6 or spectrum_no < 135: foil_periods = self._one_to_one @@ -807,18 +807,18 @@ def get_index(self, spectrum_no, foil_state_no): else: # foil_in = 2,4,6 foil out = 1,3,5 foil_periods = self._even_odd - + foil_period_no = foil_periods[foil_state_no] return foil_period_no - 1 # Minus 1 to get to WorkspaceGroup index - + def _validate_foil_number(self, foil_number): if foil_number < 1 or foil_number > 9: raise ValueError("Invalid foil state given, expected a number between 1 and 9. number=%d" % foil_number) - + def _validate_spectrum_number(self, spectrum_no): if spectrum_no < 1 or spectrum_no > 198: raise ValueError("Invalid spectrum given, expected a number between 3 and 198. spectrum=%d" % spectrum_no) - + ######################################################################################### # Registration diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py index 1d8908d12aad..00e12cc3fdaa 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskAngle.py @@ -1,4 +1,4 @@ -import mantid.simpleapi +import mantid.simpleapi import mantid.kernel import mantid.api import numpy @@ -21,7 +21,7 @@ def summary(self): """ Mantid require """ return "Algorithm to mask detectors with scattering angles in a given interval (in degrees)." - + def PyInit(self): self.declareProperty(mantid.api.WorkspaceProperty("Workspace", "",direction=mantid.kernel.Direction.Input,validator=mantid.api.InstrumentValidator()), "Input workspace") angleValidator=mantid.kernel.FloatBoundedValidator() diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py index 7e2882a96352..31a208761b65 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskBTP.py @@ -1,4 +1,4 @@ -import mantid.simpleapi +import mantid.simpleapi import mantid.api import mantid.kernel import numpy @@ -16,21 +16,21 @@ def name(self): """ Mantid required """ return "MaskBTP" - + def summary(self): """ Mantid required """ return "Algorithm to mask detectors in particular banks, tube, or pixels." - + def PyInit(self): self.declareProperty(mantid.api.WorkspaceProperty("Workspace", "",direction=mantid.kernel.Direction.InOut, optional = mantid.api.PropertyMode.Optional), "Input workspace (optional)") allowedInstrumentList=mantid.kernel.StringListValidator(["","ARCS","CNCS","CORELLI","HYSPEC","NOMAD","POWGEN","SEQUOIA","SNAP","TOPAZ"]) self.declareProperty("Instrument","",validator=allowedInstrumentList,doc="One of the following instruments: ARCS, CNCS, CORELLI, HYSPEC, NOMAD, POWGEN, SNAP, SEQUOIA, TOPAZ") self.declareProperty("Bank","",doc="Bank(s) to be masked. If empty, will apply to all banks") self.declareProperty("Tube","",doc="Tube(s) to be masked. If empty, will apply to all tubes") - self.declareProperty("Pixel","",doc="Pixel(s) to be masked. If empty, will apply to all pixels") - self.declareProperty(mantid.kernel.IntArrayProperty(name="MaskedDetectors", direction=mantid.kernel.Direction.Output), doc="List of masked detectors") - + self.declareProperty("Pixel","",doc="Pixel(s) to be masked. If empty, will apply to all pixels") + self.declareProperty(mantid.kernel.IntArrayProperty(name="MaskedDetectors", direction=mantid.kernel.Direction.Output), doc="List of masked detectors") + def PyExec(self): ws = self.getProperty("Workspace").value @@ -38,52 +38,52 @@ def PyExec(self): self.instname = self.getProperty("Instrument").value bankString = self.getProperty("Bank").value tubeString = self.getProperty("Tube").value - pixelString = self.getProperty("Pixel").value - + pixelString = self.getProperty("Pixel").value + if self.instname == "" and ws == None: - raise ValueError("No workspace or instrument were selected" ) + raise ValueError("No workspace or instrument were selected" ) if ws != None: self.instrument = ws.getInstrument() self.instname = self.instrument.getName() - + instrumentList=["ARCS","CNCS","CORELLI","HYSPEC","NOMAD","POWGEN","SEQUOIA","SNAP","TOPAZ"] self.bankmin={"ARCS":1,"CNCS":1,"CORELLI":1,"HYSPEC":1,"NOMAD":1,"POWGEN":1,"SEQUOIA":38,"SNAP":1,"TOPAZ":10} self.bankmax={"ARCS":115,"CNCS":50,"CORELLI":91,"HYSPEC":20,"NOMAD":99,"POWGEN":300,"SEQUOIA":150,"SNAP":18,"TOPAZ":59} tubemin={"ARCS":1,"CNCS":1,"CORELLI":1,"HYSPEC":1,"NOMAD":1,"POWGEN":0,"SEQUOIA":1,"SNAP":0,"TOPAZ":0} tubemax={"ARCS":8,"CNCS":8,"CORELLI":16,"HYSPEC":8,"NOMAD":8,"POWGEN":153,"SEQUOIA":8,"SNAP":255,"TOPAZ":255} pixmin={"ARCS":1,"CNCS":1,"CORELLI":1,"HYSPEC":1,"NOMAD":1,"POWGEN":0,"SEQUOIA":1,"SNAP":0,"TOPAZ":0} - pixmax={"ARCS":128,"CNCS":128,"CORELLI":256,"HYSPEC":128,"NOMAD":128,"POWGEN":6,"SEQUOIA":128,"SNAP":255,"TOPAZ":255} - + pixmax={"ARCS":128,"CNCS":128,"CORELLI":256,"HYSPEC":128,"NOMAD":128,"POWGEN":6,"SEQUOIA":128,"SNAP":255,"TOPAZ":255} + try: instrumentList.index(self.instname) except: raise ValueError("Instrument "+self.instname+" not in the allowed list") - + if (self.instrument==None): IDF=mantid.api.ExperimentInfo.getInstrumentFilename(self.instname) if mantid.mtd.doesExist(self.instname+"MaskBTP"): mantid.simpleapi.DeleteWorkspace(self.instname+"MaskBTP") ws=mantid.simpleapi.LoadEmptyInstrument(IDF,OutputWorkspace=self.instname+"MaskBTP") self.instrument=ws.getInstrument() - + if (bankString == ""): banks=numpy.arange(self.bankmax[self.instname]-self.bankmin[self.instname]+1)+self.bankmin[self.instname] else: banks=self._parseBTPlist(bankString) - + if (tubeString == ""): tubes=numpy.arange(tubemax[self.instname]-tubemin[self.instname]+1)+tubemin[self.instname] else: tubes=self._parseBTPlist(tubeString) - + if(pixelString == ""): pixels=numpy.arange(pixmax[self.instname]-pixmin[self.instname]+1)+pixmin[self.instname] else: pixels=self._parseBTPlist(pixelString) - - + + detlist=[] for b in banks: ep=self._getEightPackHandle(b) @@ -105,9 +105,9 @@ def PyExec(self): mantid.simpleapi.MaskDetectors(Workspace=ws,DetectorList=detlist) else: self.log().information("no detectors within this range") - self.setProperty("Workspace",ws.name()) + self.setProperty("Workspace",ws.name()) self.setProperty("MaskedDetectors", numpy.array(detlist)) - + def _parseBTPlist(self,value): """ Helper function to transform a string into a list of integers @@ -131,7 +131,7 @@ def _parseBTPlist(self,value): elemlist = range(startelem,endelem+1) parsed.extend(elemlist) return parsed - + def _getEightPackHandle(self,banknum): """ Helper function to return the handle to a given eightpack @@ -163,7 +163,7 @@ def _getEightPackHandle(self,banknum): elif(114<=banknum<=self.bankmax[self.instname]): return self.instrument.getComponentByName("D row")[banknum-114][0] else: - raise ValueError("Out of range index for SEQUOIA instrument bank numbers") + raise ValueError("Out of range index for SEQUOIA instrument bank numbers") elif self.instname=="CNCS" or self.instname=="HYSPEC": if (self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]): return self.instrument.getComponentByName("bank"+str(banknum))[0] @@ -173,5 +173,5 @@ def _getEightPackHandle(self,banknum): if (self.bankmin[self.instname]<=banknum<= self.bankmax[self.instname]): return self.instrument.getComponentByName("bank"+str(banknum)) else: - raise ValueError("Out of range index for "+str(self.instname)+" instrument bank numbers") + raise ValueError("Out of range index for "+str(self.instname)+" instrument bank numbers") mantid.api.AlgorithmFactory.subscribe(MaskBTP) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py index 1624b058a4e7..10848174236a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MaskWorkspaceToCalFile.py @@ -5,79 +5,79 @@ class QueryFlag: def isMasked(self, detector, yValue): - return detector.isMasked() - + return detector.isMasked() + class QueryValue: def isMasked(self, detector, yValue): - return yValue == 1 + return yValue == 1 class MaskWorkspaceToCalFile(PythonAlgorithm): - def category(self): - return "DataHandling\\Text;Diffraction;PythonAlgorithms" - - def name(self): - return "MaskWorkspaceToCalFile" - - def summary(self): - return "Saves the masking information in a workspace to a Cal File." - - def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), "The workspace containing the Masking to extract.") - self.declareProperty(FileProperty(name="OutputFile",defaultValue="",action=FileAction.Save,extensions=['cal']), "The file for the results.") - - self.declareProperty("Invert", False, "If True, masking is inverted in the input workspace. Default: False") - - def PyExec(self): - #extract settings - inputWorkspace = mtd[self.getPropertyValue("InputWorkspace")] - outputFileName = self.getProperty("OutputFile").value - invert = self.getProperty("Invert").value - mask_query = QueryFlag() - if inputWorkspace.id() == "MaskWorkspace": - mask_query = QueryValue() - + def category(self): + return "DataHandling\\Text;Diffraction;PythonAlgorithms" + + def name(self): + return "MaskWorkspaceToCalFile" + + def summary(self): + return "Saves the masking information in a workspace to a Cal File." + + def PyInit(self): + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input), "The workspace containing the Masking to extract.") + self.declareProperty(FileProperty(name="OutputFile",defaultValue="",action=FileAction.Save,extensions=['cal']), "The file for the results.") + + self.declareProperty("Invert", False, "If True, masking is inverted in the input workspace. Default: False") + + def PyExec(self): + #extract settings + inputWorkspace = mtd[self.getPropertyValue("InputWorkspace")] + outputFileName = self.getProperty("OutputFile").value + invert = self.getProperty("Invert").value + mask_query = QueryFlag() + if inputWorkspace.id() == "MaskWorkspace": + mask_query = QueryValue() + #check for consistency - if len(inputWorkspace.readX(0)) < 1: - raise RuntimeError('The input workspace is empty.') - - #define flags for masking and not-masking - masking_flag = 0 - not_masking_flag = 1 - - if invert: - masking_flag, not_masking_flag = not_masking_flag, masking_flag - - calFile = open(outputFileName,"w") - #write a header - instrumentName = inputWorkspace.getInstrument().getName() - calFile.write('# '+instrumentName+' detector file\n') - calFile.write('# Format: number UDET offset select group\n') - #save the grouping - for i in range(inputWorkspace.getNumberHistograms()): - try: - det = inputWorkspace.getDetector(i) - y_value = inputWorkspace.readY(i)[0] - if (mask_query.isMasked(det, y_value)): #check if masked - group = masking_flag - else: - group = not_masking_flag - detIDs = [] - try: - detIDs = det.getDetectorIDs() - except: - detIDs = [det.getID()] - for id in detIDs: - calFile.write(self.FormatLine(i,id,0.0,group,group)) - except: - #no detector for this spectra - pass - calFile.close() - - - def FormatLine(self,number,UDET,offset,select,group): - line = "{0:9d}{1:16d}{2:16.7f}{3:9d}{4:9d}\n".format(number,UDET,offset,select,group) - return line + if len(inputWorkspace.readX(0)) < 1: + raise RuntimeError('The input workspace is empty.') + + #define flags for masking and not-masking + masking_flag = 0 + not_masking_flag = 1 + + if invert: + masking_flag, not_masking_flag = not_masking_flag, masking_flag + + calFile = open(outputFileName,"w") + #write a header + instrumentName = inputWorkspace.getInstrument().getName() + calFile.write('# '+instrumentName+' detector file\n') + calFile.write('# Format: number UDET offset select group\n') + #save the grouping + for i in range(inputWorkspace.getNumberHistograms()): + try: + det = inputWorkspace.getDetector(i) + y_value = inputWorkspace.readY(i)[0] + if (mask_query.isMasked(det, y_value)): #check if masked + group = masking_flag + else: + group = not_masking_flag + detIDs = [] + try: + detIDs = det.getDetectorIDs() + except: + detIDs = [det.getID()] + for id in detIDs: + calFile.write(self.FormatLine(i,id,0.0,group,group)) + except: + #no detector for this spectra + pass + calFile.close() + + + def FormatLine(self,number,UDET,offset,select,group): + line = "{0:9d}{1:16d}{2:16.7f}{3:9d}{4:9d}\n".format(number,UDET,offset,select,group) + return line ############################################################################################# diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py index 3c32a2c8df93..54b5e72b53af 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Mean.py @@ -12,17 +12,17 @@ def name(self): def summary(self): return "Calculates the arithemetic mean of the workspaces provided." - + def PyInit(self): mustHaveWorkspaceNames = StringMandatoryValidator() self.declareProperty("Workspaces", "", validator=mustHaveWorkspaceNames, direction=Direction.Input, doc="Input workspaces. Comma separated workspace names") self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Output mean workspace") - + def areWorkspacesCompatible(self, a, b): - sizeA = a.blocksize() * a.getNumberHistograms() + sizeA = a.blocksize() * a.getNumberHistograms() sizeB = b.blocksize() * b.getNumberHistograms() return sizeA == sizeB - + def PyExec(self): workspaces = self.getProperty("Workspaces").value.split(',') out_ws = CloneWorkspace(InputWorkspace=mtd[workspaces[0]], OutputWorkspace=self.getPropertyValue("OutputWorkspace")) @@ -34,7 +34,7 @@ def PyExec(self): out_ws += ws out_ws /= len(workspaces) self.setProperty("OutputWorkspace", out_ws) - + ############################################################################################# diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py index 63ac11749107..ea164973bf8c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/MergeCalFiles.py @@ -11,16 +11,16 @@ def name(self): def summary(self): return "Combines the data from two Cal Files." - + def PyInit(self): self.declareProperty(FileProperty("UpdateFile","", FileAction.Load, ['cal']), doc="The cal file containing the updates to merge into another file.") self.declareProperty(FileProperty("MasterFile","", FileAction.Load, ['cal']), doc="The master file to be altered, the file must be sorted by UDET") self.declareProperty(FileProperty("OutputFile","", FileAction.Save, ['cal']), doc="The file to contain the results") - + self.declareProperty("MergeOffsets", False, doc="If True, the offsets from file1 will be merged to the master file. Default: False") self.declareProperty("MergeSelections", False, doc="If True, the selections from file1 will be merged to the master file. Default: False") self.declareProperty("MergeGroups", False, doc="If True, the Groups from file1 will be merged to the master file. Default: False") - + def PyExec(self): #extract settings mergeOffsets = self.getProperty("MergeOffsets").value @@ -29,13 +29,13 @@ def PyExec(self): updateFileName = self.getPropertyValue("UpdateFile") masterFileName = self.getPropertyValue("MasterFile") outputFileName = self.getPropertyValue("OutputFile") - - + + if (masterFileName == outputFileName) : raise RuntimeError('The output file must be different to the master file.') - + self.DisplayMessage(mergeOffsets,mergeSelections,mergeGroups,updateFileName,masterFileName) - + updateFile = open(updateFileName,"r") updateDict=dict() lastNumber = 0 @@ -52,14 +52,14 @@ def PyExec(self): pass #remeber all of the values updateDict[UDET] = (offset,select,group) - + updateFile.close() self.log().information(str(len(updateDict)) + " updates found in " + updateFileName) - - + + masterFile = open(masterFileName,"r") outputFile = open(outputFileName,"w") - + for line in masterFile: if self.IsComment(line): #copy the comment over @@ -92,29 +92,29 @@ def PyExec(self): lastNumber += 1 outputFile.write(self.FormatLine(lastNumber,UDET,offset,select,group)) linesAdded += 1 - + self.log().information("{0} lines Updated, {1} lines added, {2} lines untouched".format(linesUpdated,linesAdded,linesUntouched)) #close the files masterFile.close() outputFile.close() - + def DisplayMessage(self,mergeOffsets,mergeSelections,mergeGroups,fileName1,fileName2): #Log the settings string outputString = "Merging " - if (mergeOffsets): + if (mergeOffsets): outputString+= "offsets, " - if (mergeSelections): + if (mergeSelections): outputString+= "selections, " - if (mergeGroups): + if (mergeGroups): outputString+= "groups, " #strip the final comma outputString = outputString [0:len(outputString)-2] outputString += " from file " + fileName1 + " into " + fileName2 self.log().information(outputString) - + def IsComment(self,line): return line.startswith("#") - + def ProcessLine(self,line): try: elements = line.split() @@ -126,10 +126,10 @@ def ProcessLine(self,line): except: raise ValueError("invalid line: " + line) return (number,UDET,offset,select,group) - + def FormatLine(self,number,UDET,offset,select,group): line = "{0:9d}{1:16d}{2:16.7f}{3:9d}{4:9d}\n".format(number,UDET,offset,select,group) return line - + ############################################################################################# AlgorithmFactory.subscribe(MergeCalFiles()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py index f9e549b9f5bf..6335b9d222be 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PDDetermineCharacterizations.py @@ -37,7 +37,7 @@ def name(self): def summary(self): return "Determines the characterizations of a workspace." - + def PyInit(self): # input parameters self.declareProperty(WorkspaceProperty("InputWorkspace", "", @@ -49,16 +49,16 @@ def PyInit(self): "Table of characterization information") self.declareProperty("ReductionProperties", - "__pd_reduction_properties", + "__pd_reduction_properties", validator=StringMandatoryValidator(), doc="Property manager name for the reduction") defaultMsg = " run to use. 0 to use value in table, -1 to not use." - self.declareProperty("BackRun", 0, + self.declareProperty("BackRun", 0, doc="The background" + defaultMsg) - self.declareProperty("NormRun", 0, + self.declareProperty("NormRun", 0, doc="The background" + defaultMsg) - self.declareProperty("NormBackRun", 0, + self.declareProperty("NormBackRun", 0, doc="The background" + defaultMsg) def validateInputs(self): @@ -109,7 +109,7 @@ def PyExec(self): self.log().information("Determined frequency: " + str(frequency) \ + " Hz, center wavelength:" \ + str(wavelength) + " Angstrom") - + # get a row of the table info = self.getLine(char, frequency, wavelength) @@ -130,7 +130,7 @@ def PyExec(self): def processInformation(self, prop_man, info_dict): for key in COL_NAMES: val = info_dict[key] - # Convert comma-delimited list to array, else return the original + # Convert comma-delimited list to array, else return the original # value. if type("") == type(val): val = [float(x) for x in val.split(',')] @@ -179,7 +179,7 @@ def getFrequency(self, logs, wkspName): self.log().information(msg) else: frequency = frequency.getStatistics().mean - if frequency == 0.: + if frequency == 0.: self.log().information("'%s' mean value is zero" % name) else: self.log().information("Found frequency in %s log" \ diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py index 1820366bbc39..5120101e9c90 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PearlMCAbsorption.py @@ -10,13 +10,13 @@ def category(self): def summary(self): return "Loads pre-calculated or measured absorption correction files for Pearl." - + def PyInit(self): # Input file self.declareProperty(FileProperty("Filename","", FileAction.Load, ['.out','.dat']), doc="The name of the input file.") # Output workspace self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace","", direction=Direction.Output), doc="The name of the input file.") - + def PyExec(self): filename = self.getProperty("Filename").value thickness = self._parseHeader(filename) @@ -26,7 +26,7 @@ def PyExec(self): x_unit = 'Wavelength' else: x_unit = 'dSpacing' - + wkspace_name = self.getPropertyValue("OutputWorkspace") # Load the file ascii_wkspace = LoadAscii(Filename=filename, OutputWorkspace=wkspace_name, Separator="Space", Unit=x_unit) @@ -34,15 +34,15 @@ def PyExec(self): coeffs = ascii_wkspace else: coeffs = self._calculateAbsorption(ascii_wkspace, float(thickness)) - + coeffs.setYUnitLabel("Attenuation Factor (I/I0)") coeffs.setYUnit(""); coeffs.setDistribution(True) self.setProperty("OutputWorkspace", coeffs) def _parseHeader(self, filename): - """Parses the header in the file. - If the first line contains t= then this is assumed to be measured file else + """Parses the header in the file. + If the first line contains t= then this is assumed to be measured file else calculated is assumed. """ # Parse some header information to test whether this is a measured or calculated file diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py index 6c19116f6395..46eafcbd4886 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiMerge.py @@ -13,10 +13,10 @@ def category(self): def name(self): return "PoldiMerge" - + def summary(self): return "PoldiMerge takes a list of workspace names and adds the counts, resulting in a new workspace." - + def PyInit(self): self.declareProperty(StringArrayProperty(name="WorkspaceNames", direction=Direction.Input), diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py index 39acc23c8703..10e66a2436d7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddDir.py @@ -1,8 +1,8 @@ -from mantid.api import (PythonAlgorithm, +from mantid.api import (PythonAlgorithm, AlgorithmFactory) -from mantid.api import (FileProperty, +from mantid.api import (FileProperty, FileAction) -from mantid.api import (ITableWorkspaceProperty, +from mantid.api import (ITableWorkspaceProperty, WorkspaceFactory) from mantid.kernel import Direction @@ -15,7 +15,7 @@ class PoldiProjectAddDir(PythonAlgorithm): - + def category(self): """ Mantid required """ @@ -32,40 +32,40 @@ def summary(self): def PyInit(self): """ Mantid required """ - + self.declareProperty(FileProperty(name="Directory",defaultValue="",action=FileAction.Directory)) self.declareProperty(ITableWorkspaceProperty("PoldiAnalysis", "PoldiAnalysis", direction=Direction.Output), "Poldi analysis main worksheet") - - - - + + + + def path_leaf(path): head, tail = ntpath.split(path) return tail - - + + def interpreteName(self, name): patern="(.*[ a-zA-Z]*/*\*)*poldi(?P[0-9]*)n(?P[0-9]*)" regex = re.match(patern, name, re.M|re.I) year = int(regex.group("year")) numero = int(regex.group("numero")) return (year, numero) - - - - - - + + + + + + def PyExec(self): """ Mantid required """ self.log().warning('Poldi Data Analysis ---- add dir') load_data_at_the_end = False - + sample_info_ws_name = "" - + try: sample_info_ws_name = self.getProperty("PoldiAnalysis").value if(sample_info_ws_name == ""): @@ -86,27 +86,27 @@ def PyExec(self): sample_info_ws.addColumn("str","spl peak") load_data_at_the_end = True # self.setProperty("PoldiAnalysis", sample_info_ws) - - - + + + # self.log().debug('Poldi Data Analysis ---- %s'%(sample_info_ws_name)) # sample_info_ws = mtd[sample_info_ws_name] - - + + directory = self.getProperty("Directory").value - + onlyfiles = [ f for f in listdir(directory) if isfile(join(directory,f)) ] - + self.log().debug('Poldi - load data') for dataFile in onlyfiles: (sample_name, sampleExt) = splitext(dataFile) file_path = join(directory,dataFile) - + # PoldiProjectAddFile(File=file_path) # , PoldiAnalysis=sample_info_ws) - - - + + + if("hdf" in sampleExt): self.log().error('Poldi - samples : %s' %(sample_name)) file_path = join(directory,dataFile) @@ -115,25 +115,25 @@ def PyExec(self): sample_name_deadw = "%sDeadWires" %sample_name (sample_year, sample_numero) = self.interpreteName(sample_name) sample_name_peak = "%sPeak" %sample_name - - sample_info_ws.addRow([sample_name, sample_year, sample_numero, file_path, - sample_name_log, + + sample_info_ws.addRow([sample_name, sample_year, sample_numero, file_path, + sample_name_log, sample_name_corr, sample_name_deadw, - sample_name_peak]) + sample_name_peak]) nb_of_sample = sample_info_ws.rowCount() self.log().error('Poldi - %d samples added' %(nb_of_sample)) - - - - + + + + if(load_data_at_the_end): self.setProperty("PoldiAnalysis", sample_info_ws) - - + + # if(self.getProperty("RunTheAnalysis").value): # PoldiProjectRun(InputWorkspace=sample_info_ws) - + AlgorithmFactory.subscribe(PoldiProjectAddDir) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py index 5e226af0470b..6b93e1d1513e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectAddFile.py @@ -9,7 +9,7 @@ class PoldiProjectAddFile(PythonAlgorithm): - + def category(self): """ Mantid required """ @@ -30,32 +30,32 @@ def PyInit(self): self.declareProperty(FileProperty(name="File",defaultValue="",action=FileAction.Load), "Poldi data file") self.declareProperty(ITableWorkspaceProperty(name="OutputWorkspace", defaultValue="PoldiAnalysis", direction=Direction.Output), "Poldi analysis main worksheet") - - - + + + def path_leaf(path): head, tail = ntpath.split(path) return tail - - + + def interpreteName(self, name): patern="(.*[ a-zA-Z]*/*\*)*poldi(?P[0-9]*)n(?P[0-9]*)" regex = re.match(patern, name, re.M|re.I) year = int(regex.group("year")) numero = int(regex.group("numero")) return (year, numero) - - - - - - + + + + + + def PyExec(self): """ Mantid required """ self.log().debug('Poldi Data Analysis ---- start') sample_info_ws = None - + try: sample_info_ws_name = self.getProperty("OutputWorkspace").valueAsStr if(sample_info_ws_name == ""): @@ -74,16 +74,16 @@ def PyExec(self): sample_info_ws.addColumn("str","spl corr") sample_info_ws.addColumn("str","spl dead wires") sample_info_ws.addColumn("str","spl peak") - + dataFile = self.getProperty("File").value - + self.log().debug('Poldi - load data - %s'%(dataFile)) (sample_root, sample_name) = split(dataFile) (sample_name, sampleExt) = splitext(sample_name) self.log().error('Poldi - samples : %s' %(sample_root)) self.log().error('Poldi - : %s' %(sample_name)) self.log().error('Poldi - : %s' %(sampleExt)) - + if("hdf" in sampleExt): self.log().error('Poldi - samples : %s' %(sample_name)) file_path = dataFile @@ -92,18 +92,18 @@ def PyExec(self): sample_name_deadw = "%sDeadWires" %sample_name (sample_year, sample_numero) = self.interpreteName(sample_name) sample_name_peak = "%sPeak" %sample_name - - sample_info_ws.addRow([sample_name, sample_year, sample_numero, file_path, - sample_name_log, + + sample_info_ws.addRow([sample_name, sample_year, sample_numero, file_path, + sample_name_log, sample_name_corr, sample_name_deadw, sample_name_peak]) nb_of_sample = sample_info_ws.rowCount() self.log().error('Poldi - 1 samples added') self.log().error(' - %d samples in total' %(nb_of_sample)) - - self.setProperty("OutputWorkspace", sample_info_ws) - + + self.setProperty("OutputWorkspace", sample_info_ws) + AlgorithmFactory.subscribe(PoldiProjectAddFile) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py index 980e83f3cdc3..3480e64a2f54 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/PoldiProjectRun.py @@ -5,11 +5,11 @@ from mantid.kernel import Direction, ConfigServiceImpl from mantid.simpleapi import config, mtd -from mantid.simpleapi import (LoadSINQFile, - PoldiLoadLog, - LoadInstrument, - PoldiRemoveDeadWires, - PoldiLoadChopperSlits, +from mantid.simpleapi import (LoadSINQFile, + PoldiLoadLog, + LoadInstrument, + PoldiRemoveDeadWires, + PoldiLoadChopperSlits, PoldiLoadSpectra, PoldiLoadIPP, PoldiAutoCorrelation, @@ -22,7 +22,7 @@ class PoldiProjectRun(PythonAlgorithm): - + def category(self): """ Mantid required """ @@ -35,44 +35,44 @@ def name(self): def summary(self): return "Run the POLDI analysis process for a bunch of data files stored in a tableWorkspace." - + def PyInit(self): """ Mantid required - """ - self.declareProperty(ITableWorkspaceProperty("InputWorkspace", "PoldiAnalysis", direction=Direction.Input), + """ + self.declareProperty(ITableWorkspaceProperty("InputWorkspace", "PoldiAnalysis", direction=Direction.Input), "Poldi analysis main worksheet") self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "PoldiIPPmanager", direction=Direction.Output), "Poldi IPP table manager") - - self.declareProperty("wlenmin", 1.1, - doc = 'minimal wavelength considered' , + + self.declareProperty("wlenmin", 1.1, + doc = 'minimal wavelength considered' , direction = Direction.Input) - self.declareProperty("wlenmax", 5.0, - doc = 'maximal wavelength considered' , + self.declareProperty("wlenmax", 5.0, + doc = 'maximal wavelength considered' , direction = Direction.Input) - - - self.declareProperty("BadWiresThreshold", 0.8, - doc = 'Bad wires threshold parameter', + + + self.declareProperty("BadWiresThreshold", 0.8, + doc = 'Bad wires threshold parameter', direction = Direction.Input) - - self.declareProperty("PeakDetectionThreshold", 0.2, - doc = 'Peak detection threshold parameter', + + self.declareProperty("PeakDetectionThreshold", 0.2, + doc = 'Peak detection threshold parameter', direction = Direction.Input) - - - - - + + + + + def PyExec(self): """ Mantid required """ self.log().debug('Poldi Data Analysis ---- start') - + sample_info_ws = self.getProperty("InputWorkspace").value - + load_data_at_the_end = False try: sample_ipp_ws_name = self.getProperty("OutputWorkspace").value @@ -87,109 +87,109 @@ def PyExec(self): sample_ipp_ws.addColumn("str","spl Name") sample_ipp_ws.addColumn("str","ipp version") load_data_at_the_end = True - - + + wlen_min = self.getProperty("wlenmin").value wlen_max = self.getProperty("wlenmax").value - + bad_wires_threshold = self.getProperty("BadWiresThreshold").value peak_detect_threshold = self.getProperty("PeakDetectionThreshold").value - + self.log().information('Poldi run with parameters') self.log().information(' - wlen_min : %s' %(wlen_min)) self.log().information(' - wlen_max : %s' %(wlen_max)) self.log().information(' - bad_wires_threshold : %s' %(bad_wires_threshold)) self.log().information(' - peak_detect_threshold : %s' %(peak_detect_threshold)) - + dictsearch=os.path.join(config['instrumentDefinition.directory'],"nexusdictionaries","poldi.dic") self.log().information('Poldi instr folder - %s' %(dictsearch)) - - firstOne="" - + + firstOne="" + self.log().debug('Poldi - load data') nb_of_sample = sample_info_ws.rowCount() self.log().information('Poldi - %d samples listed' %(nb_of_sample)) - + for sample in range(nb_of_sample): sampleName = sample_info_ws.column("spl Name")[sample] filePath = sample_info_ws.column("data file")[sample] sampleNameLog = sample_info_ws.column("spl log")[sample] sampleDeadWires = sample_info_ws.column("spl dead wires")[sample] - + self.log().information('Poldi - sample %s' %(sampleName)) - LoadSINQFile(Instrument="POLDI", - Filename=filePath, + LoadSINQFile(Instrument="POLDI", + Filename=filePath, OutputWorkspace=sampleName) - + sample_output_ws = mtd[sampleName] - - PoldiLoadLog(InputWorkspace=sample_output_ws, - Filename=filePath, - Dictionary=dictsearch, + + PoldiLoadLog(InputWorkspace=sample_output_ws, + Filename=filePath, + Dictionary=dictsearch, PoldiLog=sampleNameLog) - + cfgService = ConfigServiceImpl.Instance() - LoadInstrument(Workspace=sample_output_ws, + LoadInstrument(Workspace=sample_output_ws, Filename=cfgService.getInstrumentDirectory() + "POLDI_Definition_ipp13.xml", RewriteSpectraMap=True) - - + + self.log().debug('Poldi - set ipp') sample_instrument = sample_output_ws.getInstrument() ipp_version = sample_instrument.getStringParameter("ipp")[0] - + add_this_ipp = True for ipp in range(sample_ipp_ws.rowCount()): if(sample_ipp_ws.column("ipp version")[ipp] == ipp_version): add_this_ipp = False if(add_this_ipp): sample_ipp_ws.addRow([sampleName, ipp_version]) - - + + self.log().debug('Poldi - dead wires') - PoldiRemoveDeadWires(InputWorkspace=sample_output_ws, - RemoveExcludedWires=True, + PoldiRemoveDeadWires(InputWorkspace=sample_output_ws, + RemoveExcludedWires=True, AutoRemoveBadWires=False, - BadWiresThreshold=bad_wires_threshold, + BadWiresThreshold=bad_wires_threshold, PoldiDeadWires=sampleDeadWires) - - - + + + nb_of_ipp = sample_ipp_ws.rowCount() self.log().information('Poldi - %d ipp listed' %(nb_of_ipp)) - + for ipp in range(nb_of_ipp): ex_of_sample = sample_ipp_ws.column("spl Name")[ipp] PoldiIPP = sample_ipp_ws.column("ipp version")[ipp] ipp_chopper_slits = "%s_Chopper" %PoldiIPP ipp_Poldi_spectra = "%s_Spectra" %PoldiIPP ipp_ipp_data = "%s_Data" %PoldiIPP - + ex_of_sample_ws = mtd[ex_of_sample] - + self.log().debug('Poldi - chopper slits') - PoldiLoadChopperSlits(InputWorkspace=ex_of_sample_ws, + PoldiLoadChopperSlits(InputWorkspace=ex_of_sample_ws, PoldiChopperSlits=ipp_chopper_slits) - - + + self.log().debug('Poldi - spectra') - PoldiLoadSpectra(InputWorkspace=ex_of_sample_ws, + PoldiLoadSpectra(InputWorkspace=ex_of_sample_ws, PoldiSpectra=ipp_Poldi_spectra) - - + + self.log().debug('Poldi - IPP') - PoldiLoadIPP(InputWorkspace=ex_of_sample_ws, + PoldiLoadIPP(InputWorkspace=ex_of_sample_ws, PoldiIPP=ipp_ipp_data) - - + + for sample in range(nb_of_sample): sampleName = sample_info_ws.column("spl Name" )[sample] filePath = sample_info_ws.column("data file")[sample] sampleNameLog = sample_info_ws.column("spl log" )[sample] sampleDeadWires= sample_info_ws.column("spl dead wires" )[sample] sampleNameCorr = sample_info_ws.column("spl corr" )[sample] - + groupedResults = GroupWorkspaces([mtd[sampleName].name(), sampleNameLog, sampleDeadWires]) RenameWorkspace(InputWorkspace=groupedResults, OutputWorkspace="%s_Metadata" % sampleName) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py index 6a2b537f06e4..5ab7bc8c541e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefLReduction.py @@ -19,13 +19,13 @@ def category(self): def name(self): return "RefLReduction" - + def version(self): return 1 def summary(self): return "Liquids Reflectometer (REFL) reduction" - + def PyInit(self): self.declareProperty(IntArrayProperty("RunNumbers"), "List of run numbers to process") self.declareProperty("NormalizationRunNumber", 0, "Run number of the normalization run to use") @@ -39,16 +39,16 @@ def PyInit(self): self.declareProperty(IntArrayProperty("NormPeakPixelRange", [127,133], IntArrayLengthValidator(2), direction=Direction.Input), "Pixel range defining the normalization peak") - self.declareProperty("SubtractNormBackground", True, + self.declareProperty("SubtractNormBackground", True, doc="If true, the background will be subtracted from the normalization peak") self.declareProperty(IntArrayProperty("NormBackgroundPixelRange", [127,137], IntArrayLengthValidator(2), direction=Direction.Input), - "Pixel range defining the background for the normalization") + "Pixel range defining the background for the normalization") self.declareProperty("LowResDataAxisPixelRangeFlag", True, doc="If true, the low resolution direction of the data will be cropped according to the lowResDataAxisPixelRange property") self.declareProperty(IntArrayProperty("LowResDataAxisPixelRange", [115,210], IntArrayLengthValidator(2), direction=Direction.Input), - "Pixel range to use in the low resolution direction of the data") + "Pixel range to use in the low resolution direction of the data") self.declareProperty("LowResNormAxisPixelRangeFlag", True, doc="If true, the low resolution direction of the normalization run will be cropped according to the LowResNormAxisPixelRange property") self.declareProperty(IntArrayProperty("LowResNormAxisPixelRange", [115,210], @@ -58,7 +58,7 @@ def PyInit(self): FloatArrayLengthValidator(2), direction=Direction.Input), "TOF range to use") self.declareProperty("TofRangeFlag", True, - doc="If true, the TOF will be cropped according to the TOF range property") + doc="If true, the TOF will be cropped according to the TOF range property") self.declareProperty("QMin", 0.05, doc="Mnimum Q-value") self.declareProperty("QStep", 0.02, doc="Step size in Q. Enter a negative value to get a log scale") self.declareProperty("AngleOffset", 0.0, doc="angle offset (degrees)") @@ -67,20 +67,20 @@ def PyInit(self): # self.declareProperty("", True, # doc="Use Scaling Factor configuration file") self.declareProperty("ScalingFactorFile", "", doc="Scaling factor configuration file") - self.declareProperty("SlitsWidthFlag", True, + self.declareProperty("SlitsWidthFlag", True, doc="Looking for perfect match of slits width when using Scaling Factor file") self.declareProperty("IncidentMediumSelected", "", doc="Incident medium used for those runs") self.declareProperty("GeometryCorrectionFlag", False, doc="Use or not the geometry correction") - def PyExec(self): - + def PyExec(self): + print '-- > starting new Reflectometer Reduction ...' - + import os import numpy import math from reduction.instruments.reflectometer import wks_utility - + from mantid import mtd #remove all previous workspaces list_mt = mtd.getObjectNames() @@ -93,7 +93,7 @@ def PyExec(self): # retrieve settings from GUI print '-> Retrieving settings from GUI' - + # DATA dataRunNumbers = self.getProperty("RunNumbers").value dataPeakRange = self.getProperty("SignalPeakPixelRange").value @@ -107,8 +107,8 @@ def PyExec(self): dataLowResRange = self.getProperty("LowResDataAxisPixelRange").value else: dataLowResRange = [0,maxX-1] - - # NORM + + # NORM normalizationRunNumber = self.getProperty("NormalizationRunNumber").value normFlag = self.getProperty("NormFlag") normBackRange = self.getProperty("NormBackgroundPixelRange").value @@ -122,7 +122,7 @@ def PyExec(self): normLowResRange = self.getProperty("LowResNormAxisPixelRange").value else: normLowResRange = [0,maxX-1] - + #GENERAL TOFrangeFlag = self.getProperty("TofRangeFlag") if (TOFrangeFlag): @@ -147,29 +147,29 @@ def PyExec(self): #dimension of the detector (256 by 304 pixels) maxX = 304 maxY = 256 - + h = 6.626e-34 #m^2 kg s^-1 m = 1.675e-27 #kg # sfCalculator settings slitsValuePrecision = sfCalculator.PRECISION sfFile = self.getProperty("ScalingFactorFile").value - + incidentMedium = self.getProperty("IncidentMediumSelected").value slitsWidthFlag = self.getProperty("SlitsWidthFlag").value - # ==== done retrievin the settings ===== + # ==== done retrievin the settings ===== # ==== start reduction ==== - # work with data + # work with data # load data - ws_event_data = wks_utility.loadNeXus(dataRunNumbers, 'data') - + ws_event_data = wks_utility.loadNeXus(dataRunNumbers, 'data') + ## retrieve general informations # calculate the central pixel (using weighted average) print '-> retrieving general informations' - data_central_pixel = wks_utility.getCentralPixel(ws_event_data, - dataPeakRange) + data_central_pixel = wks_utility.getCentralPixel(ws_event_data, + dataPeakRange) # get the distance moderator-detector and sample-detector [dMD, dSD] = wks_utility.getDistances(ws_event_data) # get theta @@ -182,7 +182,7 @@ def PyExec(self): ws_histo_data = wks_utility.rebinNeXus(ws_event_data, [binTOFrange[0], binTOFsteps, binTOFrange[1]], 'data') - + # get q range q_range = wks_utility.getQrange(ws_histo_data, theta, dMD, qMin, qStep) @@ -190,14 +190,14 @@ def PyExec(self): [first_slit_size, last_slit_size] = wks_utility.getSlitsSize(ws_histo_data) # keep only TOF range - ws_histo_data = wks_utility.cropTOF(ws_histo_data, + ws_histo_data = wks_utility.cropTOF(ws_histo_data, TOFrange[0], TOFrange[1], 'data') - + # normalize by current proton charge ws_histo_data = wks_utility.normalizeNeXus(ws_histo_data, 'data') - + # integrate over low resolution range [data_tof_axis, data_y_axis, data_y_error_axis] = wks_utility.integrateOverLowResRange(ws_histo_data, dataLowResRange, @@ -208,7 +208,7 @@ def PyExec(self): # data_tof_axis, # data_y_axis, # data_y_error_axis) - + tof_axis = data_tof_axis[0:-1].copy() tof_axis_full = data_tof_axis.copy() @@ -216,13 +216,13 @@ def PyExec(self): # data_y_axis.shape -> (256,61) #substract background - [data_y_axis, data_y_error_axis] = wks_utility.substractBackground(tof_axis , - data_y_axis, + [data_y_axis, data_y_error_axis] = wks_utility.substractBackground(tof_axis , + data_y_axis, data_y_error_axis, dataPeakRange, dataBackFlag, dataBackRange, - error_0, + error_0, 'data') # #DEBUG ONLY # wks_utility.ouput_big_ascii_file('/mnt/hgfs/j35/Matlab/DebugMantid/Strange0ValuesToData/data_file_back_sub_not_integrated.txt', @@ -230,11 +230,11 @@ def PyExec(self): # data_y_axis, # data_y_error_axis) - # work with normalization - + # work with normalization + # load normalization - ws_event_norm = wks_utility.loadNeXus(int(normalizationRunNumber), 'normalization') - + ws_event_norm = wks_utility.loadNeXus(int(normalizationRunNumber), 'normalization') + # get proton charge pc = wks_utility.getProtonCharge(ws_event_norm) error_0 = 1. / pc @@ -243,84 +243,84 @@ def PyExec(self): ws_histo_norm = wks_utility.rebinNeXus(ws_event_norm, [binTOFrange[0], binTOFsteps, binTOFrange[1]], 'normalization') - + # keep only TOF range - ws_histo_norm = wks_utility.cropTOF(ws_histo_norm, + ws_histo_norm = wks_utility.cropTOF(ws_histo_norm, TOFrange[0], TOFrange[1], 'normalization') - + # normalize by current proton charge ws_histo_norm = wks_utility.normalizeNeXus(ws_histo_norm, 'normalization') - + # integrate over low resolution range [norm_tof_axis, norm_y_axis, norm_y_error_axis] = wks_utility.integrateOverLowResRange(ws_histo_norm, normLowResRange, 'normalization') # substract background - [norm_y_axis, norm_y_error_axis] = wks_utility.substractBackground(norm_tof_axis[0:-1], - norm_y_axis, + [norm_y_axis, norm_y_error_axis] = wks_utility.substractBackground(norm_tof_axis[0:-1], + norm_y_axis, norm_y_error_axis, normPeakRange, normBackFlag, normBackRange, - error_0, - 'normalization') + error_0, + 'normalization') - [av_norm, av_norm_error] = wks_utility.fullSumWithError(norm_y_axis, + [av_norm, av_norm_error] = wks_utility.fullSumWithError(norm_y_axis, norm_y_error_axis) # ## DEBUGGING ONLY # wks_utility.ouput_ascii_file('/mnt/hgfs/j35/Matlab/DebugMantid/Strange0ValuesToData/norm_file_back_sub_not_integrated.txt', -# norm_tof_axis, -# av_norm, -# av_norm_error) +# norm_tof_axis, +# av_norm, +# av_norm_error) [final_data_y_axis, final_data_y_error_axis] = wks_utility.divideDataByNormalization(data_y_axis, data_y_error_axis, av_norm, - av_norm_error) - + av_norm_error) + # #DEBUG ONLY # wks_utility.ouput_big_ascii_file('/mnt/hgfs/j35/Matlab/DebugMantid/Strange0ValuesToData/data_divided_by_norm_not_integrated.txt', # data_tof_axis, # final_data_y_axis, # final_data_y_error_axis) - - # apply Scaling factor - [tof_axis_full, y_axis, y_error_axis] = wks_utility.applyScalingFactor(tof_axis_full, - final_data_y_axis, - final_data_y_error_axis, + + # apply Scaling factor + [tof_axis_full, y_axis, y_error_axis] = wks_utility.applyScalingFactor(tof_axis_full, + final_data_y_axis, + final_data_y_error_axis, incidentMedium, sfFile, slitsValuePrecision, slitsWidthFlag) - + # #DEBUG ONLY # wks_utility.ouput_big_ascii_file('/mnt/hgfs/j35/Matlab/DebugMantid/Strange0ValuesToData/after_applying_scaling_factor.txt', # data_tof_axis, # y_axis, # y_error_axis) - + if geometryCorrectionFlag: # convert To Q with correction [q_axis, y_axis, y_error_axis] = wks_utility.convertToQ(tof_axis_full, - y_axis, + y_axis, y_error_axis, - peak_range = dataPeakRange, + peak_range = dataPeakRange, central_pixel = data_central_pixel, source_to_detector_distance = dMD, sample_to_detector_distance = dSD, theta = theta, first_slit_size = first_slit_size, last_slit_size = last_slit_size) - + else: # convert to Q without correction - + [q_axis, y_axis, y_error_axis] = wks_utility.convertToQWithoutCorrection(tof_axis_full, - y_axis, + y_axis, y_error_axis, - peak_range = dataPeakRange, + peak_range = dataPeakRange, central_pixel = data_central_pixel, source_to_detector_distance = dMD, sample_to_detector_distance = dSD, @@ -328,31 +328,31 @@ def PyExec(self): first_slit_size = first_slit_size, last_slit_size = last_slit_size) - + # wks_utility.ouput_big_Q_ascii_file('/mnt/hgfs/j35/Matlab/DebugMantid/Strange0ValuesToData/after_conversion_to_q.txt', # q_axis, # y_axis, # y_error_axis) - + sz = q_axis.shape nbr_pixel = sz[0] - + # create workspace q_workspace = wks_utility.createQworkspace(q_axis, y_axis, y_error_axis) q_rebin = Rebin(InputWorkspace=q_workspace, - Params=q_range, + Params=q_range, PreserveEvents=True) - + # keep only the q values that have non zero counts - nonzero_q_rebin_wks = wks_utility.cropAxisToOnlyNonzeroElements(q_rebin, + nonzero_q_rebin_wks = wks_utility.cropAxisToOnlyNonzeroElements(q_rebin, dataPeakRange) new_q_axis = nonzero_q_rebin_wks.readX(0)[:] - + # integrate spectra (normal mean) and remove first and last Q value [final_x_axis, final_y_axis, final_error_axis] = wks_utility.integrateOverPeakRange(nonzero_q_rebin_wks, dataPeakRange) - - + + # cleanup data [final_y_axis, final_y_error_axis] = wks_utility.cleanupData1D(final_y_axis, final_error_axis) @@ -363,12 +363,12 @@ def PyExec(self): _time = int(time.time()) name_output_ws = self.getPropertyValue("OutputWorkspace") name_output_ws = name_output_ws + '_#' + str(_time) + 'ts' - final_workspace = wks_utility.createFinalWorkspace(final_x_axis, - final_y_axis, + final_workspace = wks_utility.createFinalWorkspace(final_x_axis, + final_y_axis, final_y_error_axis, name_output_ws) - + self.setProperty('OutputWorkspace', mtd[name_output_ws]) - - + + AlgorithmFactory.subscribe(RefLReduction) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py index f5c9e563d270..4db03267838d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py @@ -23,105 +23,105 @@ def name(self): def summary(self): return "Refine powder diffractomer profile parameters sequentially." - + def PyInit(self): """ Declare properties """ - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional), + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", Direction.Input, PropertyMode.Optional), "Name of data workspace containing the diffraction pattern in .prf file. ") self.declareProperty("WorkspaceIndex", 0, "Spectrum (workspace index starting from 0) of the data to refine against in input workspace.") self.declareProperty(ITableWorkspaceProperty("SeqControlInfoWorkspace", "", Direction.InOut, PropertyMode.Optional), "Name of table workspace containing sequential refinement information.") - + self.declareProperty(ITableWorkspaceProperty("InputProfileWorkspace", "", Direction.Input, PropertyMode.Optional), "Name of table workspace containing starting profile parameters.") - + self.declareProperty(ITableWorkspaceProperty("InputBraggPeaksWorkspace", "", Direction.Input, PropertyMode.Optional), "Name of table workspace containing a list of reflections. ") - - self.declareProperty(ITableWorkspaceProperty("InputBackgroundParameterWorkspace", "", Direction.Input, + + self.declareProperty(ITableWorkspaceProperty("InputBackgroundParameterWorkspace", "", Direction.Input, PropertyMode.Optional), "Name of table workspace containing a list of reflections. ") - + self.declareProperty("StartX", -0., "Start X (TOF) to refine diffraction pattern.") self.declareProperty("EndX", -0., "End X (TOF) to refine diffraction pattern.") - + funcoptions = ["Setup", "Refine", "Save", "Load"] self.declareProperty("FunctionOption", "Refine", StringListValidator(funcoptions), "Options of functionality") - + #refoptions = ["Levenberg-Marquardt", "Random Walk", "Single Peak Fit"] refoptions = ["Random Walk"] self.declareProperty("RefinementOption", "Random Walk", StringListValidator(refoptions), "Options of algorithm to refine. ") - + self.declareProperty(StringArrayProperty("ParametersToRefine", values=[], direction=Direction.Input), "List of parameters to refine.") - + self.declareProperty("NumRefineCycles", 1, "Number of refinement cycles.") - - peaktypes = ["", "Neutron Back-to-back exponential convoluted with pseudo-voigt", + + peaktypes = ["", "Neutron Back-to-back exponential convoluted with pseudo-voigt", "Thermal neutron Back-to-back exponential convoluted with pseudo-voigt"] self.declareProperty("ProfileType", "", StringListValidator(peaktypes), "Type of peak profile function.") - + bkgdtypes = ["", "Polynomial", "Chebyshev", "FullprofPolynomial"] self.declareProperty("BackgroundType", "", StringListValidator(bkgdtypes), "Type of background function.") - + self.declareProperty("FromStep", -1, "If non-negative, the previous code is not set from last step, but the step specified.") - + # Property for save project self.declareProperty(FileProperty("OutputProjectFilename","", FileAction.OptionalSave, ['.nxs']), "Name of sequential project file.") - + # Property for save project self.declareProperty(FileProperty("InputProjectFilename","", FileAction.OptionalLoad, ['.nxs']), "Name of sequential project file.") - + # Project ID self.declareProperty("ProjectID", "", "Project ID.") - + return - def PyExec(self): - """ Main + def PyExec(self): + """ Main """ # Process input self._processInputProperties() - - # Instantiaze sequential refinement + + # Instantiaze sequential refinement seqrefine = SeqRefineProfile(self._projectID, self.log()) - - # Execute - if self.functionoption == "Setup": - # Set up + + # Execute + if self.functionoption == "Setup": + # Set up if seqrefine.isSetup() is True: raise NotImplementedError("Impossible to have it set up already.") - - seqrefine.initSetup(self.dataws, self.wsindex, self.peaktype, self.profilews, self.braggpeakws, self.bkgdtype, + + seqrefine.initSetup(self.dataws, self.wsindex, self.peaktype, self.profilews, self.braggpeakws, self.bkgdtype, self.bkgdparws, self.startx, self.endx) - - elif self.functionoption == "Refine": - # Refine + + elif self.functionoption == "Refine": + # Refine if seqrefine.isSetup() is False: raise NotImplementedError("Exception because sequential refinement is not set up.") seqrefine.refine(self.dataws, self.wsindex, self.paramstofit, self.numcycles, self.startx, self.endx, self._lastStep) - + elif self.functionoption == "Save": # Save the current state to a project file seqrefine.saveProject(str(self.dataws), self.wsindex, self.outprojectfilename) - + elif self.functionoption == "Load": # Set up from an exiting project file if seqrefine.isSetup() is True: raise NotImplementedError("Impossible to have it set up already.") - + seqrefine.loadProject(self.inprojectfilename) - + else: # None-support raise NotImplementedError("Function is not supported.") - + return @@ -131,16 +131,16 @@ def _processInputProperties(self): # Input data workspace and related self.dataws = self.getProperty("InputWorkspace").value self.wsindex = self.getProperty("WorkspaceIndex").value - + self.startx = self.getProperty("StartX").value self.endx = self.getProperty("EndX").value - + self._lastStep = self.getProperty("FromStep").value - - self._projectID = self.getProperty("ProjectID").value - if len(self._projectID) == 0: + + self._projectID = self.getProperty("ProjectID").value + if len(self._projectID) == 0: raise NotImplementedError("User must specify project ID.") - + self.functionoption = self.getProperty("FunctionOption").value if self.functionoption == "Setup": # Request on 'Setup' @@ -151,32 +151,32 @@ def _processInputProperties(self): self.peaktype = "ThermalNeutronBk2BkExpConvPVoigt" else: raise NotImplementedError("Peak profile is not supported.") - + self.bkgdtype = self.getProperty("BackgroundType").value self.bkgdparws = self.getProperty("InputBackgroundParameterWorkspace").value self.profilews = self.getProperty("InputProfileWorkspace").value self.braggpeakws = self.getProperty("InputBraggPeaksWorkspace").value - - + + elif self.functionoption == "Refine": self.paramstofit = self.getProperty("ParametersToRefine").value self.numcycles = self.getProperty("NumRefineCycles").value - + elif self.functionoption == "Save": self.outprojectfilename = self.getProperty("OutputProjectFilename").value - + elif self.functionoption == "Load": self.inprojectfilename = self.getProperty("InputProjectFilename").value - + else: raise NotImplementedError("Unsupported function mode %s. " % (self.functionoption)) - + if self.functionoption != "Load": self.datawsname = str(self.dataws) if self.wsindex < 0 or self.wsindex >= self.dataws.getNumberHistograms(): - raise NotImplementedError("Input workspace index %d is out of range (0, %d)." % + raise NotImplementedError("Input workspace index %d is out of range (0, %d)." % (self.wsindex, self.dataws.getNumberHistograms())) - + return @@ -195,36 +195,36 @@ class SeqRefineProfile: the input/starting values should be from the last """ def __init__(self, ID, glog): - """ + """ """ # Set up log self.glog = glog - # Set up ID + # Set up ID self._ID = str(ID) self.glog.information("SeqRefineProfile is initialized with ID = %s" % (str(ID))) - + # Standard record table and check its existence - # FIXME - This workspace's name should be passed from Algorithm's property! + # FIXME - This workspace's name should be passed from Algorithm's property! self._recordwsname = "Record%sTable" % (str(ID)) self.glog.notice("Using record table %s" % (self._recordwsname)) - + if AnalysisDataService.doesExist(self._recordwsname): # Record workspace exists: has been set up self._isSetup = True else: # Record workspace does not exist: first time or need to load from file self._isSetup = False - + self._recordWSLastRowInvalid = False - + # Result workspace group self._wsgroupName = self._ID + "_Group" - if AnalysisDataService.doesExist(self._wsgroupName): + if AnalysisDataService.doesExist(self._wsgroupName): self._wsgroupCreated = True else: self._wsgroupCreated = False - + return @@ -239,44 +239,44 @@ def initSetup(self, dataws, wsindex, peaktype, profilews, braggpeakws, bkgdtype, startx = dataws.readX(wsindex)[0] if endx <= 0.: endx = dataws.readX(wsindex)[-1] - - # Profile + + # Profile self._peakType = peaktype self._profileWS = profilews self._braggpeakws = braggpeakws self._bkgdtype = bkgdtype self._bkgdparws = bkgdparws - + # Generate record table self._genRecordTable() - + # Check input parameters, i.e., verification/examine input parameters runner = RefineProfileParameters(self.glog) - + outwsname = self._datawsname+"_Init" - + runner.setInputs(self._datawsname, self._peakType, self._profileWS, self._braggpeakws, self._bkgdtype, self._bkgdparws) # FIXME - Need to verify whether input and output background parameter ws name can be same runner.setOutputs(outwsname, self._profileWS, self._braggpeakws, self._bkgdparws) - + self._recordPreRefineInfo(runner, -1) runner.calculate(startx, endx) self._recordPostRefineInfo(runner) - + # Group the newly generated workspace and do some record - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, self._profileWS, self._braggpeakws, self._bkgdparws), + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, self._profileWS, self._braggpeakws, self._bkgdparws), OutputWorkspace=self._wsgroupName) self._wsgroupCreated = True - + # Repository - + # Replace 'Refine' of step 0 to ID (it is always empty) self._recordws.setCell(0, 5, self._ID) # Replace 'InputProfileWorkspace' by profile type (it is alwasy same as output) self._recordws.setCell(0, 9, self._peakType) - + self._isSetup = True - + return def loadProject(self, projectfilename): @@ -285,12 +285,12 @@ def loadProject(self, projectfilename): # Load workspace group api.LoadNexusProcessed(Filename=projectfilename, OutputWorkspace=self._wsgroupName) self._wsgroup = AnalysisDataService.retrieve(self._wsgroupName) - + if self._wsgroup.__class__.__name__ != "WorkspaceGroup": raise NotImplementedError("Input is not a workspace group but a %s" % (self._wsgroup.__class__.__name__)) - else: + else: self._wsgroupCreated = True - + # Parse README wsnames = self._wsgroup.getNames() readmewsname = None @@ -300,7 +300,7 @@ def loadProject(self, projectfilename): break if readmewsname is None: raise NotImplementedError("No README workspace is found in loaded workspace group.") - + readmews = AnalysisDataService.retrieve(readmewsname) infodict = {} numrows = readmews.rowCount() @@ -330,16 +330,16 @@ def refine(self, dataws, wsindex, parametersToFit, numcycles, startx, endx, last startx = dataws.readX(wsindex)[0] if endx <= 0.: endx = dataws.readX(wsindex)[-1] - + # Set up RefineProfileParameters object runner = RefineProfileParameters(self.glog) - + # Locate refinement record table profilewsname, braggpeakwsname, bkgdtype, bkgdparamwsname, laststep = self._parseRecordTable(laststepindex) - + # Set up runner and refine runner.setupMonteCarloRefine(numcycles, parametersToFit) - + outwsname, outprofilewsname, outbraggpeakwsname = self._genOutputWorkspace(str(dataws), profilewsname, braggpeakwsname) # Set up input and output @@ -352,19 +352,19 @@ def refine(self, dataws, wsindex, parametersToFit, numcycles, startx, endx, last self._recordPreRefineInfo(runner, laststep) runner.refine(numcycles, parametersToFit, startx, endx) self._recordPostRefineInfo(runner) - + # Group newly generated workspaces and add name to reposiotry - if self._wsgroupCreated is True: - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, self._wsgroupName), + if self._wsgroupCreated is True: + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, self._wsgroupName), OutputWorkspace=self._wsgroupName) else: wsgroup = AnalysisDataService.retrieve(self._wsgroupName) hasbkgd = list(wsgroup.getNames()).count(bkgdparamwsname) - if hasbkgd == 1: - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname), + if hasbkgd == 1: + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname), OutputWorkspace=self._wsgroupName) elif hasbkgd == 0: - api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, bkgdparamwsname), + api.GroupWorkspaces(InputWorkspaces="%s, %s, %s, %s" % (outwsname, outprofilewsname, outbraggpeakwsname, bkgdparamwsname), OutputWorkspace=self._wsgroupName) else: raise NotImplementedError("Impossible to have 1 workspace appeared twice in a workspace group.") @@ -386,7 +386,7 @@ def saveProject(self, datawsname, wsindex, projectfname): # FIXME - Find out a good way to remove existing files/directories if os.path.exists(projectfname) is True: import shutil - try: + try: os.remove(projectfname) except RuntimeError: shutil.rmtree(projectfname) @@ -396,22 +396,22 @@ def saveProject(self, datawsname, wsindex, projectfname): shutil.rmtree(projectfname) api.SaveNexusProcessed(InputWorkspace=self._wsgroupName, Filename=projectfname, Append=False) - + # Add data workspace, tracking record table to workspaces - # api.GroupWorkspaces(InputWorkspaces="%s, %s, %s" % (datawsname, self._recordwsname, self._wsgroupName), + # api.GroupWorkspaces(InputWorkspaces="%s, %s, %s" % (datawsname, self._recordwsname, self._wsgroupName), # OutputWorkspace=self._wsgroupName) - self.glog.notice("Append record workspace %s" % (self._recordwsname)) + self.glog.notice("Append record workspace %s" % (self._recordwsname)) api.SaveNexusProcessed(InputWorkspace=self._recordwsname, Filename=projectfname, Append=True) - - self.glog.notice("Append data workspace %s" % (datawsname)) + + self.glog.notice("Append data workspace %s" % (datawsname)) api.SaveNexusProcessed(InputWorkspace=datawsname, Filename=projectfname, Append=True) - + # Create a new README table workspace for some other information readmewsname = "READ_%s" % (self._ID) readmews = api.CreateEmptyTableWorkspace(OutputWorkspace=readmewsname) readmews.addColumn("str", "Function") readmews.addColumn("str", "Type") - + readmews.addRow(["Peak", "Not Important"]) readmews.addRow(["Background", "Not Important"]) readmews.addRow(["ID", str(self._ID)]) @@ -420,14 +420,14 @@ def saveProject(self, datawsname, wsindex, projectfname): readmews.addRow(["Spectrum", str(wsindex)]) api.SaveNexusProcessed(InputWorkspace=readmewsname, Filename=projectfname, Append=True) - + return def _genRecordTable(self): """ Generate record table """ tablews = api.CreateEmptyTableWorkspace(OutputWorkspace=self._recordwsname) - + tablews.addColumn("int", "Step") tablews.addColumn("str", "OutProfile") tablews.addColumn("str", "OutReflection") @@ -448,8 +448,8 @@ def _genRecordTable(self): def _parseRecordTable(self, laststep): """ Parse record table and return the last refinement result - Notice that 'last row' in record table might not be a valid row (incomplete). - It might be caused by an exception raised in refinement or its setup. + Notice that 'last row' in record table might not be a valid row (incomplete). + It might be caused by an exception raised in refinement or its setup. Class variable _recordWSLastRowInvalid is used to indicate this """ # Retrieve record workspace @@ -457,14 +457,14 @@ def _parseRecordTable(self, laststep): numrows = self._recordws.rowCount() if numrows == 0: raise NotImplementedError("Empty record table workspace. ") - + # Find last valid row lastvalidrow = -1 lastrow = numrows-1 self._recordwsLastRowValid = False while self._recordwsLastRowValid is False and lastrow >= 0: profilewsname = self._recordws.cell(lastrow, 1) - if profilewsname == "": + if profilewsname == "": self.glog.warning("Profile workspace name is emtpy in row %d!" % (lastrow)) lastrow -= 1 else: @@ -482,7 +482,7 @@ def _parseRecordTable(self, laststep): self._lastValidRowIndex = lastvalidrow if laststep > lastrecordedstep: - self.glog.warning("Last step %d is not recorded. Using step %d instead. " % + self.glog.warning("Last step %d is not recorded. Using step %d instead. " % (laststep, lastrecordedstep)) laststep = lastrecordedstep elif laststep < 0: @@ -499,13 +499,13 @@ def _parseRecordTable(self, laststep): reflectwsname = self._recordws.cell(lastvalidrow, 2).strip() bkgdtype = self._recordws.cell(lastrow, 3).strip() bkgdparamwsname = self._recordws.cell(lastrow, 4).strip() - if profilewsname == "": - raise NotImplementedError("Profile workspace name is emtpy in row %d. It is not supposed to happen." % + if profilewsname == "": + raise NotImplementedError("Profile workspace name is emtpy in row %d. It is not supposed to happen." % (lastvalidrow)) break # ENDWHILE if profilewsname == "": - raise NotImplementedError("Step %d is not found in record table. It is impossible. " % + raise NotImplementedError("Step %d is not found in record table. It is impossible. " % (laststep)) # Current step @@ -517,7 +517,7 @@ def _parseRecordTable(self, laststep): self._peakType = self._recordws.cell(0, 9).strip() # Background type self._bkgdType = bkgdtype.strip() - + return (profilewsname, reflectwsname, bkgdtype, bkgdparamwsname, laststep) @@ -529,7 +529,7 @@ def _recordPreRefineInfo(self, refiner, laststep): if self._recordWSLastRowInvalid is False: self._currstep = numrows - rectablews.addRow([self._currstep, "", "", "", "", "", -1.0, laststep, -1.0, "profilews", + rectablews.addRow([self._currstep, "", "", "", "", "", -1.0, laststep, -1.0, "profilews", "reflectionws", "Polynomial", "BkgdParm"]) else: self._currstep = numrows-1 @@ -537,13 +537,13 @@ def _recordPreRefineInfo(self, refiner, laststep): # print "*** Record workspace has %d rows. current step = %d. " % (rectablews.rowCount(), self._currstep) - if len(refiner.paramToFit) > 0: + if len(refiner.paramToFit) > 0: rectablews.setCell(self._currstep, 5, str(refiner.paramToFit)) rectablews.setCell(self._currstep, 9, str(refiner.inprofilewsname)) rectablews.setCell(self._currstep, 10, str(refiner.inreflectionwsname)) rectablews.setCell(self._currstep, 11, str(refiner.bkgdtype)) rectablews.setCell(self._currstep, 12, str(refiner.bkgdtablewsname)) - + return def _recordPostRefineInfo(self, refiner): @@ -571,13 +571,13 @@ def _recordPostRefineInfo(self, refiner): rectablews.setCell(self._currstep, 2, str(refiner.outreflectionwsname)) rectablews.setCell(self._currstep, 3, str(refiner.bkgdtype)) rectablews.setCell(self._currstep, 4, str(refiner.bkgdtablewsname)) - if rwp is not None: + if rwp is not None: rectablews.setCell(self._currstep, 6, rwp) - + return def _genOutputWorkspace(self, datawsname, profilewsname, braggpeakwsname): - """ + """ """ outwsname = "%s_%s_Step%d" % (datawsname, self._ID, self._currstep) @@ -592,7 +592,7 @@ def _genOutputWorkspace(self, datawsname, profilewsname, braggpeakwsname): else: outbpwsname = braggpeakwsname outbpwsname = "%s%s_Step%d"%(outbpwsname, self._ID, self._currstep) - + return (outwsname, outprofilewsname, outbpwsname) #-------------------------------------------------------------------- @@ -601,31 +601,31 @@ def generateMCSetupTableProf9(wsname): """ Generate a Le Bail fit Monte Carlo random walk setup table """ tablews = api.CreateEmptyTableWorkspace(OutputWorkspace=str(wsname)) - + tablews.addColumn("str", "Name") tablews.addColumn("double", "A0") tablews.addColumn("double", "A1") tablews.addColumn("int", "NonNegative") tablews.addColumn("int", "Group") - + group = 0 - tablews.addRow(["Dtt1" , 5.0, 0.0, 0, group]) + tablews.addRow(["Dtt1" , 5.0, 0.0, 0, group]) tablews.addRow(["Dtt2" , 1.0, 0.0, 0, group]) tablews.addRow(["Zero" , 5.0, 0.0, 0, group]) - + group = 1 - tablews.addRow(["Beta0" , 0.50, 1.0, 0, group]) + tablews.addRow(["Beta0" , 0.50, 1.0, 0, group]) tablews.addRow(["Beta1" , 0.05, 1.0, 0, group]) - + group = 2 tablews.addRow(["Alph0" , 0.05, 1.0, 0, group]) tablews.addRow(["Alph1" , 0.02, 1.0, 0, group]) - + group = 3 tablews.addRow(["Sig0", 2.0, 1.0, 1, group]) tablews.addRow(["Sig1", 2.0, 1.0, 1, group]) tablews.addRow(["Sig2", 2.0, 1.0, 1, group]) - + group = 4 tablews.addRow(["Gam0", 2.0, 1.0, 0, group]) tablews.addRow(["Gam1", 2.0, 1.0, 0, group]) @@ -637,41 +637,41 @@ def generateMCSetupTableProf10(wsname): """ Generate a Le Bail fit Monte Carlo random walk setup table """ import mantid.simpleapi as api - + tablews = api.CreateEmptyTableWorkspace(OutputWorkspace=str(wsname)) - + tablews.addColumn("str", "Name") tablews.addColumn("double", "A0") tablews.addColumn("double", "A1") tablews.addColumn("int", "NonNegative") tablews.addColumn("int", "Group") - + group = 0 - tablews.addRow(["Dtt1" , 5.0, 0.0, 0, group]) + tablews.addRow(["Dtt1" , 5.0, 0.0, 0, group]) tablews.addRow(["Dtt1t" , 5.0, 0.0, 0, group]) tablews.addRow(["Dtt2t" , 1.0, 0.0, 0, group]) tablews.addRow(["Zero" , 5.0, 0.0, 0, group]) tablews.addRow(["Zerot" , 5.0, 0.0, 0, group]) tablews.addRow(["Width" , 0.0, 0.1, 1, group]) tablews.addRow(["Tcross", 0.0, 1.0, 1, group]) - + group = 1 - tablews.addRow(["Beta0" , 0.50, 1.0, 0, group]) + tablews.addRow(["Beta0" , 0.50, 1.0, 0, group]) tablews.addRow(["Beta1" , 0.05, 1.0, 0, group]) tablews.addRow(["Beta0t", 0.50, 1.0, 0, group]) tablews.addRow(["Beta1t", 0.05, 1.0, 0, group]) - + group = 2 tablews.addRow(["Alph0" , 0.05, 1.0, 0, group]) tablews.addRow(["Alph1" , 0.02, 1.0, 0, group]) tablews.addRow(["Alph0t", 0.10, 1.0, 0, group]) tablews.addRow(["Alph1t", 0.05, 1.0, 0, group]) - + group = 3 tablews.addRow(["Sig0", 2.0, 1.0, 1, group]) tablews.addRow(["Sig1", 2.0, 1.0, 1, group]) tablews.addRow(["Sig2", 2.0, 1.0, 1, group]) - + group = 4 tablews.addRow(["Gam0", 2.0, 1.0, 0, group]) tablews.addRow(["Gam1", 2.0, 1.0, 0, group]) @@ -715,7 +715,7 @@ def __init__(self, glog): """ Initialization """ self.peaktype = "NOSETUP" - + # Output self.outwsname = None @@ -741,9 +741,9 @@ def setInputs(self, datawsname, peaktype, profilewsname, braggpeakwsname, bkgdty self.inreflectionwsname = braggpeakwsname self.bkgdtype = bkgdtype self.bkgdtablewsname = bkgdparwsname - + self._inputIsSetup = True - + return def setOutputs(self, outwsname, profilewsname, braggpeakwsname, bkgdparwsname): @@ -753,9 +753,9 @@ def setOutputs(self, outwsname, profilewsname, braggpeakwsname, bkgdparwsname): self.outprofilewsname = profilewsname self.outreflectionwsname = braggpeakwsname self.outbkgdtablewsname = bkgdparwsname - + self._outputIsSetup = True - + return def setupMonteCarloRefine(self, numcycles, parametersToFit): @@ -763,18 +763,18 @@ def setupMonteCarloRefine(self, numcycles, parametersToFit): """ if numcycles <= 0: raise NotImplementedError("It is not allowed to set up a 0 or a negative number to MonteCarloRefine") - else: + else: self.numsteps = numcycles - + self.paramToFit = parametersToFit - + return def calculate(self, startx, endx): """ Do Le bail calculation """ if (self._inputIsSetup and self._outputIsSetup) is False: - raise NotImplementedError("Either input or output is not setup: inputIsStepUp = %s, outputIsSetup = %s" % + raise NotImplementedError("Either input or output is not setup: inputIsStepUp = %s, outputIsSetup = %s" % (str(self._inputIsSetup), str(self._outputIsSetup))) self.glog.information("**** Calculate: DataWorksapce = %s" % (str(self.datawsname))) @@ -782,18 +782,18 @@ def calculate(self, startx, endx): self.glog.information("**** Profile workspace = %s, Reflection workspace = %s" % ( self.inprofilewsname, self.inreflectionwsname)) - api.LeBailFit( + api.LeBailFit( Function = 'Calculation', - InputWorkspace = self.datawsname, + InputWorkspace = self.datawsname, OutputWorkspace = self.outwsname, InputParameterWorkspace = self.inprofilewsname, - OutputParameterWorkspace= self.outprofilewsname, + OutputParameterWorkspace= self.outprofilewsname, InputHKLWorkspace = self.inreflectionwsname, - OutputPeaksWorkspace = self.outreflectionwsname, + OutputPeaksWorkspace = self.outreflectionwsname, FitRegion = '%f, %f' % (startx, endx), PeakType = self.peaktype, BackgroundType = self.bkgdtype, - UseInputPeakHeights = False, + UseInputPeakHeights = False, PeakRadius = '8', BackgroundParametersWorkspace = self.bkgdtablewsname ) @@ -807,9 +807,9 @@ def refine(self, numsteps, parameternames, startx, endx): # Check validity if (self._inputIsSetup and self._outputIsSetup) is False: raise NotImplementedError("Either input or output is not setup.") - + self.glog.debug("[Refine] Input profile workspace = %s" % (self.inprofilewsname)) - + # Update parameters' fit table if numsteps > 0: # Set up the default parameters to refine @@ -818,35 +818,35 @@ def refine(self, numsteps, parameternames, startx, endx): # FIXME - It is found that in the 'load' mode, a ID???_Group_2 might be generated by running # UpdatePeakParameterTableValue(). It is not a real new table workspace, but a link # to the 'inprofilewsname' - # There must be something wrong in AnalysisDataService. + # There must be something wrong in AnalysisDataService. api.UpdatePeakParameterTableValue( InputWorkspace = self.inprofilewsname, Column = "FitOrTie", NewStringValue = "tie") - api.UpdatePeakParameterTableValue( - InputWorkspace = self.inprofilewsname, + api.UpdatePeakParameterTableValue( + InputWorkspace = self.inprofilewsname, Column = "FitOrTie", ParameterNames = parameternames, NewStringValue = "fit") - # Limit the range of MC + # Limit the range of MC if parameternames.count("Width") > 0: #self.cwl = 1.33 - UpdatePeakParameterTableValue( - InputWorkspace = self.inprofilewsname, + UpdatePeakParameterTableValue( + InputWorkspace = self.inprofilewsname, Column = "Min", ParameterNames = ["Width"], NewFloatValue = 0.50) #cwl*0.25) - - UpdatePeakParameterTableValue( - InputWorkspace = self.inprofilewsname, + + UpdatePeakParameterTableValue( + InputWorkspace = self.inprofilewsname, Column = "Max", ParameterNames = ["Width"], NewFloatValue = 1.25) #cwl*4.0) - + # Generate Monte carlo table wsname = "MCSetupParameterTable" - if self.peaktype == "NeutronBk2BkExpConvPVoigt": + if self.peaktype == "NeutronBk2BkExpConvPVoigt": tablews = generateMCSetupTableProf9(wsname) elif self.peaktype == "ThermalNeutronBk2BkExpConvPVoigt": tablews = generateMCSetupTableProf10(wsname) @@ -858,15 +858,15 @@ def refine(self, numsteps, parameternames, startx, endx): OutputWorkspace = self.outwsname, InputParameterWorkspace = self.inprofilewsname, OutputParameterWorkspace = self.outprofilewsname, - InputHKLWorkspace = self.inreflectionwsname, - OutputPeaksWorkspace = self.outreflectionwsname, + InputHKLWorkspace = self.inreflectionwsname, + OutputPeaksWorkspace = self.outreflectionwsname, FitRegion = '%f, %f' % (startx, endx), - Function = 'MonteCarlo', - NumberMinimizeSteps = numsteps, + Function = 'MonteCarlo', + NumberMinimizeSteps = numsteps, PeakType = self.peaktype, BackgroundType = self.bkgdtype, BackgroundParametersWorkspace = self.bkgdtablewsname, - UseInputPeakHeights = False, + UseInputPeakHeights = False, PeakRadius ='8', Minimizer = 'Levenberg-Marquardt', MCSetupWorkspace = str(wsname), @@ -876,7 +876,7 @@ def refine(self, numsteps, parameternames, startx, endx): DrunkenWalk = True) # ENDIF (step) - + return # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py index 495e71bcedad..a6c9e59a75d2 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py @@ -110,7 +110,7 @@ class FileBackedWsIterator: provided is loaded into a workspace, validated by the given ws_validator, yielded, and then deleted from memory. ''' def __init__(self, filenames): - ''' Constructor, takes in the list of filenames to load, who's + ''' Constructor, takes in the list of filenames to load, who's workspaces will be iterated over. ''' # Validate. if not isinstance(filenames, list): @@ -119,15 +119,15 @@ def __init__(self, filenames): raise TypeError("Expected a list of strings.") if len(filenames) < 1: raise ValueError("Expected at least one filename.") - + # In the general case, we may or may not have checked for the existance - # of the files previously, so before we even start iterating throw if + # of the files previously, so before we even start iterating throw if # any are missing. missing_files = list(ifilterfalse(os.path.exists, filenames)) if len(missing_files) > 0: - raise ValueError("One or more files are missing: " + + raise ValueError("One or more files are missing: " + str(missing_files)) - + self._filenames = filenames self._loaded_ws = None @@ -141,34 +141,34 @@ def __iter__(self): self._load_into_ws(filename) except RuntimeError as re: raise RuntimeError("Problem loading file \"" + filename + "\"") - + # Yield the newly loaded ws. yield self._loaded_ws - + # Final tidy-up. self._delete_loaded_ws() - + def _is_string(self, obj): ''' Convenience method to test if an object is a string or not. ''' return isinstance(obj, str) - + def _load_into_ws(self, filename): - ''' Load the given filename and return it. Use LoadRaw for raw files, + ''' Load the given filename and return it. Use LoadRaw for raw files, so we can turn LoadLogFiles off. ''' wsName = "__temp_" + filename - + base, ext = os.path.splitext(filename) if ext == ".raw": # Loading log files is extremely slow on archive - LoadRaw(Filename = filename, - OutputWorkspace = wsName, + LoadRaw(Filename = filename, + OutputWorkspace = wsName, LoadLogFiles = False) else: - Load(Filename = filename, + Load(Filename = filename, OutputWorkspace = wsName) - + self._loaded_ws = mtd[wsName] - + def _delete_loaded_ws(self): ''' If there has been a file loaded into a ws, delete it. ''' if self._loaded_ws: @@ -180,7 +180,7 @@ def category(self): def summary(self): return "Given a range of run numbers and an output workspace name, will compile a table of info for each run of the instrument you have set as default." - + def PyInit(self): # Declare algorithm properties. self.declareProperty( @@ -190,36 +190,36 @@ def PyInit(self): doc='The range of runs to retrieve the run info for. E.g. "100-105".') self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), doc= """The name of the TableWorkspace that will be created. '''You must specify a name that does not already exist.''' """) - + def PyExec(self): - PROP_NAMES = ["inst_abrv", "run_number", "user_name", "run_title", + PROP_NAMES = ["inst_abrv", "run_number", "user_name", "run_title", "hd_dur"] - + # Not all ISIS run files have the relevant prop_names, but we may as # well limit to ISIS only runs at this stage. if config['default.facility'] != 'ISIS': raise ValueError("Only ISIS runs are supported by this alg.") - + # Ensure workspace does not already exist. output_ws_name = self.getPropertyValue("OutputWorkspace") if mtd.doesExist(output_ws_name): raise ValueError("Workspace \"" + output_ws_name + "\" already " "exists. Either delete it, or choose another workspace name.") - + # Check that all run files are available. run_string = self.getPropertyValue("Runs") try: filenames = list(FileFinder.findRuns(run_string)) except RuntimeError as re: raise ValueError(str(re)) - + # Set up the output ws table. CreateEmptyTableWorkspace(OutputWorkspace=output_ws_name) output_ws = mtd[output_ws_name] for prop_name in PROP_NAMES: output_ws.addColumn(name=prop_name, type='str') - - # Set up (and iterate over) a "file backed" iterator, which takes care + + # Set up (and iterate over) a "file backed" iterator, which takes care # of loading files and then deleting the resulting workspaces in turn # when we are finished with them. ws_iter = FileBackedWsIterator(filenames) @@ -227,7 +227,7 @@ def PyExec(self): # Create a single row table for each file. temp_table_name = ws.getName() + "_INFO" CreateLogPropertyTable( - InputWorkspaces=ws.getName(), + InputWorkspaces=ws.getName(), LogPropertyNames=', '.join(PROP_NAMES), GroupPolicy="First", # Include only the 1st child of any groups. OutputWorkspace=temp_table_name) @@ -235,7 +235,7 @@ def PyExec(self): temp_table = mtd[temp_table_name] output_ws.addRow(temp_table.row(0)) DeleteWorkspace(Workspace=temp_table_name) - + self.setPropertyValue('OutputWorkspace', output_ws_name) # Register algorthm with Mantid. diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py index 5434aa27e7bd..c79e5ce731ba 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSSubtract.py @@ -1,45 +1,45 @@ from mantid.api import * -from mantid.kernel import Direction, FloatBoundedValidator -import mantid.simpleapi +from mantid.kernel import Direction, FloatBoundedValidator +import mantid.simpleapi import os class SANSSubtract(PythonAlgorithm): - """ + """ I(Q) subtraction """ def category(self): - """ + """ Return category """ return "PythonAlgorithms;SANS" - + def name(self): - """ + """ Return name """ return "SANSSubtract" - + def summary(self): return "Subtract background from an I(Q) distribution." def PyInit(self): - """ + """ Declare properties """ - self.declareProperty('DataDistribution', '', direction = Direction.Input, + self.declareProperty('DataDistribution', '', direction = Direction.Input, doc='Name of the input workspace or file path') - self.declareProperty('Background', '', direction = Direction.Input, + self.declareProperty('Background', '', direction = Direction.Input, doc='Name of the background workspace or file path') self.declareProperty("ScaleFactor", 1., FloatBoundedValidator(), doc="Scaling factor [Default: 1]") self.declareProperty("Constant", 0., FloatBoundedValidator(), doc="Additive constant [Default:0]") - self.declareProperty(FileProperty("OutputDirectory","", FileAction.OptionalDirectory), + self.declareProperty(FileProperty("OutputDirectory","", FileAction.OptionalDirectory), doc="Directory to write the output files in [optional]") self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), doc="Workspace containing data from detectors") return - + def _find_or_load(self, data_str): """ Determine whether the input data string is the name @@ -47,20 +47,20 @@ def _find_or_load(self, data_str): Return the workspace and its name. @param data_str: input string for the data """ - + if AnalysisDataService.doesExist(data_str): data = AnalysisDataService.retrieve(data_str) data_ws_name = data_str - else: + else: data_ws_name = os.path.basename(data_str) - load_alg = mantid.api.AlgorithmManager.createUnmanaged('Load') + load_alg = mantid.api.AlgorithmManager.createUnmanaged('Load') load_alg.setChild(True) load_alg.initialize() load_alg.setProperty("Filename", data_str) load_alg.setProperty("OutputWorkspace", data_ws_name) load_alg.execute() data = load_alg.getProperty("OutputWorkspace").value - + # Keep track of dQ dq = data.extractDx()[0] @@ -72,18 +72,18 @@ def _find_or_load(self, data_str): op.setProperty("OutputWorkspace", "__histo_data_%s" % data_ws_name) op.execute() data = op.getProperty("OutputWorkspace").value - + # Make sure we have the correct units, especially important # if the data was loaded from an ASCII file data.getAxis(0).setUnit('MomentumTransfer') - # Set the "distribution" flag on the matrix workspace + # Set the "distribution" flag on the matrix workspace data.setDistribution(False) - + return data, data_ws_name, dq - + def PyExec(self): - """ + """ Main execution body """ data_str = self.getProperty("DataDistribution").value @@ -91,10 +91,10 @@ def PyExec(self): scale = self.getProperty("ScaleFactor").value constant = self.getProperty("Constant").value output_dir = self.getPropertyValue("OutputDirectory") - + # Load data or get it from the ADS data, data_ws_name, dq = self._find_or_load(data_str) - + # Load background or get it from the ADS background, back_ws_name, _ = self._find_or_load(background_str) @@ -107,9 +107,9 @@ def PyExec(self): op.setProperty("OutputWorkspace", "__rebinned_bck") op.execute() rebinned_bck = op.getProperty("OutputWorkspace").value - + # Output = data - scale * background + constant - op = mantid.api.AlgorithmManager.createUnmanaged('Scale') + op = mantid.api.AlgorithmManager.createUnmanaged('Scale') op.initialize() op.setChild(True) op.setProperty("InputWorkspace", rebinned_bck) @@ -118,8 +118,8 @@ def PyExec(self): op.setProperty("Operation", "Multiply") op.execute() scaled_bck = op.getProperty("OutputWorkspace").value - - op = mantid.api.AlgorithmManager.createUnmanaged('Minus') + + op = mantid.api.AlgorithmManager.createUnmanaged('Minus') op.initialize() op.setChild(True) op.setProperty("LHSWorkspace", data) @@ -127,8 +127,8 @@ def PyExec(self): op.setProperty("OutputWorkspace", '__bck_substracted') op.execute() bck_subtr = op.getProperty("OutputWorkspace").value - - op = mantid.api.AlgorithmManager.createUnmanaged('Scale') + + op = mantid.api.AlgorithmManager.createUnmanaged('Scale') op.initialize() op.setChild(True) op.setProperty("InputWorkspace", bck_subtr) @@ -137,25 +137,25 @@ def PyExec(self): op.setProperty("Operation", "Add") op.execute() output = op.getProperty("OutputWorkspace").value - + # Put back dQ dq_scaled = output.dataDx(0) for i in range(len(dq)): dq_scaled[i] = dq[i] - + self.setProperty("OutputWorkspace", output) - + # Save the output to disk as needed if len(output_dir)>0: root_name, ext = os.path.splitext(data_ws_name) - op = mantid.api.AlgorithmManager.createUnmanaged('SaveCanSAS1D') + op = mantid.api.AlgorithmManager.createUnmanaged('SaveCanSAS1D') op.initialize() op.setChild(True) op.setProperty("InputWorkspace", output) op.setProperty("Filename", os.path.join(output_dir, root_name+'_corr.xml')) op.setProperty("RadiationSource", "Spallation Neutron Source") op.execute() - + op = mantid.api.AlgorithmManager.createUnmanaged("SaveAscii") op.initialize() op.setChild(True) @@ -166,7 +166,7 @@ def PyExec(self): op.setProperty("WriteXError", True) op.setProperty("WriteSpectrumID", False) op.execute() - - return - + + return + AlgorithmFactory.subscribe(SANSSubtract) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py index b60f8374b666..526e75c9e5d4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SANSWideAngleCorrection.py @@ -7,7 +7,7 @@ class SANSWideAngleCorrection(PythonAlgorithm): """ Calculate the Wide Angle correction for SANS transmissions. """ - + def category(self): return "CorrectionFunctions\\TransmissionCorrections" @@ -18,31 +18,31 @@ def summary(self): return "Calculate the Wide Angle correction for SANS transmissions." def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("SampleData", "", direction = Direction.Input), - "A workspace cropped to the detector to be reduced (the SAME as the input to [[Q1D]]); used to verify the solid angle. The workspace is not modified, just inspected.") + self.declareProperty(MatrixWorkspaceProperty("SampleData", "", direction = Direction.Input), + "A workspace cropped to the detector to be reduced (the SAME as the input to [[Q1D]]); used to verify the solid angle. The workspace is not modified, just inspected.") self.declareProperty(MatrixWorkspaceProperty("TransmissionData","",direction=Direction.Input), "The transmission data calculated, referred to as T_0 in equations in discussion section") self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace","",direction=Direction.Output), "The transmission corrected SANS data, normalised (divided) by T_0, see discussion section") - + def PyExec(self): """ Main body of execution """ # 1. get parameter values wd = self.getProperty("SampleData").value trans = self.getProperty("TransmissionData").value - + # check transmission input workspace if (len(trans.dataX(0)) != len(wd.dataX(0))): raise RuntimeError("Uncompatible sizes. Transmission must have the same bins of sample values") if min(trans.dataY(0)) < 0: raise RuntimeError("Invalid workspace for transmission, it does not accept negative values.") - + #check input sample has associated instrument if not wd.getInstrument().getSample(): raise RuntimeError("You can not apply this correction for workspace not associated to instrument") - #initialization of progress bar: + #initialization of progress bar: # endrange = 5+wd.getNumberHistograms() prog_reporter = Progress(self,start=0.0,end=1.0,nreports=endrange) @@ -53,7 +53,7 @@ def PyExec(self): # get the values of transmission (data, error, binning) to = np.array(trans.dataY(0)) - to_e = np.array(trans.dataE(0)) + to_e = np.array(trans.dataE(0)) x_bins = np.array(wd.dataX(0)) # get the position of the sample and the instrument @@ -67,7 +67,7 @@ def PyExec(self): # calculation of A twoTheta = wd.getDetector(i).getTwoTheta(sample_pos, inst_pos) A = 1/np.cos(twoTheta) - 1 - # calculation of factor for transmission + # calculation of factor for transmission to_l = (np.power(to,A)-1)/(np.log(to)*A) to_err_l = (np.power(to_e, A) - 1)/ (np.log(to_e) * A) # applying the data to the workspace @@ -78,6 +78,6 @@ def PyExec(self): self.getLogger().warning("WideAngleCorrection error: " + str(sys.exc_info()[2])) self.setProperty("OutputWorkspace", trans_wc) - + ############################################################################################# AlgorithmFactory.subscribe(SANSWideAngleCorrection) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py index 50152c18b0d0..dac7c172de26 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py @@ -50,9 +50,9 @@ def PyInit(self): doc="If specified overrides value in CharacterizationRunsFile. If -1 turns off correction.") self.declareProperty("VanadiumBackgroundNumber", defaultValue=0, validator=IntBoundedValidator(lower=-1), doc="If specified overrides value in CharacterizationRunsFile. If -1 turns off correction.") - self.declareProperty(FileProperty(name="CalibrationFile",defaultValue="",action=FileAction.Load, + self.declareProperty(FileProperty(name="CalibrationFile",defaultValue="",action=FileAction.Load, extensions = ["cal"])) - self.declareProperty(FileProperty(name="CharacterizationRunsFile",defaultValue="",action=FileAction.OptionalLoad, + self.declareProperty(FileProperty(name="CharacterizationRunsFile",defaultValue="",action=FileAction.OptionalLoad, extensions = ["txt"]),"File with characterization runs denoted") self.declareProperty("UnwrapRef", 0., "Reference total flight path for frame unwrapping. Zero skips the correction") @@ -172,8 +172,8 @@ def PyExec(self): polars = focuspos['Polar'][:] phis = focuspos['Azimuthal'][:] - specids.extend(specids) - l2s.extend(l2s) + specids.extend(specids) + l2s.extend(l2s) polars.extend(polars) phis.extend(phis) @@ -194,7 +194,7 @@ def PyExec(self): runnumber = temp self.log().information("[Sum] Process run number %s. " %(str(runnumber))) - temp = self._focusChunks(temp, SUFFIX, timeFilterWall, calib, + temp = self._focusChunks(temp, SUFFIX, timeFilterWall, calib, preserveEvents=preserveEvents) tempinfo = self._getinfo(temp) @@ -230,7 +230,7 @@ def PyExec(self): # first round of processing the sample if not self.getProperty("Sum").value and samRun > 0: self._info = None - returned = self._focusChunks(samRun, SUFFIX, timeFilterWall, calib, self._splitws, + returned = self._focusChunks(samRun, SUFFIX, timeFilterWall, calib, self._splitws, preserveEvents=preserveEvents) if returned.__class__.__name__ == "list": @@ -238,8 +238,8 @@ def PyExec(self): focusedwksplist = returned irun = 0 for run in focusedwksplist: - if run is not None: - samwksplist.append(run) + if run is not None: + samwksplist.append(run) workspacelist.append(str(run)) else: self.log().warning("Found a None entry in returned focused workspaces. Index = %d." % (irun)) @@ -247,27 +247,27 @@ def PyExec(self): irun += 1 # ENDFOR else: - run = returned - samwksplist.append(run) + run = returned + samwksplist.append(run) workspacelist.append(str(run)) # ENDIF # ENDIF # ENDFOR for samRun in samwksplist: - samRun = mtd[str(samRun)] - try: + samRun = mtd[str(samRun)] + try: self.log().information("[F1136] Sample Run %s: number of events = %d" % (str(samRun), samRun.getNumberEvents())) except Exception as e: self.log().information("[F1136] Unable to get number of events of sample run %s. Error message: %s" % (str(samRun), str(e))) # Get run number runnumber = samRun.getRunNumber() - if self._infodict.has_key(runnumber): + if self._infodict.has_key(runnumber): self.log().debug("[F1022A] Found run number %d in info dict." % (runnumber)) self._info = self._infodict[runnumber] else: - self.log().debug("[F1022B] Unable to find _info for run number %d in info dict. "% (runnumber)) + self.log().debug("[F1022B] Unable to find _info for run number %d in info dict. "% (runnumber)) self._info = self._getinfo(samRun) # process the container @@ -304,7 +304,7 @@ def PyExec(self): vanRun = api.RenameWorkspace(InputWorkspace=vanRun, OutputWorkspace=name) try: if self._normalisebycurrent is True: - vanRun = api.NormaliseByCurrent(InputWorkspace=vanRun, + vanRun = api.NormaliseByCurrent(InputWorkspace=vanRun, OutputWorkspace=vanRun) vanRun.getRun()['gsas_monitor'] = 1 except Exception, e: @@ -317,7 +317,7 @@ def PyExec(self): vbackRun = self._loadData(vbackRun, SUFFIX, vanFilterWall, outname="vbackRun") try: if self._normalisebycurrent is True: - vbackRun = api.NormaliseByCurrent(InputWorkspace=vbackRun, + vbackRun = api.NormaliseByCurrent(InputWorkspace=vbackRun, OutputWorkspace=vbackRun) vbackRun.getRun()['gsas_monitor'] = 1 except Exception, e: @@ -332,7 +332,7 @@ def PyExec(self): if vanRun.id() == EVENT_WORKSPACE_ID: vanRun = api.CompressEvents(InputWorkspace=vanRun, OutputWorkspace=vanRun, Tolerance=COMPRESS_TOL_TOF) # 10ns - + # do the absorption correction vanRun = api.ConvertUnits(InputWorkspace=vanRun, OutputWorkspace=vanRun, Target="TOF") api.SetSampleMaterial(InputWorkspace=vanRun, ChemicalFormula="V", SampleNumberDensity=0.0721) @@ -344,9 +344,9 @@ def PyExec(self): DMin=self._info["d_min"], DMax=self._info["d_max"], TMin=self._info["tof_min"], TMax=self._info["tof_max"], RemovePromptPulseWidth=self._removePromptPulseWidth, CompressTolerance=COMPRESS_TOL_TOF, - UnwrapRef=self._LRef, LowResRef=self._DIFCref, LowResSpectrumOffset=self._lowResTOFoffset, + UnwrapRef=self._LRef, LowResRef=self._DIFCref, LowResSpectrumOffset=self._lowResTOFoffset, CropWavelengthMin=self._wavelengthMin, **(focuspos)) - + # strip peaks if self.getProperty("StripVanadiumPeaks").value: @@ -431,7 +431,7 @@ def _loadCharacterizations(self, filename): def _loadData(self, runnumber, extension, filterWall=None, outname=None, **chunk): if runnumber is None or runnumber <= 0: return None - + name = "%s_%d" % (self._instrument, runnumber) filename = name + extension # EMPTY_INT() from C++ @@ -439,7 +439,7 @@ def _loadData(self, runnumber, extension, filterWall=None, outname=None, **chunk if "ChunkNumber" in chunk: name += "_%d" % (int(chunk["ChunkNumber"])) elif "SpectrumMin" in chunk: - name += "_%d" % (1 + int(chunk["SpectrumMin"])/(int(chunk["SpectrumMax"])-int(chunk["SpectrumMin"]))) + name += "_%d" % (1 + int(chunk["SpectrumMin"])/(int(chunk["SpectrumMax"])-int(chunk["SpectrumMin"]))) else: name += "_%d" % 0 if outname is not None: @@ -452,18 +452,18 @@ def _loadData(self, runnumber, extension, filterWall=None, outname=None, **chunk chunk["FilterByTimeStart"] = filterWall[0] if filterWall[1] > 0.: chunk["FilterByTimeStop"] = filterWall[1] - + wksp = api.Load(Filename=filename, OutputWorkspace=name, **chunk) - try: + try: self.log().debug("Load run %s: number of events = %d" % (str(runnumber), wksp.getNumberEvents())) except Exception as e: self.log().debug("Load run %s: unable to get events of %s. Error message: %s" % (str(runnumber), str(wksp), str(e))) if HAVE_MPI: msg = "MPI Task = %s ;" % (str(mpiRank)) - try: + try: msg += "Number Events = " + str(wksp.getNumberEvents()) - except Exception as e: + except Exception as e: msg += "Unable to get events of %s. Error message: %s" % (str(wksp), str(e)) self.log().debug(msg) @@ -472,7 +472,7 @@ def _loadData(self, runnumber, extension, filterWall=None, outname=None, **chunk wksp = api.FilterBadPulses(InputWorkspace=wksp, OutputWorkspace=wksp, LowerCutoff=self._filterBadPulses) if str(type(wksp)).count("IEvent") > 0: - # Event workspace + # Event workspace self.log().information("F1141D There are %d events after FilterBadPulses in workspace %s." % ( wksp.getNumberEvents(), str(wksp))) @@ -506,7 +506,7 @@ def __logChunkInfo(self, chunk): def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, preserveEvents=True): """ Load, (optional) split and focus data in chunks - Arguments: + Arguments: - runnumber : integer for run number - splitwksp: SplittersWorkspace (if None then no split) - filterWall: Enabled if splitwksp is defined @@ -522,10 +522,10 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, dosplit = False # Number of output workspaces from _focusChunk numwksp = 1 - if splitwksp is not None: + if splitwksp is not None: # Check consistency in the code - if filterWall[0] < 1.0E-20 and filterWall[1] < 1.0E-20: - # Default definition of filterWall when there is no split workspace specified. + if filterWall[0] < 1.0E-20 and filterWall[1] < 1.0E-20: + # Default definition of filterWall when there is no split workspace specified. raise NotImplementedError("It is impossible to have a not-NONE splitters workspace and (0,0) time filter wall.") # ENDIF @@ -533,7 +533,7 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, numwksp = self.getNumberOfSplittedWorkspace(splitwksp) numsplitters = splitwksp.rowCount() - # Do explicit FilterEvents if number of splitters is larger than 1. + # Do explicit FilterEvents if number of splitters is larger than 1. # If number of splitters is equal to 1, then filterWall will do the job itself. if numsplitters > 1: dosplit = True @@ -542,7 +542,7 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, firstChunkList = [] wksplist = [] - for n in xrange(numwksp): + for n in xrange(numwksp): # In some cases, there will be 1 more splitted workspace (unfiltered) firstChunkList.append(True) wksplist.append(None) @@ -561,7 +561,7 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, # Load chunk temp = self._loadData(runnumber, extension, filterWall, **chunk) if str(type(temp)).count("IEvent") > 0: - # Event workspace + # Event workspace self.log().debug("F1141C There are %d events after data is loaded in workspace %s." % ( temp.getNumberEvents(), str(temp))) @@ -571,20 +571,20 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, self._infodict[int(runnumber)] = self._info self.log().debug("[F1012] Add info for run number %d." % (int(runnumber))) - # Filtering... + # Filtering... tempwslist = [] if temp.id() == EVENT_WORKSPACE_ID: - # Filter to bad + # Filter to bad if dosplit: # Splitting workspace - basename = str(temp) - if self._splitinfotablews is None: - api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename, + basename = str(temp) + if self._splitinfotablews is None: + api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename, SplitterWorkspace=splitwksp, GroupWorkspaces=True) else: self.log().information("SplitterWorkspace = %s, Information Workspace = %s. " % ( str(splitwksp), str(self._splitinfotablews))) - api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename, + api.FilterEvents(InputWorkspace=temp, OutputWorkspaceBaseName=basename, SplitterWorkspace=splitwksp, InformationWorkspace = str(self._splitinfotablews), GroupWorkspaces=True) # ENDIF @@ -597,12 +597,12 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, self.log().debug(dbstr) tempwslist = [] - # FIXME Keep in mind to use this option. + # FIXME Keep in mind to use this option. # keepremainder = self.getProperty("KeepRemainder").value for wsname in tempwsnamelist: tempws = mtd[wsname] - if tempws is not None: - if wsname.endswith("_unfiltered") is False: + if tempws is not None: + if wsname.endswith("_unfiltered") is False: tempwslist.append(tempws) else: api.DeleteWorkspace(Workspace=tempws) @@ -639,7 +639,7 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, DMin=self._info["d_min"], DMax=self._info["d_max"], TMin=self._info["tof_min"], TMax=self._info["tof_max"], PreserveEvents=preserveEvents, RemovePromptPulseWidth=self._removePromptPulseWidth, CompressTolerance=COMPRESS_TOL_TOF, - UnwrapRef=self._LRef, LowResRef=self._DIFCref, LowResSpectrumOffset=self._lowResTOFoffset, + UnwrapRef=self._LRef, LowResRef=self._DIFCref, LowResSpectrumOffset=self._lowResTOFoffset, CropWavelengthMin=self._wavelengthMin, **(focuspos)) for iws in xrange(temp.getNumberHistograms()): spec = temp.getSpectrum(iws) @@ -665,35 +665,35 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, # Sum workspaces for all mpi tasks if HAVE_MPI: - for itemp in xrange(numwksp): - wksplist[itemp] = api.GatherWorkspaces(InputWorkspace=wksplist[itemp], + for itemp in xrange(numwksp): + wksplist[itemp] = api.GatherWorkspaces(InputWorkspace=wksplist[itemp], PreserveEvents=preserveEvents, AccumulationMethod="Add", OutputWorkspace=wksplist[itemp]) # ENDIF MPI if self._chunks > 0: # When chunks are added, proton charge is summed for all chunks - for itemp in xrange(numwksp): + for itemp in xrange(numwksp): wksplist[itemp].getRun().integrateProtonCharge() # ENDIF if (self.iparmFile is not None) and (len(self.iparmFile) > 0): # When chunks are added, add iparamFile - for itemp in xrange(numwksp): + for itemp in xrange(numwksp): wksplist[itemp].getRun()['iparm_file'] = self.iparmFile - for itemp in xrange(numwksp): - #if wksplist[itemp].__class__.__name__.count("Event") > 0: - # try: + for itemp in xrange(numwksp): + #if wksplist[itemp].__class__.__name__.count("Event") > 0: + # try: # print "[DB1050-X] Number of events = %d of split-workspace %d" % (wksplist[itemp].getNumberEvents(), itemp) # except Exception as e: # print e if wksplist[itemp].id() == EVENT_WORKSPACE_ID: - wksplist[itemp] = api.CompressEvents(InputWorkspace=wksplist[itemp], + wksplist[itemp] = api.CompressEvents(InputWorkspace=wksplist[itemp], OutputWorkspace=wksplist[itemp], Tolerance=COMPRESS_TOL_TOF) # 100ns try: if self._normalisebycurrent is True: - wksplist[itemp] = api.NormaliseByCurrent(InputWorkspace=wksplist[itemp], + wksplist[itemp] = api.NormaliseByCurrent(InputWorkspace=wksplist[itemp], OutputWorkspace=wksplist[itemp]) wksplist[itemp].getRun()['gsas_monitor'] = 1 except Exception, e: @@ -701,9 +701,9 @@ def _focusChunks(self, runnumber, extension, filterWall, calib, splitwksp=None, self._save(wksplist[itemp], self._info, False, True) self.log().information("Done focussing data of %d." % (itemp)) - - #if wksplist[itemp].__class__.__name__.count("Event") > 0: - # try: + + #if wksplist[itemp].__class__.__name__.count("Event") > 0: + # try: # print "[DB1050-Z] Number of events = %d of split-workspace %d" % (wksplist[itemp].getNumberEvents(), itemp) # except Exception as e: # print e @@ -722,7 +722,7 @@ def _getinfo(self, wksp): if mtd.doesExist("characterizations"): # get the correct row of the table charac = api.PDDetermineCharacterizations(InputWorkspace=wksp, - Characterizations="characterizations", + Characterizations="characterizations", ReductionProperties="__snspowderreduction", BackRun=self.getProperty("BackgroundNumber").value, NormRun=self.getProperty("VanadiumNumber").value, @@ -745,11 +745,11 @@ def _getinfo(self, wksp): return rowValues - def _save(self, wksp, info, normalized, pdfgetn): - prefix = str(wksp) - if len(self._outPrefix) > 0: # non-empty string - prefix = self._outPrefix - filename = os.path.join(self._outDir, prefix) + def _save(self, wksp, info, normalized, pdfgetn): + prefix = str(wksp) + if len(self._outPrefix) > 0: # non-empty string + prefix = self._outPrefix + filename = os.path.join(self._outDir, prefix) if pdfgetn: if "pdfgetn" in self._outTypes: pdfwksp = str(wksp)+"_norm" @@ -759,10 +759,10 @@ def _save(self, wksp, info, normalized, pdfgetn): api.DeleteWorkspace(pdfwksp) return # don't do the other bits of saving if "gsas" in self._outTypes: - api.SaveGSS(InputWorkspace=wksp, Filename=filename+".gsa", SplitFiles=False, Append=False, + api.SaveGSS(InputWorkspace=wksp, Filename=filename+".gsa", SplitFiles=False, Append=False, MultiplyByBinWidth=normalized, Bank=info["bank"], Format="SLOG", ExtendedHeader=True) if "fullprof" in self._outTypes: - api.SaveFocusedXYE(InputWorkspace=wksp, StartAtBankNumber=info["bank"], Filename=filename+".dat") + api.SaveFocusedXYE(InputWorkspace=wksp, StartAtBankNumber=info["bank"], Filename=filename+".dat") if "topas" in self._outTypes: api.SaveFocusedXYE(InputWorkspace=wksp, StartAtBankNumber=info["bank"], Filename=filename+".xye", Format="TOPAS") @@ -777,14 +777,14 @@ def _save(self, wksp, info, normalized, pdfgetn): return def _getTimeFilterWall(self, splitws, samrun, extension): - """ Get filter wall from splitter workspace, i.e., + """ Get filter wall from splitter workspace, i.e., get the earlies and latest TIME stamp in input splitter workspace Arguments: - splitws : splitters workspace - runstarttime : total nanoseconds of run start time (Mantid DateAndTime) - Return: tuple of start-time and stop-time relative to run start time and in unit of second + Return: tuple of start-time and stop-time relative to run start time and in unit of second If there is no split workspace defined, filter is (0., 0.) as the default """ # None case @@ -796,7 +796,7 @@ def _getTimeFilterWall(self, splitws, samrun, extension): name = "%s_%d" % (self._instrument, samrun) filename = name + extension metawsname = "temp_"+name - + metawksp = api.Load(Filename=str(filename), OutputWorkspace=str(metawsname), MetaDataOnly=True) if metawksp is None: self.log().warning("Unable to open file %s" % (filename)) @@ -807,7 +807,7 @@ def _getTimeFilterWall(self, splitws, samrun, extension): numrow = splitws.rowCount() - # Searching for the + # Searching for the tmin_absns = splitws.cell(0,0) tmax_absns = splitws.cell(0,1) @@ -839,11 +839,11 @@ def getNumberOfSplittedWorkspace(self, splitwksp): splitws = AnalysisDataService.retrieve(str(splitwksp)) numrows = splitws.rowCount() wscountdict = {} - for r in xrange(numrows): - wsindex = splitws.cell(r,2) + for r in xrange(numrows): + wsindex = splitws.cell(r,2) wscountdict[wsindex] = 0 return len(wscountdict.keys()) - + # Register algorthm with Mantid. AlgorithmFactory.subscribe(SNSPowderReduction) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py index 6b98f8ca25ae..fe1ff3fbe571 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SelectPowderDiffPeaks.py @@ -15,20 +15,20 @@ def name(self): """ """ return "SelectPowderDiffPeaks" - + def summary(self): return "Select the powder diffraction peaks for Le Bail Fit" - + def PyInit(self): """ Declare properties """ - self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Input), + self.declareProperty(ITableWorkspaceProperty("BraggPeakParameterWorkspace", "", Direction.Input), "Name of Table Workspace containing peak parameters.") - self.declareProperty(ITableWorkspaceProperty("ZscoreWorkspace", "", Direction.Input), + self.declareProperty(ITableWorkspaceProperty("ZscoreWorkspace", "", Direction.Input), "Name of Table Workspace containing z-score for the peak parametrs.") - self.declareProperty(ITableWorkspaceProperty("OutputBraggPeakParameterWorkspace", "", Direction.Output), + self.declareProperty(ITableWorkspaceProperty("OutputBraggPeakParameterWorkspace", "", Direction.Output), "Name of Table Workspace containing the filtered peaks' parameters.") self.declareProperty("MinimumPeakHeight", 0.0, "Minimum peak height allowed for the peaks to fit. ") @@ -36,7 +36,7 @@ def PyInit(self): self.declareProperty("ZscoreFilter", "", "Filter on the Zscore of the peak parameters.") return - + def PyExec(self): """ Main Execution Body """ @@ -127,8 +127,8 @@ def parseBraggPeakParameterTable(self, tablews): for irow in xrange(numrows): ppdict = {} for icol in xrange(numcols): - colname = colnames[icol] - value = tablews.cell(irow, icol) + colname = colnames[icol] + value = tablews.cell(irow, icol) ppdict[colname] = value # ENDFOR Column h = ppdict["H"] @@ -157,42 +157,42 @@ def filterByPeakHeight(self, minpeakheight): # ENDFOR return - + def filterByZscore(self, zscoredict, zscorefilter): """ Filter by zscore """ - # 1. Loop over peaks - for hkl in self.mPeaks.keys(): + # 1. Loop over peaks + for hkl in self.mPeaks.keys(): - zscores = zscoredict[hkl] + zscores = zscoredict[hkl] - deletethispeak = False + deletethispeak = False errmsgout = False - # 2. Loop over zscore filters - for parname in zscorefilter.keys(): - # Maximum allowed Z score - maxzscore = zscorefilter[parname] - # Convert to regular parameter name to parameter name in Zcore workspace - zparname = "Z_"+parname - if zscores.has_key(zparname): - # Zscore table has this parameter's zscore - zscore = zscores[zparname] - if zscore > maxzscore: - deletethispeak = True - break - # ENDIF - else: - # Zscore table has no such parameter - print "Warning! Zscore table has no parameter %s (from %s)" % (zparname, parname) + # 2. Loop over zscore filters + for parname in zscorefilter.keys(): + # Maximum allowed Z score + maxzscore = zscorefilter[parname] + # Convert to regular parameter name to parameter name in Zcore workspace + zparname = "Z_"+parname + if zscores.has_key(zparname): + # Zscore table has this parameter's zscore + zscore = zscores[zparname] + if zscore > maxzscore: + deletethispeak = True + break + # ENDIF + else: + # Zscore table has no such parameter + print "Warning! Zscore table has no parameter %s (from %s)" % (zparname, parname) errmsgout = True - # ENDIF - # ENDFOR Fitler + # ENDIF + # ENDFOR Fitler - # 3. Delete if + # 3. Delete if if deletethispeak is True: - self.mPeaks.pop(hkl) + self.mPeaks.pop(hkl) if errmsgout is True: msg = "Parameters (keys):\t\t" @@ -200,26 +200,26 @@ def filterByZscore(self, zscoredict, zscorefilter): msg += "%s,\t\t" % (key) print msg - # ENDFOR Each Peak - + # ENDFOR Each Peak + return def parseZscoreFilter(self, zscorefilterstr): - """ Parse Zscore filter string - Return: zscore filter dictionary Parameter Name: Maximum Allowed - """ - zscorefilter = {} - - terms = zscorefilterstr.split(',') - if len(terms) % 2 == 1: - raise NotImplementedError("Zscore filter is not defined correct. It must have string and float in pair.") - - for i in xrange(len(terms)/2): - parname = terms[2*i].strip() - maxzscore = float(terms[2*i+1]) - zscorefilter[parname] = maxzscore - - return zscorefilter + """ Parse Zscore filter string + Return: zscore filter dictionary Parameter Name: Maximum Allowed + """ + zscorefilter = {} + + terms = zscorefilterstr.split(',') + if len(terms) % 2 == 1: + raise NotImplementedError("Zscore filter is not defined correct. It must have string and float in pair.") + + for i in xrange(len(terms)/2): + parname = terms[2*i].strip() + maxzscore = float(terms[2*i+1]) + zscorefilter[parname] = maxzscore + + return zscorefilter # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py index 0bfa010d3154..b91261511d0c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortByQVectors.py @@ -8,9 +8,9 @@ class SortByQVectors(PythonAlgorithm): """ Sorts spectra from a workspace - + """ - + def category(self): return "Transforms\\Merging;PythonAlgorithms" @@ -22,13 +22,13 @@ def summary(self): def PyInit(self): self.declareProperty("InputWorkspace", "", "Group workspace that automatically includes all members.") - + def PyExec(self): # get parameter values wsString = self.getPropertyValue("InputWorkspace").strip() #internal values wsOutput = "__OutputWorkspace" - wsTemp = "__Sort_temp" + wsTemp = "__Sort_temp" #get the workspace list wsNames = [] for wsName in wsString.split(","): @@ -42,7 +42,7 @@ def PyExec(self): DeleteWorkspace(Workspace=wsOutput) sortStat = [] for wsName in wsNames: - if "qvectors" in wsName: + if "qvectors" in wsName: #extract the spectrum ws = mtd[wsName.strip()] for s in range(0, ws.getNumberHistograms()): @@ -58,8 +58,8 @@ def PyExec(self): yUnit = ws.getAxis(1).getUnit().unitID() transposed = False if ws.getNumberHistograms() < len(sortStat): - Transpose(InputWorkspace=wsName, OutputWorkspace=wsName) - transposed = True + Transpose(InputWorkspace=wsName, OutputWorkspace=wsName) + transposed = True for norm, spec in sortStat: ExtractSingleSpectrum(InputWorkspace=wsName, OutputWorkspace=wsTemp, WorkspaceIndex=spec) if wsOutput in mtd: @@ -81,8 +81,8 @@ def PyExec(self): Transpose(InputWorkspace=wsOutput, OutputWorkspace=wsOutput) RenameWorkspace(InputWorkspace=wsOutput, OutputWorkspace=wsName) - + def GetXValue(self, xs): return np.linalg.norm(xs) - + AlgorithmFactory.subscribe(SortByQVectors) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py index 117856dd2aa5..700ec5b13b40 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortDetectors.py @@ -11,32 +11,32 @@ def category(self): """ Return category """ return "PythonAlgorithms;Utility" - + def name(self): """ Return name """ return "SortDetectors" - + def summary(self): """ Return summary """ return "Algorithm to sort detectors by distance." - + def PyInit(self): """ Declare properties """ self.declareProperty(mantid.api.WorkspaceProperty("Workspace","",direction=mantid.kernel.Direction.Input, validator=mantid.api.InstrumentValidator()), "Input workspace") - - self.declareProperty(IntArrayProperty("UpstreamSpectra",Direction.Output)) - self.declareProperty(FloatArrayProperty("UpstreamDetectorDistances",Direction.Output)) + + self.declareProperty(IntArrayProperty("UpstreamSpectra",Direction.Output)) + self.declareProperty(FloatArrayProperty("UpstreamDetectorDistances",Direction.Output)) self.declareProperty(IntArrayProperty("DownstreamSpectra",Direction.Output)) self.declareProperty(FloatArrayProperty("DownstreamDetectorDistances",Direction.Output)) return - + def PyExec(self): """ Main execution body """ - w = self.getProperty("Workspace").value + w = self.getProperty("Workspace").value samplePos=w.getInstrument().getSample().getPos() moderatorPos=w.getInstrument().getSource().getPos() incident=samplePos-moderatorPos @@ -68,5 +68,5 @@ def PyExec(self): self.setProperty("UpstreamDetectorDistances", numpy.array(updist)) self.setProperty("DownstreamSpectra", numpy.array(downinds)) self.setProperty("DownstreamDetectorDistances", numpy.array(downdist)) - + AlgorithmFactory.subscribe(SortDetectors) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py index 515eea2a45b6..c2de7daabfa7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SortXAxis.py @@ -15,11 +15,11 @@ def name(self): def summary(self): return "Clones the input MatrixWorkspace(s) and orders the x-axis in an ascending fashion." - + def PyInit(self): self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", defaultValue="", direction=Direction.Input), doc="Input workspace") self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", defaultValue="", direction=Direction.Output), doc="Sorted Output Workspace") - + def PyExec(self): inputws = self.getProperty("InputWorkspace").value specs = inputws.getNumberHistograms() @@ -35,7 +35,7 @@ def PyExec(self): indexes = np.delete(indexes, max_index) yordered = y[indexes] eordered = e[indexes] - + outws.setX(i, xordered) outws.setY(i, yordered) outws.setE(i, eordered) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Stitch1DMany.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Stitch1DMany.py index 23711c51a6c9..f3d0ac1ca263 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Stitch1DMany.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/Stitch1DMany.py @@ -13,7 +13,7 @@ def name(self): def summary(self): return "Stitches single histogram matrix workspaces together" - + def PyInit(self): input_validator = StringMandatoryValidator() self.declareProperty(name="InputWorkspaces", defaultValue="", direction=Direction.Input, validator=input_validator, doc="Input workspaces") @@ -25,16 +25,16 @@ def PyInit(self): self.declareProperty(name="UseManualScaleFactor", defaultValue=False, doc="True to use a provided value for the scale factor.") self.declareProperty(name="ManualScaleFactor", defaultValue=1.0, doc="Provided value for the scale factor.") self.declareProperty(FloatArrayProperty(name="OutScaleFactors", direction = Direction.Output), doc="The actual used values for the scaling factors at each stitch step.") - + def __workspace_from_split_name(self, list_of_names, index): return mtd[list_of_names[index].strip()] - + def __workspaces_from_split_name(self, list_of_names): workspaces = list() for name in list_of_names: workspaces.append(mtd[name.strip()]) return workspaces - + ''' If the property value has been provided, use that. If default, then create an array of Nones so that Stitch1D can still be correctly looped over. ''' @@ -46,11 +46,11 @@ def __input_or_safe_default(self, property_name, n_entries): for i in range(0, n_entries): property_value.append(None) return property_value - - - def __do_stitch_workspace(self, lhs_ws, rhs_ws, start_overlap, end_overlap, params, scale_rhs_ws, use_manual_scale_factor, manual_scale_factor): + + + def __do_stitch_workspace(self, lhs_ws, rhs_ws, start_overlap, end_overlap, params, scale_rhs_ws, use_manual_scale_factor, manual_scale_factor): out_name = lhs_ws.name() + rhs_ws.name() - + alg = self.createChildAlgorithm("Stitch1D") alg.initialize() alg.setProperty("LHSWorkspace", lhs_ws) @@ -69,11 +69,11 @@ def __do_stitch_workspace(self, lhs_ws, rhs_ws, start_overlap, end_overlap, para out_ws = alg.getProperty("OutputWorkspace").value scale_factor = alg.getProperty("OutScaleFactor").value logger.warning(str(scale_factor)) - - #out_ws, scale_factor = Stitch1D(LHSWorkspace=lhs_ws, RHSWorkspace=rhs_ws, StartOverlap=start_overlap, EndOverlap=end_overlap, + + #out_ws, scale_factor = Stitch1D(LHSWorkspace=lhs_ws, RHSWorkspace=rhs_ws, StartOverlap=start_overlap, EndOverlap=end_overlap, # Params=params, ScaleRHSWorkspace=scale_rhs_ws, UseManualScaleFactor=use_manual_scale_factor, ManualScaleFactor=manual_scale_factor, OutputWorkspace=out_name) return (out_ws, scale_factor) - + def __check_workspaces_are_common(self, input_workspace_names): workspaces = self.__workspaces_from_split_name(input_workspace_names) exemplar = workspaces[0] @@ -84,27 +84,27 @@ def __check_workspaces_are_common(self, input_workspace_names): if isinstance(test_ws, WorkspaceGroup): if test_ws.size() != exemplar.size(): raise RuntimeError("Group Workspaces as InputWorkspaces must have the same number of sub-workspaces.") - + def __are_processing_groups(self, input_workspace_names): - test_ws = self.__workspace_from_split_name(input_workspace_names, 0) + test_ws = self.__workspace_from_split_name(input_workspace_names, 0) return isinstance(test_ws, WorkspaceGroup) - + def PyExec(self): - + inputWorkspaces = self.getProperty("InputWorkspaces").value inputWorkspaces = inputWorkspaces.split(',') numberOfWorkspaces = len(inputWorkspaces) - + startOverlaps = self.__input_or_safe_default('StartOverlaps', numberOfWorkspaces-1) endOverlaps = self.__input_or_safe_default('EndOverlaps', numberOfWorkspaces-1) - + # Just forward the other properties on. scaleRHSWorkspace = self.getProperty('ScaleRHSWorkspace').value useManualScaleFactor = self.getProperty('UseManualScaleFactor').value manualScaleFactor = self.getProperty('ManualScaleFactor').value params = self.getProperty("Params").value - - + + if not numberOfWorkspaces > 1: raise ValueError("Too few workspaces to stitch") if not (len(startOverlaps) == len(endOverlaps)): @@ -112,72 +112,72 @@ def PyExec(self): if not (len(startOverlaps) == (numberOfWorkspaces- 1)): raise ValueError("Wrong number of StartOverlaps, should be %i not %i" % (numberOfWorkspaces - 1, startOverlaps)) self.__check_workspaces_are_common(inputWorkspaces) - + scaleFactors = list() comma_separator = "," no_separator = str() - + # Identify and process as group workspaces if self.__are_processing_groups(inputWorkspaces): workspace_groups = self.__workspaces_from_split_name(inputWorkspaces) - + out_group_separator = no_separator out_group_workspaces = str() - - n_sub_workspaces = workspace_groups[0].size() + + n_sub_workspaces = workspace_groups[0].size() for i in range(n_sub_workspaces): - + to_process = str() out_name = str() separator = no_separator - + for j in range(0, numberOfWorkspaces, 1): - + to_process += separator + workspace_groups[j][i].name() out_name += workspace_groups[j][i].name() separator=comma_separator - + startOverlaps = self.getProperty("StartOverlaps").value endOverlaps = self.getProperty("EndOverlaps").value - - stitched, scaleFactorsOfIndex = Stitch1DMany(InputWorkspaces=to_process, OutputWorkspace=out_name, StartOverlaps=startOverlaps, EndOverlaps=endOverlaps, - Params=params, ScaleRHSWorkspace=scaleRHSWorkspace, UseManualScaleFactor=useManualScaleFactor, + + stitched, scaleFactorsOfIndex = Stitch1DMany(InputWorkspaces=to_process, OutputWorkspace=out_name, StartOverlaps=startOverlaps, EndOverlaps=endOverlaps, + Params=params, ScaleRHSWorkspace=scaleRHSWorkspace, UseManualScaleFactor=useManualScaleFactor, ManualScaleFactor=manualScaleFactor) # Flatten out scale factors. for sf in scaleFactorsOfIndex: - scaleFactors.append(sf) - + scaleFactors.append(sf) + out_group_workspaces += out_group_separator + out_name out_group_separator = comma_separator - - out_workspace_name = self.getPropertyValue("OutputWorkspace") + + out_workspace_name = self.getPropertyValue("OutputWorkspace") out_group = GroupWorkspaces(InputWorkspaces=out_group_workspaces, OutputWorkspace=out_workspace_name) - self.setProperty("OutputWorkspace", out_group) - + self.setProperty("OutputWorkspace", out_group) + else: - + # Iterate forward through the workspaces if scaleRHSWorkspace: - lhsWS = self.__workspace_from_split_name(inputWorkspaces, 0) - + lhsWS = self.__workspace_from_split_name(inputWorkspaces, 0) + for i in range(1, numberOfWorkspaces, 1): rhsWS = self.__workspace_from_split_name(inputWorkspaces, i) lhsWS, scaleFactor = self.__do_stitch_workspace(lhsWS, rhsWS, startOverlaps[i-1], endOverlaps[i-1], params, scaleRHSWorkspace, useManualScaleFactor, manualScaleFactor) scaleFactors.append(scaleFactor) self.setProperty('OutputWorkspace', lhsWS) - + # Iterate backwards through the workspaces. else: - rhsWS = self.__workspace_from_split_name(inputWorkspaces, -1) + rhsWS = self.__workspace_from_split_name(inputWorkspaces, -1) for i in range(0, numberOfWorkspaces-1, 1): lhsWS = self.__workspace_from_split_name(inputWorkspaces, i) - rhsWS, scaleFactor = Stitch1D(LHSWorkspace=lhsWS, RHSWorkspace=rhsWS, StartOverlap=startOverlaps[i-1], EndOverlap=endOverlaps[i-1], Params=params, ScaleRHSWorkspace=scaleRHSWorkspace, UseManualScaleFactor=useManualScaleFactor, ManualScaleFactor=manualScaleFactor) + rhsWS, scaleFactor = Stitch1D(LHSWorkspace=lhsWS, RHSWorkspace=rhsWS, StartOverlap=startOverlaps[i-1], EndOverlap=endOverlaps[i-1], Params=params, ScaleRHSWorkspace=scaleRHSWorkspace, UseManualScaleFactor=useManualScaleFactor, ManualScaleFactor=manualScaleFactor) scaleFactors.append(scaleFactor) self.setProperty('OutputWorkspace', rhsWS) - + self.setProperty('OutScaleFactors', scaleFactors) return None - + ############################################################################################# diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py index 7826e2e346bd..9cde0ae62e06 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/SuggestTibCNCS.py @@ -1,5 +1,5 @@ from mantid.api import PythonAlgorithm, AlgorithmFactory -import mantid.simpleapi +import mantid.simpleapi from mantid.kernel import FloatBoundedValidator,Direction from numpy import sqrt,floor @@ -25,7 +25,7 @@ def category(self): """ Return category """ return "PythonAlgorithms;Utility;Inelastic" - + def name(self): """ Return name """ @@ -35,17 +35,17 @@ def summary(self): """ Return summary """ return "Suggest possible time independent background range for CNCS." - + def PyInit(self): """ Declare properties """ val=mantid.kernel.FloatBoundedValidator() val.setBounds(0.5,50) #reasonable incident nergy range for CNCS self.declareProperty("IncidentEnergy",0.,val,"Incident energy (0.5 to 50 meV)") - self.declareProperty("TibMin",0.,Direction.Output) - self.declareProperty("TibMax",0.,Direction.Output) + self.declareProperty("TibMin",0.,Direction.Output) + self.declareProperty("TibMax",0.,Direction.Output) return - + def e2v(self,energy): return sqrt(energy/5.227e-6) @@ -69,44 +69,44 @@ def PyExec(self): #check for TIB dtib=3500. # default length of TIB range dtibreduced=2500 #reduced range - + dtinfminus=500 dtinfplus=1500 dtpulseminus=50 dtpulseplus=1500 - - #Create intervals that cannot be used for TIB. For ease, + + #Create intervals that cannot be used for TIB. For ease, #move everything to times lower than t_inf, make sure #one doesn't overlap with the frame edge, then if the TIB #interval is in the previous frame, jut move it up - + intervalList=[] intervalList.append(Interval(tinf-dtinfminus,tinf)) #interval close to t_inf, on the lower side intervalList.append(Interval(tmin,tmin)) #intervaldenoting frame edge. This will make sure that one cannot get an interval overlapping t_min intervalList.append(Interval(tinf-frame,tinf-frame+dtinfplus)) #interval close to t_inf, on the upper side, but moved one frame down - + if tpulse+dtpulseplustinf-frame: timestocheck.append(i.min) timestocheck.sort() timestocheck.reverse() - + for t in timestocheck: tInterval=Interval(t-dtib,t) if all( not inter.overlap(tInterval) for inter in intervalList ): @@ -118,16 +118,16 @@ def PyExec(self): tibmin=tInterval.min tibmax=tInterval.max break - - #move to the data frame + + #move to the data frame if tibmin 1: + if len(rownumberlist) > 1: rownumberlist = sorted(rownumberlist) elif len(rownumberlist) == 0: # if no input row number/parameter name, set the value to all rows @@ -71,10 +71,10 @@ def PyExec(self): # 3. Process column (to change) information colname = self.getProperty("Column").value - if colnamedict.has_key(colname): + if colnamedict.has_key(colname): icolumn = colnamedict[colname] else: - raise NotImplementedError("Column name %s does not exist in TableWorkspace %s" + raise NotImplementedError("Column name %s does not exist in TableWorkspace %s" % (colname, tablews.name())) # 3. Set value @@ -86,17 +86,17 @@ def PyExec(self): value = self.getProperty("NewFloatValue").value # print "Input Value = %s. Type = %s" % (str(value), type(value)) - + for irow in rownumberlist: irow = int(irow) - if irow >= 0: + if irow >= 0: tableWS.setCell(irow, icolumn, value) - # 4. + # 4. self.setProperty("InputWorkspace", tableWS) return - + def convertParameterNameToTableRows(self, parametername, paramnamedict): """ Convert parameter name (incomplete might be) to row number(s) An algorithm to recognize parameter with blurred definition will be use such as @@ -110,7 +110,7 @@ def convertParameterNameToTableRows(self, parametername, paramnamedict): - parametername: parameter name to change value - paramnamedict: dictionary key = parameter name, value = row number in table workspace - Return: List of row numbers (integer), a negative value might exit to represent a non-existing parameter name + Return: List of row numbers (integer), a negative value might exit to represent a non-existing parameter name """ rownumbers= [] @@ -155,7 +155,7 @@ def convertParameterNameToTableRows(self, parametername, paramnamedict): if ismatch is True: rownumber = paramnamedict[parname] rownumbers.append(rownumber) - # ENDFOR: + # ENDFOR: # 2. Take in the case that there is no match if len(rownumbers) == 0: @@ -163,7 +163,7 @@ def convertParameterNameToTableRows(self, parametername, paramnamedict): print "Warning! There is no match for parameter %s" % (parnametofit) rownumbers.append(-1000) # ENDIFELSE - + return rownumbers def parseTableWorkspace(self, tablews): @@ -185,7 +185,7 @@ def parseTableWorkspace(self, tablews): raise NotImplementedError("Input table workspace is not supported due to column size.") if colnames[0] != "Name" or colnames[1] != "Value": raise NotImplementedError("Input table workspace is not supported due to column name.") - + # 3. Parse! parametersdict = {} parnamedict = {} @@ -198,7 +198,7 @@ def parseTableWorkspace(self, tablews): parnamedict[parname] = irow self.parameternames.append(parname) - # NEW! Collect each variable in + # NEW! Collect each variable in valuelist = [] for icol in xrange(len(colnames)): value = tablews.cell(irow, icol) @@ -207,7 +207,7 @@ def parseTableWorkspace(self, tablews): # ENDFOR # ENDFOR - + return (parnamedict, colnamedict, parameterdict) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py index 3db3edf981c3..c3ebd80412da 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/DensityOfStates.py @@ -10,610 +10,610 @@ class DensityOfStates(PythonAlgorithm): - def summary(self): - return "Calculates phonon densities of states, Raman and IR spectrum." - - def PyInit(self): - #declare properties - self.declareProperty(FileProperty('File', '', action=FileAction.Load, - extensions = ["phonon", "castep"]), - doc='Filename of the file.') - - self.declareProperty(name='Function',defaultValue='Gaussian', - validator=StringListValidator(['Gaussian', 'Lorentzian']), - doc="Type of function to fit to peaks.") - - self.declareProperty(name='PeakWidth', defaultValue=10.0, - doc='Set Gaussian/Lorentzian FWHM for broadening. Default is 10') - - self.declareProperty(name='SpectrumType',defaultValue='DOS', - validator=StringListValidator(['DOS', 'IR_Active', 'Raman_Active']), - doc="Type of intensities to extract and model (fundamentals-only) from .phonon.") - - self.declareProperty(name='Scale', defaultValue=1.0, - doc='Scale the intesity by the given factor. Default is no scaling.') - - self.declareProperty(name='BinWidth', defaultValue=1.0, - doc='Set histogram resolution for binning (eV or cm**-1). Default is 1') - - self.declareProperty(name='Temperature', defaultValue=300, - doc='Temperature to use (in raman spectrum modelling). Default is 300') - - self.declareProperty(name='ZeroThreshold', defaultValue=3.0, - doc='Ignore frequencies below the this threshold. Default is 3.0') - - self.declareProperty(StringArrayProperty('Ions', Direction.Input), - doc="List of Ions to use to calculate partial density of states. If left blank, total density of states will be calculated") - - self.declareProperty(name='SumContributions', defaultValue=False, - doc="Sum the partial density of states into a single workspace.") - - self.declareProperty(WorkspaceProperty('OutputWorkspace', '', Direction.Output), - doc="Name to give the output workspace.") - - #regex pattern for a floating point number - self._float_regex = '\-?(?:\d+\.?\d*|\d*\.?\d+)' + def summary(self): + return "Calculates phonon densities of states, Raman and IR spectrum." + + def PyInit(self): + #declare properties + self.declareProperty(FileProperty('File', '', action=FileAction.Load, + extensions = ["phonon", "castep"]), + doc='Filename of the file.') + + self.declareProperty(name='Function',defaultValue='Gaussian', + validator=StringListValidator(['Gaussian', 'Lorentzian']), + doc="Type of function to fit to peaks.") + + self.declareProperty(name='PeakWidth', defaultValue=10.0, + doc='Set Gaussian/Lorentzian FWHM for broadening. Default is 10') + + self.declareProperty(name='SpectrumType',defaultValue='DOS', + validator=StringListValidator(['DOS', 'IR_Active', 'Raman_Active']), + doc="Type of intensities to extract and model (fundamentals-only) from .phonon.") + + self.declareProperty(name='Scale', defaultValue=1.0, + doc='Scale the intesity by the given factor. Default is no scaling.') + + self.declareProperty(name='BinWidth', defaultValue=1.0, + doc='Set histogram resolution for binning (eV or cm**-1). Default is 1') + + self.declareProperty(name='Temperature', defaultValue=300, + doc='Temperature to use (in raman spectrum modelling). Default is 300') + + self.declareProperty(name='ZeroThreshold', defaultValue=3.0, + doc='Ignore frequencies below the this threshold. Default is 3.0') + + self.declareProperty(StringArrayProperty('Ions', Direction.Input), + doc="List of Ions to use to calculate partial density of states. If left blank, total density of states will be calculated") + + self.declareProperty(name='SumContributions', defaultValue=False, + doc="Sum the partial density of states into a single workspace.") + + self.declareProperty(WorkspaceProperty('OutputWorkspace', '', Direction.Output), + doc="Name to give the output workspace.") + + #regex pattern for a floating point number + self._float_regex = '\-?(?:\d+\.?\d*|\d*\.?\d+)' #---------------------------------------------------------------------------------------- - - def PyExec(self): - # Run the algorithm - self._get_properties() - - file_name = self.getPropertyValue('File') - file_data = self._read_data_from_file(file_name) - frequencies, ir_intensities, raman_intensities, weights = file_data[:4] - - prog_reporter = Progress(self,0.0,1.0,1) - if self._calc_partial: - eigenvectors = file_data[4] - prog_reporter.report("Calculating partial density of states") - - if self._sum_contributions: - #sum each of the contributions - self._compute_partial(self._partial_ion_numbers, frequencies, eigenvectors, weights) - mtd[self._ws_name].setYUnit('(D/A)^2/amu') - mtd[self._ws_name].setYUnitLabel('Intensity') - else: - #output each contribution to it's own workspace - partial_workspaces = [] - for ion_name, ions in self._ion_dict.items(): - self._compute_partial(ions, frequencies, eigenvectors, weights) - mtd[self._ws_name].setYUnit('(D/A)^2/amu') - mtd[self._ws_name].setYUnitLabel('Intensity') - - partial_ws_name = self._ws_name + '_' + ion_name - partial_workspaces.append(partial_ws_name) - RenameWorkspace(self._ws_name, OutputWorkspace=partial_ws_name) - - group = ','.join(partial_workspaces) - GroupWorkspaces(group, OutputWorkspace=self._ws_name) - - elif self._spec_type == 'DOS': - prog_reporter.report("Calculating density of states") - self._compute_DOS(frequencies, np.ones_like(frequencies), weights) - mtd[self._ws_name].setYUnit('(D/A)^2/amu') - mtd[self._ws_name].setYUnitLabel('Intensity') - - elif self._spec_type == 'IR_Active': - if ir_intensities.size == 0: - raise ValueError("Could not load any IR intensities from file.") - - prog_reporter.report("Calculating IR intensities") - self._compute_DOS(frequencies, ir_intensities, weights) - mtd[self._ws_name].setYUnit('(D/A)^2/amu') - mtd[self._ws_name].setYUnitLabel('Intensity') - - elif self._spec_type == 'Raman_Active': - if raman_intensities.size == 0: - raise ValueError("Could not load any Raman intensities from file.") - - prog_reporter.report("Calculating Raman intensities") - self._compute_raman(frequencies, raman_intensities, weights) - mtd[self._ws_name].setYUnit('A^4') - mtd[self._ws_name].setYUnitLabel('Intensity') - - self.setProperty("OutputWorkspace", self._ws_name) + + def PyExec(self): + # Run the algorithm + self._get_properties() + + file_name = self.getPropertyValue('File') + file_data = self._read_data_from_file(file_name) + frequencies, ir_intensities, raman_intensities, weights = file_data[:4] + + prog_reporter = Progress(self,0.0,1.0,1) + if self._calc_partial: + eigenvectors = file_data[4] + prog_reporter.report("Calculating partial density of states") + + if self._sum_contributions: + #sum each of the contributions + self._compute_partial(self._partial_ion_numbers, frequencies, eigenvectors, weights) + mtd[self._ws_name].setYUnit('(D/A)^2/amu') + mtd[self._ws_name].setYUnitLabel('Intensity') + else: + #output each contribution to it's own workspace + partial_workspaces = [] + for ion_name, ions in self._ion_dict.items(): + self._compute_partial(ions, frequencies, eigenvectors, weights) + mtd[self._ws_name].setYUnit('(D/A)^2/amu') + mtd[self._ws_name].setYUnitLabel('Intensity') + + partial_ws_name = self._ws_name + '_' + ion_name + partial_workspaces.append(partial_ws_name) + RenameWorkspace(self._ws_name, OutputWorkspace=partial_ws_name) + + group = ','.join(partial_workspaces) + GroupWorkspaces(group, OutputWorkspace=self._ws_name) + + elif self._spec_type == 'DOS': + prog_reporter.report("Calculating density of states") + self._compute_DOS(frequencies, np.ones_like(frequencies), weights) + mtd[self._ws_name].setYUnit('(D/A)^2/amu') + mtd[self._ws_name].setYUnitLabel('Intensity') + + elif self._spec_type == 'IR_Active': + if ir_intensities.size == 0: + raise ValueError("Could not load any IR intensities from file.") + + prog_reporter.report("Calculating IR intensities") + self._compute_DOS(frequencies, ir_intensities, weights) + mtd[self._ws_name].setYUnit('(D/A)^2/amu') + mtd[self._ws_name].setYUnitLabel('Intensity') + + elif self._spec_type == 'Raman_Active': + if raman_intensities.size == 0: + raise ValueError("Could not load any Raman intensities from file.") + + prog_reporter.report("Calculating Raman intensities") + self._compute_raman(frequencies, raman_intensities, weights) + mtd[self._ws_name].setYUnit('A^4') + mtd[self._ws_name].setYUnitLabel('Intensity') + + self.setProperty("OutputWorkspace", self._ws_name) #---------------------------------------------------------------------------------------- - def _get_properties(self): - """ - Set the properties passed to the algorithm - """ - self._temperature = self.getProperty('Temperature').value - self._bin_width = self.getProperty('BinWidth').value - self._spec_type = self.getPropertyValue('SpectrumType') - self._peak_func = self.getPropertyValue('Function') - self._ws_name = self.getPropertyValue('OutputWorkspace') - self._peak_width = self.getProperty('PeakWidth').value - self._scale = self.getProperty('Scale').value - self._zero_threshold = self.getProperty('ZeroThreshold').value - self._ions = self.getProperty('Ions').value - self._sum_contributions = self.getProperty('SumContributions').value - self._calc_partial = (len(self._ions) > 0) + def _get_properties(self): + """ + Set the properties passed to the algorithm + """ + self._temperature = self.getProperty('Temperature').value + self._bin_width = self.getProperty('BinWidth').value + self._spec_type = self.getPropertyValue('SpectrumType') + self._peak_func = self.getPropertyValue('Function') + self._ws_name = self.getPropertyValue('OutputWorkspace') + self._peak_width = self.getProperty('PeakWidth').value + self._scale = self.getProperty('Scale').value + self._zero_threshold = self.getProperty('ZeroThreshold').value + self._ions = self.getProperty('Ions').value + self._sum_contributions = self.getProperty('SumContributions').value + self._calc_partial = (len(self._ions) > 0) #---------------------------------------------------------------------------------------- - def _draw_peaks(self, hist, peaks): - """ - Draw Gaussian or Lorentzian peaks to each point in the data - - @param hist - array of counts for each bin - @param peaks - the indicies of each non-zero point in the data - @return the fitted y data - """ - if self._peak_func == "Gaussian": - n_gauss = int( 3.0* self._peak_width / self._bin_width ) - sigma = self._peak_width / 2.354 - - dos = np.zeros(len(hist)-1 + n_gauss) - - for index in peaks: - for g in range(-n_gauss, n_gauss): - if index + g > 0: - dos[index+g] += hist[index] * math.exp( - (g * self._bin_width)**2 / (2 * sigma **2)) / (math.sqrt(2*math.pi) * sigma) - - elif self._peak_func == "Lorentzian": - - n_lorentz = int( 25.0 * self._peak_width / self._bin_width ) - gamma_by_2 = self._peak_width / 2 - - dos = np.zeros(len(hist)-1 + n_lorentz) - - for index in peaks: - for l in range(-n_lorentz, n_lorentz): - if index + l > 0: - dos[index+l] += hist[index] * gamma_by_2 / ( l ** 2 + gamma_by_2 **2 ) / math.pi - - return dos + def _draw_peaks(self, hist, peaks): + """ + Draw Gaussian or Lorentzian peaks to each point in the data + + @param hist - array of counts for each bin + @param peaks - the indicies of each non-zero point in the data + @return the fitted y data + """ + if self._peak_func == "Gaussian": + n_gauss = int( 3.0* self._peak_width / self._bin_width ) + sigma = self._peak_width / 2.354 + + dos = np.zeros(len(hist)-1 + n_gauss) + + for index in peaks: + for g in range(-n_gauss, n_gauss): + if index + g > 0: + dos[index+g] += hist[index] * math.exp( - (g * self._bin_width)**2 / (2 * sigma **2)) / (math.sqrt(2*math.pi) * sigma) + + elif self._peak_func == "Lorentzian": + + n_lorentz = int( 25.0 * self._peak_width / self._bin_width ) + gamma_by_2 = self._peak_width / 2 + + dos = np.zeros(len(hist)-1 + n_lorentz) + + for index in peaks: + for l in range(-n_lorentz, n_lorentz): + if index + l > 0: + dos[index+l] += hist[index] * gamma_by_2 / ( l ** 2 + gamma_by_2 **2 ) / math.pi + + return dos #---------------------------------------------------------------------------------------- - def _compute_partial(self, ion_numbers, frequencies, eigenvectors, weights): - """ - Compute partial Density Of States. - - This uses the eigenvectors in a .phonon file to calculate - the partial density of states. - - @param frequencies - frequencies read from file - @param eigenvectors - eigenvectors read from file - @param weights - weights for each frequency block - """ - - intensities = [] - for block_vectors in eigenvectors: - block_intensities = [] - for mode in xrange(self._num_branches): - #only select vectors for the ions we're interested in - lower, upper = mode*self._num_ions, (mode+1)*self._num_ions - vectors = block_vectors[lower:upper] - vectors = vectors[ion_numbers] - - #compute intensity - exponent = np.empty(vectors.shape) - exponent.fill(2) - vectors = np.power(vectors, exponent) - total = np.sum(vectors) - - block_intensities.append(total) - - intensities += block_intensities - - intensities = np.asarray(intensities) - self._compute_DOS(frequencies, intensities, weights) + def _compute_partial(self, ion_numbers, frequencies, eigenvectors, weights): + """ + Compute partial Density Of States. + + This uses the eigenvectors in a .phonon file to calculate + the partial density of states. + + @param frequencies - frequencies read from file + @param eigenvectors - eigenvectors read from file + @param weights - weights for each frequency block + """ + + intensities = [] + for block_vectors in eigenvectors: + block_intensities = [] + for mode in xrange(self._num_branches): + #only select vectors for the ions we're interested in + lower, upper = mode*self._num_ions, (mode+1)*self._num_ions + vectors = block_vectors[lower:upper] + vectors = vectors[ion_numbers] + + #compute intensity + exponent = np.empty(vectors.shape) + exponent.fill(2) + vectors = np.power(vectors, exponent) + total = np.sum(vectors) + + block_intensities.append(total) + + intensities += block_intensities + + intensities = np.asarray(intensities) + self._compute_DOS(frequencies, intensities, weights) #---------------------------------------------------------------------------------------- - def _compute_DOS(self, frequencies, intensities, weights): - """ - Compute Density Of States - - @param frequencies - frequencies read from file - @param intensities - intensities read from file - @param weights - weights for each frequency block - """ - if ( frequencies.size > intensities.size ): - #if we have less intensities than frequencies fill the difference with ones. - diff = frequencies.size-intensities.size - intensities = np.concatenate((intensities, np.ones(diff))) - - if ( frequencies.size != weights.size or frequencies.size != intensities.size ): - raise ValueError("Number of data points must match!") - - #ignore values below fzerotol - zero_mask = np.where(np.absolute(frequencies) < self._zero_threshold) - intensities[zero_mask] = 0.0 - - #sort data to follow natural ordering - permutation = frequencies.argsort() - frequencies = frequencies[permutation] - intensities = intensities[permutation] - weights = weights[permutation] - - #weight intensities - intensities = intensities * weights - - #create histogram x data - xmin, xmax = frequencies[0], frequencies[-1]+self._bin_width - bins = np.arange(xmin, xmax, self._bin_width) - - #sum values in each bin - hist = np.zeros(bins.size) - for index, (lower, upper) in enumerate(zip(bins, bins[1:])): - binMask = np.where((frequencies >= lower) & (frequencies < upper)) - hist[index] = intensities[binMask].sum() - - #find and fit peaks - peaks = hist.nonzero()[0] - dos = self._draw_peaks(hist, peaks) - - data_x = np.arange(xmin, xmin+dos.size) - CreateWorkspace(DataX=data_x, DataY=dos, OutputWorkspace=self._ws_name) - unitx = mtd[self._ws_name].getAxis(0).setUnit("Label") - unitx.setLabel("Energy Shift", 'cm^-1') - - if self._scale != 1: - Scale(InputWorkspace=self._ws_name, OutputWorkspace=self._ws_name, Factor=self._scale) + def _compute_DOS(self, frequencies, intensities, weights): + """ + Compute Density Of States + + @param frequencies - frequencies read from file + @param intensities - intensities read from file + @param weights - weights for each frequency block + """ + if ( frequencies.size > intensities.size ): + #if we have less intensities than frequencies fill the difference with ones. + diff = frequencies.size-intensities.size + intensities = np.concatenate((intensities, np.ones(diff))) + + if ( frequencies.size != weights.size or frequencies.size != intensities.size ): + raise ValueError("Number of data points must match!") + + #ignore values below fzerotol + zero_mask = np.where(np.absolute(frequencies) < self._zero_threshold) + intensities[zero_mask] = 0.0 + + #sort data to follow natural ordering + permutation = frequencies.argsort() + frequencies = frequencies[permutation] + intensities = intensities[permutation] + weights = weights[permutation] + + #weight intensities + intensities = intensities * weights + + #create histogram x data + xmin, xmax = frequencies[0], frequencies[-1]+self._bin_width + bins = np.arange(xmin, xmax, self._bin_width) + + #sum values in each bin + hist = np.zeros(bins.size) + for index, (lower, upper) in enumerate(zip(bins, bins[1:])): + binMask = np.where((frequencies >= lower) & (frequencies < upper)) + hist[index] = intensities[binMask].sum() + + #find and fit peaks + peaks = hist.nonzero()[0] + dos = self._draw_peaks(hist, peaks) + + data_x = np.arange(xmin, xmin+dos.size) + CreateWorkspace(DataX=data_x, DataY=dos, OutputWorkspace=self._ws_name) + unitx = mtd[self._ws_name].getAxis(0).setUnit("Label") + unitx.setLabel("Energy Shift", 'cm^-1') + + if self._scale != 1: + Scale(InputWorkspace=self._ws_name, OutputWorkspace=self._ws_name, Factor=self._scale) #---------------------------------------------------------------------------------------- - def _compute_raman(self, frequencies, intensities, weights): - """ - Compute Raman intensities - - @param frequencies - frequencies read from file - @param intensities - raman intensities read from file - @param weights - weights for each frequency block - """ - #we only want to use the first set - frequencies = frequencies[:self._num_branches] - intensities = intensities[:self._num_branches] - weights = weights[:self._num_branches] - - #speed of light in vaccum in m/s - c = scipy.constants.c - #wavelength of the laser - laser_wavelength = 514.5e-9 - #planck's constant - planck = scipy.constants.h - # cm(-1) => K conversion - cm1_to_K = scipy.constants.codata.value('inverse meter-kelvin relationship')*100 - - factor = (math.pow((2*math.pi / laser_wavelength), 4) * planck) / (8 * math.pi**2 * 45) * 1e12 - x_sections = np.zeros(frequencies.size) - - #use only the first set of frequencies and ignore small values - zero_mask = np.where( frequencies > self._zero_threshold ) - frequency_x_sections = frequencies[zero_mask] - intensity_x_sections = intensities[zero_mask] - - bose_occ = 1.0 / ( np.exp(cm1_to_K * frequency_x_sections / self._temperature) -1) - x_sections[zero_mask] = factor / frequency_x_sections * (1 + bose_occ) * intensity_x_sections - - self._compute_DOS(frequencies, x_sections, weights) + def _compute_raman(self, frequencies, intensities, weights): + """ + Compute Raman intensities + + @param frequencies - frequencies read from file + @param intensities - raman intensities read from file + @param weights - weights for each frequency block + """ + #we only want to use the first set + frequencies = frequencies[:self._num_branches] + intensities = intensities[:self._num_branches] + weights = weights[:self._num_branches] + + #speed of light in vaccum in m/s + c = scipy.constants.c + #wavelength of the laser + laser_wavelength = 514.5e-9 + #planck's constant + planck = scipy.constants.h + # cm(-1) => K conversion + cm1_to_K = scipy.constants.codata.value('inverse meter-kelvin relationship')*100 + + factor = (math.pow((2*math.pi / laser_wavelength), 4) * planck) / (8 * math.pi**2 * 45) * 1e12 + x_sections = np.zeros(frequencies.size) + + #use only the first set of frequencies and ignore small values + zero_mask = np.where( frequencies > self._zero_threshold ) + frequency_x_sections = frequencies[zero_mask] + intensity_x_sections = intensities[zero_mask] + + bose_occ = 1.0 / ( np.exp(cm1_to_K * frequency_x_sections / self._temperature) -1) + x_sections[zero_mask] = factor / frequency_x_sections * (1 + bose_occ) * intensity_x_sections + + self._compute_DOS(frequencies, x_sections, weights) #---------------------------------------------------------------------------------------- - def _read_data_from_file(self, file_name): - """ - Select the appropriate file parser and check data was successfully - loaded from file. + def _read_data_from_file(self, file_name): + """ + Select the appropriate file parser and check data was successfully + loaded from file. - @param file_name - path to the file. - @return tuple of the frequencies, ir and raman intensities and weights - """ - ext = os.path.splitext(file_name)[1] + @param file_name - path to the file. + @return tuple of the frequencies, ir and raman intensities and weights + """ + ext = os.path.splitext(file_name)[1] - if ext == '.phonon': - file_data = self._parse_phonon_file(file_name) - elif ext == '.castep': - if len(self._ions) > 0: - raise ValueError("Cannot compute partial density of states from .castep files.") + if ext == '.phonon': + file_data = self._parse_phonon_file(file_name) + elif ext == '.castep': + if len(self._ions) > 0: + raise ValueError("Cannot compute partial density of states from .castep files.") - file_data = self._parse_castep_file(file_name) + file_data = self._parse_castep_file(file_name) - frequencies = file_data[0] + frequencies = file_data[0] - if ( frequencies.size == 0 ): - raise ValueError("Failed to load any frequencies from file.") + if ( frequencies.size == 0 ): + raise ValueError("Failed to load any frequencies from file.") - return file_data + return file_data #---------------------------------------------------------------------------------------- - def _parse_block_header(self, header_match, block_count): - """ - Parse the header of a block of frequencies and intensities + def _parse_block_header(self, header_match, block_count): + """ + Parse the header of a block of frequencies and intensities - @param header_match - the regex match to the header - @param block_count - the count of blocks found so far - @return weight for this block of values - """ - #found header block at start of frequencies - q1, q2, q3, weight = map(float, header_match.groups()) - if block_count > 1 and sum([q1,q2,q3]) == 0: - weight = 0.0 - return weight + @param header_match - the regex match to the header + @param block_count - the count of blocks found so far + @return weight for this block of values + """ + #found header block at start of frequencies + q1, q2, q3, weight = map(float, header_match.groups()) + if block_count > 1 and sum([q1,q2,q3]) == 0: + weight = 0.0 + return weight #---------------------------------------------------------------------------------------- - def _parse_phonon_file_header(self, f_handle): - """ - Read information from the header of a <>.phonon file - - @param f_handle - handle to the file. - @return tuple of the number of ions and branches in the file - """ - while True: - line = f_handle.readline() - - if not line: - raise IOError("Could not find any header information.") - - if 'Number of ions' in line: - self._num_ions = int(line.strip().split()[-1]) - elif 'Number of branches' in line: - self._num_branches = int(line.strip().split()[-1]) - elif self._calc_partial and 'Fractional Co-ordinates' in line: - #we're calculating partial density of states - self._ion_dict = dict( (ion, []) for ion in self._ions) - - if self._num_ions == None: - raise IOError("Failed to parse file. Invalid file header.") - - #extract the mode number for each of the ions we're interested in - for _ in xrange(self._num_ions): - line = f_handle.readline() - line_data = line.strip().split() - ion = line_data[4] - - if ion in self._ions: - mode = int(line_data[0])-1 #-1 to convert to zero based indexing - self._ion_dict[ion].append(mode) - - self._partial_ion_numbers = [] - for ion, ion_nums in self._ion_dict.items(): - if len(ion_nums) == 0: - logger.warning("Could not find any ions of type %s" % ion) - self._partial_ion_numbers += ion_nums - - self._partial_ion_numbers = sorted(self._partial_ion_numbers) - self._partial_ion_numbers = np.asarray(self._partial_ion_numbers) - - if self._partial_ion_numbers.size == 0: - raise ValueError("Could not find any of the specified ions") - - if 'END header' in line: - if self._num_ions == None or self._num_branches == None: - raise IOError("Failed to parse file. Invalid file header.") - return + def _parse_phonon_file_header(self, f_handle): + """ + Read information from the header of a <>.phonon file + + @param f_handle - handle to the file. + @return tuple of the number of ions and branches in the file + """ + while True: + line = f_handle.readline() + + if not line: + raise IOError("Could not find any header information.") + + if 'Number of ions' in line: + self._num_ions = int(line.strip().split()[-1]) + elif 'Number of branches' in line: + self._num_branches = int(line.strip().split()[-1]) + elif self._calc_partial and 'Fractional Co-ordinates' in line: + #we're calculating partial density of states + self._ion_dict = dict( (ion, []) for ion in self._ions) + + if self._num_ions == None: + raise IOError("Failed to parse file. Invalid file header.") + + #extract the mode number for each of the ions we're interested in + for _ in xrange(self._num_ions): + line = f_handle.readline() + line_data = line.strip().split() + ion = line_data[4] + + if ion in self._ions: + mode = int(line_data[0])-1 #-1 to convert to zero based indexing + self._ion_dict[ion].append(mode) + + self._partial_ion_numbers = [] + for ion, ion_nums in self._ion_dict.items(): + if len(ion_nums) == 0: + logger.warning("Could not find any ions of type %s" % ion) + self._partial_ion_numbers += ion_nums + + self._partial_ion_numbers = sorted(self._partial_ion_numbers) + self._partial_ion_numbers = np.asarray(self._partial_ion_numbers) + + if self._partial_ion_numbers.size == 0: + raise ValueError("Could not find any of the specified ions") + + if 'END header' in line: + if self._num_ions == None or self._num_branches == None: + raise IOError("Failed to parse file. Invalid file header.") + return #---------------------------------------------------------------------------------------- - def _parse_phonon_freq_block(self, f_handle): - """ - Iterator to parse a block of frequencies from a .phonon file. - - @param f_handle - handle to the file. - """ - prog_reporter = Progress(self,0.0,1.0,1) - for _ in xrange( self._num_branches): - line = f_handle.readline() - line_data = line.strip().split()[1:] - line_data = map(float, line_data) - yield line_data - - prog_reporter.report("Reading frequencies.") + def _parse_phonon_freq_block(self, f_handle): + """ + Iterator to parse a block of frequencies from a .phonon file. + + @param f_handle - handle to the file. + """ + prog_reporter = Progress(self,0.0,1.0,1) + for _ in xrange( self._num_branches): + line = f_handle.readline() + line_data = line.strip().split()[1:] + line_data = map(float, line_data) + yield line_data + + prog_reporter.report("Reading frequencies.") #---------------------------------------------------------------------------------------- - def _parse_phonon_eigenvectors(self, f_handle): - vectors = [] - prog_reporter = Progress(self,0.0,1.0,self._num_branches*self._num_ions) - for _ in xrange(self._num_ions*self._num_branches): - line = f_handle.readline() - - if not line: - raise IOError("Could not parse file. Invalid file format.") - - line_data = line.strip().split() - vector_componets = line_data[2::2] - vector_componets = map(float, vector_componets) - vectors.append(vector_componets) - prog_reporter.report("Reading eigenvectors.") - - return np.asarray(vectors) + def _parse_phonon_eigenvectors(self, f_handle): + vectors = [] + prog_reporter = Progress(self,0.0,1.0,self._num_branches*self._num_ions) + for _ in xrange(self._num_ions*self._num_branches): + line = f_handle.readline() + + if not line: + raise IOError("Could not parse file. Invalid file format.") + + line_data = line.strip().split() + vector_componets = line_data[2::2] + vector_componets = map(float, vector_componets) + vectors.append(vector_componets) + prog_reporter.report("Reading eigenvectors.") + + return np.asarray(vectors) #---------------------------------------------------------------------------------------- - def _parse_phonon_file(self, file_name): - """ - Read frequencies from a <>.phonon file - - @param file_name - file path of the file to read - @return the frequencies, infra red and raman intensities and weights of frequency blocks - """ - #Header regex. Looks for lines in the following format: - # q-pt= 1 0.000000 0.000000 0.000000 1.0000000000 0.000000 0.000000 1.000000 - header_regex_str = r"^ +q-pt=\s+\d+ +(%(s)s) +(%(s)s) +(%(s)s) (?: *(%(s)s)){0,4}" % {'s': self._float_regex} - header_regex = re.compile(header_regex_str) - - eigenvectors_regex = re.compile(r"\s*Mode\s+Ion\s+X\s+Y\s+Z\s*") - block_count = 0 - - frequencies, ir_intensities, raman_intensities, weights = [], [], [], [] - eigenvectors = [] - data_lists = (frequencies, ir_intensities, raman_intensities) - with open(file_name, 'rU') as f_handle: - self._parse_phonon_file_header(f_handle) - - while True: - line = f_handle.readline() - #check we've reached the end of file - if not line: break - - #check if we've found a block of frequencies - header_match = header_regex.match(line) - if header_match: - block_count += 1 - - weight = self._parse_block_header(header_match, block_count) - weights.append(weight) - - #parse block of frequencies - for line_data in self._parse_phonon_freq_block(f_handle): - for data_list, item in zip(data_lists, line_data): - data_list.append(item) - - vector_match = eigenvectors_regex.match(line) - if vector_match: - if self._calc_partial: - #parse eigenvectors for partial dos - vectors = self._parse_phonon_eigenvectors(f_handle) - eigenvectors.append(vectors) - else: - #skip over eigenvectors - for _ in xrange(self._num_ions*self._num_branches): - line = f_handle.readline() - if not line: - raise IOError("Bad file format. Uexpectedly reached end of file.") - - frequencies = np.asarray(frequencies) - ir_intensities = np.asarray(ir_intensities) - eigenvectors = np.asarray(eigenvectors) - raman_intensities = np.asarray(raman_intensities) - warray = np.repeat(weights, self._num_branches) - - return frequencies, ir_intensities, raman_intensities, warray, eigenvectors + def _parse_phonon_file(self, file_name): + """ + Read frequencies from a <>.phonon file + + @param file_name - file path of the file to read + @return the frequencies, infra red and raman intensities and weights of frequency blocks + """ + #Header regex. Looks for lines in the following format: + # q-pt= 1 0.000000 0.000000 0.000000 1.0000000000 0.000000 0.000000 1.000000 + header_regex_str = r"^ +q-pt=\s+\d+ +(%(s)s) +(%(s)s) +(%(s)s) (?: *(%(s)s)){0,4}" % {'s': self._float_regex} + header_regex = re.compile(header_regex_str) + + eigenvectors_regex = re.compile(r"\s*Mode\s+Ion\s+X\s+Y\s+Z\s*") + block_count = 0 + + frequencies, ir_intensities, raman_intensities, weights = [], [], [], [] + eigenvectors = [] + data_lists = (frequencies, ir_intensities, raman_intensities) + with open(file_name, 'rU') as f_handle: + self._parse_phonon_file_header(f_handle) + + while True: + line = f_handle.readline() + #check we've reached the end of file + if not line: break + + #check if we've found a block of frequencies + header_match = header_regex.match(line) + if header_match: + block_count += 1 + + weight = self._parse_block_header(header_match, block_count) + weights.append(weight) + + #parse block of frequencies + for line_data in self._parse_phonon_freq_block(f_handle): + for data_list, item in zip(data_lists, line_data): + data_list.append(item) + + vector_match = eigenvectors_regex.match(line) + if vector_match: + if self._calc_partial: + #parse eigenvectors for partial dos + vectors = self._parse_phonon_eigenvectors(f_handle) + eigenvectors.append(vectors) + else: + #skip over eigenvectors + for _ in xrange(self._num_ions*self._num_branches): + line = f_handle.readline() + if not line: + raise IOError("Bad file format. Uexpectedly reached end of file.") + + frequencies = np.asarray(frequencies) + ir_intensities = np.asarray(ir_intensities) + eigenvectors = np.asarray(eigenvectors) + raman_intensities = np.asarray(raman_intensities) + warray = np.repeat(weights, self._num_branches) + + return frequencies, ir_intensities, raman_intensities, warray, eigenvectors #---------------------------------------------------------------------------------------- - def _parse_castep_file_header(self, f_handle): - """ - Read information from the header of a <>.castep file + def _parse_castep_file_header(self, f_handle): + """ + Read information from the header of a <>.castep file - @param f_handle - handle to the file. - @return tuple of the number of ions and branches in the file - """ - num_species, self._num_ions = 0,0 - while True: - line = f_handle.readline() + @param f_handle - handle to the file. + @return tuple of the number of ions and branches in the file + """ + num_species, self._num_ions = 0,0 + while True: + line = f_handle.readline() - if not line: - raise IOError("Could not find any header information.") + if not line: + raise IOError("Could not find any header information.") - if 'Total number of ions in cell =' in line: - self._num_ions = int(line.strip().split()[-1]) - elif 'Total number of species in cell = ' in line: - num_species = int(line.strip().split()[-1]) + if 'Total number of ions in cell =' in line: + self._num_ions = int(line.strip().split()[-1]) + elif 'Total number of species in cell = ' in line: + num_species = int(line.strip().split()[-1]) - if num_species > 0 and self._num_ions > 0: - self._num_branches = num_species*self._num_ions - return + if num_species > 0 and self._num_ions > 0: + self._num_branches = num_species*self._num_ions + return #---------------------------------------------------------------------------------------- - def _parse_castep_freq_block(self, f_handle): - """ - Iterator to parse a block of frequencies from a .castep file. - - @param f_handle - handle to the file. - """ - prog_reporter = Progress(self,0.0,1.0,1) - for _ in xrange(self._num_branches): - line = f_handle.readline() - line_data = line.strip().split()[1:-1] - freq = line_data[1] - intensity_data = line_data[3:] - - #remove non-active intensities from data - intensities = [] - for value, active in zip(intensity_data[::2], intensity_data[1::2]): - if self._spec_type == 'IR_Active' or self._spec_type == 'Raman_Active': - if active == 'N' and value != 0: - value = 0.0 - intensities.append(value) - - line_data = [freq] + intensities - line_data = map(float, line_data) - yield line_data - - prog_reporter.report("Reading frequencies.") + def _parse_castep_freq_block(self, f_handle): + """ + Iterator to parse a block of frequencies from a .castep file. + + @param f_handle - handle to the file. + """ + prog_reporter = Progress(self,0.0,1.0,1) + for _ in xrange(self._num_branches): + line = f_handle.readline() + line_data = line.strip().split()[1:-1] + freq = line_data[1] + intensity_data = line_data[3:] + + #remove non-active intensities from data + intensities = [] + for value, active in zip(intensity_data[::2], intensity_data[1::2]): + if self._spec_type == 'IR_Active' or self._spec_type == 'Raman_Active': + if active == 'N' and value != 0: + value = 0.0 + intensities.append(value) + + line_data = [freq] + intensities + line_data = map(float, line_data) + yield line_data + + prog_reporter.report("Reading frequencies.") #---------------------------------------------------------------------------------------- - def _find_castep_freq_block(self, f_handle, data_regex): - """ - Find the start of the frequency block in a .castep file. - This will set the file pointer to the line before the start - of the block. - - @param f_handle - handle to the file. - """ - while True: - pos = f_handle.tell() - line = f_handle.readline() - - if not line: - raise IOError("Could not parse frequency block. Invalid file format.") - - if data_regex.match(line): - f_handle.seek(pos) - return + def _find_castep_freq_block(self, f_handle, data_regex): + """ + Find the start of the frequency block in a .castep file. + This will set the file pointer to the line before the start + of the block. + + @param f_handle - handle to the file. + """ + while True: + pos = f_handle.tell() + line = f_handle.readline() + + if not line: + raise IOError("Could not parse frequency block. Invalid file format.") + + if data_regex.match(line): + f_handle.seek(pos) + return #---------------------------------------------------------------------------------------- - def _parse_castep_file(self, file_name): - """ - Read frequencies from a <>.castep file - - @param file_name - file path of the file to read - @return the frequencies, infra red and raman intensities and weights of frequency blocks - """ - #Header regex. Looks for lines in the following format: - # + q-pt= 1 ( 0.000000 0.000000 0.000000) 1.0000000000 + - header_regex_str = r" +\+ +q-pt= +\d+ \( *(?: *(%(s)s)) *(%(s)s) *(%(s)s)\) +(%(s)s) +\+" % {'s' : self._float_regex} - header_regex = re.compile(header_regex_str) - - #Data regex. Looks for lines in the following format: - # + 1 -0.051481 a 0.0000000 N 0.0000000 N + - data_regex_str = r" +\+ +\d+ +(%(s)s)(?: +\w)? *(%(s)s)? *([YN])? *(%(s)s)? *([YN])? *\+"% {'s': self._float_regex} - data_regex = re.compile(data_regex_str) - - block_count = 0 - frequencies, ir_intensities, raman_intensities, weights = [], [], [], [] - data_lists = (frequencies, ir_intensities, raman_intensities) - with open(file_name, 'rU') as f_handle: - self._parse_castep_file_header(f_handle) - - while True: - line = f_handle.readline() - #check we've reached the end of file - if not line: break - - #check if we've found a block of frequencies - header_match = header_regex.match(line) - if header_match: - block_count += 1 - weight = self._parse_block_header(header_match, block_count) - weights.append(weight) - - #move file pointer forward to start of intensity data - self._find_castep_freq_block(f_handle, data_regex) - - #parse block of frequencies - for line_data in self._parse_castep_freq_block(f_handle): - for data_list, item in zip(data_lists, line_data): - data_list.append(item) - - frequencies = np.asarray(frequencies) - ir_intensities = np.asarray(ir_intensities) - raman_intensities = np.asarray(raman_intensities) - warray = np.repeat(weights, self._num_branches) - - return frequencies, ir_intensities, raman_intensities, warray + def _parse_castep_file(self, file_name): + """ + Read frequencies from a <>.castep file + + @param file_name - file path of the file to read + @return the frequencies, infra red and raman intensities and weights of frequency blocks + """ + #Header regex. Looks for lines in the following format: + # + q-pt= 1 ( 0.000000 0.000000 0.000000) 1.0000000000 + + header_regex_str = r" +\+ +q-pt= +\d+ \( *(?: *(%(s)s)) *(%(s)s) *(%(s)s)\) +(%(s)s) +\+" % {'s' : self._float_regex} + header_regex = re.compile(header_regex_str) + + #Data regex. Looks for lines in the following format: + # + 1 -0.051481 a 0.0000000 N 0.0000000 N + + data_regex_str = r" +\+ +\d+ +(%(s)s)(?: +\w)? *(%(s)s)? *([YN])? *(%(s)s)? *([YN])? *\+"% {'s': self._float_regex} + data_regex = re.compile(data_regex_str) + + block_count = 0 + frequencies, ir_intensities, raman_intensities, weights = [], [], [], [] + data_lists = (frequencies, ir_intensities, raman_intensities) + with open(file_name, 'rU') as f_handle: + self._parse_castep_file_header(f_handle) + + while True: + line = f_handle.readline() + #check we've reached the end of file + if not line: break + + #check if we've found a block of frequencies + header_match = header_regex.match(line) + if header_match: + block_count += 1 + weight = self._parse_block_header(header_match, block_count) + weights.append(weight) + + #move file pointer forward to start of intensity data + self._find_castep_freq_block(f_handle, data_regex) + + #parse block of frequencies + for line_data in self._parse_castep_freq_block(f_handle): + for data_list, item in zip(data_lists, line_data): + data_list.append(item) + + frequencies = np.asarray(frequencies) + ir_intensities = np.asarray(ir_intensities) + raman_intensities = np.asarray(raman_intensities) + warray = np.repeat(weights, self._num_branches) + + return frequencies, ir_intensities, raman_intensities, warray # Register algorithm with Mantid AlgorithmFactory.subscribe(DensityOfStates) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py index ad4c2ba65a16..4d22ae839387 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSAzimuthalAverage1D.py @@ -4,10 +4,10 @@ import math class EQSANSAzimuthalAverage1D(PythonAlgorithm): - + def category(self): return 'Workflow\\SANS\\UsesPropertyManager' - + def name(self): return 'EQSANSAzimuthalAverage1D' @@ -15,41 +15,41 @@ def summary(self): return "Compute I(q) for reduced EQSANS data" def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty('InputWorkspace', '', + self.declareProperty(MatrixWorkspaceProperty('InputWorkspace', '', direction = Direction.Input)) - self.declareProperty('NumberOfBins', 100, - validator = IntBoundedValidator(lower = 1), + self.declareProperty('NumberOfBins', 100, + validator = IntBoundedValidator(lower = 1), doc = 'Number of Q bins to use if binning is not supplied') - self.declareProperty('LogBinning', False, + self.declareProperty('LogBinning', False, doc = "Produce log binning in Q when true and binning wasn't supplied") - self.declareProperty('IndependentBinning', True, + self.declareProperty('IndependentBinning', True, doc = 'If true and frame skipping is used, each frame will have its own binning') - self.declareProperty('ScaleResults', True, + self.declareProperty('ScaleResults', True, doc = 'If true and frame skipping is used, frame 1 will be scaled to frame 2') - self.declareProperty('ComputeResolution', True, + self.declareProperty('ComputeResolution', True, doc = 'If true the Q resolution will be computed') - self.declareProperty('SampleApertureDiameter', 10.0, + self.declareProperty('SampleApertureDiameter', 10.0, doc = 'Sample aperture diameter [mm]') - self.declareProperty('ReductionProperties', '__sans_reduction_properties', + self.declareProperty('ReductionProperties', '__sans_reduction_properties', validator = StringMandatoryValidator(), doc = 'Property manager name for the reduction') - self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '', - direction = Direction.Output), + self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '', + direction = Direction.Output), doc = 'I(q) workspace') - self.declareProperty('OutputMessage', '', direction = Direction.Output, + self.declareProperty('OutputMessage', '', direction = Direction.Output, doc = 'Output message') - + def PyExec(self): input_ws_name = self.getPropertyValue('InputWorkspace') workspace = self.getProperty('InputWorkspace').value if not AnalysisDataService.doesExist(input_ws_name): Logger('EQSANSSANSAzimuthalAverage').error('Could not find input workspace') - + # Get the source aperture from the run logs source_aperture_radius = 10.0 if workspace.getRun().hasProperty('source-aperture-diameter'): source_aperture_radius = workspace.getRun().getProperty('source-aperture-diameter').value / 2.0 - + # Perform azimuthal averaging according to whether or not # we are in frame-skipping mode if workspace.getRun().hasProperty('is_frame_skipping') \ @@ -57,7 +57,7 @@ def PyExec(self): self._no_frame_skipping(source_aperture_radius) else: self._with_frame_skipping(source_aperture_radius) - + def _no_frame_skipping(self, source_aperture_radius): """ Perform azimuthal averaging assuming no frame-skipping @@ -73,9 +73,9 @@ def _no_frame_skipping(self, source_aperture_radius): pixel_size_x = workspace.getInstrument().getNumberParameter('x-pixel-size')[0] pixel_size_y = workspace.getInstrument().getNumberParameter('y-pixel-size')[0] (output_msg, output_ws, output_binning) = \ - self._call_sans_averaging(workspace, None, - nbins, log_binning, - property_manager_name, + self._call_sans_averaging(workspace, None, + nbins, log_binning, + property_manager_name, output_ws_name) if compute_resolution: sample_aperture_radius = self.getProperty('SampleApertureDiameter').value / 2.0 @@ -89,15 +89,15 @@ def _no_frame_skipping(self, source_aperture_radius): alg.setProperty("PixelSizeY", pixel_size_y) alg.setProperty("SourceApertureRadius", source_aperture_radius) alg.setProperty("SampleApertureRadius", sample_aperture_radius) - alg.execute() - output_msg += "Resolution computed\n" - + alg.execute() + output_msg += "Resolution computed\n" + if output_msg is not None: self.setProperty('OutputMessage', output_msg) - + self.setProperty('OutputWorkspace', output_ws) - - def _call_sans_averaging(self, workspace, binning, nbins, log_binning, + + def _call_sans_averaging(self, workspace, binning, nbins, log_binning, property_manager_name, output_workspace): """ Call the generic azimuthal averaging for SANS @@ -114,7 +114,7 @@ def _call_sans_averaging(self, workspace, binning, nbins, log_binning, alg.setProperty('InputWorkspace', workspace) if binning is not None: alg.setProperty('Binning', binning) - + alg.setProperty('NumberOfBins', nbins) alg.setProperty('LogBinning', log_binning) alg.setProperty('ComputeResolution', False) @@ -126,12 +126,12 @@ def _call_sans_averaging(self, workspace, binning, nbins, log_binning, else: output_msg = None output_ws = alg.getProperty('OutputWorkspace').value - + # Get output binning output_binning = alg.getPropertyValue("Binning") return (output_msg, output_ws, output_binning) - + def _with_frame_skipping(self, source_aperture_radius): """ Perform azimuthal averaging assuming frame-skipping @@ -143,7 +143,7 @@ def _with_frame_skipping(self, source_aperture_radius): output_ws_name = self.getPropertyValue('OutputWorkspace') ws_frame1 = output_ws_name.replace('_Iq', '_frame1_Iq') ws_frame2 = output_ws_name.replace('_Iq', '_frame2_Iq') - + # Get wavelength bands # First frame wl_min_f1 = None @@ -154,7 +154,7 @@ def _with_frame_skipping(self, source_aperture_radius): wl_max_f1 = workspace.getRun().getProperty("wavelength_max").value if wl_min_f1 is None and wl_max_f1 is None: raise RuntimeError, "Could not get the wavelength band for frame 1" - + # Second frame wl_min_f2 = None wl_max_f2 = None @@ -169,29 +169,29 @@ def _with_frame_skipping(self, source_aperture_radius): if independent_binning: binning = None else: - (qmin, qstep, qmax) = self._get_binning(workspace, - min(wl_min_f1, wl_min_f2), + (qmin, qstep, qmax) = self._get_binning(workspace, + min(wl_min_f1, wl_min_f2), max(wl_max_f1, wl_max_f2)) binning = '%g, %g, %g' % (qmin, qstep, qmax) - + # Average second frame - output_frame2 = self._process_frame(workspace, wl_min_f2, wl_max_f2, + output_frame2 = self._process_frame(workspace, wl_min_f2, wl_max_f2, source_aperture_radius, '2', binning) - + # Average first frame if independent_binning: binning = None - - output_frame1 = self._process_frame(workspace, wl_min_f1, wl_max_f1, + + output_frame1 = self._process_frame(workspace, wl_min_f1, wl_max_f1, source_aperture_radius, '1', binning) - + if scale_results: - output_frame1 = self._scale(output_frame1, output_frame2) - + output_frame1 = self._scale(output_frame1, output_frame2) + self.setPropertyValue('OutputWorkspace', ws_frame1) self.setProperty('OutputWorkspace', output_frame1) - - self.declareProperty(MatrixWorkspaceProperty('OutputFrame2', ws_frame2, + + self.declareProperty(MatrixWorkspaceProperty('OutputFrame2', ws_frame2, direction = Direction.Output)) self.setProperty('OutputFrame2', output_frame2) @@ -206,7 +206,7 @@ def _process_frame(self, workspace, wl_min, wl_max, source_aperture_radius, @param wl_max: maximum wavelength @param source_aperture_radius: radius of the source aperture [mm] @param frame_ID: frame ID string, '1' or '2' - @param binning: binning parameters, or None for automated determination + @param binning: binning parameters, or None for automated determination """ log_binning = self.getProperty('LogBinning').value nbins = self.getProperty('NumberOfBins').value @@ -215,9 +215,9 @@ def _process_frame(self, workspace, wl_min, wl_max, source_aperture_radius, pixel_size_y = workspace.getInstrument().getNumberParameter('y-pixel-size')[0] output_ws_name = self.getPropertyValue('OutputWorkspace') compute_resolution = self.getProperty('ComputeResolution').value - + ws_frame = output_ws_name.replace('_Iq', '_frame'+frame_ID+'_Iq') - + # Rebin the data to cover the frame we are interested in alg = AlgorithmManager.create("Rebin") alg.initialize() @@ -243,9 +243,9 @@ def _process_frame(self, workspace, wl_min, wl_max, source_aperture_radius, output_ws = alg.getProperty("OutputWorkspace").value (output_msg, output_iq, output_binning) = \ - self._call_sans_averaging(output_ws, binning, - nbins, log_binning, - property_manager_name, + self._call_sans_averaging(output_ws, binning, + nbins, log_binning, + property_manager_name, ws_frame) if compute_resolution: sample_aperture_radius = self.getProperty('SampleApertureDiameter').value / 2.0 @@ -262,9 +262,9 @@ def _process_frame(self, workspace, wl_min, wl_max, source_aperture_radius, alg.setProperty("SourceApertureRadius", source_aperture_radius) alg.setProperty("SampleApertureRadius", sample_aperture_radius) alg.execute() - + return output_iq - + def _scale(self, ws_frame1, ws_frame2): """ Scale frame 1 to overlap frame 2 @@ -286,7 +286,7 @@ def _scale(self, ws_frame1, ws_frame2): continue if qmin is None or q_f1[i] < qmin: qmin = q_f1[i] - + if qmax is None or q_f1[i] > qmax: qmax = q_f1[i] continue @@ -298,7 +298,7 @@ def _scale(self, ws_frame1, ws_frame2): continue if qmin2 is None or q_f2[i] < qmin2: qmin2 = q_f2[i] - + if qmax2 is None or q_f2[i] > qmax2: qmax2 = q_f2[i] continue @@ -314,14 +314,14 @@ def _scale(self, ws_frame1, ws_frame2): continue if scale_f1 > 0 and scale_f2 > 0: scale_factor = scale_f2 / scale_f1 - + output_ws_name = self.getPropertyValue('OutputWorkspace') ws_frame1_name = output_ws_name.replace('_Iq', '_frame1_Iq') # Dq is not propagated by scale, so do it by hand # First, store Dq dq = ws_frame1.readDx(0) - + alg = AlgorithmManager.create("Scale") alg.initialize() alg.setChild(True) @@ -331,7 +331,7 @@ def _scale(self, ws_frame1, ws_frame2): alg.setProperty("Operation", 'Multiply') alg.execute() output_ws = alg.getProperty("OutputWorkspace").value - + # ... then put Dq back dq_output = output_ws.dataDx(0) for i in range(len(dq_output)): @@ -344,8 +344,8 @@ def _get_binning(self, workspace, wavelength_min, wavelength_max): Determine the I(Q) binning @param workspace: reduced workspace object @param wavelength_min: lower wavelength cut - @param wavelength_max: upper wavelength cut - """ + @param wavelength_max: upper wavelength cut + """ log_binning = self.getProperty("LogBinning").value nbins = self.getProperty("NumberOfBins").value sample_detector_distance = workspace.getRun().getProperty("sample_detector_distance").value @@ -366,7 +366,7 @@ def _get_binning(self, workspace, wavelength_min, wavelength_max): beam_ctr_x = property_manager.getProperty("LatestBeamCenterX").value beam_ctr_y = property_manager.getProperty("LatestBeamCenterY").value else: - raise RuntimeError, "No beam center information can be found on the data set" + raise RuntimeError, "No beam center information can be found on the data set" # Q min is one pixel from the center, unless we have the beam trap size if workspace.getRun().hasProperty("beam-trap-diameter"): @@ -374,12 +374,12 @@ def _get_binning(self, workspace, wavelength_min, wavelength_max): else: mindist = min(pixel_size_x, pixel_size_y) qmin = 4*math.pi/wavelength_max*math.sin(0.5*math.atan(mindist/sample_detector_distance)) - + dxmax = pixel_size_x*max(beam_ctr_x,nx_pixels-beam_ctr_x) dymax = pixel_size_y*max(beam_ctr_y,ny_pixels-beam_ctr_y) maxdist = math.sqrt(dxmax*dxmax+dymax*dymax) qmax = 4*math.pi/wavelength_min*math.sin(0.5*math.atan(maxdist/sample_detector_distance)) - + if not log_binning: qstep = (qmax-qmin)/nbins f_step = (qmax-qmin)/qstep @@ -395,5 +395,5 @@ def _get_binning(self, workspace, wavelength_min, wavelength_max): if f_step-n_step>10e-10: qmax = math.pow(10.0, math.log10(qmin)+qstep*n_step) return qmin, -(math.pow(10.0,qstep)-1.0), qmax - + AlgorithmFactory.subscribe(EQSANSAzimuthalAverage1D) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py index c04853931545..1f2648223ff7 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py @@ -4,10 +4,10 @@ import os class EQSANSDirectBeamTransmission(PythonAlgorithm): - + def category(self): return 'Workflow\\SANS\\UsesPropertyManager' - + def name(self): return 'EQSANSDirectBeamTransmission' @@ -15,7 +15,7 @@ def summary(self): return "Compute the transmission using the direct beam method on EQSANS" def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", direction=Direction.Input)) self.declareProperty(FileProperty("SampleDataFilename", "", action=FileAction.Load, @@ -24,37 +24,37 @@ def PyInit(self): action=FileAction.Load, extensions=['xml', 'nxs', 'nxs.h5'])) self.declareProperty("BeamRadius", 3.0, "Beam radius [pixels]") - self.declareProperty("ThetaDependent", True, + self.declareProperty("ThetaDependent", True, "If true, a theta-dependent correction will be applied") self.declareProperty(FileProperty("DarkCurrentFilename", "", action=FileAction.OptionalLoad, extensions=['xml', 'nxs', 'nxs.h5'])) - self.declareProperty("UseSampleDarkCurrent", True, + self.declareProperty("UseSampleDarkCurrent", True, "If true, the sample dark current will be used") self.declareProperty("BeamCenterX", 0.0, "Beam center position in X") self.declareProperty("BeamCenterY", 0.0, "Beam center position in Y") self.declareProperty("FitFramesTogether", False, "If true, the two frames will be fit together") - self.declareProperty("ReductionProperties", "__sans_reduction_properties", + self.declareProperty("ReductionProperties", "__sans_reduction_properties", validator=StringMandatoryValidator(), doc="Property manager name for the reduction") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output), "Workspace containing the data corrected for the transmission.") - self.declareProperty(MatrixWorkspaceProperty("TransmissionWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("TransmissionWorkspace", "", optional = PropertyMode.Optional, direction = Direction.Output), "Workspace containing the fitted transmission distribution.") - self.declareProperty(MatrixWorkspaceProperty("RawTransmissionWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("RawTransmissionWorkspace", "", optional = PropertyMode.Optional, direction = Direction.Output), "Workspace containing the transmission distribution before fitting.") - self.declareProperty("OutputMessage", "", + self.declareProperty("OutputMessage", "", direction=Direction.Output, doc = "Output message") - + def PyExec(self): workspace = self.getProperty('InputWorkspace').value - + # Perform transmission correction according to whether or not # we are in frame-skipping mode if self.getProperty('FitFramesTogether').value or \ @@ -71,13 +71,13 @@ def PyExec(self): if raw_ws is not None: self.setPropertyValue("RawTransmissionWorkspace", raw_name) self.setProperty("RawTransmissionWorkspace", raw_ws) - + # Save the transmission to disk self._save_transmission(trans_ws, raw_ws) else: ws = self._with_frame_skipping(workspace) self.setProperty("OutputWorkspace", ws) - + def _call_sans_transmission(self, workspace, output_workspace_name): """ Call the generic transmission correction for SANS @@ -120,7 +120,7 @@ def _call_sans_transmission(self, workspace, output_workspace_name): else: trans_ws = None trans_name = '' - + if alg.existsProperty('RawTransmissionWorkspace'): raw_ws = alg.getProperty('RawTransmissionWorkspace').value raw_name = alg.getPropertyValue('RawTransmissionWorkspace') @@ -128,7 +128,7 @@ def _call_sans_transmission(self, workspace, output_workspace_name): raw_ws = None raw_name = '' return (output_msg, output_ws, trans_ws, trans_name, raw_ws, raw_name) - + def _with_frame_skipping(self, workspace): """ Perform transmission correction assuming frame-skipping @@ -137,17 +137,17 @@ def _with_frame_skipping(self, workspace): input_ws_name = self.getPropertyValue('InputWorkspace') sample_file = self.getPropertyValue("SampleDataFilename") empty_file = self.getPropertyValue("EmptyDataFilename") - + property_manager_name = self.getProperty("ReductionProperties").value property_manager = PropertyManagerDataService.retrieve(property_manager_name) - + # Build the name we are going to give the transmission workspace sample_basename = os.path.basename(sample_file) empty_basename = os.path.basename(empty_file) entry_name = "Transmission%s%s" % (sample_basename, empty_basename) trans_ws_name = "__transmission_fit_%s" % sample_basename trans_ws = None - + if property_manager.existsProperty(entry_name): trans_ws_name = property_manager.getProperty(entry_name) if AnalysisDataService.doesExist(trans_ws_name): @@ -157,19 +157,19 @@ def _with_frame_skipping(self, workspace): trans_ws_name = "__transmission_fit_"+input_ws_name # Load data files sample_mon_ws, empty_mon_ws, first_det, output_str, monitor_det_ID = TransmissionUtils.load_monitors(self, property_manager) - + def _crop_and_compute(wl_min_prop, wl_max_prop, suffix): # Get the wavelength band from the run properties if workspace.getRun().hasProperty(wl_min_prop): wl_min = workspace.getRun().getProperty(wl_min_prop).value else: raise RuntimeError, "DirectBeamTransmission could not retrieve the %s property" % wl_min_prop - + if workspace.getRun().hasProperty(wl_max_prop): wl_max = workspace.getRun().getProperty(wl_max_prop).value else: raise RuntimeError, "DirectBeamTransmission could not retrieve the %s property" % wl_max_prop - + rebin_params = "%4.1f,%4.1f,%4.1f" % (wl_min, 0.1, wl_max) alg = TransmissionUtils.simple_algorithm("Rebin", {"InputWorkspace": sample_mon_ws, @@ -185,10 +185,10 @@ def _crop_and_compute(wl_min_prop, wl_max_prop, suffix): "PreserveEvents": False }) empty_ws = alg.getProperty("OutputWorkspace").value - trans_ws, raw_ws = TransmissionUtils.calculate_transmission(self, - sample_ws, - empty_ws, - first_det, + trans_ws, raw_ws = TransmissionUtils.calculate_transmission(self, + sample_ws, + empty_ws, + first_det, "__transmission_"+suffix) alg = TransmissionUtils.simple_algorithm("RebinToWorkspace", {"WorkspaceToRebin": trans_ws, @@ -196,23 +196,23 @@ def _crop_and_compute(wl_min_prop, wl_max_prop, suffix): "OutputWorkspace": "__transmission_"+suffix, "PreserveEvents": False }) - trans_ws = alg.getProperty("OutputWorkspace").value + trans_ws = alg.getProperty("OutputWorkspace").value alg = TransmissionUtils.simple_algorithm("RebinToWorkspace", {"WorkspaceToRebin": raw_ws, "WorkspaceToMatch": workspace, "OutputWorkspace": "__transmission_unfitted_"+suffix, "PreserveEvents": False }) - raw_ws = alg.getProperty("OutputWorkspace").value + raw_ws = alg.getProperty("OutputWorkspace").value return trans_ws, raw_ws - + # First frame trans_frame_1, raw_frame_1 = _crop_and_compute("wavelength_min", "wavelength_max", "_frame1") - + # Second frame trans_frame_2, raw_frame_2 = _crop_and_compute("wavelength_min_frame2", "wavelength_max_frame2", "_frame2") - + alg = TransmissionUtils.simple_algorithm("Plus", {"LHSWorkspace": trans_frame_1, "RHSWorkspace": trans_frame_2, @@ -231,10 +231,10 @@ def _crop_and_compute(wl_min_prop, wl_max_prop, suffix): raw_ws_name = "__transmission_raw_%s" % input_ws_name self.setPropertyValue("RawTransmissionWorkspace", raw_ws_name) self.setProperty("RawTransmissionWorkspace", raw_ws) - + # Save the transmission to disk self._save_transmission(trans_ws, raw_ws) - + # 2- Apply correction (Note: Apply2DTransCorr) #Apply angle-dependent transmission correction using the zero-angle transmission return TransmissionUtils.apply_transmission(self, workspace, trans_ws) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py index 0e4b7cdb8746..b9f863377703 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSNormalise.py @@ -7,7 +7,7 @@ class EQSANSNormalise(PythonAlgorithm): """ Normalise detector counts by accelerator current and beam spectrum. """ - + def category(self): return "Workflow\\SANS\\UsesPropertyManager" @@ -18,37 +18,37 @@ def summary(self): return "Normalise detector counts by accelerator current and beam spectrum" def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", direction=Direction.Input)) - self.declareProperty("NormaliseToBeam", True, + self.declareProperty("NormaliseToBeam", True, "If true, the data will also be normalise by the beam profile") self.declareProperty(FileProperty("BeamSpectrumFile", "", action=FileAction.OptionalLoad), "Beam spectrum to be used for normalisation [takes precedence over default]") self.declareProperty("NormaliseToMonitor", False, "If true, the algorithm will look for a monitor workspace to use") - self.declareProperty("ReductionProperties", "__sans_reduction_properties", + self.declareProperty("ReductionProperties", "__sans_reduction_properties", validator=StringMandatoryValidator(), doc="Property manager name for the reduction") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction=Direction.Output)) - self.declareProperty("OutputMessage", "", + self.declareProperty("OutputMessage", "", direction=Direction.Output, doc = "Output message") def PyExec(self): # If we need to normalise by monitor, skip all other options if self.getProperty("NormaliseToMonitor").value: return self._normalise_to_monitor() - + workspace = self.getProperty("InputWorkspace").value - output_ws_name = self.getPropertyValue("OutputWorkspace") + output_ws_name = self.getPropertyValue("OutputWorkspace") flux_data_path = None - + if self.getProperty("NormaliseToBeam").value: # If a spectrum file was supplied, check if it's a valid file path beam_spectrum_file = self.getPropertyValue("BeamSpectrumFile").strip() if len(beam_spectrum_file): if os.path.isfile(beam_spectrum_file): - flux_data_path = beam_spectrum_file + flux_data_path = beam_spectrum_file else: Logger("EQSANSNormalise").error("%s is not a file" % beam_spectrum_file) else: @@ -58,7 +58,7 @@ def PyExec(self): Logger("EQSANSNormalise").notice("Using beam flux file: %s" % flux_data_path) else: Logger("EQSANSNormalise").notice("Could not find beam flux file!") - + if flux_data_path is not None: beam_flux_ws_name = "__beam_flux" alg = AlgorithmManager.create("LoadAscii") @@ -108,7 +108,7 @@ def PyExec(self): workspace.getRun().addProperty("beam_flux_ws", beam_flux_ws_name, True) else: flux_data_path = "Could not find beam flux file!" - + alg = AlgorithmManager.create("NormaliseByCurrent") alg.initialize() alg.setChild(True) @@ -117,7 +117,7 @@ def PyExec(self): alg.execute() workspace = alg.getProperty("OutputWorkspace").value workspace_name = alg.getPropertyValue("OutputWorkspace") - self.setProperty("OutputMessage", "Data [%s] normalized to accelerator current\n Beam flux file: %s" % (workspace_name, str(flux_data_path))) + self.setProperty("OutputMessage", "Data [%s] normalized to accelerator current\n Beam flux file: %s" % (workspace_name, str(flux_data_path))) self.setProperty("OutputWorkspace", workspace) def _normalise_to_monitor(self): @@ -128,10 +128,10 @@ def _normalise_to_monitor(self): output_ws_name = self.getPropertyValue("OutputWorkspace") prop_mng = self.getPropertyValue("ReductionProperties") reference_flux = self.getPropertyValue("BeamSpectrumFile").strip() - + monitor_ws_name = input_ws_name+'_monitors' if AnalysisDataService.doesExist(monitor_ws_name): - + alg = AlgorithmManager.create("EQSANSMonitorTOF") alg.initialize() alg.setChild(True) @@ -139,7 +139,7 @@ def _normalise_to_monitor(self): alg.setProperty("OutputWorkspace", monitor_ws_name+'_tof') alg.execute() monitor_ws = alg.getProperty("OutputWorkspace").value - + alg = AlgorithmManager.create("ConvertUnits") alg.initialize() alg.setChild(True) @@ -148,7 +148,7 @@ def _normalise_to_monitor(self): alg.setProperty("Target", "Wavelength") alg.execute() monitor_ws = alg.getProperty("OutputWorkspace").value - + alg = AlgorithmManager.create("SANSBeamFluxCorrection") alg.initialize() alg.setChild(True) @@ -160,12 +160,12 @@ def _normalise_to_monitor(self): alg.execute() output_msg = alg.getPropertyValue("OutputMessage") output_ws = alg.getProperty("OutputWorkspace").value - + self.setProperty("OutputWorkspace", output_ws) - self.setProperty("OutputMessage", - "Data [%s] normalized to monitor\n %s" % (input_ws_name, output_msg)) + self.setProperty("OutputMessage", + "Data [%s] normalized to monitor\n %s" % (input_ws_name, output_msg)) else: - self.setProperty("OutputMessage", "Monitor not available. Data [%s] NOT normalized to monitor" % (input_ws_name)) + self.setProperty("OutputMessage", "Monitor not available. Data [%s] NOT normalized to monitor" % (input_ws_name)) ############################################################################################# AlgorithmFactory.subscribe(EQSANSNormalise) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py index e7c267cd12f4..94584c4e1363 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FuryFitMultiple.py @@ -5,7 +5,7 @@ import os.path class FuryFitMultiple(PythonAlgorithm): - + def category(self): return "Workflow\\MIDAS;PythonAlgorithms" @@ -21,11 +21,11 @@ def PyInit(self): doc='Analyser & reflection') self.declareProperty(name="RunNumber",defaultValue=-1, validator=IntBoundedValidator(lower=0), doc="Sample run number") - self.declareProperty(name="TimeMax", defaultValue=0.2, validator=FloatMandatoryValidator(), + self.declareProperty(name="TimeMax", defaultValue=0.2, validator=FloatMandatoryValidator(), doc="Multiplicative scale factor") self.declareProperty(name='Plot', defaultValue='None', validator=StringListValidator(['None', 'Intensity', 'Tau', 'Beta', 'All']), doc='Switch Plot Off/On') - + def PyExec(self): from IndirectDataAnalysis import furyfitMult diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py index 0a573cbbe891..d985f47fdcb4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py @@ -20,8 +20,8 @@ def PyInit(self): self.declareProperty('ReductionProperties', '__sans_reduction_properties', validator=StringMandatoryValidator(), doc='Property manager name for the reduction') self.declareProperty('OutputWorkspace', '', doc='Reduced workspace') self.declareProperty('OutputMessage', '', direction=Direction.Output, doc='Output message') - - def _multiple_load(self, data_file, workspace, + + def _multiple_load(self, data_file, workspace, property_manager, property_manager_name): # Check whether we have a list of files that need merging # Make sure we process a list of files written as a string @@ -39,7 +39,7 @@ def _load_data(filename, output_ws): if alg.existsProperty("OutputMessage"): msg = alg.getProperty("OutputMessage").value return msg - + # Get instrument to use with FileFinder instrument = '' if property_manager.existsProperty("InstrumentName"): @@ -50,7 +50,7 @@ def _load_data(filename, output_ws): data_file = find_data(data_file, instrument=instrument, allow_multiple=True) if type(data_file)==list: monitor = 0.0 - timer = 0.0 + timer = 0.0 for i in range(len(data_file)): if i==0: output_str += _load_data(data_file[i], workspace) @@ -67,19 +67,19 @@ def _load_data(filename, output_ws): ws = AnalysisDataService.retrieve('__tmp_wksp') monitor += ws.getRun().getProperty("monitor").value timer += ws.getRun().getProperty("timer").value - + # Get the monitor and timer of the first file, which haven't yet # been added to the total ws = AnalysisDataService.retrieve(workspace) monitor += ws.getRun().getProperty("monitor").value timer += ws.getRun().getProperty("timer").value - + # Update the timer and monitor ws.getRun().addProperty("monitor", monitor, True) ws.getRun().addProperty("timer", timer, True) - + if AnalysisDataService.doesExist('__tmp_wksp'): - AnalysisDataService.remove('__tmp_wksp') + AnalysisDataService.remove('__tmp_wksp') else: output_str += "Loaded %s\n" % data_file output_str += _load_data(data_file, workspace) @@ -87,19 +87,19 @@ def _load_data(filename, output_ws): if os.path.isdir(head): self.default_output_dir = head return output_str - + def PyExec(self): filename = self.getProperty("Filename").value output_ws = self.getPropertyValue("OutputWorkspace") #output_ws = '__'+output_ws+'_reduced' property_manager_name = self.getProperty("ReductionProperties").value property_manager = PropertyManagerDataService.retrieve(property_manager_name) - + property_list = [p.name for p in property_manager.getProperties()] - + # Keep track of best output directory guess in case it wasn't supplied self.default_output_dir = os.path.expanduser('~') - + output_msg = "" # Find the beam center if "SANSBeamFinderAlgorithm" in property_list: @@ -110,16 +110,16 @@ def PyExec(self): alg.execute() if alg.existsProperty("OutputMessage"): output_msg += alg.getProperty("OutputMessage").value+'\n' - + # Load the sample data - msg = self._multiple_load(filename, output_ws, + msg = self._multiple_load(filename, output_ws, property_manager, property_manager_name) output_msg += "Loaded %s\n" % filename output_msg += msg # Perform the main corrections on the sample data output_msg += self.process_data_file(output_ws) - + # Sample data transmission correction beam_center_x = None beam_center_y = None @@ -139,18 +139,18 @@ def PyExec(self): alg=Algorithm.fromString(p.valueAsStr) alg.setProperty("InputWorkspace", output_ws) alg.setProperty("OutputWorkspace", output_ws) - + if alg.existsProperty("BeamCenterX") \ and alg.existsProperty("BeamCenterY") \ and beam_center_x is not None \ and beam_center_y is not None: alg.setProperty("BeamCenterX", beam_center_x) - alg.setProperty("BeamCenterY", beam_center_y) - + alg.setProperty("BeamCenterY", beam_center_y) + if alg.existsProperty("ReductionProperties"): alg.setProperty("ReductionProperties", property_manager_name) alg.execute() - + if alg.existsProperty("MeasuredTransmission"): meas_trans = alg.getProperty("MeasuredTransmission").value if property_manager.existsProperty("MeasuredTransmissionValue"): @@ -158,27 +158,27 @@ def PyExec(self): else: property_manager.declareProperty("MeasuredTransmissionValue", meas_trans) if alg.existsProperty("MeasuredError"): - meas_err = alg.getProperty("MeasuredError").value + meas_err = alg.getProperty("MeasuredError").value if property_manager.existsProperty("MeasuredTransmissionError"): property_manager.setProperty("MeasuredTransmissionError", meas_err) - else: - property_manager.declareProperty("MeasuredTransmissionError", meas_err) - + else: + property_manager.declareProperty("MeasuredTransmissionError", meas_err) + if alg.existsProperty("OutputMessage"): output_msg += alg.getProperty("OutputMessage").value+'\n' - + # Process background data if "BackgroundFiles" in property_list: background = property_manager.getProperty("BackgroundFiles").value background_ws = "__background_%s" % output_ws - msg = self._multiple_load(background, background_ws, + msg = self._multiple_load(background, background_ws, property_manager, property_manager_name) bck_msg = "Loaded background %s\n" % background bck_msg += msg - + # Process background like we processed the sample data bck_msg += self.process_data_file(background_ws) - + trans_beam_center_x = None trans_beam_center_y = None if "BckTransmissionBeamCenterAlgorithm" in property_list: @@ -191,25 +191,25 @@ def PyExec(self): alg.execute() trans_beam_center_x = alg.getProperty("FoundBeamCenterX").value trans_beam_center_y = alg.getProperty("FoundBeamCenterY").value - + # Background transmission correction if "BckTransmissionAlgorithm" in property_list: p=property_manager.getProperty("BckTransmissionAlgorithm") alg=Algorithm.fromString(p.valueAsStr) alg.setProperty("InputWorkspace", background_ws) alg.setProperty("OutputWorkspace", '__'+background_ws+"_reduced") - + if alg.existsProperty("BeamCenterX") \ and alg.existsProperty("BeamCenterY") \ and trans_beam_center_x is not None \ and trans_beam_center_y is not None: alg.setProperty("BeamCenterX", trans_beam_center_x) alg.setProperty("BeamCenterY", trans_beam_center_y) - + if alg.existsProperty("ReductionProperties"): alg.setProperty("ReductionProperties", property_manager_name) alg.execute() - + if alg.existsProperty("MeasuredTransmission"): meas_trans = alg.getProperty("MeasuredTransmission").value if property_manager.existsProperty("MeasuredBckTransmissionValue"): @@ -217,16 +217,16 @@ def PyExec(self): else: property_manager.declareProperty("MeasuredBckTransmissionValue", meas_trans) if alg.existsProperty("MeasuredError"): - meas_err = alg.getProperty("MeasuredError").value + meas_err = alg.getProperty("MeasuredError").value if property_manager.existsProperty("MeasuredBckTransmissionError"): property_manager.setProperty("MeasuredBckTransmissionError", meas_err) - else: - property_manager.declareProperty("MeasuredBckTransmissionError", meas_err) - + else: + property_manager.declareProperty("MeasuredBckTransmissionError", meas_err) + if alg.existsProperty("OutputMessage"): output_msg += alg.getProperty("OutputMessage").value+'\n' background_ws = '__'+background_ws+'_reduced' - + # Subtract background api.RebinToWorkspace(WorkspaceToRebin=background_ws, WorkspaceToMatch=output_ws, @@ -235,16 +235,16 @@ def PyExec(self): api.Minus(LHSWorkspace=output_ws, RHSWorkspace=background_ws, OutputWorkspace=output_ws) - + bck_msg = bck_msg.replace('\n','\n |') output_msg += "Background subtracted [%s]%s\n" % (background_ws, bck_msg) - + # Absolute scale correction output_msg += self._simple_execution("AbsoluteScaleAlgorithm", output_ws) - + # Geometry correction output_msg += self._simple_execution("GeometryAlgorithm", output_ws) - + # Compute I(q) iq_output = None if "IQAlgorithm" in property_list: @@ -257,7 +257,7 @@ def PyExec(self): alg.setProperty("ReductionProperties", property_manager_name) alg.execute() if alg.existsProperty("OutputMessage"): - output_msg += alg.getProperty("OutputMessage").value+'\n' + output_msg += alg.getProperty("OutputMessage").value+'\n' # Compute I(qx,qy) iqxy_output = None @@ -272,23 +272,23 @@ def PyExec(self): alg.setProperty("ReductionProperties", property_manager_name) alg.execute() if alg.existsProperty("OutputMessage"): - output_msg += alg.getProperty("OutputMessage").value+'\n' - + output_msg += alg.getProperty("OutputMessage").value+'\n' + # Verify output directory and save data output_dir = '' if "OutputDirectory" in property_list: output_dir = property_manager.getProperty("OutputDirectory").value if len(output_dir)==0: output_dir = self.default_output_dir - + if os.path.isdir(output_dir): - output_msg += self._save_output(iq_output, iqxy_output, + output_msg += self._save_output(iq_output, iqxy_output, output_dir, property_manager) Logger("HFIRSANSReduction").notice("Output saved in %s" % output_dir) elif len(output_dir)>0: msg = "Output directory doesn't exist: %s\n" % output_dir Logger("HFIRSANSReduction").error(msg) - + self.setProperty("OutputMessage", output_msg) def process_data_file(self, workspace): @@ -302,13 +302,13 @@ def process_data_file(self, workspace): # Normalize output_msg += self._simple_execution("NormaliseAlgorithm", workspace) - + # Mask output_msg += self._simple_execution("MaskAlgorithm", workspace) - + # Solid angle correction output_msg += self._simple_execution("SANSSolidAngleCorrection", workspace) - + # Sensitivity correction if "SensitivityAlgorithm" in property_list: # Beam center for the sensitivity correction @@ -324,25 +324,25 @@ def process_data_file(self, workspace): alg.execute() beam_center_x = alg.getProperty("FoundBeamCenterX").value beam_center_y = alg.getProperty("FoundBeamCenterY").value - + p=property_manager.getProperty("SensitivityAlgorithm") alg=Algorithm.fromString(p.valueAsStr) alg.setProperty("InputWorkspace", workspace) alg.setProperty("OutputWorkspace", workspace) - + if alg.existsProperty("BeamCenterX") \ and alg.existsProperty("BeamCenterY") \ and beam_center_x is not None \ and beam_center_y is not None: alg.setProperty("BeamCenterX", beam_center_x) alg.setProperty("BeamCenterY", beam_center_y) - + if alg.existsProperty("ReductionProperties"): alg.setProperty("ReductionProperties", property_manager_name) alg.execute() if alg.existsProperty("OutputMessage"): output_msg += alg.getProperty("OutputMessage").value+'\n' - + # Store sensitivity beam center so that we can access it later if beam_center_x is not None and beam_center_y is not None: if property_manager.existsProperty("SensitivityBeamCenterXUsed"): @@ -355,18 +355,18 @@ def process_data_file(self, workspace): property_manager.declareProperty("SensitivityBeamCenterYUsed", beam_center_y) return output_msg - + def _simple_execution(self, algorithm_name, workspace, output_workspace=None): """ Simple execution of an algorithm on the given workspace """ property_manager_name = self.getProperty("ReductionProperties").value property_manager = PropertyManagerDataService.retrieve(property_manager_name) - + output_msg = "" if output_workspace is None: output_workspace = workspace - + if property_manager.existsProperty(algorithm_name): p=property_manager.getProperty(algorithm_name) alg=Algorithm.fromString(p.valueAsStr) @@ -382,11 +382,11 @@ def _simple_execution(self, algorithm_name, workspace, output_workspace=None): if alg.existsProperty("OutputMessage"): output_msg = alg.getProperty("OutputMessage").value+'\n' return output_msg - + def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): """ Save the I(Q) and I(QxQy) output to file. - + @param iq_output: name of the I(Q) workspace @param iqxy_output: name of the I(QxQy) workspace @param output_dir: output director path @@ -415,7 +415,7 @@ def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): proc_xml += "\n" filename = os.path.join(output_dir, iq_output+'.txt') - + alg = AlgorithmManager.create("SaveAscii") alg.initialize() alg.setChild(True) @@ -426,7 +426,7 @@ def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): alg.setProperty("WriteXError", True) alg.setProperty("WriteSpectrumID", False) alg.execute() - + filename = os.path.join(output_dir, iq_output+'.xml') alg = AlgorithmManager.create("SaveCanSAS1D") alg.initialize() @@ -439,7 +439,7 @@ def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): output_msg += "I(Q) saved in %s\n" % (filename) else: Logger("HFIRSANSReduction").error("No I(Q) output found") - + # Save I(Qx,Qy) if iqxy_output is not None: if AnalysisDataService.doesExist(iqxy_output): @@ -450,7 +450,7 @@ def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): alg.setProperty("Filename", filename) alg.setProperty("InputWorkspace", iqxy_output) alg.execute() - #api.SaveNISTDAT(InputWorkspace=iqxy_output, Filename=filename) + #api.SaveNISTDAT(InputWorkspace=iqxy_output, Filename=filename) output_msg += "I(Qx,Qy) saved in %s\n" % (filename) else: Logger("HFIRSANSReduction").error("No I(Qx,Qy) output found") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py index f1657980e43a..6fa0d2761163 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectILLReduction.py @@ -98,7 +98,7 @@ def PyExec(self): from IndirectImport import import_mantidplot mp = import_mantidplot() graph = mp.newGraph() - + for ws in output_workspaces: mp.plotSpectrum(ws, 0, window=graph) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmission.py index f4449d8b8c6b..fb1b21690639 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectTransmission.py @@ -5,92 +5,92 @@ import os.path, math class IndirectTransmission(PythonAlgorithm): - - def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" - - def summary(self): - return "Calculates the scattering & transmission for Indirect Geometry spectrometers." - - def PyInit(self): - self.declareProperty(name='Instrument',defaultValue='IRIS',validator=StringListValidator(['IRIS','OSIRIS']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite',validator=StringListValidator(['graphite','fmica']), doc='Analyser') - self.declareProperty(name='Reflection',defaultValue='002',validator=StringListValidator(['002','004']), doc='Reflection') - self.declareProperty(name='ChemicalFormula',defaultValue='',validator=StringMandatoryValidator(), doc='Sample chemical formula') - self.declareProperty(name='NumberDensity', defaultValue=0.1, doc='Number denisty. Default=0.1') - self.declareProperty(name='Thickness', defaultValue=0.1, doc='Sample thickness. Default=0.1') - self.declareProperty(WorkspaceProperty('OutputWorkspace', "", Direction.Output), doc="The name of the output workspace.") - - def PyExec(self): - from IndirectCommon import StartTime, EndTime - - StartTime('IndirectTransmission') - - instrumentName = self.getPropertyValue('Instrument') - analyser = self.getPropertyValue('Analyser') - reflection = self.getPropertyValue('Reflection') - formula = self.getPropertyValue('ChemicalFormula') - density = self.getPropertyValue('NumberDensity') - thickness = self.getPropertyValue('Thickness') - - #Load instrument defintion file - idfDir = config['instrumentDefinition.directory'] - idf = idfDir + instrumentName + '_Definition.xml' - workspace = '__empty_'+instrumentName - LoadEmptyInstrument(OutputWorkspace=workspace, Filename=idf) - - #Load instrument parameter file - nameStem = instrumentName + '_' + analyser + '_' + reflection - ipf = idfDir + nameStem + '_Parameters.xml' - LoadParameterFile(Workspace=workspace, Filename=ipf) - - #Get efixed value - instrument = mtd[workspace].getInstrument() - efixed = instrument.getNumberParameter('efixed-val')[0] - - logger.notice('Analyser : ' +analyser+reflection +' with energy = ' + str(efixed)) - - result = SetSampleMaterial(InputWorkspace=workspace,ChemicalFormula=formula) - - #elastic wavelength - wave=1.8*math.sqrt(25.2429/efixed) - - absorptionXSection = result[5]*wave/1.7982 - coherentXSection = result[4] - incoherentXSection = result[3] - scatteringXSection = incoherentXSection+coherentXSection - - thickness = float(thickness) - density = float(density) - - totalXSection = absorptionXSection + scatteringXSection - - transmission = math.exp(-density*totalXSection*thickness) - scattering = 1.0 - math.exp(-density*scatteringXSection*thickness) - - #Create table workspace to store calculations - tableWs = self.getPropertyValue('OutputWorkspace') - tableWs = CreateEmptyTableWorkspace(OutputWorkspace=tableWs) - tableWs.addColumn("str", "Name") - tableWs.addColumn("double", "Value") - - # Names for each of the output values - outputNames = ['Wavelength', 'Absorption Xsection', 'Coherent Xsection', 'Incoherent Xsection', - 'Total scattering Xsection', 'Number density', 'Thickness', 'Transmission (abs+scatt)', 'Total scattering'] - - # List of the calculated values - outputValues = [wave, absorptionXSection, coherentXSection, incoherentXSection, - scatteringXSection, density, thickness, transmission, scattering] - - #build table of values - for data in zip (outputNames, outputValues): - tableWs.addRow(list(data)) - logger.information(': '.join(map(str,list(data)))) - - #remove idf/ipf workspace - DeleteWorkspace(workspace) - self.setProperty("OutputWorkspace", tableWs) - EndTime('IndirectTransmission') + + def category(self): + return "Workflow\\MIDAS;PythonAlgorithms" + + def summary(self): + return "Calculates the scattering & transmission for Indirect Geometry spectrometers." + + def PyInit(self): + self.declareProperty(name='Instrument',defaultValue='IRIS',validator=StringListValidator(['IRIS','OSIRIS']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite',validator=StringListValidator(['graphite','fmica']), doc='Analyser') + self.declareProperty(name='Reflection',defaultValue='002',validator=StringListValidator(['002','004']), doc='Reflection') + self.declareProperty(name='ChemicalFormula',defaultValue='',validator=StringMandatoryValidator(), doc='Sample chemical formula') + self.declareProperty(name='NumberDensity', defaultValue=0.1, doc='Number denisty. Default=0.1') + self.declareProperty(name='Thickness', defaultValue=0.1, doc='Sample thickness. Default=0.1') + self.declareProperty(WorkspaceProperty('OutputWorkspace', "", Direction.Output), doc="The name of the output workspace.") + + def PyExec(self): + from IndirectCommon import StartTime, EndTime + + StartTime('IndirectTransmission') + + instrumentName = self.getPropertyValue('Instrument') + analyser = self.getPropertyValue('Analyser') + reflection = self.getPropertyValue('Reflection') + formula = self.getPropertyValue('ChemicalFormula') + density = self.getPropertyValue('NumberDensity') + thickness = self.getPropertyValue('Thickness') + + #Load instrument defintion file + idfDir = config['instrumentDefinition.directory'] + idf = idfDir + instrumentName + '_Definition.xml' + workspace = '__empty_'+instrumentName + LoadEmptyInstrument(OutputWorkspace=workspace, Filename=idf) + + #Load instrument parameter file + nameStem = instrumentName + '_' + analyser + '_' + reflection + ipf = idfDir + nameStem + '_Parameters.xml' + LoadParameterFile(Workspace=workspace, Filename=ipf) + + #Get efixed value + instrument = mtd[workspace].getInstrument() + efixed = instrument.getNumberParameter('efixed-val')[0] + + logger.notice('Analyser : ' +analyser+reflection +' with energy = ' + str(efixed)) + + result = SetSampleMaterial(InputWorkspace=workspace,ChemicalFormula=formula) + + #elastic wavelength + wave=1.8*math.sqrt(25.2429/efixed) + + absorptionXSection = result[5]*wave/1.7982 + coherentXSection = result[4] + incoherentXSection = result[3] + scatteringXSection = incoherentXSection+coherentXSection + + thickness = float(thickness) + density = float(density) + + totalXSection = absorptionXSection + scatteringXSection + + transmission = math.exp(-density*totalXSection*thickness) + scattering = 1.0 - math.exp(-density*scatteringXSection*thickness) + + #Create table workspace to store calculations + tableWs = self.getPropertyValue('OutputWorkspace') + tableWs = CreateEmptyTableWorkspace(OutputWorkspace=tableWs) + tableWs.addColumn("str", "Name") + tableWs.addColumn("double", "Value") + + # Names for each of the output values + outputNames = ['Wavelength', 'Absorption Xsection', 'Coherent Xsection', 'Incoherent Xsection', + 'Total scattering Xsection', 'Number density', 'Thickness', 'Transmission (abs+scatt)', 'Total scattering'] + + # List of the calculated values + outputValues = [wave, absorptionXSection, coherentXSection, incoherentXSection, + scatteringXSection, density, thickness, transmission, scattering] + + #build table of values + for data in zip (outputNames, outputValues): + tableWs.addRow(list(data)) + logger.information(': '.join(map(str,list(data)))) + + #remove idf/ipf workspace + DeleteWorkspace(workspace) + self.setProperty("OutputWorkspace", tableWs) + EndTime('IndirectTransmission') # Register algorithm with Mantid AlgorithmFactory.subscribe(IndirectTransmission) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py index f3612a9205fb..5ec56cf0159c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatData.py @@ -3,76 +3,76 @@ from mantid.kernel import StringListValidator, StringMandatoryValidator, logger class MuscatData(PythonAlgorithm): - - def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" - def summary(self): - return "Calculates multiple scattering using a sample S(Q,w)." + def category(self): + return "Workflow\\MIDAS;PythonAlgorithms" - def PyInit(self): - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) - self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='Sample geometry') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') - self.declareProperty(name='SqwInput',defaultValue='',validator=StringMandatoryValidator(), doc='Sqw file run number') - self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') - self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') - self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') - self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') - self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') - self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') - self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') - self.declareProperty(name='Density', defaultValue=0.1, doc='Sample number density. Default=0.1') - self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') - self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') - self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - - def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + def summary(self): + return "Calculates multiple scattering using a sample S(Q,w)." - if is_supported_f2py_platform(): - import IndirectMuscat as Main - run_f2py_compatibility_test() + def PyInit(self): + self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) + self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='Sample geometry') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') + self.declareProperty(name='SqwInput',defaultValue='',validator=StringMandatoryValidator(), doc='Sqw file run number') + self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') + self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') + self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') + self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') + self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') + self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') + self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') + self.declareProperty(name='Density', defaultValue=0.1, doc='Sample number density. Default=0.1') + self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') + self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') + self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - self.log().information('Muscat input') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - geom = self.getPropertyValue('Geom') - sam = self.getPropertyValue('SamNumber') - sqwi = self.getPropertyValue('SqwInput') - sname = prefix+sam+'_'+ana - sqw = prefix+sqwi+'_'+ana + def PyExec(self): + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - NRUN1 = self.getPropertyValue('NR1') - NRUN2 = self.getPropertyValue('NR2') - NMST = self.getPropertyValue('Nms') - JRAND = 12345 - MRAND = 67890 - neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] + if is_supported_f2py_platform(): + import IndirectMuscat as Main + run_f2py_compatibility_test() - HEIGHT = 3.0 - alfa = self.getPropertyValue('DetAngle') - THICK = self.getPropertyValue('Thick') - WIDTH = self.getPropertyValue('Width') - HEIGHT = self.getPropertyValue('Height') - if geom == 'Flat': - beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] - if geom == 'Cyl': - beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] - dens = self.getPropertyValue('Density') - sigb = self.getPropertyValue('SigScat') - siga = self.getPropertyValue('SigAbs') - temp = self.getPropertyValue('Temperature') - sam = [float(temp), float(dens), float(siga), float(sigb)] + self.log().information('Muscat input') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + geom = self.getPropertyValue('Geom') + sam = self.getPropertyValue('SamNumber') + sqwi = self.getPropertyValue('SqwInput') + sname = prefix+sam+'_'+ana + sqw = prefix+sqwi+'_'+ana - kr1 = 1 - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value - Main.MuscatDataStart(sname,geom,neut,beam,sam,sqw,kr1,verbOp,plotOp,saveOp) + NRUN1 = self.getPropertyValue('NR1') + NRUN2 = self.getPropertyValue('NR2') + NMST = self.getPropertyValue('Nms') + JRAND = 12345 + MRAND = 67890 + neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] + + HEIGHT = 3.0 + alfa = self.getPropertyValue('DetAngle') + THICK = self.getPropertyValue('Thick') + WIDTH = self.getPropertyValue('Width') + HEIGHT = self.getPropertyValue('Height') + if geom == 'Flat': + beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] + if geom == 'Cyl': + beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] + dens = self.getPropertyValue('Density') + sigb = self.getPropertyValue('SigScat') + siga = self.getPropertyValue('SigAbs') + temp = self.getPropertyValue('Temperature') + sam = [float(temp), float(dens), float(siga), float(sigb)] + + kr1 = 1 + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value + Main.MuscatDataStart(sname,geom,neut,beam,sam,sqw,kr1,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(MuscatData) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py index e31a54e5417f..a1a21ca4818d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/MuscatFunc.py @@ -3,98 +3,98 @@ from mantid.api import PythonAlgorithm, AlgorithmFactory class MuscatFunc(PythonAlgorithm): - - def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" - def summary(self): - return "Calculates multiple scattering using S(Q,w) from specified functions." + def category(self): + return "Workflow\\MIDAS;PythonAlgorithms" - def PyInit(self): - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) - self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='') - self.declareProperty(name='Dispersion',defaultValue='Poly',validator=StringListValidator(['Poly','CE','SS']), doc='') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') - self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') - self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') - self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') - self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') - self.declareProperty(name='NQ', defaultValue=10, doc='Q-w grid: number of Q values. Default=10') - self.declareProperty(name='dQ', defaultValue=0.2, doc='Q-w grid: Q increment. Default=0.2') - self.declareProperty(name='NW', defaultValue=100, doc='Q-w grid: number of w values. Default=100') - self.declareProperty(name='dW', defaultValue=2.0, doc='Q-w grid: w increment (microeV). Default=2.0') - self.declareProperty(name='Coeff1', defaultValue=0., doc='Coefficient 1. Default=0.0') - self.declareProperty(name='Coeff2', defaultValue=0., doc='Coefficient 2. Default=0.0') - self.declareProperty(name='Coeff3', defaultValue=50.0, doc='Coefficient 3. Default=50.0') - self.declareProperty(name='Coeff4', defaultValue=0., doc='Coefficient 4. Default=0.0') - self.declareProperty(name='Coeff5', defaultValue=0., doc='Coefficient 5. Default=0.0') - self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') - self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') - self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') - self.declareProperty(name='Density', defaultValue=0.1, doc='Sample density. Default=0.1') - self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') - self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') - self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - - def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + def summary(self): + return "Calculates multiple scattering using S(Q,w) from specified functions." - if is_supported_f2py_platform(): - import IndirectMuscat as Main + def PyInit(self): + self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004'])) + self.declareProperty(name='Geom',defaultValue='Flat',validator=StringListValidator(['Flat','Cyl']), doc='') + self.declareProperty(name='Dispersion',defaultValue='Poly',validator=StringListValidator(['Poly','CE','SS']), doc='') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample data run number') + self.declareProperty(name='NR1', defaultValue=1000, doc='MonteCarlo neutrons NR1. Default=1000') + self.declareProperty(name='NR2', defaultValue=1000, doc='MonteCarlo neutrons NR2. Default=1000') + self.declareProperty(name='Nms', defaultValue=1, doc='Number of scatterings. Default=1') + self.declareProperty(name='DetAngle', defaultValue=90.0, doc='Detector angle. Default=90.0') + self.declareProperty(name='NQ', defaultValue=10, doc='Q-w grid: number of Q values. Default=10') + self.declareProperty(name='dQ', defaultValue=0.2, doc='Q-w grid: Q increment. Default=0.2') + self.declareProperty(name='NW', defaultValue=100, doc='Q-w grid: number of w values. Default=100') + self.declareProperty(name='dW', defaultValue=2.0, doc='Q-w grid: w increment (microeV). Default=2.0') + self.declareProperty(name='Coeff1', defaultValue=0., doc='Coefficient 1. Default=0.0') + self.declareProperty(name='Coeff2', defaultValue=0., doc='Coefficient 2. Default=0.0') + self.declareProperty(name='Coeff3', defaultValue=50.0, doc='Coefficient 3. Default=50.0') + self.declareProperty(name='Coeff4', defaultValue=0., doc='Coefficient 4. Default=0.0') + self.declareProperty(name='Coeff5', defaultValue=0., doc='Coefficient 5. Default=0.0') + self.declareProperty(name='Thick', defaultValue='',validator=StringMandatoryValidator(), doc='Sample thickness') + self.declareProperty(name='Width', defaultValue='',validator=StringMandatoryValidator(), doc='Sample width') + self.declareProperty(name='Height', defaultValue=3.0, doc='Sample height. Default=3.0') + self.declareProperty(name='Density', defaultValue=0.1, doc='Sample density. Default=0.1') + self.declareProperty(name='SigScat', defaultValue=5.0, doc='Scattering cross-section. Default=5.0') + self.declareProperty(name='SigAbs', defaultValue=0.1, doc='Absorption cross-section. Default=0.1') + self.declareProperty(name='Temperature', defaultValue=300.0, doc='Sample temperature (K). Default=300.0') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Totals','Scat1','All'])) + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - run_f2py_compatibility_test() + def PyExec(self): + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - self.log().information('Muscat input') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - geom = self.getPropertyValue('Geom') - disp = self.getPropertyValue('Dispersion') - sam = self.getPropertyValue('SamNumber') - sname = prefix+sam+'_'+ana + if is_supported_f2py_platform(): + import IndirectMuscat as Main - NRUN1 = self.getPropertyValue('NR1') - NRUN2 = self.getPropertyValue('NR2') - NMST = self.getPropertyValue('Nms') - JRAND = 12345 - MRAND = 67890 - neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] + run_f2py_compatibility_test() - HEIGHT = 3.0 - alfa = self.getPropertyValue('DetAngle') - THICK = self.getPropertyValue('Thick') - WIDTH = self.getPropertyValue('Width') - HEIGHT = self.getPropertyValue('Height') - if geom == 'Flat': - beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] - if geom == 'Cyl': - beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] - dens = self.getPropertyValue('Density') - sigb = self.getPropertyValue('SigScat') - siga = self.getPropertyValue('SigAbs') - sigss=sigb - temp = self.getPropertyValue('Temperature') - sam = [float(temp), float(dens), float(siga), float(sigb)] + self.log().information('Muscat input') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + geom = self.getPropertyValue('Geom') + disp = self.getPropertyValue('Dispersion') + sam = self.getPropertyValue('SamNumber') + sname = prefix+sam+'_'+ana - NQ = self.getPropertyValue('NQ') - dQ = self.getPropertyValue('dQ') - Nw = self.getPropertyValue('NW') - dw = self.getPropertyValue('dW') #in microeV - grid = [int(NQ), float(dQ), int(Nw), float(dw)] - c1 = self.getPropertyValue('Coeff1') - c2 = self.getPropertyValue('Coeff2') - c3 = self.getPropertyValue('Coeff3') - c4 = self.getPropertyValue('Coeff4') - c5 = self.getPropertyValue('Coeff5') - coeff = [float(c1), float(c2), float(c3), float(c4), float(c5)] - kr1 = 1 + NRUN1 = self.getPropertyValue('NR1') + NRUN2 = self.getPropertyValue('NR2') + NMST = self.getPropertyValue('Nms') + JRAND = 12345 + MRAND = 67890 + neut = [int(NRUN1), int(NRUN2), int(JRAND), int(MRAND), int(NMST)] - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value - Main.MuscatFuncStart(sname,geom,neut,beam,sam,grid,disp,coeff,kr1,verbOp,plotOp,saveOp) + HEIGHT = 3.0 + alfa = self.getPropertyValue('DetAngle') + THICK = self.getPropertyValue('Thick') + WIDTH = self.getPropertyValue('Width') + HEIGHT = self.getPropertyValue('Height') + if geom == 'Flat': + beam = [float(THICK), float(WIDTH), float(HEIGHT), float(alfa)] + if geom == 'Cyl': + beam = [float(THICK), float(WIDTH), float(HEIGHT), 0.0] #beam = [WIDTH, WIDTH2, HEIGHT, 0.0] + dens = self.getPropertyValue('Density') + sigb = self.getPropertyValue('SigScat') + siga = self.getPropertyValue('SigAbs') + sigss=sigb + temp = self.getPropertyValue('Temperature') + sam = [float(temp), float(dens), float(siga), float(sigb)] + + NQ = self.getPropertyValue('NQ') + dQ = self.getPropertyValue('dQ') + Nw = self.getPropertyValue('NW') + dw = self.getPropertyValue('dW') #in microeV + grid = [int(NQ), float(dQ), int(Nw), float(dw)] + c1 = self.getPropertyValue('Coeff1') + c2 = self.getPropertyValue('Coeff2') + c3 = self.getPropertyValue('Coeff3') + c4 = self.getPropertyValue('Coeff4') + c5 = self.getPropertyValue('Coeff5') + coeff = [float(c1), float(c2), float(c3), float(c4), float(c5)] + kr1 = 1 + + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value + Main.MuscatFuncStart(sname,geom,neut,beam,sam,grid,disp,coeff,kr1,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(MuscatFunc) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py index 94683ebec69b..fb07bc838bd3 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/NormaliseByThickness.py @@ -6,7 +6,7 @@ class NormaliseByThickness(PythonAlgorithm): """ Normalise detector counts by the sample thickness """ - + def category(self): return "Workflow\\SANS" @@ -17,20 +17,20 @@ def summary(self): return "Normalise detector counts by the sample thickness." def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", direction=Direction.Input)) - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output), "Name of the workspace that will contain the normalised data") self.declareProperty("SampleThickness", 0.0, "Optional sample thickness value. If not provided the sample-thickness run property will be used.") - self.declareProperty("OutputMessage", "", + self.declareProperty("OutputMessage", "", direction=Direction.Output, doc = "Output message") def PyExec(self): input_ws = self.getProperty("InputWorkspace").value - - # Determine whether we should use the input thickness or try + + # Determine whether we should use the input thickness or try # to read it from the run properties thickness = self.getProperty("SampleThickness").value if thickness <= 0: @@ -47,7 +47,7 @@ def PyExec(self): api.Scale(InputWorkspace=input_ws, OutputWorkspace=output_ws_name, Factor=1.0/thickness, Operation="Multiply") - + self.setProperty("OutputWorkspace", output_ws_name) self.setProperty("OutputMessage", "Normalised by thickness [%g cm]" % thickness) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py index 252834a073b8..08b2797acd0e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py @@ -22,10 +22,10 @@ time regimes. """ class DRangeToWsMap(object): - + def __init__(self): self._map = {} - + def addWs(self, wsname): """ Takes in the given workspace and lists it alongside its time regime value. If the time regime has yet to be created, it will create it, and if there is already @@ -38,9 +38,9 @@ def addWs(self, wsname): try: dRange = timeRegimeToDRange[timeRegime] except KeyError: - raise RuntimeError("Unable to identify the DRange of " + wsname + + raise RuntimeError("Unable to identify the DRange of " + wsname + ", which has a time regime of " + str(timeRegime)) - + # Add the workspace to the map, alongside its DRange. if dRange not in self._map: self._map[dRange] = [wsname] @@ -49,24 +49,24 @@ def addWs(self, wsname): for ws_name in self._map[dRange]: map_lastx = mtd[ws_name].readX(0)[-1] ws_lastx = ws.readX(0)[-1] - + #if it matches ignore it if map_lastx == ws_lastx: DeleteWorkspace(ws) return self._map[dRange].append(wsname) - + def setItem(self, dRange, wsname): """ Set a dRange and corresponding *single* ws. """ self._map[dRange] = wsname - + def getMap(self): """ Get access to wrapped map. """ return self._map - + def averageWsList(wsList): """ Returns the average of a list of workspaces. """ @@ -74,30 +74,30 @@ def averageWsList(wsList): assert len(wsList) > 0, "getAverageWs: Trying to take an average of nothing." if len(wsList) == 1: return wsList[0] - + # Generate the final name of the averaged workspace. avName = "avg" for name in wsList: avName += "_" + name - + numWorkspaces = len(wsList) # Compute the average and put into "__temp_avg". __temp_avg = mtd[wsList[0]] for i in range(1, numWorkspaces): __temp_avg += mtd[wsList[i]] - + __temp_avg /= numWorkspaces - + # Rename the average ws and return it. RenameWorkspace(InputWorkspace=__temp_avg, OutputWorkspace=avName) return avName def findIntersectionOfTwoRanges(rangeA, rangeB): - + assert rangeA[0] < rangeA[1], "Malformed range." assert rangeB[0] < rangeB[1], "Malformed range." - + if( rangeA[0] <= rangeA[1] <= rangeB[0] <= rangeB[1]): return if( rangeB[0] <= rangeB[1] <= rangeA[0] <= rangeA[1]): @@ -110,20 +110,20 @@ def findIntersectionOfTwoRanges(rangeA, rangeB): return [rangeB[0], rangeA[1]] if( rangeB[0] <= rangeA[0] <= rangeB[1] <= rangeA[1] ): return [rangeA[0], rangeB[1]] - + assert False, "We should never reach here ..." def getIntersectionsOfRanges(rangeList): """ Get the intersections of a list of ranges. For example, given the ranges: [1, 3], [3, 5] and [4, 6], the intersections would be a single range of [4, 5]. - - NOTE: Assumes that no more than a maximum of two ranges will ever cross + + NOTE: Assumes that no more than a maximum of two ranges will ever cross at the same point. Also, all ranges should obey range[0] <= range[1]. """ # Sanity check. for range in rangeList: assert len(range) == 2, "Unable to find the intersection of a malformed range." - + # Find all combinations of ranges, and see where they intersect. rangeCombos = list(itertools.combinations(rangeList, 2)) intersections = [] @@ -131,11 +131,11 @@ def getIntersectionsOfRanges(rangeList): intersection = findIntersectionOfTwoRanges(rangePair[0], rangePair[1]) if intersection is not None: intersections.append(intersection) - + # Return the sorted intersections. intersections.sort() return intersections - + def isInRanges(rangeList, n): for range in rangeList: if range[0] < n < range[1]: @@ -159,15 +159,15 @@ def PyInit(self): self.declareProperty('Vanadium', '', doc=runs_desc) self.declareProperty(FileProperty('CalFile', '', action=FileAction.Load), doc='Filename of the .cal file to use in the [[AlignDetectors]] and [[DiffractionFocussing]] child algorithms.') - self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '', Direction.Output), + self.declareProperty(MatrixWorkspaceProperty('OutputWorkspace', '', Direction.Output), doc="Name to give the output workspace. If no name is provided, one will be generated based on the run numbers.") - + self._cal = None self._outputWsName = None - + self._samMap = DRangeToWsMap() self._vanMap = DRangeToWsMap() - + def PyExec(self): # Set OSIRIS as default instrument. config["default.instrument"] = 'OSIRIS' @@ -176,7 +176,7 @@ def PyExec(self): self._outputWsName = self.getPropertyValue("OutputWorkspace") sampleRuns = self.findRuns(self.getPropertyValue("Sample")) - + self.execDiffOnly(sampleRuns) def execDiffOnly(self, sampleRuns): @@ -194,32 +194,32 @@ def execDiffOnly(self, sampleRuns): self._samMap.addWs(sam) for van in self._vans: self._vanMap.addWs(van) - + # Check to make sure that there are corresponding vanadium files with the same DRange for each sample file. for dRange in self._samMap.getMap().iterkeys(): if dRange not in self._vanMap.getMap(): raise RuntimeError("There is no van file that covers the " + str(dRange) + " DRange.") - + # Average together any sample workspaces with the same DRange. This will mean our map of DRanges # to list of workspaces becomes a map of DRanges, each to a *single* workspace. tempSamMap = DRangeToWsMap() for dRange, wsList in self._samMap.getMap().iteritems(): tempSamMap.setItem(dRange, averageWsList(wsList)) self._samMap = tempSamMap - + # Now do the same to the vanadium workspaces. tempVanMap = DRangeToWsMap() for dRange, wsList in self._vanMap.getMap().iteritems(): tempVanMap.setItem(dRange, averageWsList(wsList)) self._vanMap = tempVanMap - + # Run necessary algorithms on BOTH the Vanadium and Sample workspaces. for dRange, ws in self._samMap.getMap().items() + self._vanMap.getMap().items(): NormaliseByCurrent(InputWorkspace=ws,OutputWorkspace=ws) AlignDetectors(InputWorkspace=ws, OutputWorkspace=ws, CalibrationFile=self._cal) DiffractionFocussing(InputWorkspace=ws, OutputWorkspace=ws, GroupingFileName=self._cal) CropWorkspace(InputWorkspace=ws, OutputWorkspace=ws, XMin=dRange[0], XMax=dRange[1]) - + # Divide all sample files by the corresponding vanadium files. for dRange in self._samMap.getMap().iterkeys(): samWs = self._samMap.getMap()[dRange] @@ -227,12 +227,12 @@ def execDiffOnly(self, sampleRuns): samWs, vanWs = self.rebinToSmallest(samWs, vanWs) Divide(LHSWorkspace=samWs, RHSWorkspace=vanWs, OutputWorkspace=samWs) ReplaceSpecialValues(InputWorkspace=samWs, OutputWorkspace=samWs, NaNValue=0.0, InfinityValue=0.0) - + # Create a list of sample workspace NAMES, since we need this for MergeRuns. samWsNamesList = [] for sam in self._samMap.getMap().itervalues(): samWsNamesList.append(sam) - + if len(samWsNamesList) > 1: # Merge the sample files into one. MergeRuns(InputWorkspaces=samWsNamesList, OutputWorkspace=self._outputWsName) @@ -242,10 +242,10 @@ def execDiffOnly(self, sampleRuns): RenameWorkspace(InputWorkspace=samWsNamesList[0],OutputWorkspace=self._outputWsName) result = mtd[self._outputWsName] - + # Create scalar data to cope with where merge has combined overlapping data. intersections = getIntersectionsOfRanges(self._samMap.getMap().keys()) - + dataX = result.dataX(0) dataY = []; dataE = [] for i in range(0, len(dataX)-1): @@ -265,11 +265,11 @@ def execDiffOnly(self, sampleRuns): result.setY(i,resultY) result.setE(i,resultE) - + # Delete all workspaces we've created, except the result. for ws in self._vanMap.getMap().values(): DeleteWorkspace(Workspace=ws) - + self.setProperty("OutputWorkspace", result) def findRuns(self, run_str): @@ -291,9 +291,9 @@ def findRuns(self, run_str): def rebinToSmallest(self, samWS, vanWS): """ At some point a change to the control program - meant that the raw data got an extra bin. This + meant that the raw data got an extra bin. This prevents runs past this point being normalised - with a vanadium from an earlier point. + with a vanadium from an earlier point. Here we simply rebin to the smallest workspace if the sizes don't match @param samWS A workspace object containing the sample run @@ -303,13 +303,13 @@ def rebinToSmallest(self, samWS, vanWS): sample_size, van_size = mtd[samWS].blocksize(), mtd[vanWS].blocksize() if sample_size == van_size: return samWS, vanWS - + if sample_size < van_size: RebinToWorkspace(WorkspaceToRebin=vanWS, WorkspaceToMatch=samWS,OutputWorkspace=vanWS) else: RebinToWorkspace(WorkspaceToRebin=samWS, WorkspaceToMatch=vanWS,OutputWorkspace=samWS) - + return samWS, vanWS - + AlgorithmFactory.subscribe(OSIRISDiffractionReduction) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py index 4441e27080d4..a2e5647bb16f 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/QLines.py @@ -5,111 +5,111 @@ import os class QLines(PythonAlgorithm): - - def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" - - def summary(self): - return "The program estimates the quasielastic components of each of the groups of spectra and requires the resolution file (.RES file) and optionally the normalisation file created by ResNorm." - - def PyInit(self): - self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) or Workspace') - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection') - self.declareProperty(name='Program',defaultValue='QL',validator=StringListValidator(['QL','QSe']), doc='Name of program to run') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') - self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') - self.declareProperty(name='ResType',defaultValue='Res',validator=StringListValidator(['Res','Data']), doc='Format of Resolution file') - self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') - self.declareProperty(name='ResNorm',defaultValue=False, doc='Use ResNorm output file') - self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') - self.declareProperty(name='ResNormNumber',defaultValue='', doc='ResNorm run number') - self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') - self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') - self.declareProperty(name='FixWidth',defaultValue=False, doc='Fix one of the widths') - self.declareProperty(name='WidthFile', defaultValue='', doc='Name of file containing fixed width values') - self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') - self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') - self.declareProperty(name='SamBinning', defaultValue=1, doc='Binning value (integer) for sample. Default=1') - self.declareProperty(name='ResBinning', defaultValue=1, doc='Binning value (integer) for resolution - QLd only. Default=1') - self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','ProbBeta','Intensity','FwHm','Fit','All']), doc='Plot options') - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - - def PyExec(self): + + def category(self): + return "Workflow\\MIDAS;PythonAlgorithms" + + def summary(self): + return "The program estimates the quasielastic components of each of the groups of spectra and requires the resolution file (.RES file) and optionally the normalisation file created by ResNorm." + + def PyInit(self): + self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) or Workspace') + self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection') + self.declareProperty(name='Program',defaultValue='QL',validator=StringListValidator(['QL','QSe']), doc='Name of program to run') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') + self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') + self.declareProperty(name='ResType',defaultValue='Res',validator=StringListValidator(['Res','Data']), doc='Format of Resolution file') + self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') + self.declareProperty(name='ResNorm',defaultValue=False, doc='Use ResNorm output file') + self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') + self.declareProperty(name='ResNormNumber',defaultValue='', doc='ResNorm run number') + self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') + self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') + self.declareProperty(name='FixWidth',defaultValue=False, doc='Fix one of the widths') + self.declareProperty(name='WidthFile', defaultValue='', doc='Name of file containing fixed width values') + self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') + self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') + self.declareProperty(name='SamBinning', defaultValue=1, doc='Binning value (integer) for sample. Default=1') + self.declareProperty(name='ResBinning', defaultValue=1, doc='Binning value (integer) for resolution - QLd only. Default=1') + self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','ProbBeta','Intensity','FwHm','Fit','All']), doc='Plot options') + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') + + def PyExec(self): from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform if is_supported_f2py_platform(): import IndirectBayes as Main - run_f2py_compatibility_test() - - self.log().information('QLines input') - inType = self.getPropertyValue('InputType') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - prog = self.getPropertyValue('Program') - sam = self.getPropertyValue('SamNumber') - rinType = self.getPropertyValue('ResInputType') - rtype = self.getPropertyValue('ResType') - res = self.getPropertyValue('ResNumber') - elastic = self.getProperty('ElasticOption').value - bgd = self.getPropertyValue('BackgroundOption') - width = self.getProperty('FixWidth').value - wfile = self.getPropertyValue('WidthFile') - rsnormType = self.getPropertyValue('ResNormInputType') - resnorm = self.getProperty('ResNorm').value - resn = self.getPropertyValue('ResNormNumber') - emin = self.getPropertyValue('EnergyMin') - emax = self.getPropertyValue('EnergyMax') - nbin = self.getPropertyValue('SamBinning') - nrbin = self.getPropertyValue('ResBinning') - nbins = [nbin, nrbin] - - if rtype == 'Res': - rext = 'res' - if rtype == 'Data': - rext = 'red' - sname = prefix+sam+'_'+ana + '_red' - rname = prefix+res+'_'+ana + '_' + rext - rsname = prefix+resn+'_'+ana + '_ResNorm_Paras' - erange = [float(emin), float(emax)] - - fitOp = [elastic, bgd, width, resnorm] - loopOp = self.getProperty('Sequence').value - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value - - workdir = config['defaultsave.directory'] - if inType == 'File': - spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file - LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) - Smessage = 'Sample from File : '+spath - else: - Smessage = 'Sample from Workspace : '+sname - if rinType == 'File': - rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file - LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) - Rmessage = 'Resolution from File : '+rpath - else: - Rmessage = 'Resolution from Workspace : '+rname - - if resnorm: - if rsnormType == 'File': - rpath = os.path.join(workdir, rsname+'.nxs') # path name for res nxs file - LoadNexusProcessed(Filename=rpath, OutputWorkspace=rsname) - Rmessage = 'ResNorm from File : '+rpath - else: - Rmessage = 'ResNorm from Workspace : '+rsname - - if verbOp: - logger.notice(Smessage) - logger.notice(Rmessage) - - rsname = rsname[:-6] - - Main.QLRun(prog,sname,rname,rsname,erange,nbins,fitOp,wfile,loopOp,verbOp,plotOp,saveOp) + run_f2py_compatibility_test() + + self.log().information('QLines input') + inType = self.getPropertyValue('InputType') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + prog = self.getPropertyValue('Program') + sam = self.getPropertyValue('SamNumber') + rinType = self.getPropertyValue('ResInputType') + rtype = self.getPropertyValue('ResType') + res = self.getPropertyValue('ResNumber') + elastic = self.getProperty('ElasticOption').value + bgd = self.getPropertyValue('BackgroundOption') + width = self.getProperty('FixWidth').value + wfile = self.getPropertyValue('WidthFile') + rsnormType = self.getPropertyValue('ResNormInputType') + resnorm = self.getProperty('ResNorm').value + resn = self.getPropertyValue('ResNormNumber') + emin = self.getPropertyValue('EnergyMin') + emax = self.getPropertyValue('EnergyMax') + nbin = self.getPropertyValue('SamBinning') + nrbin = self.getPropertyValue('ResBinning') + nbins = [nbin, nrbin] + + if rtype == 'Res': + rext = 'res' + if rtype == 'Data': + rext = 'red' + sname = prefix+sam+'_'+ana + '_red' + rname = prefix+res+'_'+ana + '_' + rext + rsname = prefix+resn+'_'+ana + '_ResNorm_Paras' + erange = [float(emin), float(emax)] + + fitOp = [elastic, bgd, width, resnorm] + loopOp = self.getProperty('Sequence').value + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value + + workdir = config['defaultsave.directory'] + if inType == 'File': + spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file + LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) + Smessage = 'Sample from File : '+spath + else: + Smessage = 'Sample from Workspace : '+sname + if rinType == 'File': + rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file + LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) + Rmessage = 'Resolution from File : '+rpath + else: + Rmessage = 'Resolution from Workspace : '+rname + + if resnorm: + if rsnormType == 'File': + rpath = os.path.join(workdir, rsname+'.nxs') # path name for res nxs file + LoadNexusProcessed(Filename=rpath, OutputWorkspace=rsname) + Rmessage = 'ResNorm from File : '+rpath + else: + Rmessage = 'ResNorm from Workspace : '+rsname + + if verbOp: + logger.notice(Smessage) + logger.notice(Rmessage) + + rsname = rsname[:-6] + + Main.QLRun(prog,sname,rname,rsname,erange,nbins,fitOp,wfile,loopOp,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(QLines) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py index a1a27c630064..b4c3a0d27b3b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Quest.py @@ -5,106 +5,106 @@ import os class Quest(PythonAlgorithm): - - def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" - def summary(self): - return "This is a variation of the stretched exponential option of Quasi." + def category(self): + return "Workflow\\MIDAS;PythonAlgorithms" - def PyInit(self): - self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) or Workspace') - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') - self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') - self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') - self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') - self.declareProperty(name='ResNormNumber',defaultValue='',validator=StringMandatoryValidator(), doc='ResNorm run number') - self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') - self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') - self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') - self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') - self.declareProperty(name='SamBinning', defaultValue=1, doc='Binning value(integer) for sample. Default=1') - self.declareProperty(name='NumberSigma', defaultValue=50, doc='Number of sigma values. Default=50') - self.declareProperty(name='NumberBeta', defaultValue=30, doc='Number of beta values. Default=30') - self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') - self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Sigma','Beta','All']), doc='Plot options') - self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - - def PyExec(self): - from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform + def summary(self): + return "This is a variation of the stretched exponential option of Quasi." - if is_supported_f2py_platform(): - import IndirectBayes as Main + def PyInit(self): + self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (.nxs) or Workspace') + self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') + self.declareProperty(name='ResInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of res input - File (_res.nxs) or Workspace') + self.declareProperty(name='ResNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Resolution run number') + self.declareProperty(name='ResNormInputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of ResNorm input - File (_red.nxs) or Workspace') + self.declareProperty(name='ResNormNumber',defaultValue='',validator=StringMandatoryValidator(), doc='ResNorm run number') + self.declareProperty(name='ElasticOption',defaultValue=True, doc='Include elastic peak in fit') + self.declareProperty(name='BackgroundOption',defaultValue='Sloping',validator=StringListValidator(['Sloping','Flat','Zero']), doc='Form of background to fit') + self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') + self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') + self.declareProperty(name='SamBinning', defaultValue=1, doc='Binning value(integer) for sample. Default=1') + self.declareProperty(name='NumberSigma', defaultValue=50, doc='Number of sigma values. Default=50') + self.declareProperty(name='NumberBeta', defaultValue=30, doc='Number of beta values. Default=30') + self.declareProperty(name='Sequence',defaultValue=True, doc='Switch Sequence Off/On') + self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Sigma','Beta','All']), doc='Plot options') + self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - run_f2py_compatibility_test() - - self.log().information('Quest input') - inType = self.getPropertyValue('InputType') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - sam = self.getPropertyValue('SamNumber') - rinType = self.getPropertyValue('ResInputType') - res = self.getPropertyValue('ResNumber') - rsnormType = self.getPropertyValue('ResNormInputType') - rsnormNum = self.getPropertyValue('ResNormNumber') - elastic = self.getProperty('ElasticOption').value - bgd = self.getPropertyValue('BackgroundOption') - emin = self.getPropertyValue('EnergyMin') - emax = self.getPropertyValue('EnergyMax') - nbin = self.getPropertyValue('SamBinning') - nbins = [nbin, 1] - nbet = self.getPropertyValue('NumberBeta') - nsig = self.getPropertyValue('NumberSigma') - nbs = [nbet, nsig] + def PyExec(self): + from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform - sname = prefix+sam+'_'+ana + '_red' - rname = prefix+res+'_'+ana + '_res' - rsname = prefix+rsnormNum+'_'+ana+ '_ResNorm_Paras' - erange = [float(emin), float(emax)] - if elastic: - o_el = 1 - else: - o_el = 0 - if bgd == 'Sloping': - o_bgd = 2 - if bgd == 'Flat': - o_bgd = 1 - if bgd == 'Zero': - o_bgd = 0 - fitOp = [o_el, o_bgd, 0, 0] - loopOp = self.getProperty('Sequence').value - verbOp = self.getProperty('Verbose').value - plotOp = self.getPropertyValue('Plot') - saveOp = self.getProperty('Save').value + if is_supported_f2py_platform(): + import IndirectBayes as Main - workdir = config['defaultsave.directory'] - if inType == 'File': - spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file - LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) - Smessage = 'Sample from File : '+spath - else: - Smessage = 'Sample from Workspace : '+sname + run_f2py_compatibility_test() - if rinType == 'File': - rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file - LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) - Rmessage = 'Resolution from File : '+rpath - else: - Rmessage = 'Resolution from Workspace : '+rname + self.log().information('Quest input') + inType = self.getPropertyValue('InputType') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + sam = self.getPropertyValue('SamNumber') + rinType = self.getPropertyValue('ResInputType') + res = self.getPropertyValue('ResNumber') + rsnormType = self.getPropertyValue('ResNormInputType') + rsnormNum = self.getPropertyValue('ResNormNumber') + elastic = self.getProperty('ElasticOption').value + bgd = self.getPropertyValue('BackgroundOption') + emin = self.getPropertyValue('EnergyMin') + emax = self.getPropertyValue('EnergyMax') + nbin = self.getPropertyValue('SamBinning') + nbins = [nbin, 1] + nbet = self.getPropertyValue('NumberBeta') + nsig = self.getPropertyValue('NumberSigma') + nbs = [nbet, nsig] - if rsnormType == 'File': - rpath = os.path.join(workdir, rsname+'.nxs') # path name for res nxs file - LoadNexusProcessed(Filename=rpath, OutputWorkspace=rsname) - Rmessage = 'ResNorm from File : '+rpath - else: - Rmessage = 'ResNorm from Workspace : '+rsname + sname = prefix+sam+'_'+ana + '_red' + rname = prefix+res+'_'+ana + '_res' + rsname = prefix+rsnormNum+'_'+ana+ '_ResNorm_Paras' + erange = [float(emin), float(emax)] + if elastic: + o_el = 1 + else: + o_el = 0 + if bgd == 'Sloping': + o_bgd = 2 + if bgd == 'Flat': + o_bgd = 1 + if bgd == 'Zero': + o_bgd = 0 + fitOp = [o_el, o_bgd, 0, 0] + loopOp = self.getProperty('Sequence').value + verbOp = self.getProperty('Verbose').value + plotOp = self.getPropertyValue('Plot') + saveOp = self.getProperty('Save').value - if verbOp: - logger.notice(Smessage) - logger.notice(Rmessage) - Main.QuestRun(sname,rname,rsname,nbs,erange,nbins,fitOp,loopOp,verbOp,plotOp,saveOp) + workdir = config['defaultsave.directory'] + if inType == 'File': + spath = os.path.join(workdir, sname+'.nxs') # path name for sample nxs file + LoadNexusProcessed(Filename=spath, OutputWorkspace=sname) + Smessage = 'Sample from File : '+spath + else: + Smessage = 'Sample from Workspace : '+sname + + if rinType == 'File': + rpath = os.path.join(workdir, rname+'.nxs') # path name for res nxs file + LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname) + Rmessage = 'Resolution from File : '+rpath + else: + Rmessage = 'Resolution from Workspace : '+rname + + if rsnormType == 'File': + rpath = os.path.join(workdir, rsname+'.nxs') # path name for res nxs file + LoadNexusProcessed(Filename=rpath, OutputWorkspace=rsname) + Rmessage = 'ResNorm from File : '+rpath + else: + Rmessage = 'ResNorm from Workspace : '+rsname + + if verbOp: + logger.notice(Smessage) + logger.notice(Rmessage) + Main.QuestRun(sname,rname,rsname,nbs,erange,nbins,fitOp,loopOp,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(Quest) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py index f2fa0d3eb9fa..d2aa68669a98 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/REFLReprocess.py @@ -17,7 +17,7 @@ class REFLReprocess(PythonAlgorithm): """ Normalise detector counts by accelerator current and beam spectrum. """ - + def category(self): return "Workflow\\REFL" @@ -27,7 +27,7 @@ def name(self): def summary(self): return "Re-reduce REFL data for an entire experiment using saved parameters" - def PyInit(self): + def PyInit(self): self.declareProperty("IPTS", '0', "IPTS number to process") self.declareProperty(FileProperty(name="OutputDirectory",defaultValue="",action=FileAction.OptionalDirectory)) self.declareProperty("LoadProcessed", False, "If True, data will be loaded instead of being processed") @@ -41,14 +41,14 @@ def PyExec(self): ipts = "IPTS-%s" % ipts_number except: pass - + Logger("REFLReprocess").notice("Processing %s" % ipts) - + # Locate the IPTS directory ipts_dir = "/SNS/REF_L/%s/shared" % ipts if not os.path.isdir(ipts_dir): ipts_dir = ipts - + # Determine the output directory output_dir = self.getProperty("OutputDirectory").value if len(output_dir)==0: @@ -78,7 +78,7 @@ def PyExec(self): Logger("REFLReprocess").error(str(sys.exc_value)) else: Logger("REFLReprocess").error("%s not a valid directory" % ipts_dir) - + def load_processed(self, output_dir): filter_string = self.getProperty("Filter").value if not os.path.isdir(output_dir): @@ -94,7 +94,7 @@ def load_processed(self, output_dir): CloneWorkspace(InputWorkspace=basename, OutputWorkspace=_name) - def stitch_data(self, input_file, output_dir, q_min, q_step): + def stitch_data(self, input_file, output_dir, q_min, q_step): from LargeScaleStructures.data_stitching import DataSet, Stitcher, RangeSelector # Identify the data sets to stitch and order them workspace_list = [] @@ -106,14 +106,14 @@ def stitch_data(self, input_file, output_dir, q_min, q_step): (_name,_ts) = item.split('_#') _list_name.append(item) _list_ts.append(_ts) - + _name_ts = zip(_list_ts, _list_name) _name_ts.sort() _ts_sorted, workspace_list = zip(*_name_ts) - + # Stitch the data s = Stitcher() - + q_max = 0 for item in workspace_list: data = DataSet(item) @@ -126,16 +126,16 @@ def stitch_data(self, input_file, output_dir, q_min, q_step): s.set_reference(0) s.compute() - # Apply the scaling factors + # Apply the scaling factors for data in s._data_sets: Scale(InputWorkspace=str(data), OutputWorkspace=data._ws_scaled, Operation="Multiply", Factor=data.get_scale()) SaveAscii(InputWorkspace=str(data), Filename=os.path.join(output_dir, '%s.txt' % str(data))) - + output_file = input_file.replace('.xml', '_reprocessed.txt') Logger("REFLReprocess").notice("Saving to %s" % output_file) - + output_ws = _average_y_of_same_x_(q_min, q_step, q_max) SaveAscii(InputWorkspace=output_ws, Filename=output_file) @@ -163,22 +163,22 @@ def weightedMean(data_array, error_array): if dataDen == 0: mean = 0 mean_error = 0 - else: + else: mean = float(dataNum) / float(dataDen) - mean_error = math.sqrt(1/dataDen) + mean_error = math.sqrt(1/dataDen) return [mean, mean_error] def _average_y_of_same_x_(q_min, q_step, q_max=2): """ - + Code taken out as-is from base_ref_reduction.py - + 2 y values sharing the same x-axis will be average using the weighted mean """ - + ws_list = AnalysisDataService.getObjectNames() scaled_ws_list = [] @@ -186,15 +186,15 @@ def _average_y_of_same_x_(q_min, q_step, q_max=2): for ws in ws_list: if ws.endswith("_scaled"): scaled_ws_list.append(ws) - - + + # get binning parameters #_from_q = str(state.data_sets[0].q_min) #_bin_size = str(state.data_sets[0].q_step) #_bin_max = str(2) #binning_parameters = _from_q + ',-' + _bin_size + ',' + _bin_max binning_parameters = "%s,-%s,%s" % (q_min, q_step, q_max) - + # Convert each histo to histograms and rebin to final binning for ws in scaled_ws_list: new_name = "%s_histo" % ws diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py index 66fad484c7e8..7f4a1e088aeb 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ReactorSANSResolution.py @@ -5,9 +5,9 @@ class ReactorSANSResolution(PythonAlgorithm): """ - Calculate and populate the Q resolution + Calculate and populate the Q resolution """ - + def category(self): return "SANS" @@ -22,7 +22,7 @@ def PyInit(self): self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", direction=Direction.Input), "Name the workspace to calculate the resolution for") - + # Dummy property for temporary backward compatibility # The output workspace property is not used and the resolution is # added to the input workspace @@ -31,35 +31,35 @@ def PyInit(self): def PyExec(self): input_ws = self.getProperty("InputWorkspace").value - + # Q resolution calculation # All distances in mm wvl = None - if input_ws.getRun().hasProperty("wavelength"): + if input_ws.getRun().hasProperty("wavelength"): wvl = input_ws.getRun().getProperty("wavelength").value - + d_wvl = None - if input_ws.getRun().hasProperty("wavelength-spread"): + if input_ws.getRun().hasProperty("wavelength-spread"): d_wvl = input_ws.getRun().getProperty("wavelength-spread").value - + source_apert_radius = None if input_ws.getRun().hasProperty("source-aperture-diameter"): source_apert_radius = input_ws.getRun().getProperty("source-aperture-diameter").value/2.0 - + sample_apert_radius = None if input_ws.getRun().hasProperty("sample-aperture-diameter"): sample_apert_radius = input_ws.getRun().getProperty("sample-aperture-diameter").value/2.0 - + source_sample_distance = None if input_ws.getRun().hasProperty("source-sample-distance"): source_sample_distance = input_ws.getRun().getProperty("source-sample-distance").value - + sample_detector_distance = None if input_ws.getRun().hasProperty("sample_detector_distance"): sample_detector_distance = input_ws.getRun().getProperty("sample_detector_distance").value - + pixel_size_x = input_ws.getInstrument().getNumberParameter("x-pixel-size")[0] - + if wvl is not None and d_wvl is not None \ and source_apert_radius is not None and sample_apert_radius is not None \ and source_sample_distance is not None and sample_detector_distance is not None: @@ -67,9 +67,9 @@ def PyExec(self): res_factor = math.pow(k*source_apert_radius/source_sample_distance, 2) res_factor += (math.pow(k*sample_apert_radius*(source_sample_distance+sample_detector_distance)/(source_sample_distance*sample_detector_distance), 2)/4.0) res_factor += math.pow(k*pixel_size_x/sample_detector_distance, 2)/12.0 - + for i in range(len(input_ws.readX(0))): - input_ws.dataDx(0)[i] = math.sqrt(res_factor+math.pow((input_ws.readX(0)[i]*d_wvl), 2)/6.0) + input_ws.dataDx(0)[i] = math.sqrt(res_factor+math.pow((input_ws.readX(0)[i]*d_wvl), 2)/6.0) else: raise RuntimeError, "ReactorSANSResolution could not find all the run parameters needed to compute the resolution." diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py index 88268bf952c1..c7dd0825540e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ResNorm.py @@ -5,7 +5,7 @@ import os class ResNorm(PythonAlgorithm): - + def category(self): return "Workflow\\MIDAS;PythonAlgorithms" @@ -25,7 +25,7 @@ def PyInit(self): self.declareProperty(name='Plot',defaultValue='None',validator=StringListValidator(['None','Intensity','Stretch','Fit','All']), doc='Plot options') self.declareProperty(name='Verbose',defaultValue=True, doc='Switch Verbose Off/On') self.declareProperty(name='Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - + def PyExec(self): from IndirectImport import run_f2py_compatibility_test, is_supported_f2py_platform @@ -33,7 +33,7 @@ def PyExec(self): import IndirectBayes as Main run_f2py_compatibility_test() - + self.log().information('ResNorm input') inType = self.getPropertyValue('InputType') prefix = self.getPropertyValue('Instrument') diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py index ec05af943ab5..6736b723ce04 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAbsoluteScale.py @@ -9,7 +9,7 @@ class SANSAbsoluteScale(PythonAlgorithm): """ Normalise detector counts by the sample thickness """ - + def category(self): return "Workflow\\SANS\\UsesPropertyManager" @@ -20,18 +20,18 @@ def summary(self): return "Calculate and apply absolute scale correction for SANS data" def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", direction=Direction.Input)) - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output)) methods = [ "Value", "ReferenceData"] self.declareProperty("Method", "Value", StringListValidator(methods), "Scaling method - either a simple scaling by value or using a reference data set") - + self.declareProperty("ScalingFactor", 1.0, "Scaling factor to use with the Value method") - + self.declareProperty(FileProperty("ReferenceDataFilename", "", action=FileAction.OptionalLoad, extensions=['xml', 'nxs', 'nxs.h5']), @@ -41,29 +41,29 @@ def PyInit(self): "Attenuator transmission used in the measurement") self.declareProperty("ApplySensitivity", False, "If True, the sensitivity correction will be applied to the reference data set") - - self.declareProperty("ReductionProperties", "__sans_reduction_properties", + + self.declareProperty("ReductionProperties", "__sans_reduction_properties", validator=StringMandatoryValidator(), doc="Property manager name for the reduction") - - self.declareProperty("OutputMessage", "", + + self.declareProperty("OutputMessage", "", direction=Direction.Output, doc = "Output message") def PyExec(self): property_manager_name = self.getProperty("ReductionProperties").value property_manager = PropertyManagerDataService.retrieve(property_manager_name) - + # Get instrument to use with FileFinder self.instrument = '' if property_manager.existsProperty("InstrumentName"): self.instrument = property_manager.getProperty("InstrumentName").value - + method = self.getPropertyValue("Method") if method=="Value": input_ws = self.getProperty("InputWorkspace").value output_ws_name = self.getPropertyValue("OutputWorkspace") scaling_factor = self.getProperty("ScalingFactor").value - + alg = AlgorithmManager.create("Scale") alg.initialize() alg.setChild(True) @@ -73,10 +73,10 @@ def PyExec(self): alg.setPropertyValue("Operation", "Multiply") alg.execute() output_ws = alg.getProperty("OutputWorkspace").value - + self.setProperty("OutputWorkspace", output_ws) self.setProperty("OutputMessage", "Applied scaling factor %g" % scaling_factor) - + elif self.instrument.lower() in ['biosans', 'gpsans', 'hfirsans']: self._hfir_scaling(property_manager) else: @@ -84,7 +84,7 @@ def PyExec(self): Logger("SANSAbsoluteScale").error(msg) self.setProperty("OutputMessage", msg) return - + def _hfir_scaling(self, property_manager): property_manager_name = self.getProperty("ReductionProperties").value input_ws = self.getProperty("InputWorkspace").value @@ -94,7 +94,7 @@ def _hfir_scaling(self, property_manager): # Load data file data_file = self.getProperty("ReferenceDataFilename").value filepath = find_data(data_file, instrument=self.instrument) - + ref_basename = os.path.basename(filepath) ref_ws_name = "__abs_scale_%s" % ref_basename @@ -118,22 +118,22 @@ def _load_data(filename, output_ws): ref_ws, msg = _load_data(filepath, ref_ws_name) output_msg += msg+'\n' - + # Get monitor value: # This call is left unprotected because it should fail if that property - # doesn't exist. It's the responsibility of the parent algorithm to + # doesn't exist. It's the responsibility of the parent algorithm to # catch that error. monitor_prop = property_manager.getProperty("NormaliseAlgorithm") alg=Algorithm.fromString(monitor_prop.valueAsStr) monitor_id = alg.getPropertyValue("NormalisationType").lower() - + monitor_value = ref_ws.getRun().getProperty(monitor_id.lower()).value # HFIR-specific: If we count for monitor we need to multiply by 1e8 # Need to be consistent with the Normalization step if monitor_id == "monitor": monitor_value /= 1.0e8 - # Get sample-detector distance + # Get sample-detector distance sdd = ref_ws.getRun().getProperty("sample_detector_distance").value # Get the beamstop diameter @@ -143,8 +143,8 @@ def _load_data(filename, output_ws): beam_diameter = ref_ws.getRun().getProperty("beam-diameter").value Logger("SANSAbsoluteScale").debug("Found beamstop diameter: %g" % beam_diameter) else: - raise RuntimeError, "AbsoluteScale could not read the beam radius and none was provided" - + raise RuntimeError, "AbsoluteScale could not read the beam radius and none was provided" + # Apply sensitivity correction apply_sensitivity = self.getProperty("ApplySensitivity").value if apply_sensitivity and property_manager.existsProperty("SensitivityAlgorithm"): @@ -160,14 +160,14 @@ def _load_data(filename, output_ws): output_msg += alg.getProperty("OutputMessage").value+'\n' # Get the reference count - Logger("SANSAbsoluteScale").information("Using beamstop diameter: %g" % beam_diameter) + Logger("SANSAbsoluteScale").information("Using beamstop diameter: %g" % beam_diameter) det_count = 1 cylXML = '' + \ '' + \ '' + \ '' % (beam_diameter/2000.0) + \ '\n' - + alg = AlgorithmManager.create("FindDetectorsInShape") alg.initialize() alg.setChild(True) @@ -191,14 +191,14 @@ def _load_data(filename, output_ws): Logger("SANSAbsoluteScale").information("Reference detector counts: %g" % det_count) if det_count <= 0: Logger("SANSAbsoluteScale").error("Bad reference detector count: check your beam parameters") - + # Pixel size, in mm pixel_size_param = ref_ws.getInstrument().getNumberParameter("x-pixel-size") if pixel_size_param is not None: pixel_size = pixel_size_param[0] else: raise RuntimeError, "AbsoluteScale could not read the pixel size" - + attenuator_trans = self.getProperty("AttenuatorTransmission").value # (detector count rate)/(attenuator transmission)/(monitor rate)*(pixel size/SDD)**2 scaling_factor = 1.0/(det_count/attenuator_trans/(monitor_value)*(pixel_size/sdd)*(pixel_size/sdd)) @@ -214,11 +214,11 @@ def _load_data(filename, output_ws): alg.execute() output_ws = alg.getProperty("OutputWorkspace").value Logger("SANSAbsoluteScale").notice( "Applied scaling factor %15.15f" % scaling_factor) - + output_msg = output_msg.replace('\n','\n |') output_msg = "Applied scaling factor %g\n%s" % (scaling_factor, output_msg) - + self.setProperty("OutputWorkspace", output_ws) self.setProperty("OutputMessage", output_msg) - + AlgorithmFactory.subscribe(SANSAbsoluteScale()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py index b6b4045e7a51..8d7a48f148bd 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSAzimuthalAverage1D.py @@ -12,31 +12,31 @@ def name(self): def summary(self): return "Compute I(q) for reduced SANS data" - + def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", direction=Direction.Input)) self.declareProperty(FloatArrayProperty("Binning", values=[0.,0.,0.], direction=Direction.InOut), "Positive is linear bins, negative is logorithmic") - + self.declareProperty("NumberOfBins", 100, validator=IntBoundedValidator(lower=1), doc="Number of Q bins to use if binning is not supplied") self.declareProperty("LogBinning", False, "Produce log binning in Q when true and binning wasn't supplied") self.declareProperty("NumberOfSubpixels", 1, "Number of sub-pixels per side of a detector pixel: use with care") self.declareProperty("ErrorWeighting", False, "Backward compatibility option: use with care") self.declareProperty('ComputeResolution', False, 'If true the Q resolution will be computed') - - self.declareProperty("ReductionProperties", "__sans_reduction_properties", + + self.declareProperty("ReductionProperties", "__sans_reduction_properties", validator=StringMandatoryValidator(), doc="Property manager name for the reduction") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output), "I(q) workspace") - self.declareProperty("OutputMessage", "", + self.declareProperty("OutputMessage", "", direction=Direction.Output, doc = "Output message") - + def PyExec(self): # Warn user if error-weighting was turned on error_weighting = self.getProperty("ErrorWeighting").value @@ -44,24 +44,24 @@ def PyExec(self): msg = "The ErrorWeighting option is turned ON. " msg += "This option is NOT RECOMMENDED" Logger("SANSAzimuthalAverage").warning(msg) - + # Warn against sub-pixels n_subpix = self.getProperty("NumberOfSubpixels").value if n_subpix != 1: msg = "NumberOfSubpixels was set to %s: " % str(n_subpix) msg += "The recommended value is 1" Logger("SANSAzimuthalAverage").warning(msg) - + # Q binning options binning = self.getProperty("Binning").value - + workspace = self.getProperty("InputWorkspace").value output_ws_name = self.getPropertyValue("OutputWorkspace") - # Q range + # Q range pixel_size_x = workspace.getInstrument().getNumberParameter("x-pixel-size")[0] pixel_size_y = workspace.getInstrument().getNumberParameter("y-pixel-size")[0] - + if len(binning)==0 or (binning[0]==0 and binning[1]==0 and binning[2]==0): # Wavelength. Read in the wavelength bins. Skip the first one which is not set up properly for EQ-SANS x = workspace.dataX(1) @@ -79,7 +79,7 @@ def PyExec(self): else: qmin = binning[0] qmax = binning[2] - + # If we kept the events this far, we need to convert the input workspace # to a histogram here if workspace.id()=="EventWorkspace": @@ -90,21 +90,21 @@ def PyExec(self): alg.setPropertyValue("OutputWorkspace", "__tmp_matrix_workspace") alg.execute() workspace = alg.getProperty("OutputWorkspace").value - + alg = AlgorithmManager.create("Q1DWeighted") alg.initialize() alg.setChild(True) alg.setProperty("InputWorkspace", workspace) tmp_binning = "%g, %g, %g" % (binning[0], binning[1], binning[2]) alg.setPropertyValue("OutputBinning", tmp_binning) - alg.setProperty("NPixelDivision", n_subpix) - alg.setProperty("PixelSizeX", pixel_size_x) - alg.setProperty("PixelSizeY", pixel_size_y) - alg.setProperty("ErrorWeighting", error_weighting) - alg.setPropertyValue("OutputWorkspace", output_ws_name) + alg.setProperty("NPixelDivision", n_subpix) + alg.setProperty("PixelSizeX", pixel_size_x) + alg.setProperty("PixelSizeY", pixel_size_y) + alg.setProperty("ErrorWeighting", error_weighting) + alg.setPropertyValue("OutputWorkspace", output_ws_name) alg.execute() output_ws = alg.getProperty("OutputWorkspace").value - + alg = AlgorithmManager.create("ReplaceSpecialValues") alg.initialize() alg.setChild(True) @@ -117,7 +117,7 @@ def PyExec(self): alg.execute() output_ws = alg.getProperty("OutputWorkspace").value - # Q resolution + # Q resolution compute_resolution = self.getProperty("ComputeResolution").value if compute_resolution: alg = AlgorithmManager.create("ReactorSANSResolution") @@ -125,13 +125,13 @@ def PyExec(self): alg.setChild(True) alg.setProperty("InputWorkspace", output_ws) alg.execute() - + msg = "Performed radial averaging between Q=%g and Q=%g" % (qmin, qmax) - self.setProperty("OutputMessage", msg) + self.setProperty("OutputMessage", msg) self.setProperty("OutputWorkspace", output_ws) - def _get_binning(self, workspace, wavelength_min, wavelength_max): + def _get_binning(self, workspace, wavelength_min, wavelength_max): log_binning = self.getProperty("LogBinning").value nbins = self.getProperty("NumberOfBins").value if workspace.getRun().hasProperty("qmin") and workspace.getRun().hasProperty("qmax"): @@ -156,7 +156,7 @@ def _get_binning(self, workspace, wavelength_min, wavelength_max): beam_ctr_x = property_manager.getProperty("LatestBeamCenterX").value beam_ctr_y = property_manager.getProperty("LatestBeamCenterY").value else: - raise RuntimeError, "No beam center information can be found on the data set" + raise RuntimeError, "No beam center information can be found on the data set" # Q min is one pixel from the center, unless we have the beam trap size if workspace.getRun().hasProperty("beam-trap-diameter"): @@ -164,12 +164,12 @@ def _get_binning(self, workspace, wavelength_min, wavelength_max): else: mindist = min(pixel_size_x, pixel_size_y) qmin = 4*math.pi/wavelength_max*math.sin(0.5*math.atan(mindist/sample_detector_distance)) - + dxmax = pixel_size_x*max(beam_ctr_x,nx_pixels-beam_ctr_x) dymax = pixel_size_y*max(beam_ctr_y,ny_pixels-beam_ctr_y) maxdist = math.sqrt(dxmax*dxmax+dymax*dymax) qmax = 4*math.pi/wavelength_min*math.sin(0.5*math.atan(maxdist/sample_detector_distance)) - + if not log_binning: qstep = (qmax-qmin)/nbins f_step = (qmax-qmin)/qstep diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py index 627a88773eb5..90b04c7fbfd4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py @@ -15,67 +15,67 @@ def name(self): def summary(self): return "Compute transmission using the beam spreader method" - + def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", direction=Direction.Input)) self.declareProperty(FileProperty("SampleSpreaderFilename", "", - action=FileAction.Load, + action=FileAction.Load, extensions=['xml', 'nxs', 'nxs.h5'])) self.declareProperty(FileProperty("DirectSpreaderFilename", "", - action=FileAction.Load, + action=FileAction.Load, extensions=['xml', 'nxs', 'nxs.h5'])) self.declareProperty(FileProperty("SampleScatteringFilename", "", - action=FileAction.Load, + action=FileAction.Load, extensions=['xml', 'nxs', 'nxs.h5'])) self.declareProperty(FileProperty("DirectScatteringFilename", "", - action=FileAction.Load, + action=FileAction.Load, extensions=['xml', 'nxs', 'nxs.h5'])) self.declareProperty("SpreaderTransmissionValue", 1.0, "Transmission of the beam spreader") self.declareProperty("SpreaderTransmissionError", 0.0, "Error on the transmission of the beam spreader") - - self.declareProperty("ThetaDependent", True, + + self.declareProperty("ThetaDependent", True, "If true, a theta-dependent correction will be applied") self.declareProperty(FileProperty("DarkCurrentFilename", "", - action=FileAction.OptionalLoad, + action=FileAction.OptionalLoad, extensions=['xml', 'nxs', 'nxs.h5'])) - self.declareProperty("UseSampleDarkCurrent", False, + self.declareProperty("UseSampleDarkCurrent", False, "If true, the sample dark current will be used") - self.declareProperty("ReductionProperties", "__sans_reduction_properties", + self.declareProperty("ReductionProperties", "__sans_reduction_properties", validator=StringMandatoryValidator(), doc="Property manager name for the reduction") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output)) - self.declareProperty("MeasuredTransmission", 0.0, + self.declareProperty("MeasuredTransmission", 0.0, direction=Direction.Output) - self.declareProperty("MeasuredError", 0.0, + self.declareProperty("MeasuredError", 0.0, direction=Direction.Output) - self.declareProperty("OutputMessage", "", + self.declareProperty("OutputMessage", "", direction=Direction.Output, doc = "Output message") - - def PyExec(self): + + def PyExec(self): # Get the reduction property manager property_manager_name = self.getProperty("ReductionProperties").value property_manager = PropertyManagerDataService.retrieve(property_manager_name) - + # Build the name we are going to give the transmission workspace sample_scatt = self.getPropertyValue("SampleScatteringFilename") sample_basename = os.path.basename(sample_scatt) entry_name = "TransmissionSpreader%s" % sample_scatt trans_ws_name = "__transmission_fit_%s" % sample_basename trans_ws = None - - # If we have already computed the transmission, used the + + # If we have already computed the transmission, used the # previously computed workspace if property_manager.existsProperty(entry_name): trans_ws_name = property_manager.getProperty(entry_name) if AnalysisDataService.doesExist(trans_ws_name): trans_ws = AnalysisDataService.retrieve(trans_ws_name) - + # Get instrument to use with FileFinder instrument = '' if property_manager.existsProperty("InstrumentName"): @@ -105,11 +105,11 @@ def _load_data(filename, output_ws): direct_spreader_ws = "__trans_direct_spreader" sample_scatt_ws = "__trans_sample_scatt" direct_scatt_ws = "__trans_direct_scatt" - + sample_spread = self.getPropertyValue("SampleSpreaderFilename") direct_spread = self.getPropertyValue("DirectSpreaderFilename") direct_scatt = self.getPropertyValue("DirectScatteringFilename") - + ws_names = [[sample_spread, sample_spreader_ws], [direct_spread, direct_spreader_ws], [sample_scatt, sample_scatt_ws], @@ -120,7 +120,7 @@ def _load_data(filename, output_ws): filepath = find_data(f[0], instrument=instrument) _load_data(filepath, f[1]) self._subtract_dark_current(f[1], property_manager) - + # Get normalization for transmission calculation monitor_det_ID = None if property_manager.existsProperty("TransmissionNormalisation"): @@ -144,12 +144,12 @@ def _normalise(workspace): return msg for f in ws_names: _normalise(f[1]) - + # Calculate transmission. Use the reduction method's normalization channel (time or beam monitor) # as the monitor channel. spreader_t_value = self.getPropertyValue("SpreaderTransmissionValue") spreader_t_error = self.getPropertyValue("SpreaderTransmissionError") - + alg = AlgorithmManager.createUnmanaged('CalculateTransmissionBeamSpreader') alg.initialize() alg.setProperty("SampleSpreaderRunWorkspace", sample_spreader_ws) @@ -161,19 +161,19 @@ def _normalise(workspace): alg.setProperty("SpreaderTransmissionValue",spreader_t_value) alg.setProperty("SpreaderTransmissionError",spreader_t_error) alg.execute() - + trans_ws = AnalysisDataService.retrieve(trans_ws_name) - + for f in ws_names: if AnalysisDataService.doesExist(f[1]): - AnalysisDataService.remove(f[1]) - - # 2- Apply correction (Note: Apply2DTransCorr) + AnalysisDataService.remove(f[1]) + + # 2- Apply correction (Note: Apply2DTransCorr) input_ws_name = self.getPropertyValue("InputWorkspace") if not AnalysisDataService.doesExist(input_ws_name): Logger("SANSBeamSpreaderTransmission").error("Could not find input workspace") workspace = AnalysisDataService.retrieve(input_ws_name).getName() - + # Clone workspace to make boost-python happy api.CloneWorkspace(InputWorkspace=workspace, OutputWorkspace='__'+workspace) @@ -183,51 +183,51 @@ def _normalise(workspace): trans = trans_ws.dataY(0)[0] error = trans_ws.dataE(0)[0] - + output_str = '' if len(trans_ws.dataY(0))==1: self.setProperty("MeasuredTransmission", trans) self.setProperty("MeasuredError", error) output_str = "\n%s T = %6.2g += %6.2g\n" % (output_str, trans, error) output_msg = "Transmission correction applied [%s]%s\n" % (trans_ws_name, output_str) - + output_ws = AnalysisDataService.retrieve(workspace) self.setProperty("OutputWorkspace", output_ws) self.setPropertyValue("OutputMessage", output_msg) - + def _apply_transmission(self, workspace, trans_workspace): """ Apply transmission correction @param workspace: workspace to apply correction to @param trans_workspace: workspace name for of the transmission """ - # Make sure the binning is compatible + # Make sure the binning is compatible api.RebinToWorkspace(WorkspaceToRebin=trans_workspace, WorkspaceToMatch=workspace, OutputWorkspace=trans_workspace+'_rebin', PreserveEvents=False) # Apply angle-dependent transmission correction using the zero-angle transmission theta_dependent = self.getProperty("ThetaDependent").value - - api.ApplyTransmissionCorrection(InputWorkspace=workspace, - TransmissionWorkspace=trans_workspace+'_rebin', + + api.ApplyTransmissionCorrection(InputWorkspace=workspace, + TransmissionWorkspace=trans_workspace+'_rebin', OutputWorkspace=workspace, - ThetaDependent=theta_dependent) + ThetaDependent=theta_dependent) if AnalysisDataService.doesExist(trans_workspace+'_rebin'): - AnalysisDataService.remove(trans_workspace+'_rebin') - + AnalysisDataService.remove(trans_workspace+'_rebin') + def _subtract_dark_current(self, workspace_name, property_manager): """ Subtract the dark current @param workspace_name: name of the workspace to subtract from - @param property_manager: property manager object + @param property_manager: property manager object """ # Subtract dark current use_sample_dc = self.getProperty("UseSampleDarkCurrent").value dark_current_data = self.getPropertyValue("DarkCurrentFilename") property_manager_name = self.getProperty("ReductionProperties").value - + dark_current_property = "DefaultDarkCurrentAlgorithm" def _dark(workspace, dark_current_property): if property_manager.existsProperty(dark_current_property): @@ -251,7 +251,7 @@ def _dark(workspace, dark_current_property): _dark(workspace_name, "DarkCurrentAlgorithm") elif len(dark_current_data.strip())>0: _dark(workspace_name, "DefaultDarkCurrentAlgorithm") - + ############################################################################################# AlgorithmFactory.subscribe(SANSBeamSpreaderTransmission) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py index 46e4a4c44822..57546fb4008b 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDirectBeamTransmission.py @@ -13,9 +13,9 @@ def name(self): def summary(self): return "Compute transmission using the direct beam method" - + def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", direction=Direction.Input)) self.declareProperty(FileProperty("SampleDataFilename", "", action=FileAction.Load, @@ -24,82 +24,82 @@ def PyInit(self): action=FileAction.Load, extensions=['xml', 'nxs', 'nxs.h5'])) self.declareProperty("BeamRadius", 3.0, "Beam radius [pixels]") - self.declareProperty("ThetaDependent", True, + self.declareProperty("ThetaDependent", True, "If true, a theta-dependent correction will be applied") self.declareProperty(FileProperty("DarkCurrentFilename", "", action=FileAction.OptionalLoad, extensions=['xml', 'nxs', 'nxs.h5'])) - self.declareProperty("UseSampleDarkCurrent", False, + self.declareProperty("UseSampleDarkCurrent", False, "If true, the sample dark current will be used") self.declareProperty("BeamCenterX", 0.0, "Beam center position in X") self.declareProperty("BeamCenterY", 0.0, "Beam center position in Y") - self.declareProperty("ReductionProperties", "__sans_reduction_properties", + self.declareProperty("ReductionProperties", "__sans_reduction_properties", validator=StringMandatoryValidator(), doc="Property manager name for the reduction") - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output), "Workspace containing the data corrected for the transmission.") - self.declareProperty(MatrixWorkspaceProperty("TransmissionWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("TransmissionWorkspace", "", optional = PropertyMode.Optional, direction = Direction.Output), "Workspace containing the fitted transmission distribution.") - self.declareProperty(MatrixWorkspaceProperty("RawTransmissionWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("RawTransmissionWorkspace", "", optional = PropertyMode.Optional, direction = Direction.Output), "Workspace containing the transmission distribution before fitting.") - self.declareProperty("MeasuredTransmission", 0.0, + self.declareProperty("MeasuredTransmission", 0.0, direction=Direction.Output) - self.declareProperty("MeasuredError", 0.0, + self.declareProperty("MeasuredError", 0.0, direction=Direction.Output) - self.declareProperty("OutputMessage", "", + self.declareProperty("OutputMessage", "", direction=Direction.Output, doc = "Output message") - + def PyExec(self): import TransmissionUtils sample_file = self.getPropertyValue("SampleDataFilename") empty_file = self.getPropertyValue("EmptyDataFilename") - + property_manager_name = self.getProperty("ReductionProperties").value property_manager = PropertyManagerDataService.retrieve(property_manager_name) - + # Build the name we are going to give the transmission workspace sample_basename = os.path.basename(sample_file) empty_basename = os.path.basename(empty_file) entry_name = "Transmission%s%s" % (sample_basename, empty_basename) trans_ws_name = "__transmission_fit_%s" % sample_basename trans_ws = None - + if property_manager.existsProperty(entry_name): trans_ws_name = property_manager.getProperty(entry_name) if AnalysisDataService.doesExist(trans_ws_name): trans_ws = AnalysisDataService.retrieve(trans_ws_name) - + if trans_ws is None: # Load data files sample_mon_ws, empty_mon_ws, first_det, output_str, monitor_det_ID = TransmissionUtils.load_monitors(self, property_manager) - trans_ws, raw_ws = TransmissionUtils.calculate_transmission(self, sample_mon_ws, empty_mon_ws, + trans_ws, raw_ws = TransmissionUtils.calculate_transmission(self, sample_mon_ws, empty_mon_ws, first_det, trans_ws_name, monitor_det_ID) - + # 2- Apply correction (Note: Apply2DTransCorr) if trans_ws is not None: input_ws = self.getProperty("InputWorkspace").value - + output_ws = TransmissionUtils.apply_transmission(self, input_ws, trans_ws) - + trans = trans_ws.dataY(0)[0] error = trans_ws.dataE(0)[0] - + if len(trans_ws.dataY(0))==1: self.setProperty("MeasuredTransmission", trans) self.setProperty("MeasuredError", error) output_str = "%s T = %6.2g += %6.2g\n" % (output_str, trans, error) - + self.setProperty("OutputWorkspace", output_ws) input_tr_name = self.getPropertyValue("TransmissionWorkspace") if len(input_tr_name.strip())==0: self.setPropertyValue("TransmissionWorkspace", trans_ws_name) self.setProperty("TransmissionWorkspace", trans_ws) - + if raw_ws is not None: raw_ws_name = "__transmission_raw_%s" % sample_basename self.setPropertyValue("RawTransmissionWorkspace", raw_ws_name) @@ -107,9 +107,9 @@ def PyExec(self): output_msg = "Transmission correction applied [%s]\n%s\n" % (trans_ws_name, output_str) else: output_msg = "Transmission correction had errors\n%s\n" % output_str - + self.setPropertyValue("OutputMessage", output_msg) - + ############################################################################################# AlgorithmFactory.subscribe(SANSDirectBeamTransmission) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py index e703fa8de664..acba4b537f19 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSMask.py @@ -9,7 +9,7 @@ class SANSMask(PythonAlgorithm): """ Normalise detector counts by the sample thickness """ - + def category(self): return "Workflow\\SANS" @@ -25,24 +25,24 @@ def PyInit(self): StringListValidator(facilities), "Facility to which the SANS instrument belongs") - self.declareProperty(MatrixWorkspaceProperty("Workspace", "", + self.declareProperty(MatrixWorkspaceProperty("Workspace", "", direction=Direction.InOut), "Workspace to apply the mask to") self.declareProperty(IntArrayProperty("MaskedDetectorList", values=[], direction=Direction.Input), "List of detector IDs to be masked") - + self.declareProperty(IntArrayProperty("MaskedEdges", values=[0,0,0,0], direction=Direction.Input), "Number of pixels to mask on the edges: X-low, X-high, Y-low, Y-high") - + sides = [ "None", "Front", "Back"] self.declareProperty("MaskedSide", "None", StringListValidator(sides), "Side of the detector to which to apply the mask") - - self.declareProperty("OutputMessage", "", + + self.declareProperty("OutputMessage", "", direction=Direction.Output, doc = "Output message") def PyExec(self): @@ -57,7 +57,7 @@ def PyExec(self): # Mask edges edge_str = self.getPropertyValue("MaskedEdges") - + edges = self.getProperty("MaskedEdges").value if len(edges)==4: if facility.upper() == "HFIR": @@ -74,7 +74,7 @@ def PyExec(self): masked_dets = self.getProperty("MaskedDetectorList").value if len(masked_dets)>0: api.MaskDetectors(Workspace=workspace, DetectorList=masked_dets) - + self.setProperty("OutputMessage", "Mask applied") def _mask_pixels(self, pixel_list, workspace, facility): @@ -86,7 +86,7 @@ def _mask_pixels(self, pixel_list, workspace, facility): masked_detectors = sns_instrument.get_detector_from_pixel(pixel_list, workspace) # Mask the pixels by passing the list of IDs api.MaskDetectors(Workspace=workspace, DetectorList = masked_detectors) - + def _apply_saved_mask(self, workspace, facility): # Check whether the workspace has mask information if workspace.getRun().hasProperty("rectangular_masks"): @@ -111,7 +111,7 @@ def _apply_saved_mask(self, workspace, facility): Logger("SANSMask").error("Badly defined mask from configuration file: %s" % str(rec)) Logger("SANSMask").error(str(sys.exc_value)) self._mask_pixels(masked_pixels, workspace, facility) - + def _mask_detector_side(self, workspace, facility): """ Mask the back side or front side as needed @@ -123,16 +123,16 @@ def _mask_detector_side(self, workspace, facility): side_to_mask = 1 else: return - + if not workspace.getInstrument().hasParameter("number-of-x-pixels") \ and not workspace.getInstrument().hasParameter("number-of-y-pixels"): Logger("SANSMask").error("Could not find number of pixels: skipping side masking") return - + nx = int(workspace.getInstrument().getNumberParameter("number-of-x-pixels")[0]) ny = int(workspace.getInstrument().getNumberParameter("number-of-y-pixels")[0]) id_side = [] - + for iy in range(ny): for ix in range(side_to_mask, nx+side_to_mask, 2): # For some odd reason the HFIR format has the x,y coordinates inverted @@ -142,5 +142,5 @@ def _mask_detector_side(self, workspace, facility): id_side.append([ix,iy]) self._mask_pixels(id_side, workspace, facility) - + AlgorithmFactory.subscribe(SANSMask()) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py index afdb25da3b41..f6940f4489e9 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py @@ -33,7 +33,7 @@ def _load_data(self, filename, output_ws, property_manager, property_manager_nam property_manager.existsProperty('LoadAlgorithm') p = property_manager.getProperty('LoadAlgorithm') alg = Algorithm.fromString(p.valueAsStr) - + if AnalysisDataService.doesExist(filename) \ and AnalysisDataService.retrieve(filename).__class__.__name__.find('EventWorkspace')>=0 \ and not AnalysisDataService.retrieve(filename).getRun().hasProperty("event_ws") \ @@ -82,9 +82,9 @@ def _py_exec(self): output_ws = self.getPropertyValue("OutputWorkspace") property_manager_name = self.getProperty("ReductionProperties").value property_manager = PropertyManagerDataService.retrieve(property_manager_name) - + property_list = [p.name for p in property_manager.getProperties()] - + output_msg = "" # Find the beam center if "SANSBeamFinderAlgorithm" in property_list: @@ -95,16 +95,16 @@ def _py_exec(self): alg.execute() if alg.existsProperty("OutputMessage"): output_msg += alg.getProperty("OutputMessage").value+'\n' - + # Load the sample data - msg = self._multiple_load(filename, output_ws, + msg = self._multiple_load(filename, output_ws, property_manager, property_manager_name) output_msg += "Loaded %s\n" % filename output_msg += msg # Perform the main corrections on the sample data output_msg += self.process_data_file(output_ws) - + # Sample data transmission correction beam_center_x = None beam_center_y = None @@ -124,18 +124,18 @@ def _py_exec(self): alg=Algorithm.fromString(p.valueAsStr) alg.setProperty("InputWorkspace", output_ws) alg.setProperty("OutputWorkspace", output_ws) - + if alg.existsProperty("BeamCenterX") \ and alg.existsProperty("BeamCenterY") \ and beam_center_x is not None \ and beam_center_y is not None: alg.setProperty("BeamCenterX", beam_center_x) - alg.setProperty("BeamCenterY", beam_center_y) - + alg.setProperty("BeamCenterY", beam_center_y) + if alg.existsProperty("ReductionProperties"): alg.setProperty("ReductionProperties", property_manager_name) alg.execute() - + if alg.existsProperty("MeasuredTransmission"): meas_trans = alg.getProperty("MeasuredTransmission").value if property_manager.existsProperty("MeasuredTransmissionValue"): @@ -143,27 +143,27 @@ def _py_exec(self): else: property_manager.declareProperty("MeasuredTransmissionValue", meas_trans) if alg.existsProperty("MeasuredError"): - meas_err = alg.getProperty("MeasuredError").value + meas_err = alg.getProperty("MeasuredError").value if property_manager.existsProperty("MeasuredTransmissionError"): property_manager.setProperty("MeasuredTransmissionError", meas_err) - else: - property_manager.declareProperty("MeasuredTransmissionError", meas_err) - + else: + property_manager.declareProperty("MeasuredTransmissionError", meas_err) + if alg.existsProperty("OutputMessage"): output_msg += alg.getProperty("OutputMessage").value+'\n' - + # Process background data if "BackgroundFiles" in property_list: background = property_manager.getProperty("BackgroundFiles").value background_ws = "__background_%s" % output_ws - msg = self._multiple_load(background, background_ws, + msg = self._multiple_load(background, background_ws, property_manager, property_manager_name) bck_msg = "Loaded background %s\n" % background bck_msg += msg - + # Process background like we processed the sample data bck_msg += self.process_data_file(background_ws) - + trans_beam_center_x = None trans_beam_center_y = None if "BckTransmissionBeamCenterAlgorithm" in property_list: @@ -176,25 +176,25 @@ def _py_exec(self): alg.execute() trans_beam_center_x = alg.getProperty("FoundBeamCenterX").value trans_beam_center_y = alg.getProperty("FoundBeamCenterY").value - + # Background transmission correction if "BckTransmissionAlgorithm" in property_list: p=property_manager.getProperty("BckTransmissionAlgorithm") alg=Algorithm.fromString(p.valueAsStr) alg.setProperty("InputWorkspace", background_ws) alg.setProperty("OutputWorkspace", '__'+background_ws+"_reduced") - + if alg.existsProperty("BeamCenterX") \ and alg.existsProperty("BeamCenterY") \ and trans_beam_center_x is not None \ and trans_beam_center_y is not None: alg.setProperty("BeamCenterX", trans_beam_center_x) alg.setProperty("BeamCenterY", trans_beam_center_y) - + if alg.existsProperty("ReductionProperties"): alg.setProperty("ReductionProperties", property_manager_name) alg.execute() - + if alg.existsProperty("MeasuredTransmission"): meas_trans = alg.getProperty("MeasuredTransmission").value if property_manager.existsProperty("MeasuredBckTransmissionValue"): @@ -202,18 +202,18 @@ def _py_exec(self): else: property_manager.declareProperty("MeasuredBckTransmissionValue", meas_trans) if alg.existsProperty("MeasuredError"): - meas_err = alg.getProperty("MeasuredError").value + meas_err = alg.getProperty("MeasuredError").value if property_manager.existsProperty("MeasuredBckTransmissionError"): property_manager.setProperty("MeasuredBckTransmissionError", meas_err) - else: - property_manager.declareProperty("MeasuredBckTransmissionError", meas_err) - + else: + property_manager.declareProperty("MeasuredBckTransmissionError", meas_err) + if alg.existsProperty("OutputMessage"): output_msg += alg.getProperty("OutputMessage").value+'\n' else: output_msg += "Transmission correction applied\n" background_ws = '__'+background_ws+'_reduced' - + # Subtract background api.RebinToWorkspace(WorkspaceToRebin=background_ws, WorkspaceToMatch=output_ws, @@ -222,16 +222,16 @@ def _py_exec(self): api.Minus(LHSWorkspace=output_ws, RHSWorkspace=background_ws+'_rebin', OutputWorkspace=output_ws) - + bck_msg = bck_msg.replace('\n','\n |') output_msg += "Background subtracted [%s]\n %s\n" % (background_ws, bck_msg) - + # Absolute scale correction output_msg += self._simple_execution("AbsoluteScaleAlgorithm", output_ws) - + # Geometry correction output_msg += self._simple_execution("GeometryAlgorithm", output_ws) - + # Compute I(q) iq_output = None if "IQAlgorithm" in property_list: @@ -244,7 +244,7 @@ def _py_exec(self): alg.setProperty("ReductionProperties", property_manager_name) alg.execute() if alg.existsProperty("OutputMessage"): - output_msg += alg.getProperty("OutputMessage").value+'\n' + output_msg += alg.getProperty("OutputMessage").value+'\n' # Compute I(qx,qy) iqxy_output = None @@ -259,8 +259,8 @@ def _py_exec(self): alg.setProperty("ReductionProperties", property_manager_name) alg.execute() if alg.existsProperty("OutputMessage"): - output_msg += alg.getProperty("OutputMessage").value+'\n' - + output_msg += alg.getProperty("OutputMessage").value+'\n' + # Verify output directory and save data if "OutputDirectory" in property_list: output_dir = property_manager.getProperty("OutputDirectory").value @@ -276,18 +276,18 @@ def _py_exec(self): if iqxy_output is not None: iqxy_frame = iqxy_output.replace('_Iqxy', '_frame%s_Iqxy' % i) if AnalysisDataService.doesExist(iq_frame): - output_msg += self._save_output(iq_frame, iqxy_frame, + output_msg += self._save_output(iq_frame, iqxy_frame, output_dir, property_manager) else: - output_msg += self._save_output(iq_output, iqxy_output, + output_msg += self._save_output(iq_output, iqxy_output, output_dir, property_manager) Logger("SANSReduction").notice("Output saved in %s" % output_dir) elif len(output_dir)>0: msg = "Output directory doesn't exist: %s\n" % output_dir Logger("SANSReduction").error(msg) - + self.setProperty("OutputMessage", output_msg) - + def process_data_file(self, workspace): output_msg = "" property_manager_name = self.getProperty("ReductionProperties").value @@ -299,13 +299,13 @@ def process_data_file(self, workspace): # Normalize output_msg += self._simple_execution("NormaliseAlgorithm", workspace) - + # Mask output_msg += self._simple_execution("MaskAlgorithm", workspace) - + # Solid angle correction output_msg += self._simple_execution("SANSSolidAngleCorrection", workspace) - + # Sensitivity correction if "SensitivityAlgorithm" in property_list: # Beam center for the sensitivity correction @@ -321,25 +321,25 @@ def process_data_file(self, workspace): alg.execute() beam_center_x = alg.getProperty("FoundBeamCenterX").value beam_center_y = alg.getProperty("FoundBeamCenterY").value - + p=property_manager.getProperty("SensitivityAlgorithm") alg=Algorithm.fromString(p.valueAsStr) alg.setProperty("InputWorkspace", workspace) alg.setProperty("OutputWorkspace", workspace) - + if alg.existsProperty("BeamCenterX") \ and alg.existsProperty("BeamCenterY") \ and beam_center_x is not None \ and beam_center_y is not None: alg.setProperty("BeamCenterX", beam_center_x) alg.setProperty("BeamCenterY", beam_center_y) - + if alg.existsProperty("ReductionProperties"): alg.setProperty("ReductionProperties", property_manager_name) alg.execute() if alg.existsProperty("OutputMessage"): output_msg += alg.getProperty("OutputMessage").value+'\n' - + # Store sensitivity beam center so that we can access it later if beam_center_x is not None and beam_center_y is not None: if property_manager.existsProperty("SensitivityBeamCenterXUsed"): @@ -352,18 +352,18 @@ def process_data_file(self, workspace): property_manager.declareProperty("SensitivityBeamCenterYUsed", beam_center_y) return output_msg - + def _simple_execution(self, algorithm_name, workspace, output_workspace=None): """ Simple execution of an algorithm on the given workspace """ property_manager_name = self.getProperty("ReductionProperties").value property_manager = PropertyManagerDataService.retrieve(property_manager_name) - + output_msg = "" if output_workspace is None: output_workspace = workspace - + if property_manager.existsProperty(algorithm_name): p=property_manager.getProperty(algorithm_name) alg=Algorithm.fromString(p.valueAsStr) @@ -379,11 +379,11 @@ def _simple_execution(self, algorithm_name, workspace, output_workspace=None): if alg.existsProperty("OutputMessage"): output_msg = alg.getProperty("OutputMessage").value+'\n' return output_msg - + def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): """ Save the I(Q) and I(QxQy) output to file. - + @param iq_output: name of the I(Q) workspace @param iqxy_output: name of the I(QxQy) workspace @param output_dir: output director path @@ -413,9 +413,9 @@ def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): filename = self.getProperty("Filename").value proc_xml += " %s\n" % filename proc_xml += "\n" - + filename = os.path.join(output_dir, iq_output+'.txt') - + alg = AlgorithmManager.create("SaveAscii") alg.initialize() alg.setChild(True) @@ -426,7 +426,7 @@ def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): alg.setProperty("WriteXError", True) alg.setProperty("WriteSpectrumID", False) alg.execute() - + filename = os.path.join(output_dir, iq_output+'.xml') alg = AlgorithmManager.create("SaveCanSAS1D") alg.initialize() @@ -439,7 +439,7 @@ def _save_output(self, iq_output, iqxy_output, output_dir, property_manager): output_msg += "I(Q) saved in %s\n" % (filename) else: Logger("SANSReduction").error("No I(Q) output found") - + # Save I(Qx,Qy) if iqxy_output is not None: if AnalysisDataService.doesExist(iqxy_output): diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py index 740fabf0e6ca..fb0e415612d4 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SavePlot1D.py @@ -1,30 +1,30 @@ import mantid,sys - + class SavePlot1D(mantid.api.PythonAlgorithm): def category(self): - """ Category - """ + """ Category + """ return "Utility;PythonAlgorithms" def name(self): - """ Algorithm name - """ + """ Algorithm name + """ return "SavePlot1D" def summary(self): return "Save 1D plots to a file" - + def checkGroups(self): return False - + def PyInit(self): #declare properties self.declareProperty(mantid.api.WorkspaceProperty("InputWorkspace","",mantid.kernel.Direction.Input),"Workspace to plot") self.declareProperty(mantid.api.FileProperty('OutputFilename', '', action=mantid.api.FileAction.Save, extensions = ["png"]), doc='Name of the image file to savefile.') self.declareProperty("XLabel","","Label on the X axis. If empty, it will be taken from workspace") self.declareProperty("YLabel","","Label on the Y axis. If empty, it will be taken from workspace") - + def PyExec(self): ok2run='' @@ -36,7 +36,7 @@ def PyExec(self): except: ok2run='Problem importing matplotlib' if ok2run!='': - raise RuntimeError(ok2run) + raise RuntimeError(ok2run) matplotlib=sys.modules['matplotlib'] matplotlib.use("agg") import matplotlib.pyplot as plt @@ -47,12 +47,12 @@ def PyExec(self): plt.subplot(self._wksp.getNumberOfEntries(),1,i+1) self.DoPlot(self._wksp.getItem(i)) else: - self.DoPlot(self._wksp) + self.DoPlot(self._wksp) plt.tight_layout(1.08) plt.show() filename = self.getProperty("OutputFilename").value - plt.savefig(filename,bbox_inches='tight') - + plt.savefig(filename,bbox_inches='tight') + def DoPlot(self,ws): plt=sys.modules['matplotlib.pyplot'] spectra=ws.getNumberHistograms() @@ -60,12 +60,12 @@ def DoPlot(self,ws): mantid.kernel.logger.warning("more than 10 spectra to plot") prog_reporter=mantid.api.Progress(self,start=0.0,end=1.0, nreports=spectra) - + for j in range(spectra): x=ws.readX(j) y=ws.readY(j) if x.size==y.size+1: - x=(x[:-1]+x[1:])*0.5 + x=(x[:-1]+x[1:])*0.5 #get labels for the curves a=ws.getAxis(1) if a.isSpectra(): @@ -74,25 +74,25 @@ def DoPlot(self,ws): LHS=a.title() if LHS=="": LHS=a.getUnit().caption() - plotlabel=LHS+" = "+str(float(a.label(j))) + plotlabel=LHS+" = "+str(float(a.label(j))) plt.plot(x,y,label=plotlabel) xlabel=self.getProperty("XLabel").value ylabel=self.getProperty("YLabel").value if xlabel=="": xaxis=ws.getAxis(0) - unitLabel=xaxis.getUnit().symbol().latex() + unitLabel=xaxis.getUnit().symbol().latex() xlabel=xaxis.getUnit().caption()+" ($"+unitLabel+"$)" if ylabel=="": - ylabel=ws.YUnit() + ylabel=ws.YUnit() if ylabel=='': - ylabel = ws.YUnitLabel() + ylabel = ws.YUnitLabel() plt.xlabel(xlabel) - plt.ylabel(ylabel) - prog_reporter.report("Processing") - if spectra>1 and spectra<=10: + plt.ylabel(ylabel) + prog_reporter.report("Processing") + if spectra>1 and spectra<=10: plt.legend() - - + + mantid.api.AlgorithmFactory.subscribe(SavePlot1D) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py index 60751de32f8d..375ef4ef1c7e 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py @@ -9,126 +9,126 @@ class SofQWMoments(PythonAlgorithm): - def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" - - def summary (self): - return "Calculates the nth moment of y(q,w)" - - def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("Sample", "", Direction.Input), doc="Sample to use.") - self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') - self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') - self.declareProperty(name='Scale', defaultValue=1.0, doc='Scale factor to multiply y(Q,w). Default=1.0') - self.declareProperty(name='Verbose', defaultValue=False, doc='Switch Verbose Off/On') - self.declareProperty(name='Plot', defaultValue=False, doc='Switch Plot Off/On') - self.declareProperty(name='Save', defaultValue=False, doc='Switch Save result to nxs file Off/On') - - self.declareProperty(WorkspaceGroupProperty("OutputWorkspace", "", Direction.Output), doc="group_workspace workspace that includes all calculated moments.") - - def PyExec(self): - from IndirectCommon import CheckHistZero, CheckElimits, StartTime, EndTime, getDefaultWorkingDirectory - - sample_workspace = self.getPropertyValue('Sample') - output_workspace = self.getPropertyValue('OutputWorkspace') - factor = self.getProperty('Scale').value - emin = self.getProperty('EnergyMin').value - emax = self.getProperty('EnergyMax').value - erange = [emin, emax] - - Verbose = self.getProperty('Verbose').value - Plot = self.getProperty('Plot').value - Save = self.getProperty('Save').value - - StartTime('SofQWMoments') - num_spectra,num_w = CheckHistZero(sample_workspace) - - if Verbose: - text = 'Sample %s has %d Q values & %d w values' % (sample_workspace, num_spectra, num_w) - logger.notice(text) - - x = np.asarray(mtd[sample_workspace].readX(0)) - CheckElimits(erange,x) - - samWS = '__temp_sqw_moments_cropped' - CropWorkspace(InputWorkspace=sample_workspace, OutputWorkspace=samWS, XMin=erange[0], XMax=erange[1]) - - if Verbose: - logger.notice('Energy range is %f to %f' % (erange[0], erange[1])) - - if factor > 0.0: - Scale(InputWorkspace=samWS, OutputWorkspace=samWS, Factor=factor, Operation='Multiply') - if Verbose: - logger.notice('y(q,w) scaled by %f' % factor) - - #calculate delta x - ConvertToPointData(InputWorkspace=samWS, OutputWorkspace=samWS) - x = np.asarray(mtd[samWS].readX(0)) - x_workspace = CreateWorkspace(OutputWorkspace="__temp_sqw_moments_x", DataX=x, DataY=x, UnitX="DeltaE") - - #calculate moments - m0 = output_workspace + '_M0' - m1 = output_workspace + '_M1' - m2 = output_workspace + '_M2' - m3 = output_workspace + '_M3' - m4 = output_workspace + '_M4' - - Multiply(x_workspace, samWS, OutputWorkspace=m1) - Multiply(x_workspace, m1, OutputWorkspace=m2) - Multiply(x_workspace, m2, OutputWorkspace=m3) - Multiply(x_workspace, m3, OutputWorkspace=m4) - DeleteWorkspace(m3) - - ConvertToHistogram(InputWorkspace=samWS, OutputWorkspace=samWS) - Integration(samWS, OutputWorkspace=m0) - - moments = [m1, m2, m4] - for moment_ws in moments: - ConvertToHistogram(InputWorkspace=moment_ws, OutputWorkspace=moment_ws) - Integration(moment_ws, OutputWorkspace=moment_ws) - Divide(moment_ws, m0, OutputWorkspace=moment_ws) - - DeleteWorkspace(samWS) - DeleteWorkspace(x_workspace) - - #create output workspace - extensions = ['_M0', '_M1', '_M2', '_M4'] - for ext in extensions: - ws_name = output_workspace+ext - Transpose(InputWorkspace=ws_name, OutputWorkspace=ws_name) - ConvertToHistogram(InputWorkspace=ws_name, OutputWorkspace=ws_name) - ConvertUnits(InputWorkspace=ws_name, OutputWorkspace=ws_name, Target='MomentumTransfer', EMode='Indirect') - - CopyLogs(InputWorkspace=sample_workspace, OutputWorkspace=ws_name) - AddSampleLog(Workspace=ws_name, LogName="energy_min", LogType="Number", LogText=str(emin)) - AddSampleLog(Workspace=ws_name, LogName="energy_max", LogType="Number", LogText=str(emax)) - AddSampleLog(Workspace=ws_name, LogName="scale_factor", LogType="Number", LogText=str(factor)) - - #group ouput workspace - group_workspaces = ','.join([output_workspace+ext for ext in extensions]) - GroupWorkspaces(InputWorkspaces=group_workspaces,OutputWorkspace=output_workspace) - - if Save: - workdir = getDefaultWorkingDirectory() - opath = os.path.join(workdir,output_workspace+'.nxs') - SaveNexusProcessed(InputWorkspace=output_workspace, Filename=opath) - - if Verbose: - logger.notice('Output file : ' + opath) - - if Plot: - self._plot_moments(output_workspace) - - self.setProperty("OutputWorkspace", output_workspace) - - EndTime('SofQWMoments') + def category(self): + return "Workflow\\MIDAS;PythonAlgorithms" + + def summary (self): + return "Calculates the nth moment of y(q,w)" + + def PyInit(self): + self.declareProperty(MatrixWorkspaceProperty("Sample", "", Direction.Input), doc="Sample to use.") + self.declareProperty(name='EnergyMin', defaultValue=-0.5, doc='Minimum energy for fit. Default=-0.5') + self.declareProperty(name='EnergyMax', defaultValue=0.5, doc='Maximum energy for fit. Default=0.5') + self.declareProperty(name='Scale', defaultValue=1.0, doc='Scale factor to multiply y(Q,w). Default=1.0') + self.declareProperty(name='Verbose', defaultValue=False, doc='Switch Verbose Off/On') + self.declareProperty(name='Plot', defaultValue=False, doc='Switch Plot Off/On') + self.declareProperty(name='Save', defaultValue=False, doc='Switch Save result to nxs file Off/On') + + self.declareProperty(WorkspaceGroupProperty("OutputWorkspace", "", Direction.Output), doc="group_workspace workspace that includes all calculated moments.") + + def PyExec(self): + from IndirectCommon import CheckHistZero, CheckElimits, StartTime, EndTime, getDefaultWorkingDirectory + + sample_workspace = self.getPropertyValue('Sample') + output_workspace = self.getPropertyValue('OutputWorkspace') + factor = self.getProperty('Scale').value + emin = self.getProperty('EnergyMin').value + emax = self.getProperty('EnergyMax').value + erange = [emin, emax] + + Verbose = self.getProperty('Verbose').value + Plot = self.getProperty('Plot').value + Save = self.getProperty('Save').value + + StartTime('SofQWMoments') + num_spectra,num_w = CheckHistZero(sample_workspace) + + if Verbose: + text = 'Sample %s has %d Q values & %d w values' % (sample_workspace, num_spectra, num_w) + logger.notice(text) + + x = np.asarray(mtd[sample_workspace].readX(0)) + CheckElimits(erange,x) + + samWS = '__temp_sqw_moments_cropped' + CropWorkspace(InputWorkspace=sample_workspace, OutputWorkspace=samWS, XMin=erange[0], XMax=erange[1]) + + if Verbose: + logger.notice('Energy range is %f to %f' % (erange[0], erange[1])) + + if factor > 0.0: + Scale(InputWorkspace=samWS, OutputWorkspace=samWS, Factor=factor, Operation='Multiply') + if Verbose: + logger.notice('y(q,w) scaled by %f' % factor) + + #calculate delta x + ConvertToPointData(InputWorkspace=samWS, OutputWorkspace=samWS) + x = np.asarray(mtd[samWS].readX(0)) + x_workspace = CreateWorkspace(OutputWorkspace="__temp_sqw_moments_x", DataX=x, DataY=x, UnitX="DeltaE") + + #calculate moments + m0 = output_workspace + '_M0' + m1 = output_workspace + '_M1' + m2 = output_workspace + '_M2' + m3 = output_workspace + '_M3' + m4 = output_workspace + '_M4' + + Multiply(x_workspace, samWS, OutputWorkspace=m1) + Multiply(x_workspace, m1, OutputWorkspace=m2) + Multiply(x_workspace, m2, OutputWorkspace=m3) + Multiply(x_workspace, m3, OutputWorkspace=m4) + DeleteWorkspace(m3) + + ConvertToHistogram(InputWorkspace=samWS, OutputWorkspace=samWS) + Integration(samWS, OutputWorkspace=m0) + + moments = [m1, m2, m4] + for moment_ws in moments: + ConvertToHistogram(InputWorkspace=moment_ws, OutputWorkspace=moment_ws) + Integration(moment_ws, OutputWorkspace=moment_ws) + Divide(moment_ws, m0, OutputWorkspace=moment_ws) + + DeleteWorkspace(samWS) + DeleteWorkspace(x_workspace) + + #create output workspace + extensions = ['_M0', '_M1', '_M2', '_M4'] + for ext in extensions: + ws_name = output_workspace+ext + Transpose(InputWorkspace=ws_name, OutputWorkspace=ws_name) + ConvertToHistogram(InputWorkspace=ws_name, OutputWorkspace=ws_name) + ConvertUnits(InputWorkspace=ws_name, OutputWorkspace=ws_name, Target='MomentumTransfer', EMode='Indirect') + + CopyLogs(InputWorkspace=sample_workspace, OutputWorkspace=ws_name) + AddSampleLog(Workspace=ws_name, LogName="energy_min", LogType="Number", LogText=str(emin)) + AddSampleLog(Workspace=ws_name, LogName="energy_max", LogType="Number", LogText=str(emax)) + AddSampleLog(Workspace=ws_name, LogName="scale_factor", LogType="Number", LogText=str(factor)) + + #group ouput workspace + group_workspaces = ','.join([output_workspace+ext for ext in extensions]) + GroupWorkspaces(InputWorkspaces=group_workspaces,OutputWorkspace=output_workspace) + + if Save: + workdir = getDefaultWorkingDirectory() + opath = os.path.join(workdir,output_workspace+'.nxs') + SaveNexusProcessed(InputWorkspace=output_workspace, Filename=opath) + + if Verbose: + logger.notice('Output file : ' + opath) + + if Plot: + self._plot_moments(output_workspace) + + self.setProperty("OutputWorkspace", output_workspace) + + EndTime('SofQWMoments') - def _plot_moments(self, inputWS): - from IndirectImport import import_mantidplot - mp = import_mantidplot() - - mp.plotSpectrum(inputWS+'_M0',0) - mp.plotSpectrum([inputWS+'_M2',inputWS+'_M4'],0) + def _plot_moments(self, inputWS): + from IndirectImport import import_mantidplot + mp = import_mantidplot() + + mp.plotSpectrum(inputWS+'_M0',0) + mp.plotSpectrum([inputWS+'_M2',inputWS+'_M4'],0) # Register algorithm with Mantid AlgorithmFactory.subscribe(SofQWMoments) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Symmetrise.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Symmetrise.py index 9d794de0ac13..48b929de4f78 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Symmetrise.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/Symmetrise.py @@ -3,38 +3,38 @@ from mantid.kernel import StringListValidator, StringMandatoryValidator class Symmetrise(PythonAlgorithm): - - def category(self): - return "Workflow\\MIDAS;PythonAlgorithms" - - def summary (self): - return "Takes and asymmetric S(Q,w) and makes it symmetric" - - def PyInit(self): - self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (_red.nxs) or Workspace') - self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') - self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection') - self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') - self.declareProperty(name='Xcut',defaultValue='',validator=StringMandatoryValidator(), doc='X cutoff value') - self.declareProperty('Verbose',defaultValue=True, doc='Switch Verbose Off/On') - self.declareProperty('Plot',defaultValue=True, doc='Switch Plot Off/On') - self.declareProperty('Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') - - def PyExec(self): - - self.log().information('Symmetrise') - inType = self.getPropertyValue('InputType') - prefix = self.getPropertyValue('Instrument') - ana = self.getPropertyValue('Analyser') - sn = self.getPropertyValue('SamNumber') - sam = prefix+sn+'_'+ana+'_red' - cut = self.getPropertyValue('Xcut') - cut = float(cut) - - verbOp = self.getProperty('Verbose').value - plotOp = self.getProperty('Plot').value - saveOp = self.getProperty('Save').value + + def category(self): + return "Workflow\\MIDAS;PythonAlgorithms" + + def summary (self): + return "Takes and asymmetric S(Q,w) and makes it symmetric" + + def PyInit(self): + self.declareProperty(name='InputType',defaultValue='File',validator=StringListValidator(['File','Workspace']), doc='Origin of data input - File (_red.nxs) or Workspace') + self.declareProperty(name='Instrument',defaultValue='iris',validator=StringListValidator(['irs','iris','osi','osiris']), doc='Instrument') + self.declareProperty(name='Analyser',defaultValue='graphite002',validator=StringListValidator(['graphite002','graphite004']), doc='Analyser & reflection') + self.declareProperty(name='SamNumber',defaultValue='',validator=StringMandatoryValidator(), doc='Sample run number') + self.declareProperty(name='Xcut',defaultValue='',validator=StringMandatoryValidator(), doc='X cutoff value') + self.declareProperty('Verbose',defaultValue=True, doc='Switch Verbose Off/On') + self.declareProperty('Plot',defaultValue=True, doc='Switch Plot Off/On') + self.declareProperty('Save',defaultValue=False, doc='Switch Save result to nxs file Off/On') + + def PyExec(self): + + self.log().information('Symmetrise') + inType = self.getPropertyValue('InputType') + prefix = self.getPropertyValue('Instrument') + ana = self.getPropertyValue('Analyser') + sn = self.getPropertyValue('SamNumber') + sam = prefix+sn+'_'+ana+'_red' + cut = self.getPropertyValue('Xcut') + cut = float(cut) + + verbOp = self.getProperty('Verbose').value + plotOp = self.getProperty('Plot').value + saveOp = self.getProperty('Save').value import IndirectSymm as Main - Main.SymmStart(inType,sam,cut,verbOp,plotOp,saveOp) + Main.SymmStart(inType,sam,cut,verbOp,plotOp,saveOp) AlgorithmFactory.subscribe(Symmetrise) # Register algorithm with Mantid diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py index 3339a2421530..ce4a8202ae0c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py @@ -28,7 +28,7 @@ def _execute(algorithm_str, parameters, is_name=True): Logger("TransmissionUtils").error("Error executing [%s]" % str(alg)) Logger("TransmissionUtils").error(str(sys.exc_value)) return alg - + def load_monitors(self, property_manager): """ Load files necessary to compute transmission. @@ -43,8 +43,8 @@ def load_monitors(self, property_manager): beam_center_y_input = self.getProperty("BeamCenterY").value if beam_center_x_input > 0 and beam_center_y_input > 0: beam_center_x = beam_center_x_input - beam_center_y = beam_center_y_input - + beam_center_y = beam_center_y_input + # Get instrument to use with FileFinder instrument = '' if property_manager.existsProperty("InstrumentName"): @@ -56,7 +56,7 @@ def _load_data(filename, output_ws): Logger("SANSDirectBeamTransmission").error("SANS reduction not set up properly: missing load algorithm") raise RuntimeError, "SANS reduction not set up properly: missing load algorithm" p=property_manager.getProperty("LoadAlgorithm") - + alg_props = {"Filename": filename, "OutputWorkspace": output_ws, "ReductionProperties": property_manager_name, @@ -64,14 +64,14 @@ def _load_data(filename, output_ws): if beam_center_x is not None and beam_center_y is not None: alg_props["BeamCenterX"] = beam_center_x alg_props["BeamCenterY"] = beam_center_y - + alg = _execute(p.valueAsStr, alg_props, is_name=False) - + msg = 'Loaded %s\n' % filename if alg.existsProperty("OutputMessage"): msg += alg.getProperty("OutputMessage").value ws = alg.getProperty("OutputWorkspace").value - + return ws, msg.replace('\n', '\n|') # Load the data files @@ -81,21 +81,21 @@ def _load_data(filename, output_ws): sample_ws_name = "__transmission_sample" sample_ws, l_text = _load_data(sample_file, sample_ws_name) tmp_str = " Sample: %s\n%s\n" % (os.path.basename(sample_file), l_text) - output_str += tmp_str.replace('\n', '\n ') - + output_str += tmp_str.replace('\n', '\n ') + sample_ws, l_text = subtract_dark_current(self, sample_ws, property_manager) if len(l_text)>0: output_str += l_text.replace('\n', '\n ')+'\n' - + empty_ws_name = "__transmission_empty" empty_ws, l_text = _load_data(empty_file, empty_ws_name) tmp_str = " Empty: %s\n%s\n" % (os.path.basename(empty_file), l_text) output_str += tmp_str.replace('\n', '\n ') - + empty_ws, l_text = subtract_dark_current(self, empty_ws, property_manager) if len(l_text)>0: output_str += l_text.replace('\n', '\n ')+'\n' - + # Find which pixels to sum up as our "monitor". At this point we have moved the detector # so that the beam is at (0,0), so all we need is to sum the area around that point. #TODO: in IGOR, the error-weighted average is computed instead of simply summing up the pixels @@ -106,7 +106,7 @@ def _load_data(filename, output_ws): '' + \ '' % (beam_radius*pixel_size_x/1000.0) + \ '\n' - + # Use the transmission workspaces to find the list of monitor pixels # since the beam center may be at a different location alg = _execute("FindDetectorsInShape", @@ -117,7 +117,7 @@ def _load_data(filename, output_ws): first_det = det_list[0] #TODO: check that both workspaces have the same masked spectra - + # Get normalization for transmission calculation monitor_det_ID = None if property_manager.existsProperty("TransmissionNormalisation"): @@ -143,7 +143,7 @@ def _normalise(workspace): output_str += " %s\n" % norm_msg.replace('\n', ' \n') sample_ws, norm_msg = _normalise(sample_ws) output_str += " %s\n" % norm_msg.replace('\n', ' \n') - + empty_mon_ws_name = "__empty_mon" sample_mon_ws_name = "__sample_mon" @@ -170,7 +170,7 @@ def _normalise(workspace): {"WorkspaceToRebin": sample_ws, "WorkspaceToMatch": reference_ws, "OutputWorkspace": sample_ws_name - }) + }) sample_ws = alg.getProperty("OutputWorkspace").value alg = _execute("GroupDetectors", @@ -180,7 +180,7 @@ def _normalise(workspace): "KeepUngroupedSpectra": True }) empty_mon_ws = alg.getProperty("OutputWorkspace").value - + alg = _execute("GroupDetectors", {"InputWorkspace": sample_ws, "OutputWorkspace": sample_mon_ws_name, @@ -188,19 +188,19 @@ def _normalise(workspace): "KeepUngroupedSpectra": True }) sample_mon_ws = alg.getProperty("OutputWorkspace").value - + alg = _execute("ConvertToMatrixWorkspace", {"InputWorkspace": empty_mon_ws, "OutputWorkspace": empty_mon_ws_name }) empty_mon_ws = alg.getProperty("OutputWorkspace").value - + alg = _execute("ConvertToMatrixWorkspace", {"InputWorkspace": sample_mon_ws, "OutputWorkspace": sample_mon_ws_name }) sample_mon_ws = alg.getProperty("OutputWorkspace").value - + alg = _execute("RebinToWorkspace", {"WorkspaceToRebin": empty_mon_ws, "WorkspaceToMatch": sample_mon_ws, @@ -209,14 +209,14 @@ def _normalise(workspace): empty_mon_ws = alg.getProperty("OutputWorkspace").value return sample_mon_ws, empty_mon_ws, first_det, output_str, monitor_det_ID - -def calculate_transmission(self, sample_mon_ws, empty_mon_ws, first_det, + +def calculate_transmission(self, sample_mon_ws, empty_mon_ws, first_det, trans_output_workspace, monitor_det_ID=None): """ Compute zero-angle transmission. - + Returns the fitted transmission workspace as well as the raw transmission workspace. - + @param sample_mon_ws: name of the sample monitor workspace @param empty_mon_ws: name of the empty monitor workspace @param first_det: ID of the first detector, so we know where to find the summed counts @@ -251,7 +251,7 @@ def calculate_transmission(self, sample_mon_ws, empty_mon_ws, first_det, except: Logger("TransmissionUtils").error("Couldn't compute transmission. Is the beam center in the right place?\n%s" % sys.exc_value) return None, None - + def apply_transmission(self, workspace, trans_workspace): """ Apply transmission correction @@ -261,7 +261,7 @@ def apply_transmission(self, workspace, trans_workspace): # Sanity check if workspace is None: return None - + # Make sure the binning is compatible alg = _execute("RebinToWorkspace", {"WorkspaceToRebin": trans_workspace, @@ -273,7 +273,7 @@ def apply_transmission(self, workspace, trans_workspace): # Apply angle-dependent transmission correction using the zero-angle transmission theta_dependent = self.getProperty("ThetaDependent").value - + alg = _execute("ApplyTransmissionCorrection", {"InputWorkspace": workspace, "TransmissionWorkspace": rebinned_ws, @@ -282,12 +282,12 @@ def apply_transmission(self, workspace, trans_workspace): }) output_ws = alg.getProperty("OutputWorkspace").value return output_ws - + def subtract_dark_current(self, workspace, property_manager): """ Subtract the dark current @param workspace: workspace object to subtract from - @param property_manager: property manager object + @param property_manager: property manager object """ # Subtract dark current use_sample_dc = self.getProperty("UseSampleDarkCurrent").value @@ -297,19 +297,19 @@ def subtract_dark_current(self, workspace, property_manager): 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): p=property_manager.getProperty(dark_current_property) - + alg_props = {"InputWorkspace": ws, "PersistentCorrection": False, "ReductionProperties": property_manager_name } if dark_current_file is not None: alg_props["Filename"] = dark_current_file - + alg = _execute(p.valueAsStr, alg_props, is_name=False) msg = "Dark current subtracted" if alg.existsProperty("OutputMessage"): @@ -320,7 +320,7 @@ def _dark(ws, dark_current_property, dark_current_file=None): if len(dark_current_data.strip())>0: return _dark(workspace, "DefaultDarkCurrentAlgorithm", - dark_current_file=dark_current_data) + dark_current_file=dark_current_data) elif use_sample_dc is True: return _dark(workspace, "DarkCurrentAlgorithm") return workspace, "" diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py index aabff3c3d6b3..5bbf242df339 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py @@ -26,9 +26,9 @@ def PyInit(self): self.declareProperty("EmptyRun", '', "Run number for the empty run") #TODO: Mask workspace - + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), "Output workspace") - + class DataFile(object): def __init__(self, workspace, monitor, empty, empty_monitor, is_scan=False, max_index=1): self.workspace = workspace @@ -37,7 +37,7 @@ def __init__(self, workspace, monitor, empty, empty_monitor, is_scan=False, max_ self.empty_monitor = empty_monitor self.is_scan = is_scan self.max_index = max_index - + def _find_monitors(self, run): """ Find a monitor file for testing purposes. @@ -50,10 +50,10 @@ def _find_monitors(self, run): else: Logger("USANSReduction").error("Could not find monitors for run %s" % run) return None - + def _load_data(self): """ - Load data and go through each file to determine how many points + Load data and go through each file to determine how many points will have to be dealt with. """ # Load the empty run @@ -62,18 +62,18 @@ def _load_data(self): # A simple Load doesn't load the instrument properties correctly with our test file # Reload the instrument for now LoadInstrument(Workspace='__empty', InstrumentName='USANS', RewriteSpectraMap=False) - + # For testing, we may have to load the monitors by hand if not mtd.doesExist('__empty_monitors'): Load(Filename=self._find_monitors(empty_run), OutputWorkspace='__empty_monitors') - + # Get the wavelength peak positions wl_cfg_str = mtd['__empty'].getInstrument().getStringParameter("wavelength_config")[0] self.wl_list = json.loads(wl_cfg_str) # Get the runs to reduce run_list = self.getProperty("RunNumbers").value - + # Total number of measurements per wavelength peak total_points = 0 # Load all files so we can determine how many points we have @@ -81,11 +81,11 @@ def _load_data(self): for item in run_list: ws_name = '__sample_%s' % item Load(Filename='USANS_%s' % item, LoadMonitors=True, OutputWorkspace=ws_name) - + # For testing, we may have to load the monitors by hand if not mtd.doesExist(ws_name+'_monitors'): Load(Filename=self._find_monitors(empty_run), OutputWorkspace=ws_name+'_monitors') - + # Determine whether we are putting together multiple files or whether # we will be looking for scan_index markers. is_scan = False @@ -97,7 +97,7 @@ def _load_data(self): if _max_index>0: max_index = _max_index is_scan = True - + # Append the info for when we do the reduction self.data_files.append(self.DataFile(workspace=ws_name, monitor=ws_name+'_monitors', @@ -106,9 +106,9 @@ def _load_data(self): is_scan=is_scan, max_index=max_index)) total_points += max_index - + return total_points - + def _process_data_file(self, file_info, index_offset): # Go through each point for point in range(file_info.max_index): @@ -121,19 +121,19 @@ def _process_data_file(self, file_info, index_offset): LogBoundary='Left') else: ws = mtd[file_info.workspace] - + # Get the two-theta value for this point if ws.getRun().getProperty("two_theta").type=='number': two_theta = ws.getRun().getProperty("two_theta").value else: two_theta = ws.getRun().getProperty("two_theta").timeAverageValue() - + # Loop through the wavelength peaks for this point for i_wl in range(len(self.wl_list)): wl = self.wl_list[i_wl]['wavelength'] # Note: TOF value is given by tof = 30.0/0.0039560*wl q = 6.28*math.sin(two_theta)/wl - + # Get I(q) for each wavelength peak i_q = self._get_intensity(mtd[file_info.workspace], mtd[file_info.empty], @@ -141,7 +141,7 @@ def _process_data_file(self, file_info, index_offset): mtd[file_info.empty_monitor], tof_min=self.wl_list[i_wl]['t_min'], tof_max=self.wl_list[i_wl]['t_max']) - # Store the reduced data + # Store the reduced data try: self.q_output[i_wl][point+index_offset] = q self.iq_output[i_wl][point+index_offset] = i_q.dataY(0)[0] @@ -151,11 +151,11 @@ def _process_data_file(self, file_info, index_offset): Logger("USANSReduction").error("Array: %s x %s Data: %s" % (len(self.wl_list), self.total_points, file_info.max_index)) Logger("USANSReduction").error(sys.exc_value) return file_info.max_index - + def PyExec(self): # Placeholder for the data file information self.data_files = [] - + # Total number of measurements per wavelength peak self.total_points = self._load_data() @@ -165,11 +165,11 @@ def PyExec(self): self.q_output = numpy.zeros(shape=(n_wl, self.total_points)) self.iq_output = numpy.zeros(shape=(n_wl, self.total_points)) self.iq_err_output = numpy.zeros(shape=(n_wl, self.total_points)) - + index_offset = 0 for item in self.data_files: index_offset += self._process_data_file(item, index_offset) - + # Create a workspace for each peak self._aggregate() @@ -193,12 +193,12 @@ def compare(p1,p2): x = self.q_output[i_wl] y = self.iq_output[i_wl] e = self.iq_err_output[i_wl] - + # Sort the I(q) point just in case we got them in the wrong order zipped = zip(x,y,e) combined = sorted(zipped, compare) x,y,e = zip(*combined) - + wl = self.wl_list[i_wl]['wavelength'] CreateWorkspace(DataX=x, DataY=y, @@ -210,7 +210,7 @@ def compare(p1,p2): zipped = zip(x_all,y_all,e_all) combined = sorted(zipped, compare) x,y,e = zip(*combined) - + # Create the combined output workspace output_ws_name = self.getPropertyValue("OutputWorkspace") out_ws = CreateWorkspace(DataX=x, @@ -223,9 +223,9 @@ def compare(p1,p2): def _get_intensity(self, sample, empty, sample_monitor, empty_monitor, tof_min, tof_max): # Number of pixels we are dealing with nspecs = sample.getNumberHistograms() - + # Apply mask - + # Get the normalized empty run counts in the transmission detector __empty_summed = _execute('SumSpectra', InputWorkspace=str(empty), StartWorkspaceIndex=nspecs/2, EndWorkspaceIndex=nspecs-1, @@ -240,7 +240,7 @@ def _get_intensity(self, sample, empty, sample_monitor, empty_monitor, tof_min, OutputWorkspace='__point') __empty_monitor_count = _execute('Integration', InputWorkspace=__point, OutputWorkspace='__empty_monitor_count') - + __normalized_empty = _execute('Divide', LHSWorkspace=__empty_count, RHSWorkspace=__empty_monitor_count, OutputWorkspace='__normalized_empty') @@ -264,12 +264,12 @@ def _get_intensity(self, sample, empty, sample_monitor, empty_monitor, tof_min, # The monitor count normalization cancels out when doing the transmission correction # of the scattering signal below __normalized_sample_trans = __trans_count#/__monitor_count - + # Transmission workspace transmission = _execute('Divide', LHSWorkspace=__normalized_sample_trans, RHSWorkspace=__normalized_empty, OutputWorkspace='transmission') - + # Scattering signal __signal_summed = _execute('SumSpectra', InputWorkspace=sample, StartWorkspaceIndex=0, @@ -282,12 +282,12 @@ def _get_intensity(self, sample, empty, sample_monitor, empty_monitor, tof_min, OutputWorkspace='__signal_count') # The monitor count normalization cancels out when doing the transmission correction __signal = __signal_count#/__monitor_count - - intensity = _execute('Divide', LHSWorkspace=__signal, + + intensity = _execute('Divide', LHSWorkspace=__signal, RHSWorkspace=transmission, OutputWorkspace='intensity') return intensity - + def _execute(algorithm_name, **parameters): alg = AlgorithmManager.create(algorithm_name) alg.initialize() diff --git a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py index 3559a9a66507..e36963c10314 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/algorithms/sfCalculator.py @@ -8,30 +8,30 @@ PRECISION = 0.020 -class sfCalculator(): +class sfCalculator(): INDEX = 0 tof_min = None #microS tof_max = None #microS - #range of x pixel to use in the X integration (we found out that there + #range of x pixel to use in the X integration (we found out that there #is a frame effect that introduces noise) - x_pixel_min = 0 #default is 90 + x_pixel_min = 0 #default is 90 x_pixel_max = 255 #default is 190 (must be below 256) #from,width,to in microS #rebin_parameters = '0,50,200000' - rebin_parameters = '0,50,100000' + rebin_parameters = '0,50,100000' #turn on or off the plots bPlot = False bFittingPlot = False - + #size of detector - alpha_pixel_nbr = 256 + alpha_pixel_nbr = 256 beta_pixel_nbr = 304 #will be integrated over this dimension - + #name of numerators and denominators numerator = None #ex: AiD0 denominator = None #ex: AiD1 @@ -40,9 +40,9 @@ class sfCalculator(): y_axis_error_numerator = None y_axis_denominator = None y_axis_error_denominator = None - x_axis = None - - #define the peak region + x_axis = None + + #define the peak region n_peak_pixel_min = 130 n_peak_pixel_max = 135 d_peak_pixel_min = 130 @@ -62,30 +62,30 @@ class sfCalculator(): y_axis_ratio = None y_axis_error_ratio = None x_axis_ratio = None - + def __init__(self, numerator=None, denominator=None, tof_range=None): - + print '---> initialize calculation' - + if (tof_range is None): self.tof_min = 10000 self.tof_max = 21600 else: self.tof_min = tof_range[0] self.tof_max = tof_range[1] - + self.numerator = numerator self.denominator = denominator self.x_axis_ratio = None self.y_axis_error_ratio = None self.y_axis_ratio = None - + def setNumerator(self, minPeak, maxPeak, minBack, maxBack): print '---> set numerator (' + self.numerator + ')' - + if minPeak != 0: self.n_peak_pixel_min = minPeak if maxPeak != 0 : @@ -94,7 +94,7 @@ def setNumerator(self, minPeak, maxPeak, minBack, maxBack): self.n_back_pixel_min = minBack if maxBack != 0: self.n_back_pixel_max = maxBack - + def setDenominator(self, minPeak, maxPeak, minBack, maxBack): print '---> set denominator (' + self.denominator + ')' @@ -107,100 +107,100 @@ def setDenominator(self, minPeak, maxPeak, minBack, maxBack): self.d_back_pixel_min = minBack if maxBack != 0: self.d_back_pixel_max = maxBack - + def run(self): """ Perform the calculation """ - + #perform calculation for numerator self._calculateFinalYAxis(bNumerator=True) # #DEBUGGING -# +# # #output the data to fit to DEBUG # x_axis = self.x_axis_ratio # y_axis = self.y_axis_numerator # y_error_axis = self.y_axis_error_numerator -# +# # print 'create sfOutputTest#' # filename = "/SNS/users/j35/sfOutputTest#%d.txt" % sfCalculator.INDEX # # filename = "/home/j35/Desktop/sfOutputTest#%d.txt" % sfCalculator.INDEX # print filename # sfCalculator.INDEX += 1 -# +# # f=open(filename,'w') -# +# # for i in range(len(x_axis)): # f.write(str(x_axis[i]) + "," + str(y_axis[i]) + "," + str(y_error_axis[i]) + "\n"); -# +# # f.close #END of DEBUGGING - + #perform calculation for denominator self._calculateFinalYAxis(bNumerator=False) # #DEBUGGING -# +# # #output the data to fit to DEBUG # x_axis = self.x_axis_ratio # y_axis = self.y_axis_denominator # y_error_axis = self.y_axis_error_denominator -# +# # print 'create sfOutputTest#' # filename = "/SNS/users/j35/sfOutputTest#%d.txt" % sfCalculator.INDEX # # filename = "/home/j35/Desktop/sfOutputTest#%d.txt" % sfCalculator.INDEX # print filename # sfCalculator.INDEX += 1 -# +# # f=open(filename,'w') -# +# # for i in range(len(x_axis)): # f.write(str(x_axis[i]) + "," + str(y_axis[i]) + "," + str(y_error_axis[i]) + "\n"); -# +# # f.close # #END of DEBUGGING - + #calculate y_axis of numerator/denominator # self._x_axis_ratio = self._x_axis - + ## code to replace this #self.y_axis_ratio = self.y_axis_numerator / self.y_axis_denominator sz = size(self.y_axis_numerator) new_y_axis_ratio = zeros(sz) for i in range(sz): - + if self.y_axis_denominator[i] == 0: self.y_axis_denominator[i] = 1 - + # print i # print self.y_axis_numerator[i] # print self.y_axis_denominator[i] # print - + new_y_axis_ratio[i] = float(self.y_axis_numerator[i]) / float(self.y_axis_denominator[i]) self.y_axis_ratio = new_y_axis_ratio - + ## code to replace this -# self.y_axis_error_ratio = ((self.y_axis_error_numerator / -# self.y_axis_numerator) ** 2 + -# (self.y_axis_error_denominator / +# self.y_axis_error_ratio = ((self.y_axis_error_numerator / +# self.y_axis_numerator) ** 2 + +# (self.y_axis_error_denominator / # self.y_axis_denominator) ** 2) # self.y_axis_error_ratio = sqrt(self.y_axis_error_ratio) # self.y_axis_error_ratio *= self.y_axis_ratio new_y_axis_error_ratio = zeros(sz) for i in range(sz): - + if self.y_axis_numerator[i] == 0: self.y_axis_numerator[i] = 1 - + tmp_value = (float(self.y_axis_error_numerator[i]) / float(self.y_axis_numerator[i])) **2 + (float(self.y_axis_error_denominator[i]) / float(self.y_axis_denominator[i])) **2 tmp_value = math.sqrt(tmp_value) new_y_axis_error_ratio[i] = self.y_axis_ratio[i]* tmp_value - self.y_axis_error_ratio = new_y_axis_error_ratio - + self.y_axis_error_ratio = new_y_axis_error_ratio + def _calculateFinalYAxis(self, bNumerator=True): """ run full calculation for numerator or denominator @@ -219,13 +219,13 @@ def _calculateFinalYAxis(self, bNumerator=True): self.peak_pixel_max = self.d_peak_pixel_max self.back_pixel_min = self.d_back_pixel_min self.back_pixel_max = self.d_back_pixel_max - + nexus_file_numerator = file print '----> loading nexus file: ' + nexus_file_numerator EventDataWks = LoadEventNexus(Filename=nexus_file_numerator) # OutputWorkspace='EventDataWks') # mt1 = mtd['EventDataWks'] - + proton_charge = self._getProtonCharge(EventDataWks) print '----> rebinning ' HistoDataWks = Rebin(InputWorkspace=EventDataWks, @@ -247,65 +247,65 @@ def _calculateFinalYAxis(self, bNumerator=True): to_peak=self.peak_pixel_max, from_back=self.back_pixel_min, to_back=self.back_pixel_max, - tof_min = self.tof_min, + tof_min = self.tof_min, tof_max = self.tof_max) - + # print '----> Convert to histogram' # IntegratedDataWks = ConvertToHistogram(InputWorkspace=OutputWorkspace) -# +# # print '----> Transpose' # TransposeIntegratedDataWks = Transpose(InputWorkspace=IntegratedDataWks) -# +# # print '----> convert to histogram' # TransposeIntegratedDataWks_t = ConvertToHistogram(InputWorkspace=TransposeIntegratedDataWks) -# +# # print '----> flat background1' # TransposeHistoFlatDataWks_1 = FlatBackground(InputWorkspace=TransposeIntegratedDataWks_t, # StartX=self.back_pixel_min, # EndX=self.peak_pixel_min, # Mode='Mean', # OutputMode="Return Background") -# +# # print '----> flat background2' # TransposeHistoFlatDataWks_2 = FlatBackground(InputWorkspace=TransposeIntegratedDataWks_t, # StartX=self.peak_pixel_max, # EndX=self.back_pixel_max, # Mode='Mean', # OutputMode="Return Background") -# +# # print '----> transpose flat background 1 -> data1' # DataWks_1 = Transpose(InputWorkspace=TransposeHistoFlatDataWks_1); -# +# # print '----> transpose flat background 2 -> data2' # DataWks_2 = Transpose(InputWorkspace=TransposeHistoFlatDataWks_2); -# +# # print '----> convert to histogram data2' # DataWks_1 = ConvertToHistogram(InputWorkspace=DataWks_1); -# +# # print '----> convert to histogram data1' # DataWks_2 = ConvertToHistogram(InputWorkspace=DataWks_2) -# +# # print '----> rebin workspace data1' # DataWks_1 = RebinToWorkspace(WorkspaceToRebin=DataWks_1, # WorkspacetoMatch=IntegratedDataWks) -# +# # print '----> rebin workspace data2' # DataWks_2 = RebinToWorkspace(WorkspaceToRebin=DataWks_2, # WorkspacetoMatch=IntegratedDataWks) -# +# # print '----> weighted mean' # DataWksWeightedMean = WeightedMean(InputWorkspace1=DataWks_1, # InputWorkspace2=DataWks_2) -# +# # print '----> minus' -# DataWks = Minus(LHSWorkspace=IntegratedDataWks, +# DataWks = Minus(LHSWorkspace=IntegratedDataWks, # RHSWorkspace=DataWksWeightedMean) - + # if not bNumerator: # import sys # sys.exit("now we are working with denominator") - - + + # mt3 = mtd['DataWks'] self._calculateFinalAxis(Workspace=DataWks, bNumerator=bNumerator) @@ -320,46 +320,46 @@ def _calculateFinalYAxis(self, bNumerator=True): # DeleteWorkspace(TransposeHistoFlatDataWks_1) # DeleteWorkspace(TransposeHistoFlatDataWks_2) DeleteWorkspace(DataWks) - + print 'done with cleaning workspaces in line 247' - + def _calculateFinalAxis(self, Workspace=None, bNumerator=None): """ - this calculates the final y_axis and y_axis_error of numerator + this calculates the final y_axis and y_axis_error of numerator and denominator """ - + print '----> calculate final axis' mt = Workspace x_axis = mt.readX(0)[:] self.x_axis = x_axis - + counts_vs_tof = mt.readY(0)[:] counts_vs_tof_error = mt.readE(0)[:] ## this is not use anymore as the integration is done in the previous step # counts_vs_tof = zeros(len(x_axis)-1) # counts_vs_tof_error = zeros(len(x_axis)-1) -# +# # for x in range(self.alpha_pixel_nbr): # counts_vs_tof += mt.readY(x)[:] # counts_vs_tof_error += mt.readE(x)[:] ** 2 # counts_vs_tof_error = sqrt(counts_vs_tof_error) -# +# # #for DEBUGGING # #output data into ascii file # f=open('/home/j35/Desktop/myASCII.txt','w') # if (not bNumerator): # f.write(self.denominator + "\n") -# +# # for i in range(len(counts_vs_tof)): # f.write(str(x_axis[i]) + "," + str(counts_vs_tof[i]) + "\n") # f.close # import sys # sys.exit("Stop in _calculateFinalAxis") ## end of for DEBUGGING #so far, so good ! - + index_tof_min = self._getIndex(self.tof_min, x_axis) index_tof_max = self._getIndex(self.tof_max, x_axis) @@ -373,9 +373,9 @@ def _calculateFinalAxis(self, Workspace=None, bNumerator=None): self.x_axis_ratio = self.x_axis[index_tof_min:index_tof_max].copy() print 'done with _calculateFinalAxis' - - - + + + def _createIntegratedWorkspace(self, InputWorkspace=None, OutputWorkspace=None, @@ -383,26 +383,26 @@ def _createIntegratedWorkspace(self, from_pixel=0, to_pixel=255): """ - This creates the integrated workspace over the second pixel range + This creates the integrated workspace over the second pixel range (beta_pixel_nbr here) and returns the new workspace handle """ print '-----> Create Integrated workspace ' x_axis = InputWorkspace.readX(0)[:] - x_size = to_pixel - from_pixel + 1 + x_size = to_pixel - from_pixel + 1 y_axis = zeros((self.alpha_pixel_nbr, len(x_axis) - 1)) y_error_axis = zeros((self.alpha_pixel_nbr, len(x_axis) - 1)) y_range = arange(x_size) + from_pixel - + # for x in range(self.beta_pixel_nbr): # for y in y_range: # index = int(self.alpha_pixel_nbr * x + y) ## y_axis[y, :] += InputWorkspace.readY(index)[:] # y_axis[y, :] += InputWorkspace.readY(index)[:] -# y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * +# y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * # (InputWorkspace.readE(index)[:])) - + #case 1 print 'using case 1' for x in range(304): @@ -410,7 +410,7 @@ def _createIntegratedWorkspace(self, index = int(y+x*256) # y_axis[y, :] += InputWorkspace.readY(index)[:] y_axis[y, :] += InputWorkspace.readY(index)[:] - y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * + y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * (InputWorkspace.readE(index)[:])) ## case 2 @@ -419,7 +419,7 @@ def _createIntegratedWorkspace(self, # index = int(x+y*304) ## y_axis[y, :] += InputWorkspace.readY(index)[:] # y_axis[y, :] += InputWorkspace.readY(index)[:] -# y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * +# y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * # (InputWorkspace.readE(index)[:])) @@ -428,83 +428,83 @@ def _createIntegratedWorkspace(self, # index = int(self.beta_pixel_nbr * x + y) ## y_axis[y, :] += InputWorkspace.readY(index)[:] # y_axis[y, :] += InputWorkspace.readY(index)[:] -# y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * +# y_error_axis[y, :] += ((InputWorkspace.readE(index)[:]) * # (InputWorkspace.readE(index)[:])) - + # #DEBUG # f=open('/home/j35/myASCIIfromCode.txt','w') # new_y_axis = zeros((len(x_axis)-1)) # # for y in range(256): # new_y_axis += y_axis[y,:] -# +# # for i in range(len(x_axis)-1): # f.write(str(x_axis[i]) + "," + str(new_y_axis[i]) + "\n"); # f.close # # print sum(new_y_axis) -# +# # #END OF DEBUG ## so far, worsk perfectly (tested with portal vs Mantid vs Matlab y_axis = y_axis.flatten() y_error_axis = sqrt(y_error_axis) - #plot_y_error_axis = _y_error_axis #for output testing only + #plot_y_error_axis = _y_error_axis #for output testing only #plt.imshow(plot_y_error_axis, aspect='auto', origin='lower') y_error_axis = y_error_axis.flatten() #normalization by proton beam y_axis /= (proton_charge * 1e-12) y_error_axis /= (proton_charge * 1e-12) - + OutputWorkspace = CreateWorkspace(DataX=x_axis, DataY=y_axis, DataE=y_error_axis, Nspec=self.alpha_pixel_nbr) - return OutputWorkspace + return OutputWorkspace def weighted_mean(self, data, error): - + sz = len(data) - + #calculate numerator dataNum = 0 for i in range(sz): if (data[i] != 0): tmpFactor = float(data[i]) / (error[i]**2) dataNum += tmpFactor - + #calculate denominator dataDen = 0 for i in range(sz): if (error[i] != 0): tmpFactor = float(1) / (error[i]**2) dataDen += tmpFactor - + if dataDen == 0: dataDen = 1 mean = dataNum / dataDen mean_error = math.sqrt(dataDen) - + return (mean, mean_error) def removeValueFromArray(self, data, background): - # Will remove the background value from each of the data + # Will remove the background value from each of the data # element (data is an array) - + sz = len(data) new_data = zeros(sz) for i in range(sz): new_data[i] = data[i] - background - + return new_data def removeValueFromArrayError(self, data_error, background_error): # will calculate the new array of error when removing # a single value from an array - + sz = len(data_error) new_data_error = zeros(sz) for i in range(sz): @@ -514,18 +514,18 @@ def removeValueFromArrayError(self, data_error, background_error): def sumWithError(self, peak, peak_error): # add the array element using their weight and return new error as well - + sz = len(peak) sum_peak = 0 sum_peak_error = 0 for i in range(sz): sum_peak += peak[i] sum_peak_error += peak_error[i]**2 - + sum_peak_error = math.sqrt(sum_peak_error) return [sum_peak, sum_peak_error] - def _removeBackground(self, + def _removeBackground(self, InputWorkspace=None, from_peak= 0, to_peak=256, @@ -533,7 +533,7 @@ def _removeBackground(self, to_back=256, tof_min = 0, tof_max = 200000): - + # retrieve various axis tof_axis = InputWorkspace.readX(0)[:] nbr_tof = len(tof_axis)-1 @@ -544,58 +544,58 @@ def _removeBackground(self, for x in range(256): data[x,:] = InputWorkspace.readY(x)[:] error[x,:] = InputWorkspace.readE(x)[:] - + peak_array = zeros(nbr_tof) peak_array_error = zeros(nbr_tof) - + bMinBack = False; bMaxBack = False; - + min_back = 0; min_back_error = 0; max_back = 0; max_back_error = 0; - + for t in (range(nbr_tof-1)): - + _y_slice = data[:,t] _y_error_slice = error[:,t] - + _y_slice = _y_slice.flatten() _y_error_slice = _y_error_slice.flatten() - + if from_back < (from_peak-1): range_back_min = _y_slice[from_back : from_peak] range_back_error_min = _y_error_slice[from_back : from_peak] [min_back, min_back_error] = self.weighted_mean(range_back_min, range_back_error_min) bMinBack = True - + if (to_peak+1) < to_back: range_back_max = _y_slice[to_peak+1: to_back+1] range_back_error_max = _y_error_slice[to_peak+1: to_back+1] [max_back, max_back_error] = self.weighted_mean(range_back_max, range_back_error_max) bMaxBack = True - + # if we have a min and max background if bMinBack & bMaxBack: [background, background_error] = self.weighted_mean([min_back,max_back],[min_back_error,max_back_error]) -# +# # if we don't have a max background, we use min background if not bMaxBack: background = min_back background_error = min_back_error -# +# # if we don't have a min background, we use max background if not bMinBack: background = max_back background_error = max_back_error - + tmp_peak = _y_slice[from_peak:to_peak+1] tmp_peak_error = _y_error_slice[from_peak:to_peak+1] new_tmp_peak = self.removeValueFromArray(tmp_peak, background) new_tmp_peak_error = self.removeValueFromArrayError(tmp_peak_error, background_error) - + [final_value, final_error] = self.sumWithError(new_tmp_peak, new_tmp_peak_error) peak_array[t] = final_value; @@ -610,18 +610,18 @@ def _removeBackground(self, DataY=y_axis, DataE=y_error_axis, Nspec=1) - + # import sys # sys.exit("in _removeBackground... so far, so good!") - + return DataWks - + def _getIndex(self, value, array): """ returns the index where the value has been found """ return array.searchsorted(value) - + def _getProtonCharge(self, st=None): """ Returns the proton charge of the given workspace in picoCoulomb @@ -631,18 +631,18 @@ def _getProtonCharge(self, st=None): proton_charge_mtd_unit = mt_run.getProperty('gd_prtn_chrg').value proton_charge = proton_charge_mtd_unit / 2.77777778e-10 return proton_charge - return None + return None def __mul__(self, other): """ operator * between two instances of the class """ - + product = sfCalculator() - + product.numerator = self.numerator + '*' + other.numerator product.denominator = self.denominator + '*' + other.denominator - + product.x_axis_ratio = self.x_axis_ratio ## replace code by @@ -652,106 +652,106 @@ def __mul__(self, other): for i in range(sz): new_y_axis_ratio[i] = self.y_axis_ratio[i] * other.y_axis_ratio[i] product.y_axis_ratio = new_y_axis_ratio - + ## replace code by #product.y_axis_error_ratio = product.y_axis_ratio * sqrt((other.y_axis_error_ratio / other.y_axis_ratio)**2 + (self.y_axis_error_ratio / self.y_axis_ratio)**2) new_y_axis_error_ratio = zeros(sz) for i in range(sz): - + # make sure we don't divide b 0 if other.y_axis_ratio[i] == 0: other.y_axis_ratio[i] = 1 if self.y_axis_ratio[i] == 0: self.y_axis_ratio[i] = 1 - + tmp_product = (other.y_axis_error_ratio[i] / other.y_axis_ratio[i]) ** 2 + (self.y_axis_error_ratio[i] / self.y_axis_ratio[i]) ** 2 tmp_product = math.sqrt(tmp_product) new_y_axis_error_ratio[i] = tmp_product * product.y_axis_ratio[i] product.y_axis_error_ratio = new_y_axis_error_ratio - + return product - + def fit(self): """ This is going to fit the counts_vs_tof with a linear expression and return the a and b coefficients (y=a+bx) """ - + DataToFit = CreateWorkspace(DataX=self.x_axis_ratio, DataY=self.y_axis_ratio, DataE=self.y_axis_error_ratio, Nspec=1) - + print 'replaceSpecialValues' - DataToFit = ReplaceSpecialValues(InputWorkspace=DataToFit, - NaNValue=0, - NaNError=0, - InfinityValue=0, + DataToFit = ReplaceSpecialValues(InputWorkspace=DataToFit, + NaNValue=0, + NaNError=0, + InfinityValue=0, InfinityError=0) # ResetNegatives(InputWorkspace='DataToFit', # OutputWorkspace='DataToFit', -# AddMinimum=0) - +# AddMinimum=0) + # #DEBUG # #output the data to fit to DEBUG # x_axis = DataToFit.readX(0)[:] # y_axis = DataToFit.readY(0)[:] # y_error_axis = DataToFit.readE(0)[:] -# +# # print 'create sfOutputTest#' # filename = "/home/j35/sfOutputTest#%d.txt" % sfCalculator.INDEX # print filename # sfCalculator.INDEX += 1 -# +# # f=open(filename,'w') -# +# # for i in range(len(x_axis)): # f.write(str(x_axis[i]) + "," + str(y_axis[i]) + "," + str(y_error_axis[i]) + "\n"); -# +# # f.close # #END OF DEBUG - + try: - + Fit(InputWorkspace=DataToFit, Function="name=UserFunction, Formula=a+b*x, a=1, b=2", Output='res') - + except: - + xaxis = self.x_axis_ratio sz = len(xaxis) xmin = xaxis[0] xmax = xaxis[sz/2] - + DataToFit = CropWorkspace(InputWorkspace=DataToFit, XMin=xmin, XMax=xmax) - + Fit(InputWorkspace=DataToFit, Function='name=UserFunction, Formula=a+b*x, a=1, b=2', Output='res') - + res = mtd['res_Parameters'] - + self.a = res.cell(0,1) self.b = res.cell(1,1) self.error_a = res.cell(0,2) self.error_b = res.cell(1,2) - + # self.a = res.getDouble("Value", 0) -# self.b = res.getDouble("Value", 1) +# self.b = res.getDouble("Value", 1) # self.error_a = res.getDouble("Error", 0) -# self.error_b = res.getDouble("Error", 1) +# self.error_b = res.getDouble("Error", 1) def plotObject(instance): - + # return # print 'a: ' + str(instance.a[-1]) -# print 'b: ' + str(instance.b[-1]) - +# print 'b: ' + str(instance.b[-1]) + figure() errorbar(instance.x_axis_ratio, instance.y_axis_ratio, @@ -760,22 +760,22 @@ def plotObject(instance): mfc='red', linestyle='', label='Exp. data') - + if (instance.a is not None): x = linspace(10000, 22000, 100) _label = "%.3f + x*%.2e" % (instance.a, instance.b) plot(x, instance.a + instance.b * x, label=_label) - + xlabel("TOF (microsS)") ylabel("Ratio") - + title(instance.numerator + '/' + instance.denominator) show() legend() def recordSettings(a, b, error_a, error_b, name, instance): """ - This function will record the various fitting parameters and the + This function will record the various fitting parameters and the name of the ratio """ print '--> recoding settings' @@ -789,9 +789,9 @@ def recordSettings(a, b, error_a, error_b, name, instance): def variable_value_splitter(variable_value): """ This function split the variable that looks like "LambdaRequested:3.75" - and returns a dictionnary of the variable name and value + and returns a dictionnary of the variable name and value """ - + _split = variable_value.split('=') variable = _split[0] value = _split[1] @@ -808,11 +808,11 @@ def isWithinRange(value1, value2): else: return False -def outputFittingParameters(a, b, error_a, error_b, +def outputFittingParameters(a, b, error_a, error_b, lambda_requested, incident_medium, - S1H, S2H, - S1W, S2W, + S1H, S2H, + S1W, S2W, output_file_name): """ Create an ascii file of the various fittings parameters @@ -835,7 +835,7 @@ def outputFittingParameters(a, b, error_a, error_b, #First we need to check if the file already exist if os.path.isfile(output_file_name): bFileExist = True - + #then if it does, parse the file and check if following infos are #already defined: # lambda_requested, S1H, S2H, S1W, S2W @@ -844,23 +844,23 @@ def outputFittingParameters(a, b, error_a, error_b, text = f.readlines() # split_lines = text.split('\n') split_lines = text - + entry_list_to_add = [] - + try: - + sz = len(a) for i in range(sz): _match = False - + for _line in split_lines: if _line[0] == '#': continue - + _line_split = _line.split(' ') _incident_medium = variable_value_splitter(_line_split[0]) - + if (_incident_medium['value'].strip() == incident_medium.strip()): _lambdaRequested = variable_value_splitter(_line_split[1]) if (isWithinRange(_lambdaRequested['value'], lambda_requested)): @@ -874,20 +874,20 @@ def outputFittingParameters(a, b, error_a, error_b, if (isWithinRange(_s2w['value'],S2W[i])): _match = True break - + if _match == False: entry_list_to_add.append(i) - except: + except: #replace file because this one has the wrong format _content = ['#y=a+bx\n', '#\n', '#lambdaRequested[Angstroms] S1H[mm] S2H[mm] S1W[mm] S2W[mm] a b error_a error_b\n', '#\n'] sz = len(a) for i in range(sz): - + _line = 'IncidentMedium=' + incident_medium.strip() + ' ' _line += 'LambdaRequested=' + str(lambda_requested) + ' ' - + _S1H = "{0:.2f}".format(abs(S1H[i])) _S2H = "{0:.2f}".format(abs(S2H[i])) _S1W = "{0:.2f}".format(abs(S1W[i])) @@ -896,7 +896,7 @@ def outputFittingParameters(a, b, error_a, error_b, _b = "{0:}".format(b[i]) _error_a = "{0:}".format(float(error_a[i])) _error_b = "{0:}".format(float(error_b[i])) - + _line += 'S1H=' + _S1H + ' ' + 'S2H=' + _S2H + ' ' _line += 'S1W=' + _S1W + ' ' + 'S2W=' + _S2W + ' ' _line += 'a=' + _a + ' ' @@ -904,7 +904,7 @@ def outputFittingParameters(a, b, error_a, error_b, _line += 'error_a=' + _error_a + ' ' _line += 'error_b=' + _error_b + '\n' _content.append(_line) - + f = open(output_file_name, 'w') f.writelines(_content) f.close() @@ -912,10 +912,10 @@ def outputFittingParameters(a, b, error_a, error_b, _content = [] for j in entry_list_to_add: - + _line = 'IncidentMedium=' + incident_medium + ' ' _line += 'LambdaRequested=' + str(lambda_requested) + ' ' - + _S1H = "{0:.2f}".format(abs(S1H[j])) _S2H = "{0:.2f}".format(abs(S2H[j])) _S1W = "{0:.2f}".format(abs(S1W[j])) @@ -924,7 +924,7 @@ def outputFittingParameters(a, b, error_a, error_b, _b = "{0:}".format(b[j]) _error_a = "{0:}".format(float(error_a[j])) _error_b = "{0:}".format(float(error_b[j])) - + _line += 'S1H=' + _S1H + ' ' + 'S2H=' + _S2H + ' ' _line += 'S1W=' + _S1W + ' ' + 'S2W=' + _S2W + ' ' _line += 'a=' + _a + ' ' @@ -932,21 +932,21 @@ def outputFittingParameters(a, b, error_a, error_b, _line += 'error_a=' + _error_a + ' ' _line += 'error_b=' + _error_b + '\n' _content.append(_line) - + f = open(output_file_name, 'a') f.writelines(_content) f.close() - + else: _content = ['#y=a+bx\n', '#\n', '#lambdaRequested[Angstroms] S1H[mm] S2H[mm] S1W[mm] S2W[mm] a b error_a error_b\n', '#\n'] sz = len(a) for i in range(sz): - + _line = 'IncidentMedium=' + incident_medium.strip() + ' ' _line += 'LambdaRequested=' + str(lambda_requested) + ' ' - + _S1H = "{0:.2f}".format(abs(S1H[i])) _S2H = "{0:.2f}".format(abs(S2H[i])) _S1W = "{0:.2f}".format(abs(S1W[i])) @@ -955,7 +955,7 @@ def outputFittingParameters(a, b, error_a, error_b, _b = "{0:}".format(b[i]) _error_a = "{0:}".format(float(error_a[i])) _error_b = "{0:}".format(float(error_b[i])) - + _line += 'S1H=' + _S1H + ' ' + 'S2H=' + _S2H + ' ' _line += 'S1W=' + _S1W + ' ' + 'S2W=' + _S2W + ' ' _line += 'a=' + _a + ' ' @@ -963,14 +963,14 @@ def outputFittingParameters(a, b, error_a, error_b, _line += 'error_a=' + _error_a + ' ' _line += 'error_b=' + _error_b + '\n' _content.append(_line) - + f = open(output_file_name, 'w') f.writelines(_content) f.close() def createIndividualList(string_list_files): """ - Using the list_files, will produce a dictionary of the run + Using the list_files, will produce a dictionary of the run number and number of attenuator ex: list_files = "1000:0, 1001:1, 1002:1, 1003:2" @@ -988,10 +988,10 @@ def createIndividualList(string_list_files): _second_split = first_split[i].split(':') list_runs.append(_second_split[0].strip()) list_attenuator.append(int(_second_split[1].strip())) - + return {'list_runs':list_runs, 'list_attenuator':list_attenuator} - + def getLambdaValue(mt): """ return the lambdaRequest value @@ -999,7 +999,7 @@ def getLambdaValue(mt): mt_run = mt.getRun() _lambda = mt_run.getProperty('LambdaRequest').value return _lambda - + def getSh(mt, top_tag, bottom_tag): """ returns the height and units of the given slits @@ -1010,7 +1010,7 @@ def getSh(mt, top_tag, bottom_tag): sh = float(sb[0]) - float(st[0]) units = mt_run.getProperty(top_tag).units return sh, units - + def getSheight(mt, index): """ return the DAS hardware slits height of slits # index @@ -1019,24 +1019,24 @@ def getSheight(mt, index): tag = 'S' + index + 'VHeight' value = mt_run.getProperty(tag).value return value[0] - + def getS1h(mt=None): - """ - returns the height and units of the slit #1 + """ + returns the height and units of the slit #1 """ if mt != None: # _h, units = getSh(mt, 's1t', 's1b') - _h = getSheight(mt, '1') + _h = getSheight(mt, '1') return _h return None - + def getS2h(mt=None): - """ - returns the height and units of the slit #2 + """ + returns the height and units of the slit #2 """ if mt != None: # _h, units = getSh(mt, 's2t', 's2b') - _h = getSheight(mt, '2') + _h = getSheight(mt, '2') return _h return None @@ -1065,35 +1065,35 @@ def getSw(mt, left_tag, right_tag): return sw, units def getS1w(mt=None): - """ - returns the width and units of the slit #1 + """ + returns the width and units of the slit #1 """ if mt != None: -# _w, units = getSw(mt, 's1l', 's1r') +# _w, units = getSw(mt, 's1l', 's1r') _w = getSwidth(mt, '1') return _w return None - + def getS2w(mt=None): - """ - returns the width and units of the slit #2 + """ + returns the width and units of the slit #2 """ if mt != None: -# _w, units = getSh(mt, 's2l', 's2r') +# _w, units = getSh(mt, 's2l', 's2r') _w = getSwidth(mt, '2') return _w return None -def getSlitsValueAndLambda(full_list_runs, - S1H, S2H, +def getSlitsValueAndLambda(full_list_runs, + S1H, S2H, S1W, S2W, lambdaRequest): """ - Retrieve the S1H (slit 1 height), - S2H (slit 2 height), - S1W (slit 1 width), - S2W (slit 2 width) and + Retrieve the S1H (slit 1 height), + S2H (slit 2 height), + S1W (slit 1 width), + S2W (slit 2 width) and lambda requested values """ _nbr_files = len(full_list_runs) @@ -1108,12 +1108,12 @@ def getSlitsValueAndLambda(full_list_runs, _s2h_value = getS2h(tmpWks) S1H[i] = _s1h_value S2H[i] = _s2h_value - + _s1w_value = getS1w(tmpWks) _s2w_value = getS2w(tmpWks) S1W[i] = _s1w_value S2W[i] = _s2w_value - + _lambda_value = getLambdaValue(tmpWks) lambdaRequest[i] = _lambda_value @@ -1125,18 +1125,18 @@ def isRunsSorted(list_runs, S1H, S2H): sTotal = zeros(sz) for i in range(sz): sTotal[i] = S1H[i] + S2H[i] - + sorted_sTotal = sorted(sTotal) - + for i in range(len(sTotal)): _left = list(sTotal)[i] _right = sorted_sTotal[i] - + _left_formated = "%2.1f" % _left _right_formated = "%2.1f" % _right if (_left_formated != _right_formated): return False - + return True def calculateAndFit(numerator='', @@ -1144,27 +1144,27 @@ def calculateAndFit(numerator='', list_peak_back_numerator=None, list_peak_back_denominator=None, list_objects=[], - tof_range=None): - + tof_range=None): + print '--> running calculate and fit algorithm' - cal1 = sfCalculator(numerator=numerator, + cal1 = sfCalculator(numerator=numerator, denominator=denominator, tof_range=tof_range) - + cal1.setNumerator(minPeak=list_peak_back_numerator[0], maxPeak=list_peak_back_numerator[1], minBack=list_peak_back_numerator[2], maxBack=list_peak_back_numerator[3]) - + cal1.setDenominator(minPeak=list_peak_back_denominator[0], maxPeak=list_peak_back_denominator[1], minBack=list_peak_back_denominator[2], - maxBack=list_peak_back_denominator[3]) + maxBack=list_peak_back_denominator[3]) cal1.run() print 'Done with cal1.run()' - + if (list_objects != [] and list_objects[-1] is not None): new_cal1 = cal1 * list_objects[-1] new_cal1.fit() @@ -1189,12 +1189,12 @@ def help(): #if __name__ == '__main__': -def calculate(string_runs=None, -# list_attenuator=None, - list_peak_back=None, +def calculate(string_runs=None, +# list_attenuator=None, + list_peak_back=None, incident_medium=None, output_file_name=None, - tof_range=None): + tof_range=None): """ In this current version, the program will automatically calculates the scaling function for up to, and included, 6 attenuators. @@ -1203,35 +1203,35 @@ def calculate(string_runs=None, .... where y=a+bx x axis is in microS - + The string runs has to be specified this way: string_runs = "run#1:nbr_attenuator, run#2:nbr_attenuator...." - + the list_peak_back is specified this way: - list_peak_back = + list_peak_back = [[peak_min_run1, peak_max_run1, back_min_run1, back_max_run1], [peak_min_run2, peak_max_run2, back_min_run2, back_max_run2], [...]] - + output_path = where the scaling factor files will be written tof_range - - """ - + + """ + list_attenuator = None; - + #use default string files if not provided if (string_runs is None): #Input from user -# list_runs = ['55889', '55890', '55891', '55892', '55893', '55894', -# '55895', '55896', '55897', '55898', '55899', '55900', +# list_runs = ['55889', '55890', '55891', '55892', '55893', '55894', +# '55895', '55896', '55897', '55898', '55899', '55900', # '55901', '55902'] - list_runs = ['55889', '55890', '55891', '55892', '55893', '55894'] + list_runs = ['55889', '55890', '55891', '55892', '55893', '55894'] nexus_path = '/mnt/hgfs/j35/results/' pre = 'REF_L_' nexus_path_pre = nexus_path + pre post = '_event.nxs' - + for (offset, item) in enumerate(list_runs): list_runs[offset] = nexus_path_pre + item + post @@ -1247,7 +1247,7 @@ def calculate(string_runs=None, msg = "RefLReduction: could not find run %s\n" %item msg += "Add your data folder to your User Data Directories in the File menu" raise RuntimeError(msg) - + list_attenuator = dico['list_attenuator'] if (incident_medium is None): @@ -1264,12 +1264,12 @@ def calculate(string_runs=None, # list_peak_back[10, ] = [128, 136, 120, 145] # list_peak_back[13, ] = [120, 145, 105, 155] # list_peak_back[12, ] = [125, 140, 115, 150] - + ##### #Input file should be as it is here ! ##### - - #retrieve the S1H and S2H val/units for each NeXus + + #retrieve the S1H and S2H val/units for each NeXus #retrieve the lambdaRequest value (Angstrom) S1H = {} S2H = {} @@ -1281,19 +1281,19 @@ def calculate(string_runs=None, #Make sure all the lambdaRequested are identical within a given range lambdaRequestPrecision = 0.01 #1% _lr = lambdaRequest[0] - + for i in lambdaRequest: _localValue = float(lambdaRequest[i][0]) _localValueRate = lambdaRequestPrecision * _localValue _leftValue = _localValue - _localValueRate _rightValue = _localValue + _localValueRate - + if (_localValue < _leftValue) or (_localValue > _rightValue): raise Exception("lambda requested do not match !") - + #make sure the file are sorted from smaller to bigger openning if isRunsSorted(list_runs, S1H, S2H): - + #initialize record fitting parameters arrays a = [] b = [] @@ -1304,7 +1304,7 @@ def calculate(string_runs=None, finalS1H = [] finalS2H = [] - + finalS1W = [] finalS2W = [] @@ -1317,15 +1317,15 @@ def calculate(string_runs=None, #array of index of first attenuator _index_first_A = [] for j in range(len(unique(list_attenuator))): - _index_first_A.append(-1) + _index_first_A.append(-1) index_numerator = -1 index_denominator = -1 - + list_objects = [] - + for i in range(len(list_runs)): - + print '> Working with index: ' + str(i) _attenuator = list_attenuator[i] @@ -1339,7 +1339,7 @@ def calculate(string_runs=None, else: index_numerator = i index_denominator = _index_first_A[_attenuator] - + print '-> numerator : ' + str(list_runs[index_numerator]) print '-> denominator: ' + str(list_runs[index_denominator]) cal = calculateAndFit(numerator=list_runs[index_numerator], @@ -1347,15 +1347,15 @@ def calculate(string_runs=None, list_peak_back_numerator=list_peak_back[index_numerator], list_peak_back_denominator=list_peak_back[index_denominator], list_objects=list_objects, - tof_range=tof_range) + tof_range=tof_range) print '-> Done with Calculate and Fit' - + recordSettings(a, b, error_a, error_b, name, cal) - + if (i < (len(list_runs) - 1) and list_attenuator[i + 1] == (_attenuator+1)): list_objects.append(cal) - + #record S1H and S2H finalS1H.append(S1H[index_numerator]) finalS2H.append(S2H[index_numerator]) @@ -1364,20 +1364,20 @@ def calculate(string_runs=None, finalS1W.append(S1W[index_numerator]) finalS2W.append(S2W[index_numerator]) - #output the fitting parameters in an ascii + #output the fitting parameters in an ascii _lambdaRequest = "{0:.2f}".format(lambdaRequest[0][0]) - + # output_pre = 'SFcalculator_lr' + str(_lambdaRequest) # output_ext = '.txt' -# output_file = output_path + '/' + output_pre + output_ext - +# output_file = output_path + '/' + output_pre + output_ext + if (output_file_name is None) or (output_file_name == ''): output_file_name = "RefLsf.cfg" - - outputFittingParameters(a, b, error_a, error_b, + + outputFittingParameters(a, b, error_a, error_b, _lambdaRequest, incident_medium, - finalS1H, finalS2H, + finalS1H, finalS2H, finalS1W, finalS2W, output_file_name) @@ -1385,7 +1385,7 @@ def calculate(string_runs=None, else: """ - sort the files + sort the files """ pass - + diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py index d5e137e49770..55d9afd1a41a 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/ChudleyElliot.py @@ -28,7 +28,7 @@ import math, numpy as np class ChudleyElliot(IFunction1D): - + def category(self): return "QuasiElastic" @@ -36,7 +36,7 @@ def init(self): # Active fitting parameters self.declareParameter("Tau", 1.0, 'Residence time') self.declareParameter("L", 1.5, 'Jump length') - + def function1D(self, xvals): tau = self.getParameterValue("Tau") length = self.getParameterValue("L") @@ -45,7 +45,7 @@ def function1D(self, xvals): hwhm = (1.0 - np.sin(xvals * length) / (xvals * length)) / tau return hwhm - + def functionDeriv1D(self, xvals, jacobian): tau = self.getParameterValue("Tau") length = self.getParameterValue("L") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py index cb9c756c0c07..887d9f12b273 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py @@ -1,4 +1,4 @@ -''' +''' @author Jose Borreguero, NScD @date October 06, 2013 diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py index a82edfeae797..314e436eaadd 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/Example1DFunction.py @@ -14,7 +14,7 @@ import numpy as np class Example1DFunction(IFunction1D): - + def category(self): """ Optional method to return the category that this @@ -34,14 +34,14 @@ def init(self): # Active fitting parameters self.declareParameter("A0") self.declareParameter("A1") - + def function1D(self, xvals): """ - Computes the function on the set of values given and returns + Computes the function on the set of values given and returns the answer as a numpy array of floats """ return self.getParameterValue("A0") + self.getParameterValue("A1")*xvals - + def functionDeriv1D(self, xvals, jacobian): """ Computes the partial derivatives of the function on the set of values given diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py index 9c7b90f0138d..a24fe9fc4d2c 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/Examples/ExamplePeakFunction.py @@ -12,7 +12,7 @@ import numpy as np class ExamplePeakFunction(IPeakFunction): - + def category(self): """ Optional method to return the category that this @@ -39,10 +39,10 @@ def init(self): # It is advisable to look at the setAttributeValue function below and take local copies # of attributes so that they do not have to be retrieved repeatedly througout the fitting. self.declareAttribute("NTerms", 1) - + def functionLocal(self, xvals): """ - Computes the function on the set of values given and returns + Computes the function on the set of values given and returns the answer as a numpy array of floats """ # As Fit progresses the declared parameter values will change @@ -58,7 +58,7 @@ def functionLocal(self, xvals): offset_sq=np.square(xvals-peak_centre) out=height*np.exp(-0.5*offset_sq*weight) return out - + def functionDerivLocal(self, xvals, jacobian): """ Computes the partial derivatives of the function on the set of values given @@ -72,7 +72,7 @@ def functionDerivLocal(self, xvals, jacobian): peak_centre = self.getParameterValue("PeakCentre"); sigma = self.getParameterValue("Sigma") weight = math.pow(1./sigma,2); - + # X index i = 0 for x in xvals: @@ -120,7 +120,7 @@ def setActiveParameter(self, index, value): else: param_value = value # Final explicit arugment is required to be false here by framework - self.setParameter(index, param_value, False) + self.setParameter(index, param_value, False) param_value = self.getParameterValue(index) if index == 2: #Sigma. Actually fit to 1/(sigma^2) for stability diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py index bacd2ad52f0e..3bac5ad211fa 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/FickDiffusion.py @@ -29,17 +29,17 @@ import numpy as np class FickDiffusion(IFunction1D): - + def category(self): return "QuasiElastic" def init(self): # Active fitting parameters self.declareParameter("D", 1.0, 'Diffusion constant') - + def function1D(self, xvals): return self.getParameterValue("D")*xvals*xvals - + def functionDeriv1D(self, xvals, jacobian): i = 0 for x in xvals: diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py index cb6056d2a749..c4a5870c7487 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/HallRoss.py @@ -28,7 +28,7 @@ import math, numpy as np class HallRoss(IFunction1D): - + def category(self): return "QuasiElastic" @@ -36,7 +36,7 @@ def init(self): # Active fitting parameters self.declareParameter("Tau", 1.0, 'Residence time') self.declareParameter("L", 0.2, 'Jump length') - + def function1D(self, xvals): tau = self.getParameterValue("Tau") l = self.getParameterValue("L") @@ -46,7 +46,7 @@ def function1D(self, xvals): hwhm = (1.0 - np.exp( -l * xvals * xvals )) / tau return hwhm - + def functionDeriv1D(self, xvals, jacobian): tau = self.getParameterValue("Tau") l = self.getParameterValue("L") diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py index 366c36915696..1602f82e012d 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/StretchedExpFT.py @@ -1,4 +1,4 @@ -''' +''' @author Jose Borreguero, NScD @date October 06, 2013 @@ -31,7 +31,7 @@ from pdb import set_trace as tr class StretchedExpFT(IFunction1D): - + def __init__(self): '''declare some constants''' super(StretchedExpFT, self).__init__() @@ -63,17 +63,17 @@ def validateParams(self): #raise ValueError(message) return None return {'height':height, 'tau':tau, 'beta':beta} - + def function1D(self, xvals, **optparms): ''' Computes the Fourier transform of the Symmetrized Stretched Exponential - + The Symmetrized Stretched Exponential: Fourier{ height * exp( - |t/tau|**beta ) } - + Given a time step dt and M=2*N+1 time points (N negative, one at zero, N positive), then fft will sample frequencies [0, 1/(M*dt), N/(M*dt), -N/(M*dt), (-N+1)/(M*dt),..,1/(M*dt)]. - + Given xvals, let: 1/(M*dt) = xvals[1]-xvals[0] N/(M*dt) = max(abs(xvals)) @@ -84,7 +84,7 @@ def function1D(self, xvals, **optparms): Its Fourier transform is real by definition, thus we return the real part of the Fast Fourier Transform (FFT). The FFT step is meant to produce some residual imaginary part due to numerical inaccuracies which we ignore. - + We take the absolute value of the real part. The Fourier transform introduces an extra factor exp(i*pi*E/de) which amounts to alternating sign every time E increases by de, the energy bin width @@ -115,7 +115,7 @@ def function1D(self, xvals, **optparms): interpolator = scipy.interpolate.interp1d(freqs, fourier) fourier = interpolator(xvals) return fourier - + def functionDeriv1D(self, xvals, jacobian): '''Numerical derivative''' p = self.validateParams() @@ -128,7 +128,7 @@ def functionDeriv1D(self, xvals, jacobian): df = (self.function1D(xvals, **pp) - f0) / dp[name] ip = self._parm2index[name] for ix in range(len(xvals)): - jacobian.set(ix, ip, df[ix]) + jacobian.set(ix, ip, df[ix]) # Required to have Mantid recognise the new function FunctionFactory.subscribe(StretchedExpFT) diff --git a/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py b/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py index 868bb8bc0193..59626aee0835 100644 --- a/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py +++ b/Code/Mantid/Framework/PythonInterface/plugins/functions/TeixeiraWater.py @@ -28,7 +28,7 @@ import math, numpy as np class TeixeiraWater(IFunction1D): - + def category(self): return "QuasiElastic" @@ -36,7 +36,7 @@ def init(self): # Active fitting parameters self.declareParameter("Tau", 1.0, 'Residence time') self.declareParameter("L", 1.5, 'Jump length') - + def function1D(self, xvals): tau = self.getParameterValue("Tau") length = self.getParameterValue("L") @@ -46,7 +46,7 @@ def function1D(self, xvals): hwhm = xvals * xvals * length / (tau * (1 + xvals * xvals * length)) return hwhm - + def functionDeriv1D(self, xvals, jacobian): tau = self.getParameterValue("Tau") length = self.getParameterValue("L") diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/ImportModuleTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/ImportModuleTest.py index 88122e372868..70a6787d5039 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/ImportModuleTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/ImportModuleTest.py @@ -3,7 +3,7 @@ from mantid.api import AlgorithmFactory class ImportModuleTest(unittest.TestCase): - + def test_import_succeeds(self): import mantid # Check content @@ -11,11 +11,11 @@ def test_import_succeeds(self): self.assertTrue('api' in attrs) self.assertTrue('geometry' in attrs) self.assertTrue('kernel' in attrs) - + def test_on_import_gui_flag_is_set_to_false_here(self): import mantid self.assertEquals(False, mantid.__gui__) - + def test_python_algorithms_are_loaded_recursively(self): """ Test needs improving when the old API goes to just check that everything loads okay @@ -23,6 +23,6 @@ def test_python_algorithms_are_loaded_recursively(self): all_algs = AlgorithmFactory.getRegisteredAlgorithms(True) self.assertTrue('SNSPowderReduction' in all_algs) self.assertTrue('Squares' in all_algs) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPIFitTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPIFitTest.py index 47193d8993a9..2cafd7398751 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPIFitTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPIFitTest.py @@ -10,9 +10,9 @@ from testhelpers import run_algorithm class SimpleAPIFitTest(unittest.TestCase): - + _raw_ws = None - + def setUp(self): if self._raw_ws is None: dataX = np.linspace(start=5.6e4,stop=5.701e4,num=101) @@ -42,7 +42,7 @@ def test_function_returns_are_correct_type_when_no_output_ws_requested(self): self.assertEquals(len(retvals), 2) self.assertTrue(isinstance(retvals[0], str)) self.assertTrue(isinstance(retvals[1], float)) - + def test_function_accepts_all_arguments_as_keywords(self): if platform.system() == 'Darwin': # crashes return @@ -58,7 +58,7 @@ def test_function_returns_are_correct_type_when_output_ws_is_requested(self): retvals = Fit("name=FlatBackground", self._raw_ws, Output="fitWS") self._check_returns_are_correct_type_with_workspaces(retvals) self.assertTrue(output_name + '_Workspace' in mtd) - + def test_other_arguments_are_accepted_by_keyword(self): if platform.system() == 'Darwin': # crashes return @@ -73,7 +73,7 @@ def test_Fit_accepts_EnableLogging_keyword(self): output_name = "otherargs_fitWS" retvals = Fit("name=FlatBackground", self._raw_ws, MaxIterations=2, Output=output_name,EnableLogging=False) self.assertTrue(output_name + '_Workspace' in mtd) - + def _check_returns_are_correct_type_with_workspaces(self, retvals): self.assertEquals(len(retvals), 5) self.assertTrue(isinstance(retvals[0], str)) @@ -82,7 +82,7 @@ def _check_returns_are_correct_type_with_workspaces(self, retvals): self.assertTrue(isinstance(retvals[3], ITableWorkspace)) self.assertTrue(isinstance(retvals[4], MatrixWorkspace)) - + def test_that_dialog_call_raises_runtime_error(self): try: FitDialog() @@ -96,25 +96,25 @@ def test_Fit_works_with_multidomain_functions(self): y1 = np.empty(0) y2 = np.empty(0) y3 = np.empty(0) - + for x in x1: y1 = np.append(y1, 3) y2 = np.append(y2, 2.9 + 3*x) y3 = np.append(y3, 3.1 + 3*x*x) - + x = np.concatenate((x1,x1,x1)) y = np.concatenate((y1,y2,y3)) - + data_name = 'dataWS' run_algorithm('CreateWorkspace',OutputWorkspace=data_name,DataX=x, DataY=y,DataE=np.ones(30),NSpec=3,UnitX='TOF') - + f1 = ';name=UserFunction,$domains=i,Formula=a+b*x+c*x^2' func= 'composite=MultiDomainFunction,NumDeriv=1' + f1 + f1 + f1 + ';ties=(f2.a=f1.a=f0.a)' - + output_name = "fitWS" Fit(Function=func,InputWorkspace=data_name,WorkspaceIndex=0,Output=output_name, InputWorkspace_1=data_name,WorkspaceIndex_1=1,InputWorkspace_2=data_name,WorkspaceIndex_2=2) - + self.assertTrue(output_name + '_Parameters' in mtd) params = mtd[output_name+'_Parameters'] self.assertEqual(params.rowCount(), 10) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPILoadTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPILoadTest.py index d94a9bef5955..bdc640064158 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPILoadTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPILoadTest.py @@ -6,27 +6,27 @@ from mantid.api import mtd, MatrixWorkspace, WorkspaceGroup class SimpleAPILoadTest(unittest.TestCase): - + def tearDown(self): """Clear up after each test""" mtd.clear() - + def test_Load_uses_lhs_var_as_workspace_name_for_single_item_return(self): data = Load('IRS21360.raw') self._do_name_check(data, 'data') - + def test_Load_returns_correct_args_when_extra_output_props_are_added_at_execute_time(self): try: data, monitors = Load('IRS21360.raw', LoadMonitors='Separate') except Exception, exc: self.fail("An error occurred when returning outputs declared at algorithm execution: '%s'" % str(exc)) - + self.assertTrue(isinstance(data, MatrixWorkspace)) self._do_name_check(data, 'data') - + self.assertTrue(isinstance(monitors, MatrixWorkspace)) self._do_name_check(monitors, 'data_monitors') - + def test_Load_returns_just_the_WorkspaceGroup_when_final_output_is_a_group(self): data = Load('CSP78173.raw') self.assertTrue(isinstance(data, WorkspaceGroup)) @@ -35,12 +35,12 @@ def test_Load_returns_only_the_WorkspaceGroups_when_final_output_is_a_group_and_ outputs = Load('CSP78173.raw', LoadMonitors='Separate') self.assertTrue(isinstance(outputs, tuple)) self.assertEquals(len(outputs), 2) - + self.assertTrue(isinstance(outputs[0], WorkspaceGroup)) self._do_name_check(outputs[0], 'outputs') self.assertTrue(isinstance(outputs[1], WorkspaceGroup)) self._do_name_check(outputs[1], 'outputs_monitors') - + def test_Load_call_with_just_filename_executes_correctly(self): try: raw = Load('IRS21360.raw') @@ -54,7 +54,7 @@ def test_Load_call_with_other_args_executes_correctly(self): except RuntimeError: self.fail("Load with a filename and extra args should not raise an exception") self.assertEquals(1, raw.getNumberHistograms()) - + def test_Load_call_with_all_keyword_args_executes_correctly(self): raw = Load(Filename='IRS21360.raw', SpectrumMax=1) self.assertEquals(1, raw.getNumberHistograms()) @@ -65,7 +65,7 @@ def test_Load_call_with_args_that_do_not_apply_executes_correctly(self): except RuntimeError: self.fail("Load with a filename and extra args should not raise an exception") self.assertEquals(1, raw.getNumberHistograms()) - + def test_Load_uses_OutputWorkspace_keyword_over_lhs_var_name_if_provided(self): wsname = 'test_Load_uses_OutputWorkspace_keyword_over_lhs_var_name_if_provided' wkspace = Load('IRS21360.raw',OutputWorkspace=wsname) @@ -88,6 +88,6 @@ def test_that_dialog_call_raises_runtime_error(self): def _do_name_check(self, wkspace, expected_name): self.assertEqual(wkspace.getName(), expected_name) self.assertTrue(expected_name in mtd) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPITest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPITest.py index 54f19d234c8f..235b1ad6226a 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPITest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/SimpleAPITest.py @@ -16,16 +16,16 @@ class TemporaryPythonAlgorithm(object): """ def __init__(self, name, code): from mantid import config - + plugin_dirs = config['python.plugins.directories'].split(";") if len(plugin_dirs) == 0: raise RuntimeError("No Python algorithm directories defined") - + self._pyfile = os.path.join(plugin_dirs[0], name + ".py") alg_file = open(self._pyfile, "w") alg_file.write(code) alg_file.close() - + def __del__(self): try: os.remove(self._pyfile) @@ -40,29 +40,29 @@ class SimpleAPITest(unittest.TestCase): def tearDown(self): mtd.clear() - + def test_version_number_equals_2(self): self.assertEquals(simpleapi.apiVersion(), 2) - + def test_module_dict_seems_to_be_correct_size(self): # Check that the module has at least the same number # of attributes as unique algorithms module_dict = dir(simpleapi) all_algs = AlgorithmFactory.getRegisteredAlgorithms(True) self.assertTrue( len(module_dict) > len(all_algs) ) - + def test_alg_has_expected_doc_string(self): # Test auto generated string, Load is manually written expected_doc = \ """Rebins data with new X bin boundaries. For EventWorkspaces, you can very quickly rebin in-place by keeping the same output name and PreserveEvents=true. -Property descriptions: +Property descriptions: InputWorkspace(Input:req) *MatrixWorkspace* Workspace containing the input data OutputWorkspace(Output:req) *MatrixWorkspace* The name to give the output workspace -Params(Input:req) *dbl list* A comma separated list of first bin boundary, width, last bin boundary. Optionally this can be followed by a comma and more widths and last boundary pairs. Optionally this can also be a single number, which is the bin width. In this case, the boundary of binning will be determined by minimum and maximum TOF values among all events, or previous binning boundary, in case of event Workspace, or non-event Workspace, respectively. Negative width values indicate logarithmic binning. +Params(Input:req) *dbl list* A comma separated list of first bin boundary, width, last bin boundary. Optionally this can be followed by a comma and more widths and last boundary pairs. Optionally this can also be a single number, which is the bin width. In this case, the boundary of binning will be determined by minimum and maximum TOF values among all events, or previous binning boundary, in case of event Workspace, or non-event Workspace, respectively. Negative width values indicate logarithmic binning. PreserveEvents(Input) *boolean* Keep the output workspace as an EventWorkspace, if the input has events. If the input and output EventWorkspace names are the same, only the X bins are set, which is very quick. If false, then the workspace gets converted to a Workspace2D histogram. @@ -71,31 +71,31 @@ def test_alg_has_expected_doc_string(self): doc = simpleapi.rebin.__doc__ self.assertTrue(len(doc) > 0 ) self.assertEquals(doc, expected_doc) - + def test_function_call_executes_correct_algorithm_when_passed_correct_args(self): wsname = 'test_function_call_executes_correct_algorithm_when_passed_correct_args' data = [1.0,2.0,3.0,4.0,5.0] simpleapi.CreateWorkspace(data,data,OutputWorkspace=wsname,NSpec=1,UnitX='Wavelength') self.assertTrue( wsname in mtd ) - + def test_function_call_executes_with_output_workspace_on_lhs(self): data = [1.0,2.0,3.0,4.0,5.0] wavelength = simpleapi.CreateWorkspace(data,data,NSpec=1,UnitX='Wavelength') wsname = 'wavelength' self.assertTrue( wsname in mtd ) - + def test_function_call_executes_when_algorithm_has_only_inout_workspace_props(self): data = [1.0,2.0,3.0,4.0,5.0, 6.0] wavelength = simpleapi.CreateWorkspace(data,data,NSpec=3,UnitX='Wavelength') simpleapi.MaskDetectors(wavelength,WorkspaceIndexList=[1,2]) - + def test_function_accepts_EnableLogging_keyword(self): # The test here is that the algorithm runs without falling over about the EnableLogging keyword being a property wsname = 'test_function_call_executes_correct_algorithm_when_passed_correct_args' data = [1.0,2.0,3.0,4.0,5.0] simpleapi.CreateWorkspace(data,data,OutputWorkspace=wsname,NSpec=1,UnitX='Wavelength',EnableLogging=False) self.assertTrue( wsname in mtd ) - + def test_function_call_raises_ValueError_when_passed_args_with_invalid_values(self): # lhs code bug means we can't do this "self.assertRaises(simpleapi.LoadNexus, 'DoesNotExist')" --> ticket #4186 try: @@ -103,7 +103,7 @@ def test_function_call_raises_ValueError_when_passed_args_with_invalid_values(se self.fail("A ValueError was not thrown") except ValueError: pass - + def test_function_call_raises_RuntimeError_when_passed_incorrect_args(self): try: simpleapi.LoadNexus(NotAProperty=1) @@ -120,7 +120,7 @@ def test_function_call_raises_RuntimeError_if_num_of_ret_vals_doesnt_match_num_a pass else: self.fail("Exception was raised but it did not have the correct message: '%s'" % str(exc)) - + def test_function_returns_correct_args_when_extra_output_props_are_added_at_execute_time(self): ws1 = simpleapi.CreateWorkspace([1.5],[1.5],NSpec=1,UnitX='Wavelength') ws2 = simpleapi.CreateWorkspace([1.5],[1.5],NSpec=1,UnitX='Wavelength') @@ -128,13 +128,13 @@ def test_function_returns_correct_args_when_extra_output_props_are_added_at_exec ws1a,ws2a = simpleapi.RenameWorkspaces(InputWorkspaces="ws1,ws2",WorkspaceNames="ws1a,ws2a") self.assertTrue(isinstance(ws1a, MatrixWorkspace)) self.assertTrue(isinstance(ws2a, MatrixWorkspace)) - + def test_function_uses_OutputWorkspace_keyword_over_lhs_var_name_if_provided(self): wsname = 'test_function_uses_OutputWorkspace_keyword_over_lhs_var_name_if_provided' data = [1.0,2.0,3.0,4.0,5.0] wkspace = simpleapi.CreateWorkspace(data,data,OutputWorkspace=wsname,NSpec=1,UnitX='Wavelength') self.assertTrue( wsname in mtd ) - + def test_function_returns_only_mandatory_workspace_when_optional_output_is_not_given(self): _demo = simpleapi.CreateMDHistoWorkspace(SignalInput='1,2,3,4,5',ErrorInput='1,1,1,1,1', Dimensionality='1',Extents='-1,1',NumberOfBins='5',Names='A',Units='U') @@ -152,13 +152,13 @@ def test_function_returns_both_mandatory_and_optional_workspaces_when_optional_o wsname_box = wsname + '_box' query = simpleapi.QueryMDWorkspace(InputWorkspace=_demo,OutputWorkspace=wsname,MaximumRows='500', Normalisation='volume',BoxDataTable=wsname_box) - + self.assertTrue( wsname in mtd ) self.assertTrue( wsname_box in mtd ) - + self.assertTrue( type(query) == tuple ) self.assertEquals( 2, len(query) ) - + self.assertTrue( isinstance(query[0], ITableWorkspace) ) self.assertTrue( isinstance(query[1], ITableWorkspace) ) @@ -170,7 +170,7 @@ def test_function_attached_as_workpace_method_is_attached_to_correct_types(self) def test_function_attached_as_workpace_method_has_same_metainformation_as_free_function(self): self.assertEqual(MatrixWorkspace.rebin.__name__, simpleapi.Rebin.__name__) self.assertEqual(MatrixWorkspace.rebin.__doc__, simpleapi.Rebin.__doc__) - + # Signature of method will have extra self argument freefunction_sig = simpleapi.rebin.func_code.co_varnames expected_method_sig = ['self'] @@ -201,13 +201,13 @@ def test_that_dialog_call_raises_runtime_error(self): msg = str(exc) if msg != "Can only display properties dialog in gui mode": self.fail("Dialog function raised the correct exception type but the message was wrong") - + def test_call_inside_function_uses_new_variable_name(self): def rebin(workspace): # Should replace the input workspace workspace = simpleapi.Rebin(workspace, Params=[1,0.1,10]) return workspace - + dataX=numpy.linspace(start=1,stop=3,num=11) dataY=numpy.linspace(start=1,stop=3,num=10) raw = simpleapi.CreateWorkspace(DataX=dataX,DataY=dataY,NSpec=1) @@ -220,7 +220,7 @@ def rebin(workspace): def test_python_alg_can_use_other_python_alg_through_simple_api(self): """ Runs a test in a separate process as it requires a reload of the - whole mantid module + whole mantid module """ src = """ from mantid.api import PythonAlgorithm, AlgorithmFactory @@ -234,7 +234,7 @@ def PyInit(self): def PyExec(self): %(execline1)s %(execline2)s - + AlgorithmFactory.subscribe(%(name)s) """ name1 = "SimpleAPIPythonAlgorithm1" @@ -250,10 +250,10 @@ def PyExec(self): subprocess.check_call(cmd,shell=True) except subprocess.CalledProcessError, exc: self.fail("Error occurred running one Python algorithm from another: %s" % str(exc)) - + # Ensure the files are removed promptly del a,b - + def test_optional_workspaces_are_ignored_if_not_present_in_output_even_if_given_as_input(self): # Test algorithm from mantid.api import AlgorithmManager,PropertyMode,PythonAlgorithm,MatrixWorkspaceProperty,WorkspaceFactory @@ -262,14 +262,14 @@ class OptionalWorkspace(PythonAlgorithm): def PyInit(self): self.declareProperty(MatrixWorkspaceProperty("RequiredWorkspace", "", Direction.Output)) self.declareProperty(MatrixWorkspaceProperty("OptionalWorkspace", "", Direction.Output, PropertyMode.Optional)) - + def PyExec(self): ws = WorkspaceFactory.create("Workspace2D", NVectors=1, YLength=1,XLength=1) ws.dataY(0)[0] = 5 self.setProperty("RequiredWorkspace", ws) self.getLogger().notice("done!") AlgorithmFactory.subscribe(OptionalWorkspace) - + # temporarily attach it to simpleapi module name="OptionalWorkspace" algm_object = AlgorithmManager.createUnmanaged(name, 1) @@ -281,13 +281,13 @@ def PyExec(self): self.assertTrue(isinstance(result, MatrixWorkspace)) self.assertAlmostEqual(5, result.readY(0)[0], places=12) mtd.remove("required") - + # Call with both outputs specified result = simpleapi.OptionalWorkspace(RequiredWorkspace="required",OptionalWorkspace="optional") self.assertTrue(isinstance(result, MatrixWorkspace)) self.assertAlmostEqual(5, result.readY(0)[0], places=12) mtd.remove("required") - + # Tidy up simple api function del simpleapi.OptionalWorkspace diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmFactoryTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmFactoryTest.py index 73bc67567e29..fc7dae558216 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmFactoryTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmFactoryTest.py @@ -6,12 +6,12 @@ class IsAnAlgorithm(PythonAlgorithm): def PyInit(self): pass - + class NotAnAlgorithm(object): pass class AlgorithmFactoryTest(unittest.TestCase): - + def test_get_algorithm_factory_does_not_return_None(self): self.assertTrue(AlgorithmFactory is not None ) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmHistoryTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmHistoryTest.py index 9166d4d2f1d8..e27bb6f7f5b6 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmHistoryTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmHistoryTest.py @@ -26,14 +26,14 @@ def PyInit(self): doc="Name to give the input workspace.") def PyExec(self): - + alg = self.createChildAlgorithm('ChildAlg') alg.initialize() args = {} kwargs = {} _set_properties(alg, *args, **kwargs) alg.execute() - + AlgorithmFactory.subscribe(ParentAlg) @@ -43,10 +43,10 @@ def test_nested_history(self): ws_name = '__tmp_test_algorithm_history' ws = CreateWorkspace([0, 1, 2], [0, 1, 2], OutputWorkspace=ws_name) alg = self._run_algorithm("ParentAlg", Workspace=ws_name) - + history = ws.getHistory() alg_hists = history.getAlgorithmHistories() - + self.assertEquals(history.size(), 2) self.assertEquals(len(alg_hists), 2) @@ -66,7 +66,7 @@ def test_disable_history(self): ws_name = '__tmp_test_algorithm_history' ws = CreateWorkspace([0, 1, 2], [0, 1, 2], OutputWorkspace=ws_name) alg = self._run_algorithm('ParentAlg', child_algorithm=True, record_history=False, Workspace=ws_name) - + history = ws.getHistory() alg_hists = history.getAlgorithmHistories() @@ -74,7 +74,7 @@ def test_disable_history(self): self.assertEquals(len(alg_hists), 1) #------------------------------------------------------------------------- - # Test Helper Functions + # Test Helper Functions #------------------------------------------------------------------------- def _run_algorithm(self, algorithm_name, child_algorithm=False, record_history=True, **kwargs): diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmManagerTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmManagerTest.py index 761ee95d540b..aee11b608349 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmManagerTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmManagerTest.py @@ -5,7 +5,7 @@ import sys class AlgorithmManagerTest(unittest.TestCase): - + def test_create_default_version(self): alg = testhelpers.assertRaisesNothing(self, AlgorithmManager.create, "ConvertUnits") # Tests @@ -13,14 +13,14 @@ def test_create_default_version(self): self.assertEquals(alg.name(), "ConvertUnits") self.assertEquals(alg.version(), 1) self.assertEquals(alg.category(), "Transforms\\Units") - + def test_create_unknown_alg_throws(self): self.assertRaises(RuntimeError, AlgorithmManager.create,"DoesNotExist") - + def test_created_alg_isinstance_of_IAlgorithm(self): alg = AlgorithmManager.create("ConvertUnits") self.assertTrue(isinstance(alg, IAlgorithm)) - + def test_managed_cppalg_isinstance_of_AlgorithmProxy(self): alg = AlgorithmManager.create("ConvertUnits") self.assertTrue(isinstance(alg, AlgorithmProxy)) @@ -40,7 +40,7 @@ def test_getAlgorithm_returns_correct_instance(self): id = returned_instance.getAlgorithmID() mgr_instance = AlgorithmManager.getAlgorithm(id) self.assertEquals(id, mgr_instance.getAlgorithmID()) - + def test_removeById_removes_correct_instance(self): alg = AlgorithmManager.create("ConvertUnits") alg2 = AlgorithmManager.create("ConvertUnits") @@ -52,14 +52,14 @@ def test_newestInstanceOf_returns_correct_instance(self): alg = AlgorithmManager.create("ConvertUnits") alg2 = AlgorithmManager.create("ConvertUnits") alg3 = AlgorithmManager.newestInstanceOf("ConvertUnits") - + self.assertEquals(alg2.getAlgorithmID(), alg3.getAlgorithmID()) self.assertNotEqual(alg.getAlgorithmID(), alg3.getAlgorithmID()) - + def test_runningInstancesOf_returns_python_list(self): algs = AlgorithmManager.runningInstancesOf("ConvertUnits") self.assertTrue(isinstance(algs, list)) - + import threading class AlgThread(threading.Thread): def __init__(self): @@ -95,4 +95,4 @@ def test_clear_removes_all_managed_algorithms(self): if __name__ == '__main__': - unittest.main() + unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmPropertyTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmPropertyTest.py index 1eb7e81c1738..487c2280dba6 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmPropertyTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmPropertyTest.py @@ -6,13 +6,13 @@ class AlgorithmPropertyTest(unittest.TestCase): def test_construction_with_name_produces_input_property(self): prop = AlgorithmProperty("TestProperty") - + self.assertEquals(Direction.Input, prop.direction) def test_value_method_returns_an_algorithm_type(self): prop = AlgorithmProperty("TestProperty") prop.valueAsStr = 'CreateWorkspace(OutputWorkspace="ws",DataY="1",DataX="1",NSpec=1' - + alg = prop.value self.assertTrue(isinstance(alg,IAlgorithm)) self.assertEquals("CreateWorkspace",alg.name()) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmTest.py index 7a7bdaafa396..155cc3f93289 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AlgorithmTest.py @@ -5,14 +5,14 @@ ########################################################### class AlgorithmTest(unittest.TestCase): - + _load = None def setUp(self): if self._load is None: self.__class__._load = AlgorithmManager.createUnmanaged('Load') self._load.initialize() - + def test_alg_attrs_are_correct(self): self.assertEquals('Load', self._load.name()) self.assertEquals(1, self._load.version()) @@ -22,21 +22,21 @@ def test_alg_attrs_are_correct(self): def test_get_unknown_property_raises_error(self): self.assertRaises(RuntimeError, self._load.getProperty, "NotAProperty") - + def test_alg_set_valid_prop_succeeds(self): self._load.setProperty('Filename', 'LOQ48127.raw') - + def test_alg_set_invalid_prop_raises_error(self): alg = AlgorithmManager.createUnmanaged('Load') alg.initialize() args = ('Filename', 'nonexistent.txt') self.assertRaises(ValueError, alg.setProperty, *args) - + def test_cannot_execute_with_invalid_properties(self): alg = AlgorithmManager.createUnmanaged('Load') alg.initialize() self.assertRaises(RuntimeError, alg.execute) - + def test_execute_succeeds_with_valid_props(self): data = [1.0,2.0,3.0] alg = run_algorithm('CreateWorkspace',DataX=data,DataY=data,NSpec=1,UnitX='Wavelength',child=True) @@ -47,10 +47,10 @@ def test_execute_succeeds_with_valid_props(self): self.assertEquals(alg.getProperty('NSpec').name, 'NSpec') ws = alg.getProperty('OutputWorkspace').value self.assertTrue(ws.getMemorySize() > 0.0 ) - + as_str = str(alg) self.assertEquals(as_str, "CreateWorkspace.1(OutputWorkspace=UNUSED_NAME_FOR_CHILD,DataX=1,2,3,DataY=1,2,3,UnitX=Wavelength)") - + def test_getAlgorithmID_returns_AlgorithmID_object(self): alg = AlgorithmManager.createUnmanaged('Load') self.assertEquals(AlgorithmID, type(alg.getAlgorithmID())) @@ -58,7 +58,7 @@ def test_getAlgorithmID_returns_AlgorithmID_object(self): def test_AlgorithmID_compares_by_value(self): alg = AlgorithmManager.createUnmanaged('Load') id = alg.getAlgorithmID() - self.assertEquals(id, id) # equals itself + self.assertEquals(id, id) # equals itself alg2 = AlgorithmManager.createUnmanaged('Load') id2 = alg2.getAlgorithmID() self.assertNotEqual(id2, id) @@ -75,7 +75,7 @@ def test_cancel_does_nothing_to_executed_algorithm(self): def test_createChildAlgorithm_creates_new_algorithm_that_is_set_as_child(self): parent_alg = AlgorithmManager.createUnmanaged('Load') child_alg = parent_alg.createChildAlgorithm('Rebin') - + self.assertTrue(child_alg.isChild()) def test_createChildAlgorithm_respects_keyword_arguments(self): @@ -84,10 +84,10 @@ def test_createChildAlgorithm_respects_keyword_arguments(self): child_alg = parent_alg.createChildAlgorithm(name='Rebin',version=1,startProgress=0.5,endProgress=0.9,enableLogging=True) except Exception,exc: self.fail("Expected createChildAlgorithm not to throw but it did: %s" % (str(exc))) - + # Unknown keyword self.assertRaises(Exception, parent_alg.createChildAlgorithm, name='Rebin',version=1,startProgress=0.5,endProgress=0.9,enableLogging=True, unknownKW=1) - + if __name__ == '__main__': unittest.main() - + diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AnalysisDataServiceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AnalysisDataServiceTest.py index 1d52d3b78a6f..b96212c38a84 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AnalysisDataServiceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AnalysisDataServiceTest.py @@ -4,10 +4,10 @@ from mantid import mtd class AnalysisDataServiceTest(unittest.TestCase): - + def test_len_returns_correct_value(self): self.assertEquals(len(AnalysisDataService), 0) - + def test_mtd_is_same_object_type_as_analysis_data_service(self): self.assertTrue(isinstance(AnalysisDataService, AnalysisDataServiceImpl)) self.assertTrue(isinstance(mtd, AnalysisDataServiceImpl)) @@ -34,7 +34,7 @@ def test_len_increases_when_item_added(self): self.assertEquals(len(AnalysisDataService), current_len + 1) # Remove to clean the test up AnalysisDataService.remove(wsname) - + def test_len_decreases_when_item_removed(self): wsname = 'ADSTest_test_len_decreases_when_item_removed' self._run_createws(wsname) @@ -42,7 +42,7 @@ def test_len_decreases_when_item_removed(self): # Remove to clean the test up del AnalysisDataService[wsname] self.assertEquals(len(AnalysisDataService), current_len - 1) - + def test_add_raises_error_if_name_exists(self): data = [1.0,2.0,3.0] alg = run_algorithm('CreateWorkspace',DataX=data,DataY=data,NSpec=1,UnitX='Wavelength', child=True) @@ -63,29 +63,29 @@ def test_addOrReplace_replaces_workspace_with_existing_name(self): len_after = len(AnalysisDataService) self.assertEquals(len_after, len_before) AnalysisDataService.remove(name) - + def do_check_for_matrix_workspace_type(self, workspace): self.assertTrue(isinstance(workspace, MatrixWorkspace)) self.assertNotEquals(workspace.getName(), '') self.assertTrue(hasattr(workspace, 'getNumberHistograms')) self.assertTrue(hasattr(workspace, 'getMemorySize')) - + def test_retrieve_gives_back_derived_type_not_DataItem(self): wsname = 'ADSTest_test_retrieve_gives_back_derived_type_not_DataItem' self._run_createws(wsname) self.do_check_for_matrix_workspace_type(AnalysisDataService.retrieve(wsname)) AnalysisDataService.remove(wsname) - + def test_key_operator_does_same_as_retrieve(self): wsname = 'ADSTest_test_key_operator_does_same_as_retrieve' self._run_createws(wsname) ws_from_op = AnalysisDataService[wsname] ws_from_method = AnalysisDataService.retrieve(wsname) - + self.do_check_for_matrix_workspace_type(ws_from_op) self.do_check_for_matrix_workspace_type(ws_from_method) - + self.assertEquals(ws_from_op.name(), ws_from_method.name()) self.assertEquals(ws_from_op.getMemorySize(), ws_from_method.getMemorySize()) @@ -108,17 +108,17 @@ def test_removing_item_invalidates_extracted_handles(self): self.assertTrue(succeeded, "DataItem handle should be valid and allow function calls") AnalysisDataService.remove(wsname) self.assertRaises(RuntimeError, ws_handle.id) - + def test_importAll_exists_as_member(self): self.assertTrue(hasattr(AnalysisDataService, "importAll")) - + def test_importAll_creates_variable_in_current_global_dict_pointing_to_each_workspace(self): obj_names = mtd.getObjectNames() extra_names = ["ADSTest_test_1", "ADSTest_test_2", "ADSTest_test_3"] for name in extra_names: self._run_createws(name) obj_names += extra_names - + # Check no names are in globals for name in obj_names: self.assertFalse(name in locals()) @@ -128,7 +128,7 @@ def test_importAll_creates_variable_in_current_global_dict_pointing_to_each_work # Are they in the local namespace for name in obj_names: self.assertTrue(name in locals()) - + # Clean up for name in obj_names: try: diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AxisTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AxisTest.py index e412ceca319a..1fd9ab9c163a 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AxisTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/AxisTest.py @@ -4,9 +4,9 @@ import numpy as np class AxisTest(unittest.TestCase): - + _test_ws = None - + def setUp(self): if self.__class__._test_ws is None: datY=[1,2,3] @@ -41,26 +41,26 @@ def test_axis_unit_can_be_replaced(self): ws.getAxis(0).setUnit("Label").setLabel("Time", "ns") ws.getAxis(1).setUnit("Label").setLabel("Temperature", "K") - + unitx = ws.getAxis(0).getUnit() unity = ws.getAxis(1).getUnit() self.assertEquals("Time",unitx.caption()) self.assertEquals("ns",unitx.label()) self.assertEquals("Temperature",unity.caption()) self.assertEquals("K",unity.label()) - + def test_value_axis(self): yAxis = self._test_ws.getAxis(1) for i in range(1,4): # Not including 4 self.assertEquals(yAxis.getValue(i-1), i) - + def test_extract_numerical_axis_values_to_numpy(self): yAxis = self._test_ws.getAxis(1) values = yAxis.extractValues() self.assertTrue(isinstance(values, np.ndarray)) for index, value in enumerate(values): self.assertEquals(value, index + 1) - + def test_extract_string_axis_values_to_list(self): data = [1.,2.,3.] axis_values = ["a","b","c"] @@ -73,6 +73,6 @@ def test_extract_string_axis_values_to_list(self): self.assertTrue(isinstance(values, list)) for index, value in enumerate(values): self.assertEquals(value, axis_values[index]) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/CatalogManagerTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/CatalogManagerTest.py index 518e4eb41841..0b8bc43aae83 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/CatalogManagerTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/CatalogManagerTest.py @@ -5,13 +5,13 @@ class CatalogManagerTest(unittest.TestCase): - + def test_get_catalog_manager_does_not_return_None(self): self.assertTrue(CatalogManager is not None ) - + def test_count_active_sessions(self): self.assertEqual(0, CatalogManager.numberActiveSessions(), "Should have zero active sessions without logging on.") - + def test_get_active_sessions(self): list_of_sessions = CatalogManager.getActiveSessions() self.assertTrue(isinstance(list_of_sessions, list), "Expect a list of sessions back") diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/DeprecatedAlgorithmCheckerTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/DeprecatedAlgorithmCheckerTest.py index 2a3b5af09f9c..611eec3cece6 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/DeprecatedAlgorithmCheckerTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/DeprecatedAlgorithmCheckerTest.py @@ -16,6 +16,6 @@ def test_deprecated_algorithm_returns_non_empty_string_from_isDeprecated(self): msg = deprecation_check.isDeprecated() self.assertTrue(len(msg) > 0) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ExperimentInfoTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ExperimentInfoTest.py index 59e76febf4b4..73ce0b7ebcd0 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ExperimentInfoTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ExperimentInfoTest.py @@ -1,6 +1,6 @@ import unittest ############################################################################### -# This has to be tested through a workspace as it cannot be created in +# This has to be tested through a workspace as it cannot be created in # Python ############################################################################### from testhelpers import run_algorithm, WorkspaceCreationHelper @@ -8,37 +8,37 @@ from mantid.api import Sample, Run class ExperimentInfoTest(unittest.TestCase): - + _expt_ws = None - + def setUp(self): if self.__class__._expt_ws is None: alg = run_algorithm('CreateWorkspace', DataX=[1,2,3,4,5], DataY=[1,2,3,4,5],NSpec=1, child=True) ws = alg.getProperty("OutputWorkspace").value ws.run().addProperty("run_number", 48127, True) self.__class__._expt_ws = ws - + def test_information_access(self): inst = self._expt_ws.getInstrument() self.assertTrue(isinstance(inst, Instrument)) self.assertEquals(self._expt_ws.getRunNumber(), 48127) - + def test_sample_access_returns_sample_object(self): sample = self._expt_ws.sample() self.assertTrue(isinstance(sample, Sample)) - + def test_run_access_returns_run_object(self): run = self._expt_ws.run() self.assertTrue(isinstance(run, Run)) - + def test_get_energy_mode(self): - emode = self._expt_ws.getEMode() - self.assertEquals(emode, 0) - + emode = self._expt_ws.getEMode() + self.assertEquals(emode, 0) + # def test_set_and_get_efixed(self): -# ws = WorkspaceCreationHelper.create2DWorkspaceWithFullInstrument(1, 5, False, False) +# ws = WorkspaceCreationHelper.create2DWorkspaceWithFullInstrument(1, 5, False, False) # ws.setEFixed(1, 3.1415) -# self.assertEquals(ws.getEFixed(1), 3.1415) +# self.assertEquals(ws.getEFixed(1), 3.1415) if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FileFinderTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FileFinderTest.py index b6f806011ebd..3239da6c206a 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FileFinderTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FileFinderTest.py @@ -3,13 +3,13 @@ import os class FileFinderTest(unittest.TestCase): - + def test_full_path_returns_an_absolute_path_and_the_files_exists(self): path = FileFinder.getFullPath("CNCS_7860_event.nxs") self.assertTrue(len(path) > 0) # We can't be sure what the full path is in general but it should certainly exist! self.assertTrue(os.path.exists(path)) - + def test_find_runs_returns_absolute_paths_of_given_runs(self): runs = FileFinder.findRuns("CNCS7860") self.assertTrue(len(runs) == 1) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FilePropertyTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FilePropertyTest.py index c70ad077a2d7..c4bb3be35783 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FilePropertyTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FilePropertyTest.py @@ -3,12 +3,12 @@ from mantid.kernel import Direction class FilePropertyTest(unittest.TestCase): - + def test_constructor_with_name_and_default_and_action(self): prop = FileProperty("LoadProperty", "", FileAction.Load) self.assertNotEquals("", prop.isValid) self.assertEquals(Direction.Input, prop.direction) - + def test_constructor_with_name_and_default_and_action_and_exts_list(self): prop = FileProperty("LoadProperty", "", FileAction.Load, ['.nxs', '.raw']) self.assertNotEquals("", prop.isValid) @@ -28,7 +28,7 @@ def test_constructor_with_name_and_default_and_action_and_single_ext_and_directi prop = FileProperty("LoadProperty", "", FileAction.Load, ['.nxs'], Direction.InOut) self.assertNotEquals("", prop.isValid) self.assertEquals(Direction.InOut, prop.direction) - + def test_alg_get_property_converts_to_this(self): alg = AlgorithmManager.createUnmanaged("LoadRaw") alg.initialize() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FrameworkManagerTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FrameworkManagerTest.py index d545264ff511..7973e621c898 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FrameworkManagerTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FrameworkManagerTest.py @@ -11,6 +11,6 @@ def test_clear_functions_do_not_throw(self): testhelpers.assertRaisesNothing(self, FrameworkManager.clearAlgorithms) testhelpers.assertRaisesNothing(self, FrameworkManager.clearInstruments) testhelpers.assertRaisesNothing(self, FrameworkManager.clearPropertyManagers) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FunctionFactoryTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FunctionFactoryTest.py index 75433b8252f4..58847e23208d 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FunctionFactoryTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FunctionFactoryTest.py @@ -3,12 +3,12 @@ from mantid.api import IFunction1D, FunctionFactory class TestFunction(IFunction1D): - + def init(self): pass class FunctionFactoryTest(unittest.TestCase): - + def test_get_function_factory_does_not_return_None(self): self.assertTrue(FunctionFactory is not None) @@ -24,19 +24,19 @@ def test_get_Gaussian(self): self.assertTrue(len(func.__repr__()) > len(name)) self.assertTrue("Peak" in func.categories()) - + def test_function_subscription(self): nfuncs_orig = len(FunctionFactory.getFunctionNames()) FunctionFactory.subscribe(TestFunction) new_funcs = FunctionFactory.getFunctionNames() self.assertEquals(nfuncs_orig+1, len(new_funcs)) self.assertTrue("TestFunction" in new_funcs) - + FunctionFactory.unsubscribe("TestFunction") new_funcs = FunctionFactory.getFunctionNames() self.assertEquals(nfuncs_orig, len(new_funcs)) self.assertTrue("TestFunction" not in new_funcs) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FunctionPropertyTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FunctionPropertyTest.py index 80941c907e42..c1868fe32cfd 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FunctionPropertyTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/FunctionPropertyTest.py @@ -16,7 +16,7 @@ def PyExec(self): func = fp.value if not isinstance(func, IFunction): raise RuntimeError("Expected an IFunction but found %s " % str(type(func))) - + height=func.getParamValue(0) if math.fabs(height - 1.0) > 1e-12: raise RuntimeError("Height does not have the expected value") @@ -25,7 +25,7 @@ def PyExec(self): #---- Success cases ---- def test_constructor_succeeds_with_non_empty_string_name(self): assertRaisesNothing(self, FunctionProperty, "Function") - + def test_type_string_returns_Function(self): func = FunctionProperty("fun") self.assertEqual("Function", func.type) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IEventWorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IEventWorkspaceTest.py index 5135b82c5a24..ce5cc3175e0d 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IEventWorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IEventWorkspaceTest.py @@ -31,19 +31,19 @@ def test_that_clearing_mru_does_not_raise_an_error(self): except: error_raised = True self.assertFalse(error_raised) - + def test_event_list_is_return_as_correct_type(self): el = self._test_ws.getEventList(0) self.assertTrue(isinstance(el, IEventList)) self.assertEquals(el.getNumberEvents(), 200) - + def test_event_list_getWeights(self): el = self._test_ws.getEventList(0) self.assertTrue(isinstance(el, IEventList)) TofList = el.getTofs() self.assertEquals(len(TofList), el.getNumberEvents()) #check length self.assertAlmostEquals(TofList[0], 0.5) #first value - + def test_event_list_getWeights(self): el = self._test_ws.getEventList(0) self.assertTrue(isinstance(el, IEventList)) @@ -51,7 +51,7 @@ def test_event_list_getWeights(self): self.assertEquals(len(weightList), el.getNumberEvents()) #check length self.assertAlmostEquals(weightList[0], 1.0) #first value self.assertAlmostEquals(weightList[len(weightList)-1], 1.0) #last value - + def test_event_list_getWeightErrors(self): el = self._test_ws.getEventList(0) self.assertTrue(isinstance(el, IEventList)) @@ -59,7 +59,7 @@ def test_event_list_getWeightErrors(self): self.assertEquals(len(weightErrorList), el.getNumberEvents()) #check length self.assertAlmostEquals(weightErrorList[0], 1.0) #first value self.assertAlmostEquals(weightErrorList[len(weightErrorList)-1], 1.0) #last value - - + + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IFunction1DTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IFunction1DTest.py index 198dfb0155a9..5782ee41ff06 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IFunction1DTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IFunction1DTest.py @@ -3,12 +3,12 @@ import numpy as np class NoCatgeoryFunction(IFunction1D): - + def init(self): pass class Times2(IFunction1D): - + def category(self): return "SimpleFunction" @@ -17,11 +17,11 @@ def init(self): self.declareAttribute("DoubleAtt", 3.4) self.declareAttribute("StringAtt", "filename") self.declareAttribute("BoolAtt", True) - + self.declareParameter("ParamZeroInitNoDescr") self.declareParameter("ParamNoDescr", 1.5) self.declareParameter("OtherParam",4,"Some fitting parameter") - + def function1D(self, xvals): return 2*xvals @@ -53,13 +53,13 @@ def test_category_override_returns_overridden_result(self): def test_declareAttribute_only_accepts_known_types(self): func = Times2() func.initialize() # Contains known types - self.assertEquals(4, func.nAttributes()) # Make sure initialize ran + self.assertEquals(4, func.nAttributes()) # Make sure initialize ran self.assertRaises(ValueError, func.declareAttribute, "ListAtt", [1,2,3]) def test_correct_attribute_values_are_returned_when_asked(self): func = Times2() func.initialize() # Contains known types - + self.assertEquals(1, func.getAttributeValue("IntAtt")) self.assertEquals(3.4, func.getAttributeValue("DoubleAtt")) self.assertEquals("filename", func.getAttributeValue("StringAtt")) @@ -68,7 +68,7 @@ def test_correct_attribute_values_are_returned_when_asked(self): def test_correct_parameters_are_attached_during_init(self): func = Times2() func.initialize() - + self.assertEquals(3, func.nParams()) self.assertEquals("ParamZeroInitNoDescr",func.parameterName(0)) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py index 5b918267af72..3832a39214ed 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeakFunctionTest.py @@ -4,7 +4,7 @@ import numpy as np class MyPeak(IPeakFunction): - + def init(self): self.declareAttribute("Centre", 1) self.declareAttribute("Height", 3.4) @@ -27,7 +27,7 @@ def test_instance_can_be_created_from_factory(self): self.assertTrue(isinstance(func, IPeakFunction)) self.assertTrue(isinstance(func, IFunction1D)) FunctionFactory.unsubscribe(func_name) - + def test_functionLocal_can_be_called_directly(self): func = MyPeak() func.initialize() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py index 725ff9a1000a..9726f2b928cd 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/IPeaksWorkspaceTest.py @@ -7,14 +7,14 @@ class IPeaksWorkspaceTest(unittest.TestCase): """ Test the python interface to PeaksWorkspace's """ - + def test_interface(self): """ Rudimentary test to get peak and get/set some values """ pws = WorkspaceCreationHelper.createPeaksWorkspace(1) self.assertTrue(isinstance(pws, IPeaksWorkspace)) self.assertEqual(pws.getNumberPeaks(), 1) p = pws.getPeak(0) - + # Try a few IPeak get/setters. Not everything. p.setH(234) self.assertEqual(p.getH(), 234) @@ -22,36 +22,36 @@ def test_interface(self): self.assertEqual(p.getH(), 5) self.assertEqual(p.getK(), 6) self.assertEqual(p.getL(), 7) - + hkl = p.getHKL() self.assertEquals(hkl, V3D(5,6,7)) - + p.setIntensity(456) p.setSigmaIntensity(789) self.assertEqual(p.getIntensity(), 456) self.assertEqual(p.getSigmaIntensity(), 789) - + # Finally try to remove a peak pws.removePeak(0) self.assertEqual(pws.getNumberPeaks(), 0) - + # Create a new peak at some Q in the lab frame qlab = V3D(1,2,3) p = pws.createPeak(qlab, 1.54) self.assertAlmostEquals( p.getQLabFrame().X(), 1.0, 3) - + # Now try to add the peak back pws.addPeak(p) self.assertEqual(pws.getNumberPeaks(), 1) - + # Check that it is what we added to it p = pws.getPeak(0) self.assertAlmostEquals( p.getQLabFrame().X(), 1.0, 3) - + # Peaks workspace will not be integrated by default. self.assertTrue(not pws.hasIntegratedPeaks()) - + if __name__ == '__main__': unittest.main() - + diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ITableWorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ITableWorkspaceTest.py index 0ad1f28fde37..c7ac606f0af5 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ITableWorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ITableWorkspaceTest.py @@ -5,29 +5,29 @@ import numpy class ITableWorkspaceTest(unittest.TestCase): - + _test_ws = None - + def setUp(self): if self._test_ws is None: alg = run_algorithm('RawFileInfo', Filename='LOQ48127.raw',GetRunParameters=True, child=True) self.__class__._test_ws = alg.getProperty('RunParameterTable').value - + def test_meta_information_is_correct(self): self.assertEquals(self._test_ws.columnCount(), 19) self.assertEquals(self._test_ws.rowCount(), 1) - + column_names = self._test_ws.getColumnNames() self.assertEquals(len(column_names), 19) self.assertEquals(type(column_names), std_vector_str) - + def test_cell_access_returns_variables_as_native_python_types(self): self.assertAlmostEquals(self._test_ws.cell('r_gd_prtn_chrg',0), 10.040912628173828, 15) self.assertAlmostEquals(self._test_ws.cell(0, 7), 10.040912628173828, 15) - + self.assertEquals(self._test_ws.cell('r_goodfrm', 0), 9229) self.assertEquals(self._test_ws.cell(0, 9), 9229) - + self.assertEquals(self._test_ws.cell('r_enddate', 0), "18-DEC-2008") self.assertEquals(self._test_ws.cell(0, 16), "18-DEC-2008") @@ -55,7 +55,7 @@ def test_table_is_resized_correctly(self): self.assertEquals(len(table), 5) self.assertTrue(table.addColumn(type="int",name="index")) self.assertEquals(table.columnCount(), 1) - + def test_setcell_sets_the_correct_cell(self): test_table = self._create_test_table() data = '11' @@ -74,16 +74,16 @@ def test_adding_table_data_using_dictionary(self): self.assertEquals(table.columnCount(), 1) table.addColumn(type="str",name="value") self.assertEquals(table.columnCount(), 2) - + nextrow = {'index':1, 'value':'10'} table.addRow(nextrow) self.assertEquals(len(table), 1) insertedrow = table.row(0) self.assertEquals(insertedrow, nextrow) - + incorrect_type = {'index':1, 'value':10} self.assertRaises(ValueError, table.addRow, incorrect_type) - + def test_adding_table_data_using_list(self): table = WorkspaceFactory.createTable() @@ -91,7 +91,7 @@ def test_adding_table_data_using_list(self): self.assertEquals(table.columnCount(), 1) table.addColumn(type="str",name="value") self.assertEquals(table.columnCount(), 2) - + nextrow = {'index':1, 'value':'10'} values = nextrow.values() table.addRow(nextrow) @@ -100,13 +100,13 @@ def test_adding_table_data_using_list(self): self.assertEquals(insertedrow, nextrow) insertedrow = table.row(0) self.assertEquals(insertedrow, nextrow) - + def test_set_and_extract_boolean_columns(self): table = WorkspaceFactory.createTable() table.addColumn(type='bool', name='yes_no') table.addRow([True]) table.addRow([False]) - + self.assertTrue(table.cell(0, 0)) self.assertFalse(table.cell(1, 0)) @@ -130,6 +130,6 @@ def test_set_and_extract_vector_columns(self): self.assertTrue( numpy.array_equal( table.cell(0,0), numpy.array([1,2,3,4,5]) ) ) self.assertTrue( numpy.array_equal( table.cell(1,0), numpy.array([6,7,8,9,10]) ) ) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MDHistoWorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MDHistoWorkspaceTest.py index 2b3b55bcbf47..96f411c3f2d4 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MDHistoWorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MDHistoWorkspaceTest.py @@ -8,31 +8,31 @@ class MDHistoWorkspaceTest(unittest.TestCase): """ Test the interface to MDHistoWorkspaces """ - + def setUp(self): run_algorithm('CreateMDWorkspace', Dimensions='3',Extents='0,10,0,10,0,10',Names='x,y,z',Units='m,m,m',SplitInto='5', MaxRecursionDepth='20',OutputWorkspace='mdw') run_algorithm('FakeMDEventData', InputWorkspace="mdw", UniformParams="1e4") - run_algorithm('BinMD',InputWorkspace="mdw", OutputWorkspace="A", AxisAligned=True, AlignedDim0="x,0,10,10", AlignedDim1="y,0,10,10", + run_algorithm('BinMD',InputWorkspace="mdw", OutputWorkspace="A", AxisAligned=True, AlignedDim0="x,0,10,10", AlignedDim1="y,0,10,10", AlignedDim2="z,0,10,10", IterateEvents="1", Parallel="0") - run_algorithm('BinMD',InputWorkspace="mdw", OutputWorkspace="B", AxisAligned=True, AlignedDim0="x,0,10,10", AlignedDim1="y,0,10,10", + run_algorithm('BinMD',InputWorkspace="mdw", OutputWorkspace="B", AxisAligned=True, AlignedDim0="x,0,10,10", AlignedDim1="y,0,10,10", AlignedDim2="z,0,10,10", IterateEvents="1", Parallel="0") - + def tearDown(self): for name in ('A','B','C','D','E','F','G','H'): mtd.remove(name) mtd.remove('mdw') - + def test_interface(self): A = mtd['A'] - self.assertEqual(A.getNumDims(), 3) + self.assertEqual(A.getNumDims(), 3) self.assertEqual(A.getNPoints(), 1000) # Can set/read signal and error - A.setSignalAt(23, 123.0) - A.setErrorSquaredAt(23, 345.0) - self.assertEqual(A.signalAt(23), 123.0) + A.setSignalAt(23, 123.0) + A.setErrorSquaredAt(23, 345.0) + self.assertEqual(A.signalAt(23), 123.0) self.assertEqual(A.errorSquaredAt(23), 345.0) - + def test_signal_array_is_wrapped_in_read_only_numpy_array(self): run_algorithm('CreateMDHistoWorkspace', SignalInput='1,2,3,4,5,6,7,8,9',ErrorInput='1,1,1,1,1,1,1,1,1', Dimensionality='2',Extents='-1,1,-1,1',NumberOfBins='3,3',Names='A,B',Units='U,T',OutputWorkspace='demo') @@ -40,7 +40,7 @@ def test_signal_array_is_wrapped_in_read_only_numpy_array(self): signal = testWS.getSignalArray() expected = numpy.array([[1,2,3],[4,5,6],[7,8,9]]) self._verify_numpy_data(signal, expected) - + mtd.remove('demo') def test_errorSquared_array_is_wrapped_in_read_only_numpy_array(self): @@ -50,9 +50,9 @@ def test_errorSquared_array_is_wrapped_in_read_only_numpy_array(self): errors = testWS.getErrorSquaredArray() expected = numpy.array([[1,1,1],[1,1,1],[1,1,1]]) self._verify_numpy_data(errors, expected) - + mtd.remove('demo') - + def test_set_signal_array_throws_if_input_array_is_of_incorrect_size(self): run_algorithm('CreateMDHistoWorkspace', SignalInput='1,2,3,4,5,6,7,8,9',ErrorInput='1,1,1,1,1,1,1,1,1', Dimensionality='2',Extents='-1,1,-1,1',NumberOfBins='3,3',Names='A,B',Units='U,T',OutputWorkspace='demo') @@ -88,8 +88,8 @@ def _verify_numpy_data(self, test_array, expected): self.assertTrue(len(expected.shape), len(test_array.shape)) self.assertTrue(not numpy.all(test_array.flags.writeable)) self.assertTrue(numpy.all(numpy.equal(expected, test_array))) - - + + """ Note: Look at each test for PlusMD MinusMD, and MDHistoWorkspaceTest for detailed tests including checking results. These tests only check that they do run. """ def test_operators_md_md(self): @@ -103,7 +103,7 @@ def test_operators_md_md(self): A *= B A /= B A -= B - + """ MDHistoWorkspace + a number """ def test_operators_md_double(self): A = mtd['A'] @@ -116,11 +116,11 @@ def test_operators_md_double(self): A *= B A /= B A -= B - + def test_compound_arithmetic(self): A = mtd['A'] B = mtd['B'] - C = (A + B) / (A - B) + C = (A + B) / (A - B) self.assertTrue(C is not None) """ boolean_workspace = MDHistoWorkspace < MDHistoWorkspace """ @@ -146,7 +146,7 @@ def test_comparisons_and_boolean_operations(self): H = C ^ D self.assertEqual( H.name(), 'H') self.assertEqual( H.signalAt(0), 1.0) - + def test_comparisons_histo_scalar(self): A = mtd['A'] C = A < 1000.0 @@ -162,7 +162,7 @@ def test_inplace_boolean_operations(self): B += 1 C = A < B # all 1 (true) D = A > B # all 0 (false) - + C |= D self.assertEqual( C.signalAt(0), 1.0) C &= D @@ -171,7 +171,7 @@ def test_inplace_boolean_operations(self): self.assertEqual( C.signalAt(0), 1.0) C ^= C self.assertEqual( C.signalAt(0), 0.0) - + def test_not_operator(self): A = mtd['A'] A *= 0 @@ -189,41 +189,41 @@ def test_compound_comparison(self): C = (A > B) & (A > 123) & (B < 2345) self.assertTrue(C is not None) - + def test_compound_boolean_operations(self): A = mtd['A'] A *= 0 B = A + 1 - C = ~(A | B) + C = ~(A | B) self.assertEqual( C.signalAt(0), 0.0) - C = ~(A | B) | B + C = ~(A | B) | B self.assertEqual( C.signalAt(0), 1.0) - C = ~(A | B) | ~A + C = ~(A | B) | ~A self.assertEqual( C.signalAt(0), 1.0) - C = ~(A | B) | ~(A & B) + C = ~(A | B) | ~(A & B) self.assertEqual( C.signalAt(0), 1.0) - + def test_integrated_bin(self): - run_algorithm('BinMD',InputWorkspace="mdw", OutputWorkspace="BH", AxisAligned=True, AlignedDim0="x,0,10,20", AlignedDim1="y,0,10,1", + run_algorithm('BinMD',InputWorkspace="mdw", OutputWorkspace="BH", AxisAligned=True, AlignedDim0="x,0,10,20", AlignedDim1="y,0,10,1", AlignedDim2="z,0,10,30", IterateEvents="1", Parallel="0") BH = mtd['BH'] signal = BH.getSignalArray() - expected =(30L,20L) + expected =(30L,20L) shape = signal.shape self.assertEqual(shape,expected) - mtd.remove('BH') + mtd.remove('BH') def test_composed_bin(self): - run_algorithm('BinMD',InputWorkspace="mdw", OutputWorkspace="BH", AxisAligned=True, AlignedDim0="x,0,10,20", AlignedDim1="y,0,10,1", + run_algorithm('BinMD',InputWorkspace="mdw", OutputWorkspace="BH", AxisAligned=True, AlignedDim0="x,0,10,20", AlignedDim1="y,0,10,1", IterateEvents="1", Parallel="0") BH = mtd['BH'] signal = BH.getSignalArray() expected =(20L,) shape = signal.shape self.assertEqual(shape,expected) - mtd.remove('BH') - - + mtd.remove('BH') + + def test_heterogeneous_bin(self): run_algorithm('CreateMDWorkspace', Dimensions='3',Extents='0,10,0,10,0,10',Names='x,y,z',Units='m,m,m',SplitInto='10', MaxRecursionDepth='1',OutputWorkspace='mdwHW') @@ -232,28 +232,28 @@ def test_heterogeneous_bin(self): SH = mtd['mdwHW'] nEvents = SH.getNPoints(); self.assertEqual(nEvents,1000); - run_algorithm('BinMD',InputWorkspace="mdwHW", OutputWorkspace="BH", AxisAligned=True, AlignedDim0="x,0,10,20", AlignedDim1="y,0,10,5", - AlignedDim2="z,0,10,40", IterateEvents="1", Parallel="0") + run_algorithm('BinMD',InputWorkspace="mdwHW", OutputWorkspace="BH", AxisAligned=True, AlignedDim0="x,0,10,20", AlignedDim1="y,0,10,5", + AlignedDim2="z,0,10,40", IterateEvents="1", Parallel="0") BH = mtd['BH'] nEvents = BH.getNEvents(); self.assertEqual(nEvents,1000); signal = BH.getSignalArray() - expected =(40L,5L,20L) + expected =(40L,5L,20L) shape = signal.shape self.assertEqual(shape,expected) - - for i in range(0,expected[1]): - self.assertEqual(signal[2,i,1],2) - self.assertEqual(signal[1,i,2],0) - + + for i in range(0,expected[1]): + self.assertEqual(signal[2,i,1],2) + self.assertEqual(signal[1,i,2],0) + self.assertEqual(BH.signalAt(3+20*(2+5*1)),signal[1,2,3]) - self.assertEqual(BH.signalAt(4+20*(3+5*2)),signal[2,3,4]) + self.assertEqual(BH.signalAt(4+20*(3+5*2)),signal[2,3,4]) mtd.remove('BH') - mtd.remove('mdwHW') + mtd.remove('mdwHW') + - if __name__ == '__main__': unittest.main() - + diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MatrixWorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MatrixWorkspaceTest.py index 6ea0731986f7..8f107cb34cfb 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MatrixWorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MatrixWorkspaceTest.py @@ -1,5 +1,5 @@ import unittest -import sys +import sys import math from testhelpers import create_algorithm, run_algorithm, can_be_instantiated, WorkspaceCreationHelper from mantid.api import (MatrixWorkspace, MatrixWorkspaceProperty, WorkspaceProperty, Workspace, @@ -20,7 +20,7 @@ def setUp(self): def test_that_one_cannot_be_instantiated_directly(self): self.assertFalse(can_be_instantiated(MatrixWorkspace)) - + def test_hierarchy_is_as_expected(self): self.assertTrue(issubclass(MatrixWorkspace, ExperimentInfo)) self.assertTrue(issubclass(MatrixWorkspace, Workspace)) @@ -33,7 +33,7 @@ def test_meta_information(self): self.assertEquals(self._test_ws.isDirty(), False) self.assertTrue(self._test_ws.getMemorySize() > 0.0) self.assertEquals(self._test_ws.threadSafe(), True) - + def test_workspace_data_information(self): self.assertEquals(self._test_ws.getNumberHistograms(), 2) self.assertEquals(self._test_ws.blocksize(), 102) @@ -45,13 +45,13 @@ def test_axes(self): self.assertEquals(self._test_ws.axes(), 2) xaxis = self._test_ws.getAxis(0) yaxis = self._test_ws.getAxis(1) - + self.assertTrue(xaxis.isNumeric()) self.assertTrue(yaxis.isSpectra()) - + self.assertEquals(xaxis.length(), 103) self.assertEquals(yaxis.length(), 2) - + xunit = xaxis.getUnit() self.assertEquals(xunit.caption(), "Time-of-flight") self.assertEquals(xunit.label(), "microsecond") @@ -62,14 +62,14 @@ def test_axes(self): self.assertEquals(yunit.label(), "") self.assertEquals(yunit.unitID(), "Label") - + def test_detector_retrieval(self): det = self._test_ws.getDetector(0) self.assertTrue(isinstance(det, Detector)) self.assertEquals(det.getID(), 1) self.assertFalse(det.isMasked()) self.assertAlmostEqual(2.71496516, det.getTwoTheta(V3D(0,0,11), V3D(0,0,1))) - + def test_spectrum_retrieval(self): # Spectrum spec = self._test_ws.getSpectrum(1) @@ -100,7 +100,7 @@ def test_that_a_histogram_workspace_is_returned_as_a_MatrixWorkspace_from_a_prop self.assertEquals(type(propValue), MatrixWorkspace) mem = propValue.getMemorySize() self.assertTrue( (mem > 0) ) - + AnalysisDataService.remove(wsname) def test_read_data_members_give_readonly_numpy_array(self): @@ -112,7 +112,7 @@ def do_numpy_test(arr): y = self._test_ws.readY(0) e = self._test_ws.readE(0) dx = self._test_ws.readDx(0) - + for attr in [x,y,e,dx]: do_numpy_test(attr) @@ -121,7 +121,7 @@ def test_setting_spectra_from_array_of_incorrect_length_raises_error(self): xlength = 11 ylength = 10 test_ws = WorkspaceFactory.create("Workspace2D", nvectors, xlength, ylength) - + values = np.arange(xlength + 1) self.assertRaises(ValueError, test_ws.setX, 0, values) self.assertRaises(ValueError, test_ws.setY, 0, values) @@ -132,7 +132,7 @@ def test_setting_spectra_from_array_of_incorrect_shape_raises_error(self): xlength = 11 ylength = 10 test_ws = WorkspaceFactory.create("Workspace2D", nvectors, xlength, ylength) - + values = np.linspace(0,1,num=xlength-1) values = values.reshape(5,2) self.assertRaises(ValueError, test_ws.setX, 0, values) @@ -147,7 +147,7 @@ def test_setting_spectra_from_array_using_incorrect_index_raises_error(self): test_ws = WorkspaceFactory.create("Workspace2D", nvectors, xlength, ylength) xvalues = np.arange(xlength) self.assertRaises(RuntimeError, test_ws.setX, 3, xvalues) - + def test_setting_spectra_from_array_sets_expected_values(self): nvectors = 2 xlength = 11 @@ -165,7 +165,7 @@ def test_setting_spectra_from_array_sets_expected_values(self): test_ws.setY(ws_index, values) ws_values = test_ws.readY(ws_index) self.assertTrue(np.array_equal(values, ws_values)) - + values = np.sqrt(values) test_ws.setE(ws_index, values) ws_values = test_ws.readE(ws_index) @@ -176,7 +176,7 @@ def test_data_can_be_extracted_to_numpy_successfully(self): y = self._test_ws.extractY() e = self._test_ws.extractE() dx = self._test_ws.extractDx() - + self.assertTrue(len(dx), 0) self._do_numpy_comparison(self._test_ws, x, y, e) @@ -189,11 +189,11 @@ def _do_numpy_comparison(self, workspace, x_np, y_np, e_np, index = None): nhist = 1 start = index end = index+nhist - + blocksize = workspace.blocksize() for arr in (x_np, y_np, e_np): self.assertEquals(type(arr), np.ndarray) - + if nhist > 1: self.assertEquals(x_np.shape, (nhist, blocksize + 1)) # 2 rows, 103 columns self.assertEquals(y_np.shape, (nhist, blocksize)) # 2 rows, 102 columns @@ -202,11 +202,11 @@ def _do_numpy_comparison(self, workspace, x_np, y_np, e_np, index = None): self.assertEquals(x_np.shape, (blocksize + 1,)) # 2 rows, 103 columns self.assertEquals(y_np.shape, (blocksize,)) # 2 rows, 102 columns self.assertEquals(e_np.shape, (blocksize,)) # 2 rows, 102 columns - - + + for i in range(start, end): if nhist > 1: - x_arr = x_np[i] + x_arr = x_np[i] y_arr = y_np[i] e_arr = e_np[i] else: @@ -219,37 +219,37 @@ def _do_numpy_comparison(self, workspace, x_np, y_np, e_np, index = None): self.assertEquals(e_arr[j], workspace.readE(i)[j]) # Extra X boundary self.assertEquals(x_arr[blocksize], workspace.readX(i)[blocksize]) - + def test_data_members_give_writable_numpy_array(self): def do_numpy_test(arr): self.assertEquals(type(arr), np.ndarray) self.assertTrue(arr.flags.writeable) - + x = self._test_ws.dataX(0) y = self._test_ws.dataY(0) e = self._test_ws.dataE(0) dx = self._test_ws.dataDx(0) - + for attr in [x,y,e,dx]: do_numpy_test(attr) - + self.assertTrue(len(dx), 0) self._do_numpy_comparison(self._test_ws, x, y, e, 0) - + # Can we change something ynow = y[0] ynow *= 2.5 y[0] = ynow self.assertEquals(self._test_ws.readY(0)[0], ynow) - - + + def test_operators_with_workspaces_in_ADS(self): run_algorithm('CreateWorkspace', OutputWorkspace='a',DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') ads = AnalysisDataService A = ads['a'] run_algorithm('CreateWorkspace', OutputWorkspace='b', DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') B = ads['b'] - + # Equality self.assertTrue(A.equals(B, 1e-8)) # Two workspaces @@ -257,7 +257,7 @@ def test_operators_with_workspaces_in_ADS(self): C = A - B C = A * B C = A / B - + C -= B self.assertTrue(isinstance(C, MatrixWorkspace)) C += B @@ -266,7 +266,7 @@ def test_operators_with_workspaces_in_ADS(self): self.assertTrue(isinstance(C, MatrixWorkspace)) C /= B self.assertTrue(isinstance(C, MatrixWorkspace)) - + # Workspace + double B = 123.456 C = A + B @@ -294,11 +294,11 @@ def test_operators_with_workspaces_in_ADS(self): # Commutative: double + workspace C = B * A C = B + A - + ads.remove('A') ads.remove('B') ads.remove('C') - + def test_complex_binary_ops_do_not_leave_temporary_workspaces_behind(self): run_algorithm('CreateWorkspace', OutputWorkspace='ca', DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') ads = AnalysisDataService @@ -307,7 +307,7 @@ def test_complex_binary_ops_do_not_leave_temporary_workspaces_behind(self): self.assertTrue('w1' in ads) self.assertTrue('ca' in ads) self.assertTrue('__python_op_tmp0' not in ads) - + def test_history_access(self): run_algorithm('CreateWorkspace', OutputWorkspace='raw',DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') run_algorithm('Rebin', InputWorkspace='raw', Params=[1.,0.5,3.],OutputWorkspace='raw') @@ -321,7 +321,7 @@ def test_history_access(self): self.assertEquals(first.getPropertyValue("OutputWorkspace"), "raw") AnalysisDataService.remove('raw') - def test_setTitleAndComment(self): + def test_setTitleAndComment(self): run_algorithm('CreateWorkspace', OutputWorkspace='ws1',DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') ws1 = AnalysisDataService['ws1'] title = 'test_title' @@ -334,4 +334,4 @@ def test_setTitleAndComment(self): if __name__ == '__main__': unittest.main() - + diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MultipleFilePropertyTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MultipleFilePropertyTest.py index 3955b8ae5b88..a1b5c17c3a3d 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MultipleFilePropertyTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/MultipleFilePropertyTest.py @@ -30,6 +30,6 @@ def test_value_member_returns_nested_python_list_for_summed_files(self): self.assertTrue(isinstance(filenames, list)) self.assertTrue(isinstance(filenames[0], str)) self.assertEquals(len(filenames[1]), 2) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ProgressTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ProgressTest.py index 7d9d04ccf066..71cbb3a6d0be 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ProgressTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/ProgressTest.py @@ -9,14 +9,14 @@ def test_class_inherits_ProgressBase(self): def test_object_can_be_constructed_with_PythonAlgorithm(self): class ProgressConstructTestAlgorithm(PythonAlgorithm): - + def PyInit(self): pass def PyExec(self): prog_reporter = Progress(self,0.0,1.0,100) if not isinstance(prog_reporter, Progress): raise RuntimeError("Object constructed but it is not of the correct type!") - + # Test test_alg = ProgressConstructTestAlgorithm() test_alg.initialize() @@ -24,7 +24,7 @@ def PyExec(self): def test_object_can_be_successfully_report_with_PythonAlgorithm(self): class ProgressReportTestAlgorithm(PythonAlgorithm): - + def PyInit(self): pass def PyExec(self): diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmChildAlgCallTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmChildAlgCallTest.py index 0659db3b79ad..8645d20fb3ad 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmChildAlgCallTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmChildAlgCallTest.py @@ -18,9 +18,9 @@ class PythonAlgorithmChildAlgCallTestAlg(PythonAlgorithm): def PyInit(self): - self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("InputWorkspace", "", direction=Direction.Input)) - self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", + self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output)) def PyExec(self): @@ -33,11 +33,11 @@ def PyExec(self): class PythonAlgorithmChildAlgCallTest(unittest.TestCase): - + _alg_reg = False _ws_name = "test_ws" _ws_name2 = "test_ws_1" - + def setUp(self): if not self._alg_reg: # Register algorithm @@ -49,7 +49,7 @@ def tearDown(self): mtd.remove(self._ws_name) if self._ws_name2 in mtd: mtd.remove(self._ws_name2) - + def test_ChildAlg_call_with_output_and_input_ws_the_same_succeeds(self): data = [1.0] api.CreateWorkspace(DataX=data,DataY=data,NSpec=1,UnitX='Wavelength', OutputWorkspace=self._ws_name) @@ -64,7 +64,7 @@ def test_ChildAlg_call_with_output_and_input_ws_the_same_succeeds(self): def test_ChildAlg_call_with_output_and_input_ws_different_succeeds(self): data = [1.0] api.CreateWorkspace(DataX=data,DataY=data,NSpec=1,UnitX='Wavelength', OutputWorkspace=self._ws_name) - + try: run_algorithm('PythonAlgorithmChildAlgCallTestAlg', InputWorkspace=self._ws_name, OutputWorkspace=self._ws_name2) except Exception,exc: diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmPropertiesTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmPropertiesTest.py index 5bd4527b81d9..46c85e4873ca 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmPropertiesTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmPropertiesTest.py @@ -1,4 +1,4 @@ -"""Defines tests for the simple property declarations types within +"""Defines tests for the simple property declarations types within Python algorithms """ @@ -12,13 +12,13 @@ # ====================================================================== class PythonAlgorithmPropertiesTest(unittest.TestCase): - + def test_simple_property_declarations_have_correct_attrs(self): """ Test the basic property declarations without validators """ class BasicPropsAlg(PythonAlgorithm): - + _testdocstring = "This is a doc string" def PyInit(self): self.declareProperty('SimpleInput', 1) @@ -28,7 +28,7 @@ def PyInit(self): self.declareProperty('PropWithDocDefaultDir', 1, self._testdocstring) self.declareProperty('PropWithDocOutputDir', 1.0, self._testdocstring, Direction.Output) - + def PyExec(self): pass ########################################################################## @@ -38,7 +38,7 @@ def PyExec(self): alg.initialize() props = alg.getProperties() self.assertEquals(6, len(props)) - + input = alg.getProperty("SimpleInput") self.assertEquals(input.direction, Direction.Input) self.assertEquals(input.value, 1) @@ -51,27 +51,27 @@ def PyExec(self): str_prop = alg.getProperty("InputString") self.assertEquals(str_prop.direction, Direction.Input) self.assertEquals(str_prop.value, "") - + doc_prop_def_dir = alg.getProperty("PropWithDocDefaultDir") self.assertEquals(doc_prop_def_dir.direction, Direction.Input) self.assertEquals(doc_prop_def_dir.documentation, alg._testdocstring) doc_prop_out_dir = alg.getProperty("PropWithDocOutputDir") self.assertEquals(doc_prop_out_dir.direction, Direction.Output) self.assertEquals(doc_prop_out_dir.documentation, alg._testdocstring) - + def test_properties_obey_attached_validators(self): """ Test property declarations with validator. The validators each have their own test. """ class PropertiesWithValidation(PythonAlgorithm): - + def PyInit(self): only_positive = IntBoundedValidator() only_positive.setLower(0) self.declareProperty('NumPropWithDefaultDir', -1, only_positive) self.declareProperty('NumPropWithInOutDir', -1, only_positive,"doc string", Direction.InOut) - + def PyExec(self): pass ################################################### @@ -79,25 +79,25 @@ def PyExec(self): alg.initialize() props = alg.getProperties() self.assertEquals(2, len(props)) - + def_dir = alg.getProperty("NumPropWithDefaultDir") self.assertEquals(def_dir.direction, Direction.Input) self.assertNotEquals("", def_dir.isValid) self.assertRaises(ValueError, alg.setProperty, "NumPropWithDefaultDir", -10) testhelpers.assertRaisesNothing(self, alg.setProperty, "NumPropWithDefaultDir", 11) - + def test_specialized_property_declaration(self): """ Test property declaration using a specialised property. The property types should have their own tests too. """ class SpecializedProperties(PythonAlgorithm): - + _testdocstring = 'This is a FileProperty' def PyInit(self): self.declareProperty(FileProperty("NoDocString", "", FileAction.Load)) self.declareProperty(FileProperty("WithDocString", "", FileAction.Load), self._testdocstring) - + def PyExec(self): pass #################################################### @@ -105,7 +105,7 @@ def PyExec(self): alg.initialize() props = alg.getProperties() self.assertEquals(2, len(props)) - + nodoc = alg.getProperty("NoDocString") self.assertTrue(isinstance(nodoc, FileProperty)) self.assertEquals("", nodoc.documentation) @@ -118,12 +118,12 @@ def test_passing_settings_object_connects_to_correct_object(self): from mantid.kernel import EnabledWhenProperty, PropertyCriterion class DummyAlg(PythonAlgorithm): - + def PyInit(self): self.declareProperty("BasicProp1",1) self.declareProperty("BasicProp2",1) self.setPropertySettings("BasicProp2", EnabledWhenProperty("BasicProp1", PropertyCriterion.IsDefault)) - + def PyExec(self): pass ## @@ -134,7 +134,7 @@ def PyExec(self): self.assertTrue(settings.isEnabled(alg)) alg.setProperty("BasicProp1", 2) # not default self.assertTrue(not settings.isEnabled(alg)) - - + + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmTraitsTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmTraitsTest.py index b30f74d9bfc5..6dc25ccad3d4 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmTraitsTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmTraitsTest.py @@ -7,7 +7,7 @@ import types from mantid.kernel import Direction -from mantid.api import (PythonAlgorithm, AlgorithmProxy, Algorithm, IAlgorithm, +from mantid.api import (PythonAlgorithm, AlgorithmProxy, Algorithm, IAlgorithm, AlgorithmManager, AlgorithmFactory) ########################### Test classes ##################################### @@ -15,60 +15,60 @@ class TestPyAlgDefaultAttrs(PythonAlgorithm): def PyInit(self): pass - + def PyExec(self): pass class TestPyAlgOverriddenAttrs(PythonAlgorithm): - + def version(self): return 2 - + def category(self): return "BestAlgorithms" - + def isRunning(self): return True - + def PyInit(self): pass - + def PyExec(self): pass - + class TestPyAlgIsRunningReturnsNonBool(PythonAlgorithm): def isRunning(self): return 1 - + def PyInit(self): pass - + def PyExec(self): pass class CancellableAlg(PythonAlgorithm): - + is_running = True - + def PyInit(self): pass - + def PyExec(self): pass - + def isRunning(self): return self.is_running - + def cancel(self): self.is_running = False ############################################################################### class PythonAlgorithmTest(unittest.TestCase): - + _registered = None - + def setUp(self): if self.__class__._registered is None: self.__class__._registered = True @@ -76,7 +76,7 @@ def setUp(self): AlgorithmFactory.subscribe(TestPyAlgOverriddenAttrs) AlgorithmFactory.subscribe(TestPyAlgIsRunningReturnsNonBool) AlgorithmFactory.subscribe(CancellableAlg) - + def test_managed_alg_is_descendent_of_AlgorithmProxy(self): alg = AlgorithmManager.create("TestPyAlgDefaultAttrs") self.assertTrue(isinstance(alg, AlgorithmProxy)) @@ -87,12 +87,12 @@ def test_unmanaged_alg_is_descendent_of_PythonAlgorithm(self): self.assertTrue(isinstance(alg, PythonAlgorithm)) self.assertTrue(isinstance(alg, Algorithm)) self.assertTrue(isinstance(alg, IAlgorithm)) - + def test_alg_with_default_attrs(self): testhelpers.assertRaisesNothing(self,AlgorithmManager.createUnmanaged, "TestPyAlgDefaultAttrs") alg = AlgorithmManager.createUnmanaged("TestPyAlgDefaultAttrs") testhelpers.assertRaisesNothing(self,alg.initialize) - + self.assertEquals(alg.name(), "TestPyAlgDefaultAttrs") self.assertEquals(alg.version(), 1) self.assertEquals(alg.category(), "PythonAlgorithms") @@ -111,7 +111,7 @@ def test_alg_can_be_cancelled(self): self.assertTrue(alg.isRunning()) alg.cancel() self.assertTrue(not alg.isRunning()) - + # --------------------------- Failure cases -------------------------------------------- def test_isRunning_returning_non_bool_raises_error(self): alg = AlgorithmManager.createUnmanaged("TestPyAlgIsRunningReturnsNonBool") diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmWorkspacePropertyTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmWorkspacePropertyTest.py index 861677156f29..b3cc1571dbc9 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmWorkspacePropertyTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/PythonAlgorithmWorkspacePropertyTest.py @@ -1,4 +1,4 @@ -"""Defines tests for the WorkspaceProperty types within +"""Defines tests for the WorkspaceProperty types within Python algorithms """ import unittest @@ -6,19 +6,19 @@ from mantid.kernel import Direction class PythonAlgorithmWorkspacePropertyTest(unittest.TestCase): - + def _do_test(self, classtype): """Perform the test for the given type - + @param classtype :: The property class to declare """ class WorkspaceProperties(PythonAlgorithm): - + _testdocstring = 'This is a workspace property' def PyInit(self): self.declareProperty(classtype("NoDocString", "", Direction.Input)) self.declareProperty(classtype("WithDocString", "", Direction.Input), self._testdocstring) - + def PyExec(self): pass ####################################################### @@ -26,14 +26,14 @@ def PyExec(self): alg.initialize() props = alg.getProperties() self.assertEquals(2, len(props)) - + nodoc = alg.getProperty("NoDocString") self.assertTrue(isinstance(nodoc, classtype)) self.assertEquals("", nodoc.documentation) withdoc = alg.getProperty("WithDocString") self.assertTrue(isinstance(withdoc, classtype)) self.assertEquals(alg._testdocstring, withdoc.documentation) - + def test_alg_accepts_WorkspaceProperty_declaration(self): """Runs test for a general WorkspaceProperty """ @@ -41,4 +41,3 @@ def test_alg_accepts_WorkspaceProperty_declaration(self): if __name__ == "__main__": unittest.main() - \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/RunPythonScriptTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/RunPythonScriptTest.py index edd958a63303..633b128ce5a9 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/RunPythonScriptTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/RunPythonScriptTest.py @@ -11,7 +11,7 @@ class RunPythonScriptTest(unittest.TestCase): """ Try out RunPythonScript """ - + def setUp(self): CreateWorkspace(OutputWorkspace='ws',DataX='1,2,3,4',DataY='1,2,3',DataE='1,2,3') @@ -19,16 +19,16 @@ def tearDown(self): mtd.clear() # ======================== Success cases ===================================================== - + def test_Code_Without_Workspaces_Is_Successful_If_Code_Does_Not_Use_Workspace_References(self): code = "x = 5 + 2" RunPythonScript(Code=code) - + def test_simplePlus(self): code = "Plus(LHSWorkspace=input, RHSWorkspace=input, OutputWorkspace=output)" RunPythonScript(InputWorkspace="ws", Code=code, OutputWorkspace='ws_out') ws_out = mtd['ws_out'] - + self.assertAlmostEqual(ws_out.dataY(0)[0], 2.0, 3) self.assertAlmostEqual(ws_out.dataY(0)[1], 4.0, 3) self.assertAlmostEqual(ws_out.dataY(0)[2], 6.0, 3) @@ -38,7 +38,7 @@ def test_usingOperators(self): code = "output = input * 5.0" RunPythonScript(InputWorkspace="ws", Code=code, OutputWorkspace='ws_out') ws_out = mtd['ws_out'] - + self.assertAlmostEqual(ws_out.dataY(0)[0], 5.0, 3) self.assertAlmostEqual(ws_out.dataY(0)[1],10.0, 3) self.assertAlmostEqual(ws_out.dataY(0)[2],15.0, 3) @@ -55,7 +55,7 @@ def test_input_EventWorkspace_has_correct_python_type_when_executed(self): if not isinstance(input, IEventWorkspace): raise RuntimeError("Input workspace is not an IEventWorkspace in Python: Type=%s" % str(type(input))) """ RunPythonScript(InputWorkspace=test_eventws, Code=code) - + # Properties handle MDWorkspace types. def test_withMDWorkspace(self): CreateMDWorkspace(OutputWorkspace="ws", Dimensions='1', Extents='-10,10', Names='x', Units='m') @@ -69,7 +69,7 @@ def test_withMDWorkspace(self): if not isinstance(input, IMDEventWorkspace): raise RuntimeError("Input workspace is not an IMDHistoWorkspace in Python: Type=%s" % str(type(input))) """ RunPythonScript(InputWorkspace=mtd['ws'], Code=code) - + def test_withNoInputWorkspace(self): c = RunPythonScript(Code="output = CreateSingleValuedWorkspace(DataValue='1')") self.assertEqual(c.readY(0)[0], 1) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/RunTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/RunTest.py index a3dcbbcccc14..5def188c15de 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/RunTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/RunTest.py @@ -7,7 +7,7 @@ class RunTest(unittest.TestCase): _expt_ws = None _nspec=1 - + def setUp(self): if self.__class__._expt_ws is None: alg = run_algorithm('CreateWorkspace', DataX=[1,2,3,4,5], DataY=[1,2,3,4,5],NSpec=self._nspec, child=True) @@ -27,7 +27,7 @@ def test_proton_charge_returns_a_double(self): charge = run.getProtonCharge() self.assertEquals(type(charge), float) self.assertAlmostEquals(charge, 10.05, 2) - + def test_run_hasProperty(self): self.assertTrue(self._expt_ws.run().hasProperty('start_time')) self.assertTrue('start_time' in self._expt_ws.run()) @@ -37,7 +37,7 @@ def test_run_getProperty(self): run_start = self._expt_ws.run().getProperty('start_time') self.assertEquals(type(run_start.value), str) self.assertEquals(run_start.value, "2008-12-18T17:58:38") - + def do_spectra_check(nspectra): self.assertEquals(type(nspectra.value), int) self.assertEquals(nspectra.value, self._nspec) @@ -50,7 +50,7 @@ def do_spectra_check(nspectra): # get returns the default if key does not exist, or None if no default self.assertEquals(self._expt_ws.run().get('not_a_log'), None) self.assertEquals(self._expt_ws.run().get('not_a_log', 5.), 5.) - + def test_add_property_with_known_type_succeeds(self): run = self._expt_ws.run() nprops = len(run.getProperties()) @@ -73,12 +73,12 @@ def test_add_propgates_units_correctly(self): def test_add_property_with_unknown_type_raises_error(self): run = self._expt_ws.run() self.assertRaises(ValueError, run.addProperty, 'dict_t', {}, False) - + def test_keys_returns_a_list_of_the_property_names(self): run = self._expt_ws.run() names = run.keys() self.assertEqual(type(names), list) - + # Test a few self.assertTrue('nspectra' in names) self.assertTrue('start_time' in names) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceFactoryTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceFactoryTest.py index 69ad04e7b5e7..d18f4ced57a3 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceFactoryTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceFactoryTest.py @@ -7,11 +7,11 @@ class WorkspaceFactoryTest(unittest.TestCase): def test_WorkspaceFactory_isinstance_of_WorkspaceFactoryImpl(self): self.assertTrue(isinstance(WorkspaceFactory, WorkspaceFactoryImpl)) - + def _create_clean_workspace(self, nhist, xlength, ylength): - return WorkspaceFactory.create("Workspace2D", NVectors=nhist, + return WorkspaceFactory.create("Workspace2D", NVectors=nhist, XLength=xlength, YLength=ylength) - + def _verify(self, wksp, nhist, xlength, ylength): self.assertEquals(type(wksp), MatrixWorkspace) self.assertEquals(wksp.id(), "Workspace2D") @@ -25,7 +25,7 @@ def test_creating_a_clean_workspace_is_correct_size_and_type(self): ylength = 4 wksp = self._create_clean_workspace(nhist, xlength, ylength) self._verify(wksp, nhist, xlength, ylength) - + def test_creating_a_workspace_from_another_gives_one_of_same_size(self): nhist = 2 xlength = 3 @@ -33,7 +33,7 @@ def test_creating_a_workspace_from_another_gives_one_of_same_size(self): clean = self._create_clean_workspace(nhist, xlength, ylength) copy = WorkspaceFactory.create(clean) self._verify(copy, nhist, xlength, ylength) - + def test_creating_a_workspace_from_another_with_different_size(self): clean = self._create_clean_workspace(nhist=2, xlength=3, ylength=4) nhist = 4 @@ -41,7 +41,7 @@ def test_creating_a_workspace_from_another_with_different_size(self): ylength = 6 copy = WorkspaceFactory.create(clean, nhist, xlength, ylength) self._verify(copy, nhist, xlength, ylength) - + def test_creating_a_tableworkspace(self): table = WorkspaceFactory.createTable() self.assertTrue(isinstance(table, ITableWorkspace)) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceGroupTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceGroupTest.py index dc08f562c06d..4bc3c5f2e561 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceGroupTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceGroupTest.py @@ -3,7 +3,7 @@ from mantid.api import mtd, WorkspaceGroup, MatrixWorkspace class WorkspaceGroupTest(unittest.TestCase): - + def test_group_interface(self): run_algorithm('CreateWorkspace', OutputWorkspace='First',DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') run_algorithm('CreateWorkspace', OutputWorkspace='Second',DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') @@ -21,7 +21,7 @@ def test_group_interface(self): expected = ['First', 'Second'] for i in range(len(names)): self.assertEquals(expected[i], names[i]) - + # Clearing the data should leave the handle unusable mtd.clear() try: @@ -29,14 +29,14 @@ def test_group_interface(self): self.fail("WorkspaceGroup handle is still usable after ADS has been cleared, it should be a weak reference and raise an error.") except RuntimeError, exc: self.assertEquals(str(exc), 'Variable invalidated, data has been deleted.') - + def test_group_index_access_returns_correct_workspace(self): run_algorithm('CreateWorkspace', OutputWorkspace='First',DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') run_algorithm('CreateWorkspace', OutputWorkspace='Second',DataX=[4.,5.,6.], DataY=[4.,5.], DataE=[2.,3.],UnitX='TOF') run_algorithm('CreateWorkspace', OutputWorkspace='Third',DataX=[7.,8.,9.], DataY=[6.,7.], DataE=[2.,3.],UnitX='TOF') run_algorithm('GroupWorkspaces',InputWorkspaces='First,Second,Third',OutputWorkspace='grouped') group = mtd['grouped'] - + self.assertRaises(IndexError, group.__getitem__, 3) # Index out of bounds for i in range(3): member = group[i] @@ -44,7 +44,7 @@ def test_group_index_access_returns_correct_workspace(self): def test_SimpleAlgorithm_Accepts_Group_Handle(self): from mantid.simpleapi import Scale - + run_algorithm('CreateWorkspace', OutputWorkspace='First',DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') run_algorithm('CreateWorkspace', OutputWorkspace='Second',DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') run_algorithm('GroupWorkspaces',InputWorkspaces='First,Second',OutputWorkspace='group') @@ -62,9 +62,9 @@ def test_complex_binary_operations_with_group_do_not_leave_temporary_workspaces_ run_algorithm('CreateWorkspace', OutputWorkspace='grouped_1',DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') run_algorithm('CreateWorkspace', OutputWorkspace='grouped_2',DataX=[1.,2.,3.], DataY=[2.,3.], DataE=[2.,3.],UnitX='TOF') run_algorithm('GroupWorkspaces',InputWorkspaces='grouped_1,grouped_2',OutputWorkspace='grouped') - + w1=(mtd['grouped']*0.0)+1.0 - + self.assertTrue('w1' in mtd) self.assertTrue('grouped' in mtd) self.assertTrue('grouped_1' in mtd) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspacePropertiesTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspacePropertiesTest.py index 41dd7e6546ce..fc302d2482ec 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspacePropertiesTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspacePropertiesTest.py @@ -1,10 +1,10 @@ -"""Tests the construction of the various workspace +"""Tests the construction of the various workspace property types """ import unittest import testhelpers -from mantid.api import (WorkspaceProperty, WorkspaceGroupProperty, MatrixWorkspaceProperty, - IEventWorkspaceProperty, ITableWorkspaceProperty, IMDHistoWorkspaceProperty, +from mantid.api import (WorkspaceProperty, WorkspaceGroupProperty, MatrixWorkspaceProperty, + IEventWorkspaceProperty, ITableWorkspaceProperty, IMDHistoWorkspaceProperty, PropertyMode, LockMode) from mantid.kernel import Direction, Property @@ -14,14 +14,14 @@ def _do_test(self, classtype): self.assertTrue(issubclass(WorkspaceGroupProperty, Property)) self._do_construction_with_name_default_direction(classtype) self._do_construction_with_name_default_direction_optional(classtype) - + def _do_construction_with_name_default_direction(self, classtype): prop = classtype("NoValidation", "test", Direction.Output) self.assertTrue(isinstance(prop, classtype)) self.assertEquals("NoValidation", prop.name) self.assertEquals(Direction.Output, prop.direction) self.assertEquals("test", prop.valueAsStr) - + def _do_construction_with_name_default_direction_optional(self, classtype): prop = classtype("IsOptional", "test", Direction.Output, PropertyMode.Optional) self.assertTrue(isinstance(prop, classtype)) @@ -38,7 +38,7 @@ def _do_construction_with_name_default_direction_optional_no_locking(self, class self.assertTrue(prop.isOptional()) self.assertFalse(prop.isLocking()) self.assertEquals("test", prop.valueAsStr) - + def test_WorkspaceProperty_can_be_instantiated(self): self._do_test(WorkspaceProperty) @@ -53,9 +53,9 @@ def test_IEventWorkspaceProperty_can_be_instantiated(self): def test_ITableWorkspaceProperty_can_be_instantiated(self): self._do_test(ITableWorkspaceProperty) - - def test_IHistoWorkspaceProperty_can_be_instantiated(self): + + def test_IHistoWorkspaceProperty_can_be_instantiated(self): self._do_test(IMDHistoWorkspaceProperty) - + if __name__ == "__main__": unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceTest.py index 863882078048..c94c9861aa70 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceTest.py @@ -3,7 +3,7 @@ from mantid.api import Workspace class WorkspaceTest(unittest.TestCase): - + def test_that_one_cannot_be_instantiated(self): try: Workspace() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceValidatorsTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceValidatorsTest.py index 0a856fc23a4e..0d21b8cf5d8c 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceValidatorsTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/api/WorkspaceValidatorsTest.py @@ -4,18 +4,18 @@ import unittest import testhelpers from mantid.kernel import IValidator -from mantid.api import (WorkspaceUnitValidator, HistogramValidator, +from mantid.api import (WorkspaceUnitValidator, HistogramValidator, RawCountValidator, CommonBinsValidator, SpectraAxisValidator, NumericAxisValidator, InstrumentValidator) class WorkspaceValidatorsTest(unittest.TestCase): - + def test_WorkspaceUnitValidator_construction(self): """ Test that the WorkspaceUnitValidator can be constructed with a single string - """ + """ testhelpers.assertRaisesNothing(self, WorkspaceUnitValidator,"DeltaE") self.assertRaises(Exception, WorkspaceUnitValidator) @@ -25,13 +25,13 @@ def test_CommonBinsValidator_construction(self): with no args """ testhelpers.assertRaisesNothing(self, CommonBinsValidator) - + def test_HistogramValidator_construction(self): """ Test that the HistogramValidator can be constructed with no args or a single bool """ - testhelpers.assertRaisesNothing(self, HistogramValidator) + testhelpers.assertRaisesNothing(self, HistogramValidator) testhelpers.assertRaisesNothing(self, HistogramValidator, False) def test_RawCountValidator_construction(self): @@ -39,31 +39,31 @@ def test_RawCountValidator_construction(self): Test that the HistogramValidator can be constructed with no args or a single bool """ - testhelpers.assertRaisesNothing(self, RawCountValidator) - testhelpers.assertRaisesNothing(self, RawCountValidator, False) + testhelpers.assertRaisesNothing(self, RawCountValidator) + testhelpers.assertRaisesNothing(self, RawCountValidator, False) def test_SpectraAxisValidator_construction(self): """ Test that the SpectraAxis can be constructed with no args or a single integer """ - testhelpers.assertRaisesNothing(self, SpectraAxisValidator) + testhelpers.assertRaisesNothing(self, SpectraAxisValidator) testhelpers.assertRaisesNothing(self, SpectraAxisValidator, 0) - + def test_NumericAxisValidator_construction(self): """ Test that the NumericAxis can be constructed with no args or a single integer """ - testhelpers.assertRaisesNothing(self, NumericAxisValidator) + testhelpers.assertRaisesNothing(self, NumericAxisValidator) testhelpers.assertRaisesNothing(self, NumericAxisValidator, 0) - + def test_InstrumentValidator_construction(self): """ Test that the InstrumentValidator can be constructed with no args """ - testhelpers.assertRaisesNothing(self, InstrumentValidator) - + testhelpers.assertRaisesNothing(self, InstrumentValidator) + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/IComponentTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/IComponentTest.py index 187bd1186c36..7482db74e8c0 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/IComponentTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/IComponentTest.py @@ -3,10 +3,10 @@ from mantid.geometry import IComponent class IComponentTest(unittest.TestCase): - + def test_IComponent_cannot_be_instantiated(self): self.assertFalse(can_be_instantiated(IComponent)) - + def test_IComponent_has_expected_attributes(self): attrs = dir(IComponent) expected_attrs = ["getPos", "getDistance", "getName", "type"] diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/InstrumentTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/InstrumentTest.py index 860d3f211b3e..be3f1c313759 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/InstrumentTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/InstrumentTest.py @@ -4,14 +4,14 @@ from testhelpers import can_be_instantiated, WorkspaceCreationHelper class InstrumentTest(unittest.TestCase): - + __testws = None - + def setUp(self): if self.__testws is None: self.__class__.__testws = \ WorkspaceCreationHelper.create2DWorkspaceWithFullInstrument(1,1) - + def test_Instrument_cannot_be_instantiated(self): self.assertFalse(can_be_instantiated(Instrument)) @@ -26,7 +26,7 @@ def test_getSource(self): def test_getComponentByName(self): comp = self.__testws.getInstrument().getComponentByName("pixel-0)") self.assertTrue(isinstance(comp, Detector)) - + def test_getDetector(self): comp = self.__testws.getInstrument().getDetector(1) self.assertTrue(isinstance(comp, Detector)) @@ -39,7 +39,7 @@ def test_ValidDates(self): inst = self.__testws.getInstrument() valid_from = inst.getValidFromDate() valid_to = inst.getValidToDate() - + self.assertTrue(isinstance(valid_from, DateAndTime)) self.assertTrue(isinstance(valid_to, DateAndTime)) @@ -47,6 +47,6 @@ def test_baseInstrument_Can_Be_Retrieved(self): inst = self.__testws.getInstrument() base_inst = inst.getBaseInstrument() self.assertEquals("testInst", base_inst.getName()) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/ObjectTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/ObjectTest.py index 977e7ff37e8c..4e26463140f7 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/ObjectTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/ObjectTest.py @@ -2,9 +2,9 @@ from mantid.geometry import BoundingBox, Object class ObjectTest(unittest.TestCase): - + _testws = None - + def setUp(self): import testhelpers if not self.__class__._testws: diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/OrientedLatticeTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/OrientedLatticeTest.py index d3387d12f12f..ba0e5b253a9e 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/OrientedLatticeTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/OrientedLatticeTest.py @@ -5,7 +5,7 @@ import numpy as np class OrientedLatticeTest(unittest.TestCase): - + def test_OrientedLattice_is_subclass_of_UnitCell(self): self.assertTrue(issubclass(OrientedLattice, UnitCell)) @@ -21,7 +21,7 @@ def test_simple_values(self): self.assertAlmostEqual(u3.volume(),1./u2.recVolume(),10) u2.seta(3); self.assertAlmostEqual(u2.a(),3,10) - + def test_setu_matrix_from_vectors(self): def run_test(v1, v2): cell = OrientedLattice() @@ -36,7 +36,7 @@ def run_test(v1, v2): run_test([1,0,0],[0,1,0]) # Set from numpy arrays run_test(np.array([1,0,0]),np.array([0,1,0])) - + def test_qFromHKL(self): ol = OrientedLattice(1,1,1) hkl = V3D(1,1,1) @@ -44,8 +44,8 @@ def test_qFromHKL(self): self.assertAlmostEqual(hkl.X() * 2 * np.pi, qVec.X(), 9) self.assertAlmostEqual(hkl.Y() * 2 * np.pi, qVec.Y(), 9) self.assertAlmostEqual(hkl.Z() * 2 * np.pi, qVec.Z(), 9) - - + + def test_hklFromQ(self): ol = OrientedLattice(1,1,1) qVec = V3D(1,1,1) @@ -53,30 +53,30 @@ def test_hklFromQ(self): self.assertAlmostEqual(hkl.X() * 2 * np.pi, qVec.X(), 9) self.assertAlmostEqual(hkl.Y() * 2 * np.pi, qVec.Y(), 9) self.assertAlmostEqual(hkl.Z() * 2 * np.pi, qVec.Z(), 9) - + def test_qFromHLK_input_types(self): ''' Test that you can provide input hkl values as different python types. ''' ol = OrientedLattice(1,1,1) - + self.assertTrue(isinstance( ol.qFromHKL(V3D(1,1,1)), V3D), "Should work with V3D input") - + self.assertTrue(isinstance( ol.qFromHKL([1,1,1]), V3D), "Should work with python array input" ) - + self.assertTrue(isinstance( ol.qFromHKL(np.array([1,1,1])), V3D), "Should work with numpy array input" ) - + def test_hklFromQ_input_types(self): ''' Test that you can provide input q values as different python types. ''' ol = OrientedLattice(1,1,1) - + self.assertTrue(isinstance( ol.hklFromQ(V3D(1,1,1)), V3D), "Should work with V3D input") - + self.assertTrue(isinstance( ol.hklFromQ([1,1,1]), V3D), "Should work with python array input" ) - + self.assertTrue(isinstance( ol.hklFromQ(np.array([1,1,1])), V3D), "Should work with numpy array input" ) - + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/RectangularDetectorTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/RectangularDetectorTest.py index ab426a4ccd49..6afedaa3cbbe 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/RectangularDetectorTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/RectangularDetectorTest.py @@ -3,16 +3,16 @@ from testhelpers import can_be_instantiated, WorkspaceCreationHelper class RectangularDetectorTest(unittest.TestCase): - + def test_RectangularDetector_cannot_be_instantiated(self): self.assertFalse(can_be_instantiated(RectangularDetector)) - + def test_RectangularDetector_has_expected_attributes(self): attrs = dir(RectangularDetector) expected_attrs = ['idfillbyfirst_y','idstart', 'idstep','idstepbyrow', 'maxDetectorID', 'minDetectorID', 'xpixels', 'xsize', 'xstart', 'xstep', 'ypixels', 'ysize', 'ystart', 'ystep','type','nelements'] for att in expected_attrs: self.assertTrue(att in attrs) - + def test_RectangularDetector_getattributes(self): testws = WorkspaceCreationHelper.create2DWorkspaceWithRectangularInstrument(3,5,5) i = testws.getInstrument() @@ -28,6 +28,6 @@ def test_RectangularDetector_getattributes(self): self.assertEquals(i[1].idstepbyrow(),5) self.assertEquals(i[1].maxDetectorID(),74) self.assertEquals(i[1].minDetectorID(),50) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/ReferenceFrameTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/ReferenceFrameTest.py index b179fdc8f98a..756f1cc48664 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/ReferenceFrameTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/ReferenceFrameTest.py @@ -9,6 +9,6 @@ def test_ReferenceFrame_has_expected_attrs(self): expected_attrs = ["pointingAlongBeam", "pointingUp", "vecPointingAlongBeam", "vecPointingUp", "pointingUpAxis", "pointingAlongBeamAxis", "pointingHorizontalAxis"] for att in expected_attrs: self.assertTrue(att in attrs) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/UnitCellTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/UnitCellTest.py index 93b81492a31b..a3a8b7620768 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/UnitCellTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/geometry/UnitCellTest.py @@ -5,30 +5,30 @@ import numpy as np class UnitCellTest(unittest.TestCase): - + def test_invalid_parameters_throw(self): self.assertRaises(RuntimeError, UnitCell, 0, 0, 0, 0, 0, 0) - + def test_simple_constructor(self): u1 = UnitCell() self.assertEquals(u1.a1(), 1) self.assertEquals(u1.alpha(), 90) - + u2 = UnitCell(3,4,5) self.assertAlmostEquals(u2.b1(),1./3., 10) self.assertAlmostEquals(u2.alphastar(), 90, 10) - + u4 = u2 self.assertAlmostEquals(u4.volume(),1./u2.recVolume(),10) u2.seta(3); self.assertAlmostEquals(u2.a(),3,10) - + def test_numpy_array_conversion(self): row0 = (0.162546756312, 0.00815256992072, -0.00145274558861) row1 = (row0[1], 0.028262965555, 0.00102046431298) row2 = (row0[2], row1[2], 0.0156808990098 ) gstar = np.array( [row0,row1,row2] ) - + u = UnitCell() testhelpers.assertRaisesNothing(self, u.recalculateFromGstar, gstar) self._check_cell(u) @@ -40,7 +40,7 @@ def _check_cell(self, cell): self.assertAlmostEqual(cell.alpha(),93,10) self.assertAlmostEqual(cell.beta(),88,10) self.assertAlmostEqual(cell.gamma(),97,10) - + # get the some elements of the B matrix self.assertEquals(type(cell.getB()), np.ndarray) self.assertAlmostEqual(cell.getB()[0][0],0.403170877311,10) @@ -53,10 +53,10 @@ def _check_cell(self, cell): self.assertAlmostEqual(cell.d(V3D(1.,1.,1.)),2.1227107587,10) # angle self.assertAlmostEqual(cell.recAngle(1,1,1,1,0,0,AngleUnits.Radians),0.471054990614,10) - + self.assertEquals(type(cell.getG()), np.ndarray) self.assertEquals(type(cell.getGstar()), np.ndarray) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayBoundedValidatorTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayBoundedValidatorTest.py index 80660c38a59b..a5a939ac5b57 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayBoundedValidatorTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayBoundedValidatorTest.py @@ -40,8 +40,8 @@ def test_clear_members_remove_bounds(self): validator.clearUpper() self.assertFalse(validator.hasLower()) self.assertFalse(validator.hasUpper()) - - + + def test_values_within_array_bounds_are_accepted_by_validator(self): alg = self._create_alg_with_ArrayBoundedValidator(5.1, 10.4) input_vals = [5.1, 5.6, 10.4, 9.2] @@ -51,25 +51,25 @@ def test_values_lower_than_array_bounds_are_not_accepted_by_validator(self): alg = self._create_alg_with_ArrayBoundedValidator(5.1, 10.4) input_vals = [5.4, 6.2, 1.3] self.assertRaises(ValueError, alg.setProperty, "Input", input_vals) - + def test_values_greater_than_array_bounds_are_not_accepted_by_validator(self): alg = self._create_alg_with_ArrayBoundedValidator(5.1, 10.4) input_vals = [5.4, 20.1, 8.3, ] self.assertRaises(ValueError, alg.setProperty, "Input", input_vals) - + def _create_alg_with_ArrayBoundedValidator(self, lower, upper): """ Creates a test algorithm with a bounded validator """ class TestAlgorithm(PythonAlgorithm): - + def PyInit(self): validator = FloatArrayBoundedValidator(lower, upper) self.declareProperty(FloatArrayProperty("Input", validator)) def PyExec(self): pass - + alg = TestAlgorithm() alg.initialize() return alg diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayLengthValidatorTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayLengthValidatorTest.py index 543df1ce3332..13553a95218b 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayLengthValidatorTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayLengthValidatorTest.py @@ -11,7 +11,7 @@ def test_empty_constructor_has_no_lengths_set(self): self.assertFalse(validator.hasLength()) self.assertFalse(validator.hasMinLength()) self.assertFalse(validator.hasMaxLength()) - + def test_fixed_length_constructor_return_hasLength(self): fixedlength = 9 validator = FloatArrayLengthValidator(fixedlength) @@ -26,7 +26,7 @@ def test_range_length_constructor_returns_hasMinMax(self): self.assertTrue(validator.hasMaxLength()) self.assertEquals(validator.getMinLength(), lower) self.assertEquals(validator.getMaxLength(), upper) - + def test_setFixedLength_alters_accepted_lenth(self): validator = FloatArrayLengthValidator() self.assertFalse(validator.hasLength()) @@ -51,7 +51,7 @@ def test_setMinMaxLength_alters_accepted_range(self): self.assertTrue(validator.hasMinLength()) self.assertTrue(validator.hasMaxLength()) self.assertEquals(validator.getMaxLength(), upper) - + validator.clearLengthMin() self.assertFalse(validator.hasMinLength()) self.assertTrue(validator.hasMaxLength()) @@ -64,13 +64,13 @@ def test_Validator_on_ArrayProperty_accepts_array_of_specified_length(self): alg = self._create_alg_with_fixedlength_validator(fixedlength) input_vals = [1.,2.4,5.6,8.0,4.6,6.] testhelpers.assertRaisesNothing(self, alg.setProperty, "Input", input_vals) - + def test_Validator_on_ArrayProperty_rejects_array_of_without_correct_length(self): fixedlength = 6 alg = self._create_alg_with_fixedlength_validator(fixedlength) input_vals = [1.,2.4,5.6] self.assertRaises(ValueError, alg.setProperty, "Input", input_vals) - + def test_Validator_on_ArrayProperty_accepts_array_with_length_in_range(self): alg = self._create_alg_with_range_validator(3,5) input_vals = [] @@ -80,20 +80,20 @@ def test_Validator_on_ArrayProperty_accepts_array_with_length_in_range(self): self.assertRaises(ValueError, alg.setProperty, "Input", input_vals) else: testhelpers.assertRaisesNothing(self, alg.setProperty, "Input", input_vals) - + def _create_alg_with_fixedlength_validator(self, fixedlength): """ Creates a test algorithm with a fixed length validator """ class TestAlgorithm(PythonAlgorithm): - + def PyInit(self): validator = FloatArrayLengthValidator(fixedlength) self.declareProperty(FloatArrayProperty("Input", validator)) def PyExec(self): pass - + alg = TestAlgorithm() alg.initialize() return alg @@ -103,14 +103,14 @@ def _create_alg_with_range_validator(self, minlength, maxlength): Creates a test algorithm with a range length validator """ class TestAlgorithm(PythonAlgorithm): - + def PyInit(self): validator = FloatArrayLengthValidator(minlength, maxlength) self.declareProperty(FloatArrayProperty("Input", validator)) def PyExec(self): pass - + alg = TestAlgorithm() alg.initialize() return alg diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayPropertyTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayPropertyTest.py index 6a320f71d72c..9a5941dc8fb8 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayPropertyTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ArrayPropertyTest.py @@ -1,22 +1,22 @@ """Test the exposed ArrayProperty """ import unittest -from mantid.kernel import (FloatArrayProperty, StringArrayProperty, IntArrayProperty, Direction, +from mantid.kernel import (FloatArrayProperty, StringArrayProperty, IntArrayProperty, Direction, NullValidator) from mantid.api import PythonAlgorithm import numpy as np class ArrayPropertyTest(unittest.TestCase): - + def test_default_constructor_raises_an_exception(self): """ Test that the class cannot be default constructed """ self.assertRaises(Exception, FloatArrayProperty) - + def test_name_only_constructor_gives_correct_object(self): """ - Tests the simplest constructor that takes + Tests the simplest constructor that takes only a name """ name = "numbers" @@ -26,14 +26,14 @@ def test_name_only_constructor_gives_correct_object(self): def test_name_direction_constructor_gives_correct_object(self): """ - Tests the constructor that takes + Tests the constructor that takes only a name & direction """ name = "numbers" direc = Direction.Output arr = FloatArrayProperty(name, direc) self._check_object_attributes(arr, name, direc) - + def test_name_validator_direction_constructor_gives_correct_object(self): """ Test the constructor that takes a name, validator & direction @@ -58,11 +58,11 @@ def test_name_string_values_validator_direction_constructor_gives_correct_object self.assertEquals(arr.isValid, "") values = arr.value self.assertTrue(isinstance(values, np.ndarray)) - - + + def test_name_values_from_list_validator_direction_constructor_gives_correct_object(self): """ - Test the constructor that takes a name, values from python object, + Test the constructor that takes a name, values from python object, validator & direction """ name = "numbers" @@ -74,7 +74,7 @@ def test_name_values_from_list_validator_direction_constructor_gives_correct_obj def test_name_values_from_array_validator_direction_constructor_gives_correct_object(self): """ - Test the constructor that takes a name, values from python object, + Test the constructor that takes a name, values from python object, validator & direction """ name = "numbers" @@ -91,13 +91,13 @@ def _check_object_attributes(self, arrprop, name, direction, length = 0): self.assertEquals(arrprop.name, name) self.assertEquals(arrprop.direction, direction) self.assertEquals(len(arrprop.value), length) - + def test_PythonAlgorithm_setProperty_with_FloatArrayProperty(self): """ Test ArrayProperty within a python algorithm """ class AlgWithFloatArrayProperty(PythonAlgorithm): - + _input_values = None def PyInit(self): @@ -107,17 +107,17 @@ def PyInit(self): def PyExec(self): self._input_values = self.getProperty("Input").value - + input_values = [1.1,2.5,5.6,4.6,9.0,6.0] self._do_algorithm_test(AlgWithFloatArrayProperty, input_values) - + def test_PythonAlgorithm_setProperty_With_Ranges(self): """ Test ArrayProperty within a python algorithm can be set with a string range """ class AlgWithIntArrayProperty(PythonAlgorithm): - + _input_values = None def PyInit(self): @@ -125,12 +125,12 @@ def PyInit(self): def PyExec(self): self._input_values = self.getProperty("Input").value - + alg = AlgWithIntArrayProperty() alg.initialize() alg.setProperty("Input", "10:15") alg.execute() - + self.assertEquals(6, len(alg._input_values)) def test_PythonAlgorithm_setProperty_with_StringArrayProperty(self): @@ -138,7 +138,7 @@ def test_PythonAlgorithm_setProperty_with_StringArrayProperty(self): Test StringArrayProperty within a python algorithm """ class AlgWithStringArrayProperty(PythonAlgorithm): - + _input_values = None def PyInit(self): @@ -147,7 +147,7 @@ def PyInit(self): def PyExec(self): self._input_values = self.getProperty("Input").value - + input_values = ["val1","val2","val3"] self._do_algorithm_test(AlgWithStringArrayProperty, input_values) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/BoundedValidatorTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/BoundedValidatorTest.py index 2ee63df77937..fc8cff3aeba1 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/BoundedValidatorTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/BoundedValidatorTest.py @@ -6,10 +6,10 @@ class BoundedValidatorTest(unittest.TestCase): def test_construction_does_not_raise_error_when_both_are_floats(self): testhelpers.assertRaisesNothing(self, FloatBoundedValidator, 1.0, 2.0) - + def test_construction_with_Exclusive_bounds_with_floats(self): testhelpers.assertRaisesNothing(self, FloatBoundedValidator, 1.0, 2.0, True) - + def test_constructor_sets_both_boundary_values_correctly(self): validator = FloatBoundedValidator(1.3, 2.6) self.assertTrue(validator.hasLower()) @@ -18,7 +18,7 @@ def test_constructor_sets_both_boundary_values_correctly(self): self.assertEquals(validator.upper(), 2.6) self.assertFalse(validator.isLowerExclusive()) self.assertFalse(validator.isUpperExclusive()) - + def test_constructor_sets_both_Exclusive_boundary_values_correctly(self): validator = FloatBoundedValidator(1.3, 2.6, True) self.assertTrue(validator.hasLower()) @@ -30,7 +30,7 @@ def test_constructor_sets_both_Exclusive_boundary_values_correctly(self): def test_construction_does_not_raise_error_when_both_are_ints(self): testhelpers.assertRaisesNothing(self, IntBoundedValidator, 1, 20) - + def test_construction_with_Exclusive_bounds_with_ints(self): testhelpers.assertRaisesNothing(self, IntBoundedValidator, 1, 20, True) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/CompositeValidatorTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/CompositeValidatorTest.py index eb99b28155cd..1dd35f10b601 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/CompositeValidatorTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/CompositeValidatorTest.py @@ -20,7 +20,7 @@ def test_creation_with_constructor_and_list(self): """ validation = CompositeValidator([FloatBoundedValidator(lower=5), FloatBoundedValidator(upper=10)]) self._do_validation_test(validation) - + def _do_validation_test(self, validation): """Run the validator tests""" test_alg = self._create_test_algorithm(validation) @@ -29,17 +29,17 @@ def _do_validation_test(self, validation): test_alg.setProperty("Input", 6.8) self.assertEquals(prop.isValid, "") self.assertRaises(ValueError, test_alg.setProperty, "Input", 15) - + def _create_test_algorithm(self, validator): """Create a test algorithm""" class TestAlgorithm(PythonAlgorithm): - + def PyInit(self): self.declareProperty("Input", -1.0, validator) def PyExec(self): pass - + alg = TestAlgorithm() alg.initialize() return alg diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ConfigServiceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ConfigServiceTest.py index 0975c52f82a0..5f0064c92b7c 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ConfigServiceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ConfigServiceTest.py @@ -1,14 +1,14 @@ import unittest import os -from mantid.kernel import (ConfigService, ConfigServiceImpl, config, +from mantid.kernel import (ConfigService, ConfigServiceImpl, config, std_vector_str, FacilityInfo, InstrumentInfo) class ConfigServiceTest(unittest.TestCase): __dirs_to_rm = [] __init_dir_list = '' - + def test_singleton_returns_instance_of_ConfigService(self): self.assertTrue(isinstance(config, ConfigServiceImpl)) @@ -28,20 +28,20 @@ def test_getFacility_With_Name_Returns_A_FacilityInfo_Object(self): facility = config.getFacility("ISIS") self.assertTrue(isinstance(facility, FacilityInfo)) self.assertRaises(RuntimeError, config.getFacility, "MadeUpFacility") - + def test_getFacilities_Returns_A_FacilityInfo_List(self): facilities = config.getFacilities() self.assertTrue(isinstance(facilities[0], FacilityInfo)) - + def test_getFacilities_and_Facility_Names_are_in_sync_and_non_empty(self): facilities = config.getFacilities() names = config.getFacilityNames() - + self.assertTrue(len(names)>0) self.assertEquals(len(names),len(facilities)) for i in range(len(names)): self.assertEquals(names[i],facilities[i].name()) - + def test_update_and_set_facility(self): self.assertFalse("TEST" in config.getFacilityNames()) ConfigService.updateFacilities(os.path.join(ConfigService.getInstrumentDirectory(),"IDFs_for_UNIT_TESTING/UnitTestFacilities.xml")) @@ -66,7 +66,7 @@ def test_service_acts_like_dictionary(self): self.assertEquals(config.getString(test_prop), "1") config[test_prop] = "2" self.assertEquals(config.getString(test_prop), "2") - + config.setString(test_prop, old_value) def test_getting_search_paths(self): @@ -84,12 +84,12 @@ def test_setting_paths_via_single_string(self): # Clean up here do that if the assert fails # it doesn't bring all the other tests down self._clean_up_test_areas() - + self.assertTrue(len(paths), 2) self.assertTrue('tmp' in paths[0]) self.assertTrue('tmp_2' in paths[1]) self._clean_up_test_areas() - + def _setup_test_areas(self): """Create a new data search path string @@ -109,12 +109,12 @@ def _setup_test_areas(self): self.__dirs_to_rm.append(test_path_two) except OSError: pass - + return [test_path, test_path_two] def _clean_up_test_areas(self): config['datasearch.directories'] = self.__init_dir_list - + # Remove temp directories for p in self.__dirs_to_rm: try: diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/DateAndTimeTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/DateAndTimeTest.py index 6120cec508f2..04a85d6ce346 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/DateAndTimeTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/DateAndTimeTest.py @@ -11,10 +11,10 @@ def test_construction_with_ISO_string_produces_expected_object(self): dt = DateAndTime(self.iso_str) self.assertEquals(self.iso_str_plus_space, str(dt)) self.assertEquals(dt.totalNanoseconds(), 598471118000000000) - + def test_construction_with_total_nano_seconds(self): dt = DateAndTime(598471118000000000) self.assertEquals(self.iso_str_plus_space, str(dt)) - + if __name__ == "__main__": unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/DeltaEModeTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/DeltaEModeTest.py index 19a0c786773e..cddcac1d82b5 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/DeltaEModeTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/DeltaEModeTest.py @@ -4,16 +4,16 @@ class DeltaEModeTest(unittest.TestCase): def test_availableTypes_contains_three_modes(self): - + modes = DeltaEMode.availableTypes() - + self.assertEquals(3, len(modes)) self.assertTrue("Elastic" in modes) self.assertTrue("Direct" in modes) self.assertTrue("Indirect" in modes) def test_DeltaEModeType_has_three_attrs_corresponding_to_three_modes(self): - + self.assertTrue(hasattr(DeltaEModeType, "Elastic")) self.assertTrue(hasattr(DeltaEModeType, "Direct")) self.assertTrue(hasattr(DeltaEModeType, "Indirect")) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/EnabledWhenPropertyTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/EnabledWhenPropertyTest.py index 1c349524fd38..7bd0b7c774eb 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/EnabledWhenPropertyTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/EnabledWhenPropertyTest.py @@ -15,7 +15,7 @@ def test_Property_Criterion_Has_Expected_Attrs(self): self.assertTrue(hasattr(PropertyCriterion, att)) #------------ Failure cases ------------------ - + def test_default_construction_raises_error(self): try: EnabledWhenProperty() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/FacilityInfoTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/FacilityInfoTest.py index 200fd40a0b6c..73d9205b7f2e 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/FacilityInfoTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/FacilityInfoTest.py @@ -8,10 +8,10 @@ def test_construction_raies_an_error(self): def _get_test_facility(self): return ConfigService.getFacility("ISIS") - + def test_attributes_are_as_expected(self): test_facility = self._get_test_facility() - + self.assertEquals(test_facility.name(), "ISIS") self.assertEquals(test_facility.zeroPadding(), 5) self.assertEquals(test_facility.delimiter(), "") diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/FilteredTimeSeriesPropertyTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/FilteredTimeSeriesPropertyTest.py index 7aea98ad22cc..e670f742b558 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/FilteredTimeSeriesPropertyTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/FilteredTimeSeriesPropertyTest.py @@ -15,23 +15,23 @@ def setUp(self): height.addValue("2007-11-30T16:17:20",3) height.addValue("2007-11-30T16:17:30",4) height.addValue("2007-11-30T16:17:40",5) - + filter = BoolTimeSeriesProperty("filter") filter.addValue("2007-11-30T16:16:50",False) filter.addValue("2007-11-30T16:17:25",True) filter.addValue("2007-11-30T16:17:39",False) - + self.__class__._source = height self.__class__._filter = filter def test_constructor_filters_source_series(self): filtered = FloatFilteredTimeSeriesProperty(self._source, self._filter,False) self.assertEquals(filtered.size(), 2) - + def test_unfiltered_returns_source_property(self): filtered = FloatFilteredTimeSeriesProperty(self._source, self._filter,False) unfiltered = filtered.unfiltered() - + self.assertEquals(self._source.size(),unfiltered.size()) if __name__ == '__main__': diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/InstrumentInfoTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/InstrumentInfoTest.py index be3a9cd5c908..7ba0337c855c 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/InstrumentInfoTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/InstrumentInfoTest.py @@ -8,7 +8,7 @@ def test_construction_raies_an_error(self): def test_instrument_name(self): pass - + def test_instrument_shortName(self): pass diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ListValidatorTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ListValidatorTest.py index 2cf824b2b723..956a8317755f 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ListValidatorTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/ListValidatorTest.py @@ -13,14 +13,14 @@ def test_empty_ListValidator_allows_nothing(self): """ class EmptyListValidator(PythonAlgorithm): - + def PyInit(self): validator = StringListValidator() self.declareProperty("Input", "", validator) def PyExec(self): pass - + alg = EmptyListValidator() alg.initialize() self.assertRaises(ValueError, alg.setProperty, "Input", "AnyOldString") @@ -32,7 +32,7 @@ def test_ListValidator_plus_addAllowedValued_allows_that_value(self): """ class SingleItemListValidator(PythonAlgorithm): - + _allowed = "OnlyThis" def PyInit(self): @@ -42,7 +42,7 @@ def PyInit(self): def PyExec(self): pass - + alg = SingleItemListValidator() alg.initialize() self.assertRaises(ValueError, alg.setProperty, "Input", "NotValid") @@ -55,7 +55,7 @@ def test_ListValidator_with_values_in_constructor_restricts_property_values(self """ class MultiValueValidator(PythonAlgorithm): - + _allowed_vals = ["Val1", "Val2","Val3"] def PyInit(self): @@ -64,7 +64,7 @@ def PyInit(self): def PyExec(self): pass - + alg = MultiValueValidator() alg.initialize() self.assertRaises(ValueError, alg.setProperty, "Input", "NotValid") diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/LoggerTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/LoggerTest.py index 2a5be80b6005..922ff26dcdc4 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/LoggerTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/LoggerTest.py @@ -3,7 +3,7 @@ from mantid.kernel import Logger class LoggerTest(unittest.TestCase): - + def test_logger_creation_does_not_raise_an_error(self): logger = Logger("LoggerTest") self.assertTrue(isinstance(logger, Logger)) @@ -12,6 +12,6 @@ def test_logger_creation_does_not_raise_an_error(self): if not hasattr(logger, att): self.fail("Logger object does not have the required attribute '%s'" % att) - + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/MandatoryValidatorTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/MandatoryValidatorTest.py index 0f906cf32dfe..ea6c09a79ebc 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/MandatoryValidatorTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/MandatoryValidatorTest.py @@ -7,23 +7,23 @@ class MandatoryValidatorTest(unittest.TestCase): def test_constructor_does_not_raise_error(self): testhelpers.assertRaisesNothing(self, StringMandatoryValidator) - + def test_validator_restricts_property_values_to_non_empty(self): class TestAlgorithm(PythonAlgorithm): - + def PyInit(self): self.declareProperty("StringInput", "", StringMandatoryValidator()) self.declareProperty(FloatArrayProperty("ArrayInput", FloatArrayMandatoryValidator())) def PyExec(self): pass - + alg = TestAlgorithm() alg.initialize() - + self.assertRaises(ValueError, alg.setProperty, "StringInput", "") testhelpers.assertRaisesNothing(self, alg.setProperty, "StringInput", "value") - + self.assertRaises(ValueError, alg.setProperty, "ArrayInput", []) testhelpers.assertRaisesNothing(self, alg.setProperty, "ArrayInput", [1.2,3.4]) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/PropertyWithValueTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/PropertyWithValueTest.py index 7faa4f6022c7..013f85db7d2e 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/PropertyWithValueTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/PropertyWithValueTest.py @@ -4,12 +4,12 @@ import numpy as np class PropertyWithValueTest(unittest.TestCase): - + # Integration algorithm handle _integration = None # MaskDetectors algorithm handle _mask_dets = None - + def setUp(self): if self._integration is None: self.__class__._integration = AlgorithmManager.createUnmanaged("Integration") @@ -17,25 +17,25 @@ def setUp(self): if self._mask_dets is None: self.__class__._mask_dets = AlgorithmManager.createUnmanaged("MaskDetectors") self.__class__._mask_dets.initialize() - + def test_value_setting_as_string_gives_expected_value_for_correct_type(self): prop = self.__class__._integration.getProperty("RangeLower") prop.valueAsStr = "15.5" - + self.assertAlmostEqual(15.5, prop.value) - + def test_type_str_is_not_empty(self): rangeLower=self.__class__._integration.getProperty("RangeLower") self.assertTrue(len(rangeLower.type) > 0) - + def test_getproperty_value_returns_derived_type(self): data = [1.0,2.0,3.0] alg = run_algorithm('CreateWorkspace',DataX=data,DataY=data,NSpec=1,UnitX='Wavelength',child=True) wksp = alg.getProperty("OutputWorkspace").value self.assertTrue(isinstance(wksp,MatrixWorkspace)) - + def test_set_property_int(self): - self._integration.setProperty("StartWorkspaceIndex", 5) + self._integration.setProperty("StartWorkspaceIndex", 5) self.assertEquals(self._integration.getProperty("StartWorkspaceIndex").value, 5) def test_set_property_float(self): @@ -56,16 +56,16 @@ def test_set_property_succeeds_with_python_int_lists(self): for i in range(5): self.assertEquals(idx_list[i], i+2) value.append(7) - + self._mask_dets.setProperty("DetectorList", value) #integer - det_list = self._mask_dets.getProperty("DetectorList").value + det_list = self._mask_dets.getProperty("DetectorList").value self.assertEquals(len(det_list), 6) for i in range(6): self.assertEquals(det_list[i], i+2) - + def test_set_array_property_with_single_item_correct_type_suceeds(self): self._mask_dets.setProperty("WorkspaceIndexList", 10) - + val = self._mask_dets.getProperty("WorkspaceIndexList").value self.assertEquals(10, val) @@ -78,7 +78,7 @@ def test_set_property_succeeds_with_python_float_lists(self): self.assertEquals(len(params), 3) for i in range(3): self.assertEquals(params[i], input[i]) - + def test_set_property_raises_type_error_when_a_list_contains_multiple_types(self): values = [2,3,4.0,5,6] self.assertRaises(TypeError, self._mask_dets.setProperty, "WorkspaceIndexList", values) #size_t @@ -88,11 +88,11 @@ def test_set_property_of_vector_double_succeeds_with_numpy_array_of_float_type(s def test_set_property_of_vector_double_succeeds_with_numpy_array_of_int_type(self): self._do_vector_double_numpy_test(True) - + def test_set_property_using_list_extracted_from_other_property_succeeds(self): det_list_prop = self._mask_dets.getProperty("DetectorList") det_list_prop.valueAsStr = "1,2,3,4,5" - + det_list = det_list_prop.value self._mask_dets.setProperty("DetectorList", det_list) @@ -107,7 +107,7 @@ def _do_vector_double_numpy_test(self, int_type=False): x_values = create_ws.getProperty('DataX').value self.assertEquals(len(x_values), 10) for i in range(10): - self.assertEquals(x_values[i], i) + self.assertEquals(x_values[i], i) def _do_vector_int_numpy_test(self, property_name, dtype=None): # Use the maskdetectors alg @@ -116,12 +116,12 @@ def _do_vector_int_numpy_test(self, property_name, dtype=None): prop_values = self._mask_dets.getProperty(property_name).value self.assertEquals(len(prop_values), 6) for i in range(6): - self.assertEquals(prop_values[i], i) + self.assertEquals(prop_values[i], i) def test_set_property_of_vector_int_succeeds_with_numpy_array_of_int_type(self): - # Minor hole with int64 as that technically can't be converted to an int32 without precision loss + # Minor hole with int64 as that technically can't be converted to an int32 without precision loss # but I don't think it will be heavily used so we'll see - self._do_vector_int_numpy_test('DetectorList', np.int32) + self._do_vector_int_numpy_test('DetectorList', np.int32) def test_set_property_of_vector_int_succeeds_with_numpy_array_of_int_type(self): self._do_vector_int_numpy_test('WorkspaceIndexList') diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/PythonPluginsTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/PythonPluginsTest.py index 0ccf18521fba..78fb059dcd60 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/PythonPluginsTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/PythonPluginsTest.py @@ -13,15 +13,15 @@ class TestPyAlg(PythonAlgorithm): def PyInit(self): pass - + def PyExec(self): pass - + AlgorithmFactory.subscribe(TestPyAlg) """ class PythonPluginsTest(unittest.TestCase): - + def setUp(self): # Make a test directory and test plugin self._testdir = os.path.join(os.getcwd(), 'PythonPluginsTest_TmpDir') @@ -40,7 +40,7 @@ def tearDown(self): shutil.rmtree(self._testdir) except shutil.Error: pass - + def test_loading_python_algorithm_increases_registered_algs_by_one(self): loaded = plugins.load(self._testdir) self.assertTrue(len(loaded) > 0) @@ -57,7 +57,7 @@ def test_loading_python_algorithm_increases_registered_algs_by_one(self): self.assertEquals(1, test_alg.version()) except RuntimeError, exc: self.fail("Failed to create plugin algorithm from the manager: '%s' " %s) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/QuatTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/QuatTest.py index 38534f93b718..de05cc61276e 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/QuatTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/QuatTest.py @@ -18,8 +18,8 @@ def test_value_constructor(self): self.assertEquals(q[1],2.0) self.assertEquals(q[2],3.0) self.assertEquals(q[3],4.0) - - def test_angle_axis_constructor(self): + + def test_angle_axis_constructor(self): v = V3D(1,1,1); # Construct quaternion to represent rotation # of 45 degrees around the 111 axis. @@ -53,13 +53,13 @@ def test_rotate(self): v = V3D(1,0,0) orig_v = v; p.rotate(v); - self.assertEquals(orig_v,v) + self.assertEquals(orig_v,v) # Now do more angles v = V3D(1,0,0); p = Quat(90., V3D(0,1,0)); #90 degrees, right-handed, around y p.rotate(v); self.assertEquals(v, V3D(0,0,-1)) - + v = V3D(1,0,0); p = Quat(45., V3D(0,0,1)) p.rotate(v); diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/StatisticsTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/StatisticsTest.py index 13c1a8077141..c1e7d95bf538 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/StatisticsTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/StatisticsTest.py @@ -33,13 +33,13 @@ def test_getStatistics_accepts_sorted_arg(self): self.assertEquals(12.6, stats.minimum) self.assertEquals(18.3, stats.maximum) self.assertEquals(17.2, stats.median) - + def test_getZScores(self): """Data taken from C++ test""" values = [12,13,9,18,7,9,14,16,10,12,7,13,14,19,10,16,12,16,19,11] arr = numpy.array(values,dtype=numpy.float64) - + zscore = Stats.getZscore(arr) self.assertAlmostEqual(1.63977, zscore[4], places = 4) self.assertAlmostEqual(0.32235, zscore[6], places = 4) @@ -64,12 +64,12 @@ def test_getMoments(self): indep = numpy.arange(numX, dtype=numpy.float64) indep = indep*deltaX + offsetX - + # y-values # test different type depend = numpy.arange(numX, dtype=numpy.int32) self.assertRaises(ValueError, Stats.getMomentsAboutOrigin, indep, depend) - + # now correct y values weightedDiff = (indep-mean)/sigma depend = numpy.exp(-0.5*weightedDiff*weightedDiff)/sigma/math.sqrt(2.*math.pi) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/TimeSeriesPropertyTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/TimeSeriesPropertyTest.py index 9668cdca2e00..7cb07bcb66cf 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/TimeSeriesPropertyTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/TimeSeriesPropertyTest.py @@ -2,7 +2,7 @@ import numpy as np import mantid -from mantid.kernel import (DateAndTime, BoolTimeSeriesProperty, FloatTimeSeriesProperty, Int64TimeSeriesProperty, +from mantid.kernel import (DateAndTime, BoolTimeSeriesProperty, FloatTimeSeriesProperty, Int64TimeSeriesProperty, StringTimeSeriesProperty) from testhelpers import run_algorithm @@ -18,7 +18,7 @@ def setUp(self): alg = run_algorithm('CreateWorkspace', DataX=[1,2,3,4,5], DataY=[1,2,3,4,5],NSpec=1, child=True) ws = alg.getProperty("OutputWorkspace").value run = ws.run() - + start_time = DateAndTime("2008-12-18T17:58:38") nanosec = 1000000000 # === Float type === @@ -52,7 +52,7 @@ def setUp(self): self.__class__._test_ws = ws - + def test_time_series_double_can_be_extracted(self): log_series = self._test_ws.getRun()["TEMP1"] self._check_has_time_series_attributes(log_series) @@ -70,12 +70,12 @@ def test_time_series_string_can_be_extracted(self): self._check_has_time_series_attributes(log_series, list) self.assertEquals(log_series.size(), 4) self.assertEquals(log_series.nthValue(0).strip(), 'CHANGE_PERIOD 1') - + def test_time_series_bool_can_be_extracted(self): log_series = self._test_ws.getRun()["period 1"] self._check_has_time_series_attributes(log_series) self.assertEquals(log_series.size(), 1) - + def _check_has_time_series_attributes(self, log, values_type=np.ndarray): self.assertTrue(hasattr(log, "value")) self.assertTrue(hasattr(log, "times")) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/UnitConversionTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/UnitConversionTest.py index d0e896e35cd9..03da5a06fef7 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/UnitConversionTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/UnitConversionTest.py @@ -8,11 +8,11 @@ def test_run_accepts_string_units(self): src_unit = "Wavelength" src_value = 1.5 dest_unit = "Momentum" - + l1 = l2 = twoTheta = efixed = 0.0 emode = DeltaEModeType.Indirect; expected = 2.0*math.pi/src_value - + result = UnitConversion.run(src_unit, dest_unit, src_value, l1, l2, twoTheta, emode, efixed) self.assertAlmostEqual(result, expected, 12) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/UnitFactoryTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/UnitFactoryTest.py index 7d4834abfc05..ecbcb6f596fb 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/UnitFactoryTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/UnitFactoryTest.py @@ -11,12 +11,12 @@ def test_known_unit_can_be_created(self): self.assertTrue(isinstance(energy, Unit)) def test_unknown_unit_raises_error(self): - self.assertRaises(RuntimeError, UnitFactory.create, + self.assertRaises(RuntimeError, UnitFactory.create, "NotAUnit") - + def test_keys_returns_a_non_empty_python_list_of_unit_keys(self): known_units = UnitFactory.getKeys() - + self.assertEquals(type(known_units), list) # Check length is at least the known core units # but allow for others to be added diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/V3DTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/V3DTest.py index 312712e8fbc6..4bdc8f3b4593 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/V3DTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/V3DTest.py @@ -3,19 +3,19 @@ from mantid.kernel import V3D class V3DTest(unittest.TestCase): - + def test_default_construction_is_at_origin(self): p = V3D() self.assertEquals(p.X(), 0.0) self.assertEquals(p.Y(), 0.0) self.assertEquals(p.Z(), 0.0) - + def test_construction_with_xyz(self): p = V3D(1.5,2.4,6.5) self.assertEquals(p.X(), 1.5) self.assertEquals(p.Y(), 2.4) self.assertEquals(p.Z(), 6.5) - + def test_distance(self): a = V3D(0.0,0.0,0.0) b = V3D(2.0,2.0,2.0) @@ -31,7 +31,7 @@ def test_angle(self): self.assertAlmostEquals(a.angle(b), math.pi / 2.0) self.assertAlmostEquals(a.angle(c), math.pi / 4.0) self.assertAlmostEquals(a.angle(d), math.pi) - + def test_zenith(self): b = V3D(0.0, 0.0, 0.0) a = V3D(9.9, 7.6, 0.0) @@ -51,7 +51,7 @@ def test_scalarprod(self): b = V3D(1.0,-2.0,-1.0) sp = a.scalar_prod(b) self.assertAlmostEquals(sp,-4.0) - + def test_crossprod(self): a = V3D(1.0,0.0,0.0) b = V3D(0.0,1.0,0.0) @@ -63,7 +63,7 @@ def test_crossprod(self): def test_norm(self): p = V3D(1.0,-5.0,8.0); self.assertAlmostEquals(p.norm(), math.sqrt(90.0)) - + def test_norm2(self): p = V3D(1.0,-5.0,8.0); self.assertAlmostEquals(p.norm2(), 90.0) @@ -79,7 +79,7 @@ def test_inequality_operators_use_value_comparison(self): self.assertFalse(p1 != p2) p3 = V3D(1.0,-5.0,10.0) self.assertTrue(p1 != p3) - + def test_directionAngles_rads(self): v = V3D(1, 1, 1) inDegrees = False @@ -87,16 +87,16 @@ def test_directionAngles_rads(self): self.assertAlmostEquals(math.acos(1.0/math.sqrt(3.0)), angles.X()) self.assertAlmostEquals(math.acos(1.0/math.sqrt(3.0)), angles.Y()) self.assertAlmostEquals(math.acos(1.0/math.sqrt(3.0)), angles.Z()) - + def test_directionAngles(self): v = V3D(1, 1, 1) angles = v.directionAngles() self.assertAlmostEquals(math.acos(1.0/math.sqrt(3.0)) * 180 / math.pi, angles.X()) self.assertAlmostEquals(math.acos(1.0/math.sqrt(3.0)) * 180 / math.pi, angles.Y()) self.assertAlmostEquals(math.acos(1.0/math.sqrt(3.0)) * 180 / math.pi, angles.Z()) - - - + + + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/VMDTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/VMDTest.py index 60bd1c6bb714..92f00c63e068 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/VMDTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/VMDTest.py @@ -32,7 +32,7 @@ def test_crossprod(self): def test_norm(self): p = VMD(1.0,-5.0,8.0); self.assertAlmostEquals(p.norm(), math.sqrt(90.0),places=6) - + def test_norm2(self): p = VMD(1.0,-5.0,8.0); self.assertAlmostEquals(p.norm2(), 90.0, places=6) @@ -67,7 +67,7 @@ def test_value_write_access_succeeds_for_valid_indices(self): def test_standard_mathematical_operators(self): v1 = VMD(1.0,2.0) v2 = VMD(5.0,-1.0) - + v3 = v1 + v2 self.assertAlmostEqual(6.0, v3[0]) self.assertAlmostEqual(1.0, v3[1]) @@ -80,11 +80,11 @@ def test_standard_mathematical_operators(self): v3 = v1 / v2 self.assertAlmostEqual(1.0/5.0, v3[0]) self.assertAlmostEqual(-2.0, v3[1]) - + def test_inplace_mathematical_operators(self): v1 = VMD(1.0,2.0) v2 = VMD(5.0,-1.0) - + v1 += v2 self.assertAlmostEqual(6.0, v1[0]) self.assertAlmostEqual(1.0, v1[1]) @@ -100,7 +100,7 @@ def test_inplace_mathematical_operators(self): v1 /= v2 self.assertAlmostEqual(1.0/5.0, v1[0]) self.assertAlmostEqual(-2.0, v1[1]) - + def test_equality_operators(self): v1 = VMD(1.0,2.0) self.assertTrue(v1 == v1) @@ -119,7 +119,7 @@ def test_value_read_access_raises_error_for_invalid_indices(self): def test_value_write_access_raises_error_for_invalid_indices(self): vector = VMD(1.0,2.0) self.assertRaises(IndexError, vector.__setitem__, 2, 5.0) - + def test_scalar_prod_raises_error_with_dimension_mismatch(self): v1 = VMD(1,2,3) v2 = VMD(1,2,3,4) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/VisibleWhenPropertyTest.py b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/VisibleWhenPropertyTest.py index 1399338f872d..692d2b832ee4 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/VisibleWhenPropertyTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/mantid/kernel/VisibleWhenPropertyTest.py @@ -10,7 +10,7 @@ def test_construction_with_name_criterion_value_succeeds(self): p = VisibleWhenProperty("OtherProperty", PropertyCriterion.IsEqualTo, "value") #------------ Failure cases ------------------ - + def test_default_construction_raises_error(self): try: VisibleWhenProperty() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CheckForSampleLogsTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CheckForSampleLogsTest.py index 5aad0e9c16b1..7ef00ec8f693 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CheckForSampleLogsTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CheckForSampleLogsTest.py @@ -3,14 +3,14 @@ class CheckForSampleLogsTest(unittest.TestCase): - def test_simple(self): - w=mantid.simpleapi.Load('CNCS_7860_event.nxs') - result=mantid.simpleapi.CheckForSampleLogs(w) - self.assertEquals(result,'') - result=mantid.simpleapi.CheckForSampleLogs(w,'Phase1') - self.assertEquals(result,'') - result=mantid.simpleapi.CheckForSampleLogs(w,'Phrase1') - self.assertNotEquals(result,'') + def test_simple(self): + w=mantid.simpleapi.Load('CNCS_7860_event.nxs') + result=mantid.simpleapi.CheckForSampleLogs(w) + self.assertEquals(result,'') + result=mantid.simpleapi.CheckForSampleLogs(w,'Phase1') + self.assertEquals(result,'') + result=mantid.simpleapi.CheckForSampleLogs(w,'Phrase1') + self.assertNotEquals(result,'') if __name__=="__main__": - unittest.main() + unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ConjoinSpectraTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ConjoinSpectraTest.py index 9444db1c82f3..b387d4197b07 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ConjoinSpectraTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ConjoinSpectraTest.py @@ -12,15 +12,15 @@ def setUp(self): dataX = range(0,6) dataY = range(0,5) dataE = [1] * 5 - - createWSAlg = run_algorithm( "CreateWorkspace", DataX=dataX, DataY=dataY, DataE=dataE, NSpec=1,UnitX="Wavelength", OutputWorkspace="single_spectra_ws") + + createWSAlg = run_algorithm( "CreateWorkspace", DataX=dataX, DataY=dataY, DataE=dataE, NSpec=1,UnitX="Wavelength", OutputWorkspace="single_spectra_ws") self._aWS = createWSAlg.getPropertyValue("OutputWorkspace") - - + + def test_basicRun(self): conjoinAlg = run_algorithm( "ConjoinSpectra", InputWorkspaces="%s,%s" % (self._aWS, self._aWS), OutputWorkspace="conjoined" ) conjoinedWS = mtd.retrieve('conjoined') - + wsIndex = 0 inDataY = mtd[self._aWS].readY(wsIndex) inDataE = mtd[self._aWS].readE(wsIndex) @@ -28,19 +28,19 @@ def test_basicRun(self): outDataY2 = conjoinedWS.readY(1) outDataE1 = conjoinedWS.readE(0) outDataE2 = conjoinedWS.readE(1) - + # Check output shape self.assertEqual(len(inDataY), len(outDataY1)) self.assertEqual(len(inDataY), len(outDataY2)) self.assertEqual(len(inDataE), len(outDataE1)) self.assertEqual(len(inDataE), len(outDataE2)) self.assertEqual(2, conjoinedWS.getNumberHistograms()) # Should always have 2 histograms - + self.assertEquals(set(inDataY), set(outDataY1)) self.assertEquals(set(inDataY), set(outDataY2)) self.assertEquals(set(inDataE), set(outDataE1)) self.assertEquals(set(inDataE), set(outDataE2)) - - + + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CorrectLogTimesTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CorrectLogTimesTest.py index 1a33b125b19f..d1e0700a367e 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CorrectLogTimesTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CorrectLogTimesTest.py @@ -5,7 +5,7 @@ from numpy import * class CorrectLogTimesTest(unittest.TestCase): - + def testCLTWrongLog(self): w=CreateSingleValuedWorkspace(DataValue='1',ErrorValue='1') LoadNexusLogs(Workspace=w,Filename='CNCS_7860_event.nxs') @@ -17,7 +17,7 @@ def testCLTWrongLog(self): pass finally: DeleteWorkspace(w) - + def testCLTsingle(self): w=CreateSingleValuedWorkspace(DataValue='1',ErrorValue='1') LoadNexusLogs(Workspace=w,Filename='CNCS_7860_event.nxs') @@ -25,15 +25,15 @@ def testCLTsingle(self): CorrectLogTimes(Workspace=w,LogNames="Speed4") self.assertTrue(w.getRun()['proton_charge'].firstTime()==w.getRun()['Speed4'].firstTime()) self.assertFalse(w.getRun()['proton_charge'].firstTime()==w.getRun()['Speed5'].firstTime()) - DeleteWorkspace(w) + DeleteWorkspace(w) def testCLTall(self): w=CreateSingleValuedWorkspace(DataValue='1',ErrorValue='1') LoadNexusLogs(Workspace=w,Filename='CNCS_7860_event.nxs') self.assertFalse(w.getRun()['proton_charge'].firstTime()==w.getRun()['Speed4'].firstTime()) - CorrectLogTimes(Workspace=w,LogNames="") + CorrectLogTimes(Workspace=w,LogNames="") self.assertTrue(w.getRun()['proton_charge'].firstTime()==w.getRun()['Speed4'].firstTime()) self.assertTrue(w.getRun()['proton_charge'].firstTime()==w.getRun()['Speed5'].firstTime()) - DeleteWorkspace(w) + DeleteWorkspace(w) if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateLeBailFitInputTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateLeBailFitInputTest.py index 5f76f67fe9d2..0909de16affd 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateLeBailFitInputTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateLeBailFitInputTest.py @@ -13,7 +13,7 @@ def test_LoadHKLFile(self): """ Test to load a .hkl file """ # Set up - alg_test = run_algorithm("CreateLeBailFitInput", + alg_test = run_algorithm("CreateLeBailFitInput", ReflectionsFile = "LB4853b2.hkl", FullprofParameterFile = "2011B_HR60b2.irf", Bank = 2, @@ -30,7 +30,7 @@ def test_LoadHKLFile(self): paramws = AnalysisDataService.retrieve("PG3_Bank2_Foo") paramname0 = paramws.cell(0, 0) - + if paramname0.lower() == "bank": numrowgood = 29 else: @@ -60,7 +60,7 @@ def test_genHKLList(self): """ Test to load a .hkl file """ # Set up - alg_test = run_algorithm("CreateLeBailFitInput", + alg_test = run_algorithm("CreateLeBailFitInput", ReflectionsFile = "", MaxHKL = "12,12,12", FullprofParameterFile = "2011B_HR60b2.irf", @@ -79,7 +79,7 @@ def test_genHKLList(self): paramws = AnalysisDataService.retrieve("PG3_Bank2_Foo2") paramname0 = paramws.cell(0, 0) - + if paramname0.lower() == "bank": numrowgood = 28 else: diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateWorkspaceTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateWorkspaceTest.py index fd50695a442d..9dc8497df81f 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateWorkspaceTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/CreateWorkspaceTest.py @@ -5,16 +5,16 @@ import numpy as np class CreateWorkspaceTest(unittest.TestCase): - + def test_create_with_1D_numpy_array(self): x = np.array([1.,2.,3.,4.]) y = np.array([1.,2.,3.]) e = np.sqrt(np.array([1.,2.,3.])) - + wksp = CreateWorkspace(DataX=x, DataY=y,DataE=e,NSpec=1,UnitX='TOF') self.assertTrue(isinstance(wksp, MatrixWorkspace)) self.assertEquals(wksp.getNumberHistograms(), 1) - + self.assertEquals(len(wksp.readY(0)), len(y)) self.assertEquals(len(wksp.readX(0)), len(x)) self.assertEquals(len(wksp.readE(0)), len(e)) @@ -43,24 +43,24 @@ def test_create_with_2D_numpy_array(self): self.assertEquals(wksp.readX(i)[j], x[j]) # Last X value self.assertEquals(wksp.readX(i)[len(x)-1], x[len(x)-1]) - + AnalysisDataService.remove("wksp") - + def test_with_data_from_other_workspace(self): wsname = 'LOQ' x1 = np.array([1.,2.,3.,4.]) y1 = np.array([[1.,2.,3.],[4.,5.,6.]]) e1 = np.sqrt(y1) loq = CreateWorkspace(DataX=x1, DataY=y1,DataE=e1,NSpec=2,UnitX='Wavelength') - + x2 = loq.extractX() y2 = loq.extractY() e2 = loq.extractE() - + wksp = CreateWorkspace(DataX=x2, DataY=y2,DataE=e2,NSpec=2,UnitX='Wavelength') self.assertTrue(isinstance(wksp, MatrixWorkspace)) self.assertEquals(wksp.getNumberHistograms(), 2) - + for i in [0,1]: for j in range(len(y2[0])): self.assertEquals(wksp.readY(i)[j], loq.readY(i)[j]) @@ -79,7 +79,7 @@ def test_create_with_numerical_vertical_axis_values(self): wksp = alg.getProperty("OutputWorkspace").value for i in range(len(axis_values)): self.assertEquals(wksp.getAxis(1).getValue(i), axis_values[i]) - + def test_create_with_numpy_vertical_axis_values(self): data = [1.,2.,3.] axis_values = np.array([6.,7.,8.]) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/DSFinterpTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/DSFinterpTest.py index 06a4191e9b58..ae4e1d03959d 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/DSFinterpTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/DSFinterpTest.py @@ -70,4 +70,4 @@ def test_input_exceptions(self): self.cleanup(nf) if __name__=="__main__": - unittest.main() + unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/DakotaChiSquaredTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/DakotaChiSquaredTest.py index a747e48b937d..d210e3e6c545 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/DakotaChiSquaredTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/DakotaChiSquaredTest.py @@ -4,99 +4,99 @@ class DakotaChiSquaredTest(unittest.TestCase): - def makeFiles(self): - mantid.simpleapi.CreateWorkspace(OutputWorkspace='data',DataX='1,2,3,4,5',DataY='1,0,1,4,4',DataE='1,0,1,2,2') - mantid.simpleapi.CreateWorkspace(OutputWorkspace='sim',DataX='1,2,3,4,5',DataY='1,1,1,1,1',DataE='0,0,0,0,0') - mantid.simpleapi.CreateWorkspace(OutputWorkspace='simwrong',DataX='1,2,3,4',DataY='1,1,1,1',DataE='0,0,0,0') + def makeFiles(self): + mantid.simpleapi.CreateWorkspace(OutputWorkspace='data',DataX='1,2,3,4,5',DataY='1,0,1,4,4',DataE='1,0,1,2,2') + mantid.simpleapi.CreateWorkspace(OutputWorkspace='sim',DataX='1,2,3,4,5',DataY='1,1,1,1,1',DataE='0,0,0,0,0') + mantid.simpleapi.CreateWorkspace(OutputWorkspace='simwrong',DataX='1,2,3,4',DataY='1,1,1,1',DataE='0,0,0,0') - self.datafile=os.path.join(mantid.config.getString('defaultsave.directory'),'DakotaChiSquared_data.nxs') - self.simfile=os.path.join(mantid.config.getString('defaultsave.directory'),'DakotaChiSquared_sim.nxs') - self.simwrongfile=os.path.join(mantid.config.getString('defaultsave.directory'),'DakotaChiSquared_simwrong.nxs') - self.chifile=os.path.join(mantid.config.getString('defaultsave.directory'),'DakotaChiSquared_chi.txt') + self.datafile=os.path.join(mantid.config.getString('defaultsave.directory'),'DakotaChiSquared_data.nxs') + self.simfile=os.path.join(mantid.config.getString('defaultsave.directory'),'DakotaChiSquared_sim.nxs') + self.simwrongfile=os.path.join(mantid.config.getString('defaultsave.directory'),'DakotaChiSquared_simwrong.nxs') + self.chifile=os.path.join(mantid.config.getString('defaultsave.directory'),'DakotaChiSquared_chi.txt') - mantid.simpleapi.SaveNexus('data',self.datafile) - mantid.simpleapi.SaveNexus('sim',self.simfile) - mantid.simpleapi.SaveNexus('simwrong',self.simwrongfile) + mantid.simpleapi.SaveNexus('data',self.datafile) + mantid.simpleapi.SaveNexus('sim',self.simfile) + mantid.simpleapi.SaveNexus('simwrong',self.simwrongfile) - mantid.api.AnalysisDataService.remove("data") - mantid.api.AnalysisDataService.remove("sim") - mantid.api.AnalysisDataService.remove("simwrong") + mantid.api.AnalysisDataService.remove("data") + mantid.api.AnalysisDataService.remove("sim") + mantid.api.AnalysisDataService.remove("simwrong") - def cleanup(self): - if os.path.exists(self.datafile): - os.remove(self.datafile) - if os.path.exists(self.simfile): - os.remove(self.simfile) - if os.path.exists(self.simwrongfile): - os.remove(self.simwrongfile) - if os.path.exists(self.chifile): - os.remove(self.chifile) + def cleanup(self): + if os.path.exists(self.datafile): + os.remove(self.datafile) + if os.path.exists(self.simfile): + os.remove(self.simfile) + if os.path.exists(self.simwrongfile): + os.remove(self.simwrongfile) + if os.path.exists(self.chifile): + os.remove(self.chifile) - def test_wrongType(self): - self.makeFiles() - try: - mantid.simpleapi.DakotaChiSquared(self.datafile,'CNCS_7860_event.nxs',self.chifile) - except RuntimeError as e: - self.assertNotEquals(str(e).find('Wrong workspace type for calculated file'),-1) - except: - assert False, "Raised the wrong exception type" - else: - assert False, "Didn't raise any exception" - try: - mantid.simpleapi.DakotaChiSquared('CNCS_7860_event.nxs',self.simfile,self.chifile) - except RuntimeError as e: - self.assertNotEquals(str(e).find('Wrong workspace type for data file'),-1) - except: - assert False, "Raised the wrong exception type" - else: - assert False, "Didn't raise any exception" - self.cleanup() + def test_wrongType(self): + self.makeFiles() + try: + mantid.simpleapi.DakotaChiSquared(self.datafile,'CNCS_7860_event.nxs',self.chifile) + except RuntimeError as e: + self.assertNotEquals(str(e).find('Wrong workspace type for calculated file'),-1) + except: + assert False, "Raised the wrong exception type" + else: + assert False, "Didn't raise any exception" + try: + mantid.simpleapi.DakotaChiSquared('CNCS_7860_event.nxs',self.simfile,self.chifile) + except RuntimeError as e: + self.assertNotEquals(str(e).find('Wrong workspace type for data file'),-1) + except: + assert False, "Raised the wrong exception type" + else: + assert False, "Didn't raise any exception" + self.cleanup() - def test_wrongSize(self): - self.makeFiles() - try: - mantid.simpleapi.DakotaChiSquared(self.datafile,self.simwrongfile,self.chifile) - except RuntimeError as e: - self.assertNotEquals(str(e).find('The file sizes are different'),-1) - except: - assert False, "Raised the wrong exception type" - else: - assert False, "Didn't raise any exception" - self.cleanup() + def test_wrongSize(self): + self.makeFiles() + try: + mantid.simpleapi.DakotaChiSquared(self.datafile,self.simwrongfile,self.chifile) + except RuntimeError as e: + self.assertNotEquals(str(e).find('The file sizes are different'),-1) + except: + assert False, "Raised the wrong exception type" + else: + assert False, "Didn't raise any exception" + self.cleanup() - def test_value(self): - self.makeFiles() - try: - mantid.simpleapi.DakotaChiSquared(self.datafile,self.simfile,self.chifile) - f = open(self.chifile,'r') - chistr=f.read() - self.assertEquals(chistr,'4.5 obj_fn\n') - f.close() - except: - assert False, "Raised an exception" - self.cleanup() + def test_value(self): + self.makeFiles() + try: + mantid.simpleapi.DakotaChiSquared(self.datafile,self.simfile,self.chifile) + f = open(self.chifile,'r') + chistr=f.read() + self.assertEquals(chistr,'4.5 obj_fn\n') + f.close() + except: + assert False, "Raised an exception" + self.cleanup() - def test_output(self): - self.makeFiles() - try: - alg=mantid.simpleapi.DakotaChiSquared(self.datafile,self.simfile,self.chifile) - self.assertEquals(len(alg),2) - self.assertEquals(alg[0],4.5) - self.assertEquals(alg[1].getName(),"alg") - self.assertEquals(alg[1].blocksize(),5) - self.assertEquals(alg[1].getNumberHistograms(),1) - self.assertEquals(alg[1].dataY(0)[3],1.5) - mantid.api.AnalysisDataService.remove("alg") - alg1=mantid.simpleapi.DakotaChiSquared(self.datafile,self.simfile,self.chifile,ResidualsWorkspace="res") - self.assertEquals(alg1[0],4.5) - self.assertEquals(alg1[1].getName(),"res") - mantid.api.AnalysisDataService.remove("res") - except: - assert False, "Raised an exception" - self.cleanup() + def test_output(self): + self.makeFiles() + try: + alg=mantid.simpleapi.DakotaChiSquared(self.datafile,self.simfile,self.chifile) + self.assertEquals(len(alg),2) + self.assertEquals(alg[0],4.5) + self.assertEquals(alg[1].getName(),"alg") + self.assertEquals(alg[1].blocksize(),5) + self.assertEquals(alg[1].getNumberHistograms(),1) + self.assertEquals(alg[1].dataY(0)[3],1.5) + mantid.api.AnalysisDataService.remove("alg") + alg1=mantid.simpleapi.DakotaChiSquared(self.datafile,self.simfile,self.chifile,ResidualsWorkspace="res") + self.assertEquals(alg1[0],4.5) + self.assertEquals(alg1[1].getName(),"res") + mantid.api.AnalysisDataService.remove("res") + except: + assert False, "Raised an exception" + self.cleanup() if __name__=="__main__": - unittest.main() + unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ExportExperimentLogTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ExportExperimentLogTest.py index 580ebc6cf7be..3b5e3ac84f16 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ExportExperimentLogTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ExportExperimentLogTest.py @@ -1,6 +1,6 @@ import unittest -import numpy -from numpy import * +import numpy +from numpy import * from mantid.kernel import * from mantid.api import * import mantid.kernel as kernel @@ -18,7 +18,7 @@ def test_exportFileNew(self): AnalysisDataService.addOrReplace("TestMatrixWS", ws) # Test algorithm - alg_test = run_algorithm("ExportExperimentLog", + alg_test = run_algorithm("ExportExperimentLog", InputWorkspace = "TestMatrixWS", OutputFilename = "TestRecord.txt", SampleLogNames = ["run_number", "duration", "proton_charge"], @@ -40,11 +40,11 @@ def test_exportFileNew(self): print "Unable to open file %s. " % (outfilename) self.assertTrue(False) return - + # Last line cannot be empty, i.e., before EOF '\n' is not allowed lastline = lines[-1] self.assertTrue(len(lastline.strip()) > 0) - + # Number of lines self.assertEquals(len(lines), 2) @@ -53,11 +53,11 @@ def test_exportFileNew(self): terms = firstdataline.strip().split("\t") self.assertEquals(len(terms), 3) - # - # # Remove generated files + # + # # Remove generated files os.remove(outfilename) AnalysisDataService.remove("TestMatrixWS") - + return @@ -70,16 +70,16 @@ def test_exportFileFastAppend(self): # Test algorithm # create new file - alg_test = run_algorithm("ExportExperimentLog", + alg_test = run_algorithm("ExportExperimentLog", InputWorkspace = "TestMatrixWS", OutputFilename = "TestRecord.txt", SampleLogNames = ["run_number", "duration", "proton_charge"], SampleLogTitles = ["RUN", "Duration", "ProtonCharge"], SampleLogOperation = [None, None, "sum"], - FileMode = "new") - - # Fast append - alg_test = run_algorithm("ExportExperimentLog", + FileMode = "new") + + # Fast append + alg_test = run_algorithm("ExportExperimentLog", InputWorkspace = "TestMatrixWS", OutputFilename = "TestRecord.txt", SampleLogNames = ["run_number", "duration", "proton_charge"], @@ -100,11 +100,11 @@ def test_exportFileFastAppend(self): print "Unable to open file %s. " % (outfilename) self.assertTrue(False) return - + # Last line cannot be empty, i.e., before EOF '\n' is not allowed lastline = lines[-1] self.assertTrue(len(lastline.strip()) > 0) - + # Number of lines self.assertEquals(len(lines), 3) @@ -113,13 +113,13 @@ def test_exportFileFastAppend(self): terms = firstdataline.strip().split("\t") self.assertEquals(len(terms), 3) - # Remove generated files + # Remove generated files os.remove(outfilename) AnalysisDataService.remove("TestMatrixWS") - + return - - + + def test_exportFileAppend(self): """ Test to export logs without header file """ @@ -129,16 +129,16 @@ def test_exportFileAppend(self): # Test algorithm # create new file - alg_test = run_algorithm("ExportExperimentLog", + alg_test = run_algorithm("ExportExperimentLog", InputWorkspace = "TestMatrixWS", OutputFilename = "TestRecord.txt", SampleLogNames = ["run_number", "duration", "proton_charge"], SampleLogTitles = ["RUN", "Duration", "ProtonCharge"], SampleLogOperation = [None, None, "sum"], - FileMode = "new") - + FileMode = "new") + # append - alg_test = run_algorithm("ExportExperimentLog", + alg_test = run_algorithm("ExportExperimentLog", InputWorkspace = "TestMatrixWS", OutputFilename = "TestRecord.txt", SampleLogNames = ["run_number", "duration", "proton_charge"], @@ -160,11 +160,11 @@ def test_exportFileAppend(self): print "Unable to open file %s. " % (outfilename) self.assertTrue(False) return - + # Last line cannot be empty, i.e., before EOF '\n' is not allowed lastline = lines[-1] self.assertTrue(len(lastline.strip()) > 0) - + # Number of lines self.assertEquals(len(lines), 3) @@ -173,38 +173,38 @@ def test_exportFileAppend(self): terms = firstdataline.strip().split("\t") self.assertEquals(len(terms), 3) - # - # # Remove generated files + # + # # Remove generated files os.remove(outfilename) AnalysisDataService.remove("TestMatrixWS") - + return - + def test_exportFileAppend2(self): - """ Test to export file in appending mode - In this case, the original file will be renamed and a new file will + """ Test to export file in appending mode + In this case, the original file will be renamed and a new file will be creatd """ import datetime import time - + # Generate the matrix workspace with some logs ws = self.createTestWorkspace() AnalysisDataService.addOrReplace("TestMatrixWS", ws) # Test algorithm # create new file - alg_test = run_algorithm("ExportExperimentLog", + alg_test = run_algorithm("ExportExperimentLog", InputWorkspace = "TestMatrixWS", OutputFilename = "TestRecord.txt", SampleLogNames = ["run_number", "duration", "proton_charge"], SampleLogTitles = ["RUN", "Duration", "ProtonCharge"], SampleLogOperation = [None, None, "sum"], - FileMode = "new") - + FileMode = "new") + # append - alg_test = run_algorithm("ExportExperimentLog", + alg_test = run_algorithm("ExportExperimentLog", InputWorkspace = "TestMatrixWS", OutputFilename = "TestRecord.txt", SampleLogNames = ["run_number", "duration", "proton_charge", "SensorA"], @@ -226,11 +226,11 @@ def test_exportFileAppend2(self): print "Unable to open file %s. " % (outfilename) self.assertTrue(False) return - + # Last line cannot be empty, i.e., before EOF '\n' is not allowed lastline = lines[-1] self.assertTrue(len(lastline.strip()) > 0) - + # Number of lines self.assertEquals(len(lines), 2) @@ -238,29 +238,29 @@ def test_exportFileAppend2(self): firstdataline = lines[1] terms = firstdataline.strip().split("\t") self.assertEquals(len(terms), 4) - + # Locate the previos file - + # Rename old file and reset the file mode - + # Rename the old one: split path from file, new name, and rename fileName, fileExtension = os.path.splitext(outfilename) now = datetime.datetime.now() nowstr = time.strftime("%Y_%B_%d_%H_%M") oldfilename = fileName + "_" + nowstr + fileExtension print "Saved old file is %s. " % (oldfilename) - self.assertTrue(os.path.exists(oldfilename)) + self.assertTrue(os.path.exists(oldfilename)) - # Remove generated files + # Remove generated files os.remove(outfilename) os.remove(oldfilename) AnalysisDataService.remove("TestMatrixWS") - + return - + def test_exportFileNewCSV(self): - """ Test to export logs without header file in csv format + """ Test to export logs without header file in csv format and with a name not endind with .csv """ # Generate the matrix workspace with some logs @@ -268,7 +268,7 @@ def test_exportFileNewCSV(self): AnalysisDataService.addOrReplace("TestMatrixWS", ws) # Test algorithm - alg_test = run_algorithm("ExportExperimentLog", + alg_test = run_algorithm("ExportExperimentLog", InputWorkspace = "TestMatrixWS", OutputFilename = "TestRecord.txt", SampleLogNames = ["run_number", "duration", "proton_charge"], @@ -291,11 +291,11 @@ def test_exportFileNewCSV(self): print "Unable to open file %s. " % (outfilename) self.assertTrue(False) return - + # Last line cannot be empty, i.e., before EOF '\n' is not allowed lastline = lines[-1] self.assertTrue(len(lastline.strip()) > 0) - + # Number of lines self.assertEquals(len(lines), 2) @@ -304,36 +304,36 @@ def test_exportFileNewCSV(self): terms = firstdataline.strip().split(",") self.assertEquals(len(terms), 3) - # - # # Remove generated files + # + # # Remove generated files os.remove(outfilename) AnalysisDataService.remove("TestMatrixWS") - - return + + return def createTestWorkspace(self): """ Create a workspace for testing against with ideal log values """ from mantid.simpleapi import CreateWorkspace from mantid.simpleapi import AddSampleLog - from time import gmtime, strftime,mktime + from time import gmtime, strftime,mktime import numpy as np - + # Create a matrix workspace x = np.array([1.,2.,3.,4.]) y = np.array([1.,2.,3.]) e = np.sqrt(np.array([1.,2.,3.])) wksp = CreateWorkspace(DataX=x, DataY=y,DataE=e,NSpec=1,UnitX='TOF') - # Add run_start + # Add run_start tmptime = strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(gmtime()))) AddSampleLog(Workspace=wksp,LogName='run_start',LogText=str(tmptime)) - tsp_a=kernel.FloatTimeSeriesProperty("proton_charge") + tsp_a=kernel.FloatTimeSeriesProperty("proton_charge") tsp_b=kernel.FloatTimeSeriesProperty("SensorA") - for i in arange(25): + for i in arange(25): tmptime = strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(gmtime())+i)) - tsp_a.addValue(tmptime, 1.0*i*i) + tsp_a.addValue(tmptime, 1.0*i*i) tsp_b.addValue(tmptime, 1.234*(i+1)) wksp.mutableRun()['run_number']="23456" diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ExportSampleLogsToCSVFileTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ExportSampleLogsToCSVFileTest.py index 847f8381c966..3be6c74cff39 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ExportSampleLogsToCSVFileTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/ExportSampleLogsToCSVFileTest.py @@ -1,6 +1,6 @@ import unittest -import numpy -from numpy import * +import numpy +from numpy import * from mantid.kernel import * from mantid.api import * import mantid.kernel as kernel @@ -18,7 +18,7 @@ def test_exportFileOnly(self): AnalysisDataService.addOrReplace("TestMatrixWS", ws) # Test algorithm - alg_test = run_algorithm("ExportSampleLogsToCSVFile", + alg_test = run_algorithm("ExportSampleLogsToCSVFile", InputWorkspace = "TestMatrixWS", OutputFilename = "furnace20333.txt", SampleLogNames = ["SensorA", "SensorB", "SensorC"], @@ -37,7 +37,7 @@ def test_exportFileOnly(self): print "Unable to open file %s. " % (outfilename) self.assertTrue(False) return - + # Count lines in the file goodlines = 0 for line in lines: @@ -47,16 +47,16 @@ def test_exportFileOnly(self): # ENDIF # ENDFOR self.assertEquals(goodlines, 25) - - # Remove generated files + + # Remove generated files os.remove(outfilename) AnalysisDataService.remove("TestMatrixWS") - + return def test_exportFile2(self): - """ Get a partial of real load frame log values, and set them to + """ Get a partial of real load frame log values, and set them to different logs """ # Generate the matrix workspace with some logs @@ -64,11 +64,11 @@ def test_exportFile2(self): AnalysisDataService.addOrReplace("TestMatrixWS2", ws) # Test algorithm - alg_test = run_algorithm("ExportSampleLogsToCSVFile", + alg_test = run_algorithm("ExportSampleLogsToCSVFile", InputWorkspace = "TestMatrixWS2", OutputFilename = "furnace20334.txt", SampleLogNames = ["SensorA", "SensorB", "SensorC", "SensorD"], - WriteHeaderFile = False, + WriteHeaderFile = False, TimeTolerance = 1.0) # Validate @@ -93,7 +93,7 @@ def test_exportFile2(self): goodlines += 1 self.assertEquals(goodlines, 64) - # Remove generated files + # Remove generated files os.remove(outfilename) AnalysisDataService.remove("TestMatrixWS2") @@ -110,13 +110,13 @@ def test_exportFileAndHeader(self): AnalysisDataService.addOrReplace("TestMatrixWS", ws) # Test algorithm - alg_test = run_algorithm("ExportSampleLogsToCSVFile", + alg_test = run_algorithm("ExportSampleLogsToCSVFile", InputWorkspace = "TestMatrixWS", OutputFilename = "furnace20339.txt", SampleLogNames = ["SensorA", "SensorB", "SensorC"], - WriteHeaderFile = True, + WriteHeaderFile = True, Header = "SensorA[K]\t SensorB[K]\t SensorC[K]") - + # Validate self.assertTrue(alg_test.isExecuted()) @@ -147,7 +147,7 @@ def test_exportFileAndHeader(self): os.remove(outfilename) os.remove(headerfilename) AnalysisDataService.remove("TestMatrixWS") - + return @@ -159,7 +159,7 @@ def test_exportFileMissingLog(self): AnalysisDataService.addOrReplace("TestMatrixWS", ws) # Test algorithm - alg_test = run_algorithm("ExportSampleLogsToCSVFile", + alg_test = run_algorithm("ExportSampleLogsToCSVFile", InputWorkspace = "TestMatrixWS", OutputFilename = "furnace20335.txt", SampleLogNames = ["SensorA", "SensorB", "SensorX", "SensorC"], @@ -197,7 +197,7 @@ def test_exportFileMissingLog(self): # Clean os.remove(outfilename) AnalysisDataService.remove("TestMatrixWS") - + return def createTestWorkspace(self): @@ -205,27 +205,27 @@ def createTestWorkspace(self): """ from mantid.simpleapi import CreateWorkspace from mantid.simpleapi import AddSampleLog - from time import gmtime, strftime,mktime + from time import gmtime, strftime,mktime import numpy as np - + # Create a matrix workspace x = np.array([1.,2.,3.,4.]) y = np.array([1.,2.,3.]) e = np.sqrt(np.array([1.,2.,3.])) wksp = CreateWorkspace(DataX=x, DataY=y,DataE=e,NSpec=1,UnitX='TOF') - # Add run_start + # Add run_start tmptime = strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(gmtime()))) AddSampleLog(Workspace=wksp,LogName='run_start',LogText=str(tmptime)) - tsp_a=kernel.FloatTimeSeriesProperty("SensorA") - tsp_b=kernel.FloatTimeSeriesProperty("SensorB") - tsp_c=kernel.FloatTimeSeriesProperty("SensorC") - for i in arange(25): + tsp_a=kernel.FloatTimeSeriesProperty("SensorA") + tsp_b=kernel.FloatTimeSeriesProperty("SensorB") + tsp_c=kernel.FloatTimeSeriesProperty("SensorC") + for i in arange(25): tmptime = strftime("%Y-%m-%d %H:%M:%S", gmtime(mktime(gmtime())+i)) - tsp_a.addValue(tmptime, 1.0*i*i) - tsp_b.addValue(tmptime, 2.0*i*i) - tsp_c.addValue(tmptime, 3.0*i*i) + tsp_a.addValue(tmptime, 1.0*i*i) + tsp_b.addValue(tmptime, 2.0*i*i) + tsp_c.addValue(tmptime, 3.0*i*i) wksp.mutableRun()['SensorA']=tsp_a wksp.mutableRun()['SensorB']=tsp_b @@ -235,21 +235,21 @@ def createTestWorkspace(self): def createTestWorkspace2(self): - """ Create a workspace for testing against with more situation + """ Create a workspace for testing against with more situation """ from mantid.simpleapi import CreateWorkspace from mantid.simpleapi import AddSampleLog - from time import gmtime, strftime,mktime + from time import gmtime, strftime,mktime from datetime import datetime, timedelta import numpy as np - + # Create a matrix workspace x = np.array([1.,2.,3.,4.]) y = np.array([1.,2.,3.]) e = np.sqrt(np.array([1.,2.,3.])) wksp = CreateWorkspace(DataX=x, DataY=y,DataE=e,NSpec=1,UnitX='TOF') - # Add run_start + # Add run_start year = 2014 month = 2 day = 15 @@ -264,29 +264,29 @@ def createTestWorkspace2(self): runstart = datetime(year, month, day, hour, minute, second) AddSampleLog(Workspace=wksp,LogName='run_start',LogText=str(runstart)) - tsp_a = kernel.FloatTimeSeriesProperty("SensorA") - tsp_b = kernel.FloatTimeSeriesProperty("SensorB") - tsp_c = kernel.FloatTimeSeriesProperty("SensorC") - tsp_d = kernel.FloatTimeSeriesProperty("SensorD") + tsp_a = kernel.FloatTimeSeriesProperty("SensorA") + tsp_b = kernel.FloatTimeSeriesProperty("SensorB") + tsp_c = kernel.FloatTimeSeriesProperty("SensorC") + tsp_d = kernel.FloatTimeSeriesProperty("SensorD") logs = [tsp_a, tsp_b, tsp_c, tsp_d] - + dbbuf = "" random.seed(0) - for i in arange(25): + for i in arange(25): # Randomly pick up log without records # first iteration must have all the record skiploglist = [] if i > 0: numnorecord = random.randint(-1, 4) - if numnorecord > 0: + if numnorecord > 0: for j in xrange(numnorecord): logindex = random.randint(0, 6) skiploglist.append(logindex) - # ENDFOR (j) + # ENDFOR (j) # ENDIF (numnorecord) # ENDIF (i) - + dbbuf += "----------- %d -------------\n" % (i) # Record @@ -297,7 +297,7 @@ def createTestWorkspace2(self): # get random time shifts timeshift = (random.random()-0.5)*timefluc - + if i == 0: # first record should have the 'exactly' same time stamps timeshift *= 0.0001 @@ -306,13 +306,13 @@ def createTestWorkspace2(self): tmptime = str(runstart + deltatime) tmpvalue = float(i*i*6)+j logs[j].addValue(tmptime, tmpvalue) - + dbbuf += "%s: %s = %d\n" % (logs[j].name, tmptime, tmpvalue) - + # ENDFOR (j) # ENDFOR (i) - - # print dbbuf + + # print dbbuf wksp.mutableRun()['SensorA']=tsp_a wksp.mutableRun()['SensorB']=tsp_b @@ -320,7 +320,7 @@ def createTestWorkspace2(self): wksp.mutableRun()['SensorD']=tsp_d return wksp - + def Untest_exportVulcanFile(self): """ Test to export logs without header file File 2: VULCAN_41739_event @@ -328,13 +328,13 @@ def Untest_exportVulcanFile(self): from mantid.simpleapi import Load # Generate the matrix workspace with some logs - Load(Filename="/home/wzz/Projects/MantidProjects/Mantid2/Code/debug/VULCAN_41703_event.nxs", + Load(Filename="/home/wzz/Projects/MantidProjects/Mantid2/Code/debug/VULCAN_41703_event.nxs", OutputWorkspace="VULCAN_41703", MetaDataOnly = True, LoadLog = True) # Test algorithm - alg_test = run_algorithm("ExportSampleLogsToCSVFile", + alg_test = run_algorithm("ExportSampleLogsToCSVFile", InputWorkspace = "VULCAN_41703", OutputFilename = "/tmp/furnace41703.txt", SampleLogNames = ["furnace.temp1", "furnace.temp2", "furnace.power"], diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/FilterLogByTimeTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/FilterLogByTimeTest.py index 9946448123bc..7c7e553ab9ad 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/FilterLogByTimeTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/FilterLogByTimeTest.py @@ -5,9 +5,9 @@ from mantid.api import * class FilterLogByTimeTest(unittest.TestCase): - + __ws = None - + ''' Log file contents. 2008-06-17T11:10:44 -0.86526 2008-06-17T11:10:45 -1.17843 @@ -37,61 +37,61 @@ class FilterLogByTimeTest(unittest.TestCase): 2008-06-17T11:21:25 0 2008-06-17T11:21:32 0 ''' - + def setUp(self): x = numpy.arange(0, 1, 0.25) ws =CreateWorkspace(UnitX="1/q", DataX=x, DataY=[0,0,0], NSpec=1) self.__ws = ws LoadLog(Workspace=self.__ws,Filename='CSP78173_height.txt',Names='height') - - + + def tearDown(self): DeleteWorkspace(self.__ws) - + def test_startdate_after_enddate(self): try: results = FilterLogByTime(InputWorkspace=self.__ws, LogName='height', StartTime=1, EndTime=0) self.assertTrue(False, "End time < Start time.") except RuntimeError: pass - + def test_without_limits(self): AddSampleLog(Workspace=self.__ws,LogName='run_start',LogText='1900-Jan-01 00:00:00') AddSampleLog(Workspace=self.__ws,LogName='run_end',LogText='2100-Jan-02 00:00:00') - + results, stats = FilterLogByTime(InputWorkspace=self.__ws, LogName='height') self.assertTrue(isinstance(results, numpy.ndarray), "Should give back an array") self.assertTrue(isinstance(stats, float), "Should give back a single result") expected_size = self.__ws.getRun().getLogData('height').size() actual_size = results.size self.assertEqual(expected_size, actual_size, "Nothing filtered out") - + def test_with_start_limit(self): AddSampleLog(Workspace=self.__ws,LogName='run_start',LogText='2008-06-17T11:10:44') AddSampleLog(Workspace=self.__ws,LogName='run_end',LogText='2100-Jan-02 00:00:00') - + results, stats = FilterLogByTime(InputWorkspace=self.__ws, LogName='height', StartTime=1) self.assertTrue(isinstance(results, numpy.ndarray), "Should give back an array") self.assertTrue(isinstance(stats, float), "Should give back a single result") expected_size = self.__ws.getRun().getLogData('height').size() - 1 actual_size = results.size self.assertEqual(expected_size, actual_size, "Should filter one out expected_size %s, actual_size %s" % (str(expected_size), str(actual_size))) - + def test_with_end_limit(self): AddSampleLog(Workspace=self.__ws,LogName='run_start',LogText='2008-06-17T11:10:44') AddSampleLog(Workspace=self.__ws,LogName='run_end',LogText='2100-Jan-02 00:00:00') - + results, stats = FilterLogByTime(InputWorkspace=self.__ws, LogName='height', EndTime=0.99) self.assertTrue(isinstance(results, numpy.ndarray), "Should give back an array") self.assertTrue(isinstance(stats, float), "Should give back a single result") expected_size = 1 actual_size = results.size self.assertEqual(expected_size, actual_size, "Expected_size %s, actual_size %s" % (str(expected_size), str(actual_size))) - + def test_with_both_limits(self): AddSampleLog(Workspace=self.__ws,LogName='run_start',LogText='2008-06-17T11:10:44') AddSampleLog(Workspace=self.__ws,LogName='run_end',LogText='2100-Jan-02 00:00:00') - + results, stats = FilterLogByTime(InputWorkspace=self.__ws, LogName='height', StartTime=1, EndTime=3) self.assertTrue(isinstance(results, numpy.ndarray), "Should give back an array") self.assertTrue(isinstance(stats, float), "Should give back a single result") @@ -99,28 +99,28 @@ def test_with_both_limits(self): actual_size = results.size self.assertEqual(expected_size, actual_size, "Should filter one out expected_size %s, actual_size %s" % (str(expected_size), str(actual_size))) self.assertEqual(stats, (-1.17843 -1.27995)/2, "The 2nd and 3rd entry. Default stats should be mean of these.") - + def __doStats(self, method): AddSampleLog(Workspace=self.__ws,LogName='run_start',LogText='2008-06-17T11:10:44') AddSampleLog(Workspace=self.__ws,LogName='run_end',LogText='2100-Jan-02 00:00:00') - + results, stats = FilterLogByTime(InputWorkspace=self.__ws, LogName='height', StartTime=1, EndTime=3, Method=method) self.assertTrue(isinstance(results, numpy.ndarray), "Should give back an array") self.assertTrue(isinstance(stats, float), "Should give back a single result") return stats - + def test_calculate_mean(self): stats = self.__doStats("mean") self.assertEqual(stats, (-1.17843 -1.27995)/2) - + def test_calculate_max(self): stats = self.__doStats("max") self.assertEqual(stats, -1.17843) - + def test_calculate_min(self): stats = self.__doStats("min") self.assertEqual(stats, -1.27995) - - + + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/FindReflectometryLinesTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/FindReflectometryLinesTest.py index c8ebb22086bc..d68910755620 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/FindReflectometryLinesTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/FindReflectometryLinesTest.py @@ -14,39 +14,39 @@ class FindReflectometryLinesTest(unittest.TestCase): def setUp(self): if self.__class__._no_peak_ws == None: # Create test workspace with no peaks - dataX = [0, 1] - dataY = [0] - dataE = [0] + dataX = [0, 1] + dataY = [0] + dataE = [0] nSpec = 1 no_peak_ws_alg = run_algorithm("CreateWorkspace", DataX=dataX, DataY=dataY, DataE=dataE, NSpec=nSpec, UnitX="Wavelength", VerticalAxisUnit="SpectraNumber", OutputWorkspace="no_peak_ws") self.__class__._no_peak_ws = no_peak_ws_alg.getPropertyValue("OutputWorkspace") - + # Create test workspace with a single peak - dataX = [0, 1, 0, 1, 0, 1] # Setup enough X values {0, 1} to create a histo workspace with a single bin. - dataY = [0, 1, 0] # One real peak + dataX = [0, 1, 0, 1, 0, 1] # Setup enough X values {0, 1} to create a histo workspace with a single bin. + dataY = [0, 1, 0] # One real peak dataE = [0, 0, 0] # Errors are not considered in the algorithm nSpec = 3 one_peak_ws_alg = run_algorithm("CreateWorkspace", DataX=dataX, DataY=dataY, DataE=dataE, NSpec=nSpec, UnitX="Wavelength", VerticalAxisUnit="SpectraNumber", OutputWorkspace="one_peak_ws") self.__class__._one_peak_ws = one_peak_ws_alg.getPropertyValue("OutputWorkspace") - + # Create test workspace with two peaks - dataX = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] # Setup enough X values {0, 1} to create a histo workspace with a single bin. + dataX = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] # Setup enough X values {0, 1} to create a histo workspace with a single bin. dataY = [0.1, 1, 0.1, 0.2, 0.1, 2, 0.1] # Real peaks with values 1, 2, false peak with value 0.2 dataE = [0, 0, 0, 0, 0, 0, 0] # Errors are not considered in the algorithm nSpec = 7 two_peak_ws_alg = run_algorithm("CreateWorkspace", DataX=dataX, DataY=dataY, DataE=dataE, NSpec=nSpec, UnitX="Wavelength", VerticalAxisUnit="SpectraNumber", OutputWorkspace="two_peak_ws") self.__class__._two_peak_ws = two_peak_ws_alg.getPropertyValue("OutputWorkspace") - + # Create test workspace with three peaks - dataX = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] # Setup enough X values {0, 1} to create a histo workspace with a single bin. + dataX = [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1] # Setup enough X values {0, 1} to create a histo workspace with a single bin. dataY = [0, 1, 0, 1, 0, 1, 0, 1, 0] # 3 real peaks dataE = [0, 0, 0, 0, 0, 0, 0, 0, 0] # Errors are not considered in the algorithm nSpec = 9 three_peak_ws_alg = run_algorithm("CreateWorkspace", DataX=dataX, DataY=dataY, DataE=dataE, NSpec=nSpec, UnitX="Wavelength", VerticalAxisUnit="SpectraNumber", OutputWorkspace="three_peak_ws") self.__class__._three_peak_ws = three_peak_ws_alg.getPropertyValue("OutputWorkspace") - + def test_inputs_ws_not_in_wavelength(self): - units = "TOF" + units = "TOF" run_algorithm("CreateWorkspace", DataX=[0, 1], DataY=[0], DataE=[0], NSpec=1, UnitX=units, VerticalAxisUnit="SpectraNumber", OutputWorkspace="in_tof") try: # This should throw, because input units are in TOF, not wavelength! @@ -64,7 +64,7 @@ def test_start_wavlength_too_low(self): self.assertTrue(True) else: self.assertTrue(False) - + def test_keep_intermeidate_workspaces_off_by_default(self): alg = run_algorithm('FindReflectometryLines', InputWorkspace=self.__class__._two_peak_ws , OutputWorkspace='spectrum_numbers') keep_workspaces = alg.getPropertyValue("KeepIntermediateWorkspaces") @@ -74,7 +74,7 @@ def test_keep_intermeidate_workspaces_off_by_default(self): self.assertTrue(not mtd.doesExist('summed_ws')) #clean-up mtd.remove('spectrum_numbers') - + def test_switch_intermediate_workspaces_on(self): alg = run_algorithm('FindReflectometryLines', InputWorkspace=self.__class__._two_peak_ws , OutputWorkspace='spectrum_numbers', KeepIntermediateWorkspaces=True) self.assertTrue(mtd.doesExist('spectrum_numbers')) @@ -84,7 +84,7 @@ def test_switch_intermediate_workspaces_on(self): mtd.remove('cropped_ws') mtd.remove('summed_ws') mtd.remove('spectrum_numbers') - + def test_find_no_peaks_throws(self): try: alg = run_algorithm('FindReflectometryLines', InputWorkspace=self.__class__._no_peak_ws , OutputWorkspace='spectrum_numbers', child=True) @@ -92,7 +92,7 @@ def test_find_no_peaks_throws(self): self.assertTrue(True) #We expect the algorithm to fail if no peaks are found. else: self.assertTrue(False) - + def test_find_three_peaks_throws(self): try: alg = run_algorithm('FindReflectometryLines', InputWorkspace=self.__class__._three_peak_ws , OutputWorkspace='spectrum_numbers', child=True) @@ -100,25 +100,25 @@ def test_find_three_peaks_throws(self): self.assertTrue(True) #We expect the algorithm to fail if three peaks are found. else: self.assertTrue(False) - + def test_find_one_peaks(self): alg = run_algorithm('FindReflectometryLines', InputWorkspace=self.__class__._one_peak_ws, OutputWorkspace='spectrum_numbers') spectrum_workspace = mtd.retrieve('spectrum_numbers') - + # Should create a table with a SINGLE column (reflected spectra #) and one row. self.assertEquals(1, spectrum_workspace.columnCount()) self.assertEquals(1, spectrum_workspace.rowCount()) - self.assertEquals(2, spectrum_workspace.cell(0,0)) # Match of exact spectrum that should be found + self.assertEquals(2, spectrum_workspace.cell(0,0)) # Match of exact spectrum that should be found def test_find_two_peaks(self): alg = run_algorithm('FindReflectometryLines', InputWorkspace=self.__class__._two_peak_ws, OutputWorkspace='spectrum_numbers') spectrum_workspace = mtd.retrieve('spectrum_numbers') - + # Should create a table with a TWO columns (reflected spectra #, transmission spectra #) and one row. self.assertEquals(2, spectrum_workspace.columnCount()) self.assertEquals(1, spectrum_workspace.rowCount()) - self.assertEquals(6, spectrum_workspace.cell(0,0)) # Match of exact spectrum that should be found - self.assertEquals(2, spectrum_workspace.cell(0,1)) # Match of exact spectrum that should be found - + self.assertEquals(6, spectrum_workspace.cell(0,0)) # Match of exact spectrum that should be found + self.assertEquals(2, spectrum_workspace.cell(0,1)) # Match of exact spectrum that should be found + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/GetEiT0atSNSTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/GetEiT0atSNSTest.py index 0f622dd90880..c20607d9c3c5 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/GetEiT0atSNSTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/GetEiT0atSNSTest.py @@ -6,7 +6,7 @@ from string import * class GetEiT0atSNSTest(unittest.TestCase): - + def testGETS(self): w=Load('ADARAMonitors.nxs') LoadInstrument(Workspace=w,InstrumentName='SEQUOIA',RewriteSpectraMap='0') @@ -20,7 +20,7 @@ def testGETS(self): except Exception as e: s="Could not get Ei, and this is not a white beam run\nNo peak found for the monitor with spectra num: 2" self.assertEquals(find(e.message,s),0) - DeleteWorkspace(w) - + DeleteWorkspace(w) + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadFullprofFileTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadFullprofFileTest.py index 47064b5dce66..bce50752a4d7 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadFullprofFileTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadFullprofFileTest.py @@ -16,8 +16,8 @@ def test_LoadHKLFile(self): hklfilename = "test.hkl" self._createHKLFile(hklfilename) - # 2. - alg_test = run_algorithm("LoadFullprofFile", Filename = hklfilename, + # 2. + alg_test = run_algorithm("LoadFullprofFile", Filename = hklfilename, OutputWorkspace = "Foo", PeakParameterWorkspace = "PeakParameterTable") self.assertTrue(alg_test.isExecuted()) @@ -72,7 +72,7 @@ def test_LoadPRFFile(self): dataws = AnalysisDataService.retrieve("Data") self.assertEqual(dataws.getNumberHistograms(), 4) self.assertEqual(len(dataws.readX(0)), 36) - + # value self.assertEqual(dataws.readX(0)[13], 5026.3223) self.assertEqual(dataws.readY(1)[30], 0.3819) @@ -94,68 +94,68 @@ def _createPrfFile(self, filename): prffile.write("LaB6 NIST SRM-660b standard 2013-A Dec PAC CELL: 4.15689 4.15689 4.15689 90.0000 90.0000 90.0000 SPGR: P m -3 m\n") prffile.write("1 5741 1.00000 1.00000 2.33738 22580.59180 0.00000 1\n") prffile.write("1539 0 0\n") - prffile.write(" T.O.F. Yobs Ycal Yobs-Ycal Backg Posr (hkl) K \n") - prffile.write(" 5000.2583 0.3715 0.4031 -3.3748 0.3288\n") - prffile.write(" 5002.2583 0.3590 0.3963 -3.3804 0.3287\n") - prffile.write(" 5004.2593 0.3494 0.3914 -3.3851 0.3286\n") - prffile.write(" 5006.2612 0.3652 0.3874 -3.3654 0.3285\n") - prffile.write(" 5008.2637 0.3676 0.3832 -3.3587 0.3284\n") - prffile.write(" 5010.2666 0.3471 0.3798 -3.3758 0.3284\n") - prffile.write(" 5012.2710 0.3819 0.3777 -3.3390 0.3283\n") - prffile.write(" 5014.2759 0.3271 0.3773 -3.3934 0.3282\n") - prffile.write(" 5016.2817 0.3881 0.3798 -3.3348 0.3281\n") - prffile.write(" 5018.2881 0.3833 0.3868 -3.3467 0.3280\n") - prffile.write(" 5020.2954 0.3684 0.3921 -3.3669 0.3280\n") - prffile.write(" 5022.3037 0.3604 0.3891 -3.3719 0.3279\n") - prffile.write(" 5024.3125 0.3802 0.3846 -3.3476 0.3278\n") - prffile.write(" 5026.3223 0.3487 0.3812 -3.3756 0.3277\n") - prffile.write(" 5028.3325 0.3489 0.3784 -3.3726 0.3277\n") - prffile.write(" 5030.3438 0.3728 0.3759 -3.3463 0.3276\n") - prffile.write(" 5032.3560 0.3425 0.3743 -3.3749 0.3275\n") - prffile.write(" 5034.3691 0.3490 0.3736 -3.3678 0.3274\n") - prffile.write(" 5036.3828 0.3383 0.3746 -3.3795 0.3273\n") - prffile.write(" 5038.3975 0.3677 0.3789 -3.3544 0.3273\n") - prffile.write(" 5040.4126 0.3574 0.3873 -3.3730 0.3272\n") - prffile.write(" 5042.4287 0.3802 0.3912 -3.3541 0.3271\n") - prffile.write(" 5044.4458 0.3741 0.3880 -3.3571 0.3270\n") - prffile.write(" 5046.4639 0.3636 0.3852 -3.3647 0.3269\n") - prffile.write(" 5048.4824 0.3707 0.3841 -3.3565 0.3269\n") - prffile.write(" 5050.5015 0.3697 0.3824 -3.3558 0.3268\n") - prffile.write(" 5052.5220 0.3683 0.3818 -3.3566 0.3267\n") - prffile.write(" 5054.5430 0.3379 0.3844 -3.3896 0.3266\n") - prffile.write(" 5056.5645 0.3444 0.3865 -3.3853 0.3265\n") - prffile.write(" 5058.5874 0.3657 0.3841 -3.3616 0.3265\n") - prffile.write(" 5060.6108 0.3922 0.3819 -3.3329 0.3264\n") - prffile.write(" 5062.6348 0.3568 0.3815 -3.3679 0.3263\n") - prffile.write(" 5064.6602 0.3783 0.3799 -3.3448 0.3262\n") - prffile.write(" 5066.6860 0.3388 0.3769 -3.3813 0.3261\n") - prffile.write(" 5068.7124 0.3528 0.3744 -3.3647 0.3261\n") - prffile.write(" 5070.7402 0.3429 0.3727 -3.3729 0.3260\n") - prffile.write("6866.4219 0 ( 13 3 3) 0 1\n") - prffile.write("6884.8496 0 ( 11 7 4) 0 1\n") - prffile.write("6884.8496 0 ( 11 8 1) 0 1\n") - prffile.write("6884.8496 0 ( 13 4 1) 0 1\n") - prffile.write("6903.4258 0 ( 10 7 6) 0 1\n") - prffile.write("6903.4258 0 ( 10 9 2) 0 1\n") - prffile.write("6903.4258 0 ( 11 8 0) 0 1\n") - prffile.write("6903.4258 0 ( 12 5 4) 0 1\n") - prffile.write("6903.4258 0 ( 13 4 0) 0 1\n") - prffile.write("6922.1533 0 ( 12 6 2) 0 1\n") - prffile.write("6960.0708 0 ( 10 9 1) 0 1\n") - prffile.write("6960.0708 0 ( 11 6 5) 0 1\n") - prffile.write("6960.0703 0 ( 13 3 2) 0 1\n") - prffile.write("6979.2642 0 ( 9 8 6) 0 1\n") - prffile.write("6979.2642 0 ( 10 9 0) 0 1\n") - prffile.write("6979.2651 0 ( 12 6 1) 0 1\n") - prffile.write("6998.6177 0 ( 10 8 4) 0 1\n") - prffile.write("6998.6187 0 ( 12 6 0) 0 1\n") - prffile.write("7018.1333 0 ( 9 7 7) 0 1\n") - prffile.write("7018.1328 0 ( 11 7 3) 0 1\n") - prffile.write("7018.1333 0 ( 13 3 1) 0 1\n") - prffile.write("7037.8135 0 ( 9 9 4) 0 1\n") - prffile.write("7037.8135 0 ( 12 5 3) 0 1\n") - prffile.write("7037.8135 0 ( 13 3 0) 0 1\n") - prffile.write("7057.6597 0 ( 8 8 7) 0 1\n") + prffile.write(" T.O.F. Yobs Ycal Yobs-Ycal Backg Posr (hkl) K \n") + prffile.write(" 5000.2583 0.3715 0.4031 -3.3748 0.3288\n") + prffile.write(" 5002.2583 0.3590 0.3963 -3.3804 0.3287\n") + prffile.write(" 5004.2593 0.3494 0.3914 -3.3851 0.3286\n") + prffile.write(" 5006.2612 0.3652 0.3874 -3.3654 0.3285\n") + prffile.write(" 5008.2637 0.3676 0.3832 -3.3587 0.3284\n") + prffile.write(" 5010.2666 0.3471 0.3798 -3.3758 0.3284\n") + prffile.write(" 5012.2710 0.3819 0.3777 -3.3390 0.3283\n") + prffile.write(" 5014.2759 0.3271 0.3773 -3.3934 0.3282\n") + prffile.write(" 5016.2817 0.3881 0.3798 -3.3348 0.3281\n") + prffile.write(" 5018.2881 0.3833 0.3868 -3.3467 0.3280\n") + prffile.write(" 5020.2954 0.3684 0.3921 -3.3669 0.3280\n") + prffile.write(" 5022.3037 0.3604 0.3891 -3.3719 0.3279\n") + prffile.write(" 5024.3125 0.3802 0.3846 -3.3476 0.3278\n") + prffile.write(" 5026.3223 0.3487 0.3812 -3.3756 0.3277\n") + prffile.write(" 5028.3325 0.3489 0.3784 -3.3726 0.3277\n") + prffile.write(" 5030.3438 0.3728 0.3759 -3.3463 0.3276\n") + prffile.write(" 5032.3560 0.3425 0.3743 -3.3749 0.3275\n") + prffile.write(" 5034.3691 0.3490 0.3736 -3.3678 0.3274\n") + prffile.write(" 5036.3828 0.3383 0.3746 -3.3795 0.3273\n") + prffile.write(" 5038.3975 0.3677 0.3789 -3.3544 0.3273\n") + prffile.write(" 5040.4126 0.3574 0.3873 -3.3730 0.3272\n") + prffile.write(" 5042.4287 0.3802 0.3912 -3.3541 0.3271\n") + prffile.write(" 5044.4458 0.3741 0.3880 -3.3571 0.3270\n") + prffile.write(" 5046.4639 0.3636 0.3852 -3.3647 0.3269\n") + prffile.write(" 5048.4824 0.3707 0.3841 -3.3565 0.3269\n") + prffile.write(" 5050.5015 0.3697 0.3824 -3.3558 0.3268\n") + prffile.write(" 5052.5220 0.3683 0.3818 -3.3566 0.3267\n") + prffile.write(" 5054.5430 0.3379 0.3844 -3.3896 0.3266\n") + prffile.write(" 5056.5645 0.3444 0.3865 -3.3853 0.3265\n") + prffile.write(" 5058.5874 0.3657 0.3841 -3.3616 0.3265\n") + prffile.write(" 5060.6108 0.3922 0.3819 -3.3329 0.3264\n") + prffile.write(" 5062.6348 0.3568 0.3815 -3.3679 0.3263\n") + prffile.write(" 5064.6602 0.3783 0.3799 -3.3448 0.3262\n") + prffile.write(" 5066.6860 0.3388 0.3769 -3.3813 0.3261\n") + prffile.write(" 5068.7124 0.3528 0.3744 -3.3647 0.3261\n") + prffile.write(" 5070.7402 0.3429 0.3727 -3.3729 0.3260\n") + prffile.write("6866.4219 0 ( 13 3 3) 0 1\n") + prffile.write("6884.8496 0 ( 11 7 4) 0 1\n") + prffile.write("6884.8496 0 ( 11 8 1) 0 1\n") + prffile.write("6884.8496 0 ( 13 4 1) 0 1\n") + prffile.write("6903.4258 0 ( 10 7 6) 0 1\n") + prffile.write("6903.4258 0 ( 10 9 2) 0 1\n") + prffile.write("6903.4258 0 ( 11 8 0) 0 1\n") + prffile.write("6903.4258 0 ( 12 5 4) 0 1\n") + prffile.write("6903.4258 0 ( 13 4 0) 0 1\n") + prffile.write("6922.1533 0 ( 12 6 2) 0 1\n") + prffile.write("6960.0708 0 ( 10 9 1) 0 1\n") + prffile.write("6960.0708 0 ( 11 6 5) 0 1\n") + prffile.write("6960.0703 0 ( 13 3 2) 0 1\n") + prffile.write("6979.2642 0 ( 9 8 6) 0 1\n") + prffile.write("6979.2642 0 ( 10 9 0) 0 1\n") + prffile.write("6979.2651 0 ( 12 6 1) 0 1\n") + prffile.write("6998.6177 0 ( 10 8 4) 0 1\n") + prffile.write("6998.6187 0 ( 12 6 0) 0 1\n") + prffile.write("7018.1333 0 ( 9 7 7) 0 1\n") + prffile.write("7018.1328 0 ( 11 7 3) 0 1\n") + prffile.write("7018.1333 0 ( 13 3 1) 0 1\n") + prffile.write("7037.8135 0 ( 9 9 4) 0 1\n") + prffile.write("7037.8135 0 ( 12 5 3) 0 1\n") + prffile.write("7037.8135 0 ( 13 3 0) 0 1\n") + prffile.write("7057.6597 0 ( 8 8 7) 0 1\n") prffile.close() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadLiveDataTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadLiveDataTest.py index 192600b9df46..7b22dbac79ef 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadLiveDataTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadLiveDataTest.py @@ -9,65 +9,65 @@ class LoadLiveDataTest(unittest.TestCase): """ Test LoadLiveData when passing a python snippet to it. """ - + def setUp(self): FrameworkManager.clearData() ConfigService.updateFacilities(os.path.join(ConfigService.getInstrumentDirectory(),"IDFs_for_UNIT_TESTING/UnitTestFacilities.xml")) ConfigService.setFacility("TEST") pass - - - # -------------------------------------------------------------------------- + + + # -------------------------------------------------------------------------- def doChunkTest(self, code): """ Test that whatever the code is, it rebins to 20 bins """ - LoadLiveData(Instrument='FakeEventDataListener', ProcessingScript=code, + LoadLiveData(Instrument='FakeEventDataListener', ProcessingScript=code, OutputWorkspace='fake') - ws = mtd['fake'] + ws = mtd['fake'] # The rebin call in the code made 20 bins self.assertEquals( len(ws.readY(0)), 20 ) # First bin is correct self.assertAlmostEqual(ws.readX(0)[0], 40e3, 3) - - - # -------------------------------------------------------------------------- + + + # -------------------------------------------------------------------------- def test_chunkProcessing(self): code = """Rebin(InputWorkspace=input,Params='40e3,1e3,60e3',OutputWorkspace=output)""" self.doChunkTest(code) - - # -------------------------------------------------------------------------- + + # -------------------------------------------------------------------------- def test_chunkProcessing_changing_outputVariable(self): code = """ Rebin(input,Params='40e3,1e3,60e3', OutputWorkspace='my_temp_name') output = mtd['my_temp_name'] """ self.doChunkTest(code) - - # -------------------------------------------------------------------------- + + # -------------------------------------------------------------------------- def test_chunkProcessing_complexCode(self): code = """ import sys def MyMethod(a, b): Rebin(a,Params='40e3,1e3,60e3', OutputWorkspace=b) - + MyMethod(input, output) """ self.doChunkTest(code) - - # -------------------------------------------------------------------------- + + # -------------------------------------------------------------------------- def test_PostProcessing(self): code = """Rebin(InputWorkspace=input,Params='40e3,1e3,60e3',OutputWorkspace=output)""" - - LoadLiveData(Instrument='FakeEventDataListener', PostProcessingScript=code, + + LoadLiveData(Instrument='FakeEventDataListener', PostProcessingScript=code, AccumulationWorkspace='fake_accum', OutputWorkspace='fake') - ws = mtd['fake'] + ws = mtd['fake'] # The rebin call in the code made 20 bins self.assertEquals( len(ws.readY(0)), 20 ) # First bin is correct self.assertAlmostEqual(ws.readX(0)[0], 40e3, 3) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadLogPropertyTableTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadLogPropertyTableTest.py index a5151bb8f118..6096f065ba48 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadLogPropertyTableTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadLogPropertyTableTest.py @@ -10,8 +10,8 @@ class LoadLogPropertyTableTest(unittest.TestCase): def test_LoadValidFilesComments(self): outputWorskapceName = "LoadLogPropertyTableTest_Test1" - - alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "MUSR00015189.nxs", + + alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "MUSR00015189.nxs", LastFile = "MUSR00015193.nxs", LogNames="comment", OutputWorkspace = outputWorskapceName) self.assertTrue(alg_test.isExecuted()) @@ -20,19 +20,19 @@ def test_LoadValidFilesComments(self): tablews = AnalysisDataService.retrieve(outputWorskapceName) self.assertEqual(5, tablews.rowCount()) self.assertEqual(2, tablews.columnCount()) - + self.assertEqual("18.95MHz 100W", tablews.cell(0,1)) self.assertEqual(15189, tablews.cell(0,0)) self.assertEqual(15193, tablews.cell(4,0)) run_algorithm("DeleteWorkspace", Workspace = outputWorskapceName) - + return - + def test_LoadPartiallyValidFilesMultipleLogValues(self): outputWorskapceName = "LoadLogPropertyTableTest_Test2" - - alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "emu00006473.nxs", + + alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "emu00006473.nxs", LastFile = "emu00006475.nxs", LogNames="Temp_Sample,dur", OutputWorkspace = outputWorskapceName) self.assertTrue(alg_test.isExecuted()) @@ -41,7 +41,7 @@ def test_LoadPartiallyValidFilesMultipleLogValues(self): tablews = AnalysisDataService.retrieve(outputWorskapceName) self.assertEqual(2, tablews.rowCount()) self.assertEqual(3, tablews.columnCount()) - + self.assertEqual(6473, tablews.cell(0,0)) self.assertAlmostEqual(200.078, tablews.cell(0,1),2) self.assertEqual("8697", tablews.cell(0,2)) @@ -50,13 +50,13 @@ def test_LoadPartiallyValidFilesMultipleLogValues(self): self.assertEqual("5647", tablews.cell(1,2)) run_algorithm("DeleteWorkspace", Workspace = outputWorskapceName) - + return - + def test_LoadValidFilesBlankLog(self): outputWorskapceName = "LoadLogPropertyTableTest_Test3" - - alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "MUSR00015189.nxs", + + alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "MUSR00015189.nxs", LastFile = "MUSR00015193.nxs", OutputWorkspace = outputWorskapceName) self.assertTrue(alg_test.isExecuted()) @@ -65,42 +65,42 @@ def test_LoadValidFilesBlankLog(self): tablews = AnalysisDataService.retrieve(outputWorskapceName) self.assertEqual(5, tablews.rowCount()) self.assertEqual(1, tablews.columnCount()) - + self.assertEqual(15189, tablews.cell(0,0)) self.assertEqual(15193, tablews.cell(4,0)) run_algorithm("DeleteWorkspace", Workspace = outputWorskapceName) - + return - + def test_LoadInValidValues(self): outputWorskapceName = "LoadLogPropertyTableTest_Test4" - + #invalid log name - alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "emu00006473.nxs", + alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "emu00006473.nxs", LastFile = "emu00006475.nxs", LogNames="WrongTemp", OutputWorkspace = outputWorskapceName) self.assertFalse(alg_test.isExecuted()) - + #invalid first file ExecptionThrownOnBadFileParameter = False try: - alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "emu0000000.nxs", + alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "emu0000000.nxs", LastFile = "emu00006475.nxs", LogNames="Temp_Sample", OutputWorkspace = outputWorskapceName) self.assertFalse(alg_test.isExecuted()) except: ExecptionThrownOnBadFileParameter = True self.assertEqual(True,ExecptionThrownOnBadFileParameter) - + #invalid last file ExecptionThrownOnBadFileParameter = False try: - alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "emu00006473.nxs", + alg_test = run_algorithm("LoadLogPropertyTable", FirstFile = "emu00006473.nxs", LastFile = "emu9999999.nxs", LogNames="Temp_Sample", OutputWorkspace = outputWorskapceName) self.assertFalse(alg_test.isExecuted()) except: ExecptionThrownOnBadFileParameter = True self.assertEqual(True,ExecptionThrownOnBadFileParameter) - + return diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadMultipleGSSTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadMultipleGSSTest.py index a0552c56a8ca..3f31de9698d7 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadMultipleGSSTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/LoadMultipleGSSTest.py @@ -6,7 +6,7 @@ class LoadMultipleGSSTest(unittest.TestCase): def test_LoadMultipleGSSTest(self): # Set up - alg_test = run_algorithm("LoadMultipleGSS", + alg_test = run_algorithm("LoadMultipleGSS", FilePrefix = "PG3", RunNumbers = [11485,11486], Directory = "") diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskAngleTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskAngleTest.py index 2563a9dd46af..3e71307fa873 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskAngleTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskAngleTest.py @@ -5,7 +5,7 @@ from numpy import * class MaskAngleTest(unittest.TestCase): - + def testMaskAngle(self): w=WorkspaceCreationHelper.create2DWorkspaceWithFullInstrument(30,5,False,False) AnalysisDataService.add('w',w) @@ -17,7 +17,7 @@ def testMaskAngle(self): self.assertTrue(w.getInstrument().getDetector(int(i)).isMasked()) DeleteWorkspace(w) self.assertTrue(array_equal(masklist,arange(10)+10)) - + def testFailNoInstrument(self): w1=CreateWorkspace(arange(5),arange(5)) try: @@ -27,7 +27,7 @@ def testFailNoInstrument(self): pass finally: DeleteWorkspace(w1) - + def testFailLimits(self): w2=WorkspaceCreationHelper.create2DWorkspaceWithFullInstrument(30,5,False,False) AnalysisDataService.add('w2',w2) @@ -39,14 +39,14 @@ def testFailLimits(self): except ValueError: pass finally: - DeleteWorkspace('w2') + DeleteWorkspace('w2') try: MaskAngle(w3,10,200) self.fail("Should not have got here. Wrong angle.") except ValueError: pass finally: - DeleteWorkspace('w3') + DeleteWorkspace('w3') try: MaskAngle(w4,100,20) self.fail("Should not have got here. Wrong angle.") @@ -54,6 +54,6 @@ def testFailLimits(self): pass finally: DeleteWorkspace('w4') - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskBTPTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskBTPTest.py index 6189f4931421..3c53d6a56db7 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskBTPTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskBTPTest.py @@ -5,7 +5,7 @@ from numpy import * class MaskBTPTest(unittest.TestCase): - + def testMaskBTPWrongInstrument(self): w=WorkspaceCreationHelper.create2DWorkspaceWithFullInstrument(30,5,False,False) AnalysisDataService.add('w',w) @@ -16,7 +16,7 @@ def testMaskBTPWrongInstrument(self): pass finally: DeleteWorkspace(w) - + def testMaskBTPWrongLimits(self): try: MaskBTP(Instrument='ARCS', Pixel="129") @@ -27,16 +27,16 @@ def testMaskBTPWrongLimits(self): MaskBTP(Instrument='SEQUOIA', Bank="1") self.fail("Should not have got here.") except RuntimeError: - pass + pass try: MaskBTP(Instrument='HYSPEC', Tube="18") self.fail("Should not have got here.") except RuntimeError: - pass + pass DeleteWorkspace("ARCSMaskBTP") DeleteWorkspace("HYSPECMaskBTP") DeleteWorkspace("SEQUOIAMaskBTP") - + def testMaskBTP(self): m1=MaskBTP(Instrument='CNCS', Pixel="1-3,5") m2=MaskBTP(Workspace='CNCSMaskBTP', Bank="1-2") @@ -48,18 +48,18 @@ def testMaskBTP(self): b5t3=arange(128)+4*1024+2*128 self.assertTrue(array_equal(m3,concatenate((b5t3,b5t3+1024,b5t3+2048)))) #check whether some pixels are masked when they should - w=mtd['CNCSMaskBTP'] + w=mtd['CNCSMaskBTP'] self.assertTrue(w.getInstrument().getDetector(29696).isMasked()) #pixel1 self.assertTrue(w.getInstrument().getDetector(29697).isMasked()) #pixel2 self.assertTrue(w.getInstrument().getDetector(29698).isMasked()) #pixel3 self.assertTrue(not w.getInstrument().getDetector(29699).isMasked()) #pixel4 self.assertTrue(w.getInstrument().getDetector(29700).isMasked()) #pixel5 - + self.assertTrue(w.getInstrument().getDetector(1020).isMasked()) #bank 1 self.assertTrue(not w.getInstrument().getDetector(3068).isMasked()) #bank3, tube 8 - + self.assertTrue(w.getInstrument().getDetector(4400).isMasked()) #bank5, tube 3 DeleteWorkspace(w) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskWorkspaceToCalFileTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskWorkspaceToCalFileTest.py index 5b523bc27823..651158b3d327 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskWorkspaceToCalFileTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MaskWorkspaceToCalFileTest.py @@ -14,7 +14,7 @@ def get_masking_for_index(self, cal_file, requested_index): raise LookupError line_contents = line.split() try: - index = int(line_contents[0].strip()) + index = int(line_contents[0].strip()) select = int(line_contents[3].strip()) group = int(line_contents[4].strip()) if(index == requested_index): @@ -25,7 +25,7 @@ def get_masking_for_index(self, cal_file, requested_index): def do_test_cal_file(self, masked_workspace, should_invert, expected_masking_identifier, expected_not_masking_identifier, masking_edge): cal_filename = 'wish_masking_system_test_temp.cal' cal_file_alg = run_algorithm('MaskWorkspaceToCalFile',InputWorkspace=masked_workspace.name(), OutputFile=cal_filename, Invert=should_invert, rethrow=True) - + cal_file_full_path = str(cal_file_alg.getPropertyValue('OutputFile')) file = open(cal_file_full_path, 'r') try: @@ -39,7 +39,7 @@ def do_test_cal_file(self, masked_workspace, should_invert, expected_masking_ide finally: file.close() os.remove(cal_file_full_path) - + # Test creating a cal file from a masked MatrixWorkspace directly def test_calfile_from_masked_workspace(self): run_algorithm('Load', Filename='LOQ49886.nxs', OutputWorkspace='LOQ49886', rethrow=True) @@ -49,8 +49,8 @@ def test_calfile_from_masked_workspace(self): masking_identifier = 0 not_masking_identifier = 1 self.do_test_cal_file(masked_workspace, should_invert, masking_identifier, not_masking_identifier, 700) - - # Test creating a cal file from a MaskWorkspace + + # Test creating a cal file from a MaskWorkspace def test_calfile_from_extracted_masking_workspace(self): run_algorithm('Load', Filename='LOQ49886.nxs', OutputWorkspace='LOQ49886', rethrow=True) run_algorithm('MaskDetectors', Workspace='LOQ49886',WorkspaceIndexList='0-700', MaskedWorkspace='LOQ49886', rethrow=True) @@ -70,8 +70,8 @@ def test_calfile_from_masked_workspace_inverse(self): masking_identifier = 1 not_masking_identifier = 0 self.do_test_cal_file(masked_workspace, should_invert, masking_identifier, not_masking_identifier, 700) - - # Test creating a cal file from a MaskWorkspace with masking inverted + + # Test creating a cal file from a MaskWorkspace with masking inverted def test_calfile_from_extracted_masking_workspace_inverse(self): run_algorithm('Load', Filename='LOQ49886.nxs', OutputWorkspace='LOQ49886', rethrow=True) run_algorithm('MaskDetectors', Workspace='LOQ49886',WorkspaceIndexList='0-700', MaskedWorkspace='LOQ49886', rethrow=True) @@ -80,9 +80,9 @@ def test_calfile_from_extracted_masking_workspace_inverse(self): should_invert = True masking_identifier = 1 not_masking_identifier = 0 - self.do_test_cal_file(extracted_workspace, should_invert, masking_identifier, not_masking_identifier, 700) + self.do_test_cal_file(extracted_workspace, should_invert, masking_identifier, not_masking_identifier, 700) + - if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MeanTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MeanTest.py index 57233f989eac..3c8f48167ec2 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MeanTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MeanTest.py @@ -3,7 +3,7 @@ from mantid.api import * class MeanTest(unittest.TestCase): - + def test_throws_if_non_existing_names(self): a = CreateWorkspace(DataX=[1,2,3],DataY=[1,2,3],DataE=[1,1,1],UnitX='TOF') try: @@ -13,7 +13,7 @@ def test_throws_if_non_existing_names(self): pass finally: DeleteWorkspace(a) - + def test_throws_if_workspace_axis0_unequal(self): a = CreateWorkspace(DataX=[1,2,3],DataY=[1,2,3],DataE=[1,1,1],UnitX='TOF') b = CreateWorkspace(DataX=[1,2,3,4],DataY=[1,2,3,4],DataE=[1,1,1,1],UnitX='TOF') @@ -25,7 +25,7 @@ def test_throws_if_workspace_axis0_unequal(self): finally: DeleteWorkspace(a) DeleteWorkspace(b) - + def test_throws_if_workspace_axis1_unequal(self): a = CreateWorkspace(DataX=[1,2,3,4],DataY=[1,2,3,4],DataE=[1,1,1,1],UnitX='TOF',NSpec=1) b = CreateWorkspace(DataX=[1,2,3,4],DataY=[1,2,3,4],DataE=[1,1,1,1],UnitX='TOF',NSpec=2) @@ -37,7 +37,7 @@ def test_throws_if_workspace_axis1_unequal(self): finally: DeleteWorkspace(a) DeleteWorkspace(b) - + def test_mean(self): a = CreateWorkspace(DataX=[1,2,3],DataY=[1,2,3],DataE=[1,1,1],UnitX='TOF') b = CreateWorkspace(DataX=[1,2,3],DataY=[1,2,3],DataE=[1,1,1],UnitX='TOF') @@ -45,12 +45,12 @@ def test_mean(self): d = (a + b) / 2 # Do algorithm work manually for purposes of comparison. message = CheckWorkspacesMatch(Workspace1=c, Workspace2=d) self.assertEquals("Success!", message) - + # Clean-up DeleteWorkspace(a) DeleteWorkspace(b) DeleteWorkspace(c) DeleteWorkspace(d) - + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MergeCalFilesTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MergeCalFilesTest.py index 1c3e34ab63dd..c132a1d87111 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MergeCalFilesTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/MergeCalFilesTest.py @@ -10,78 +10,78 @@ Helper type to represent an entry in a cal file ''' class CalFileLine: - + _number = None _UDET = None _offset = None _select = None _group = None - + def __init__(self, number, UDET, offset, select, group): self._number = number self._UDET = UDET self._offset = offset self._select = select self._group = group - + def getNumber(self): return self._number - + def getUDET(self): return self._UDET - + def getOffset(self): return self._offset - + def getSelect(self): return self._select - + def getGroup(self): return self._group - + ''' A helper resource managing wrapper over a new calfile object. Creates cal file and allows writing to it. ''' -class DisposableCalFileObject: - +class DisposableCalFileObject: + _fullpath = None - + def __init__(self, name): dirpath = tempfile.mkdtemp() self._fullpath = os.path.join(dirpath, name) file = open(self._fullpath, 'w') file.close() - + def writeline(self, entry): file = open(self._fullpath, 'a') file.write("%i\t%i\t%f\t%i\t%i\n" %(entry.getNumber(), entry.getUDET(), entry.getOffset(), entry.getSelect(), entry.getGroup()) ) file.close() - + def __del__(self): os.remove(self._fullpath) - + def getPath(self): return self._fullpath ''' A helper resource managing wrapper over an existing cal file for reading. Disposes of it after reading. -''' +''' class ReadableCalFileObject: - + _fullpath = None - + def __init__(self, fullpath): if not os.path.exists(fullpath): raise RuntimeError("No readable cal file at location: " + fullpath) else: self._fullpath = fullpath - + def __del__(self): pass os.remove(self._fullpath) - + def getPath(self): return _fullpath - + def readline(self): result = None file = open(self._fullpath, 'r') @@ -93,29 +93,29 @@ def readline(self): group = int(line[4]) result = CalFileLine(number, udet, offset, select, group) file.close() - + return result - - + + class MergeCalFilesTest(unittest.TestCase): - - + + def do_execute(self, masterEntry, updateEntry, mergeOffsets, mergeSelect, mergeGroups): - + # Create the master cal file masterfile = DisposableCalFileObject("master.cal") masterfile.writeline(masterEntry) - - # Create the update cal file + + # Create the update cal file updatefile = DisposableCalFileObject("update.cal") - updatefile.writeline(updateEntry) - + updatefile.writeline(updateEntry) + # Create a temp file location dirpath = tempfile.mkdtemp() outputfilestring = os.path.join(dirpath, "product.cal") - + # Run the algorithm - run_algorithm("MergeCalFiles", UpdateFile=updatefile.getPath(), MasterFile=masterfile.getPath(), + run_algorithm("MergeCalFiles", UpdateFile=updatefile.getPath(), MasterFile=masterfile.getPath(), OutputFile=outputfilestring, MergeOffsets=mergeOffsets, MergeSelections=mergeSelect, MergeGroups=mergeGroups) # Read the results file and return the first line as a CalFileEntry @@ -124,63 +124,63 @@ def do_execute(self, masterEntry, updateEntry, mergeOffsets, mergeSelect, mergeG return firstLineOutput def test_replace_nothing(self): - + masterEntry = CalFileLine(1, 1, 1.0, 1, 1) - updateEntry = CalFileLine(1, 1, 2.0, 2, 2) - + updateEntry = CalFileLine(1, 1, 2.0, 2, 2) + firstLineOutput = self.do_execute(masterEntry=masterEntry, updateEntry=updateEntry, mergeOffsets=False, mergeSelect=False, mergeGroups=False) - + self.assertEqual(masterEntry.getOffset(), firstLineOutput.getOffset()) self.assertEqual(masterEntry.getSelect(), firstLineOutput.getSelect()) self.assertEqual(masterEntry.getGroup(), firstLineOutput.getGroup()) - + def test_replace_offset_only(self): - + masterEntry = CalFileLine(1, 1, 1.0, 1, 1) - updateEntry = CalFileLine(1, 1, 2.0, 2, 2) - + updateEntry = CalFileLine(1, 1, 2.0, 2, 2) + firstLineOutput = self.do_execute(masterEntry=masterEntry, updateEntry=updateEntry, mergeOffsets=True, mergeSelect=False, mergeGroups=False) - + self.assertEqual(updateEntry.getOffset(), firstLineOutput.getOffset()) self.assertEqual(masterEntry.getSelect(), firstLineOutput.getSelect()) self.assertEqual(masterEntry.getGroup(), firstLineOutput.getGroup()) - + def test_replace_select_only(self): - + masterEntry = CalFileLine(1, 1, 1.0, 1, 1) - updateEntry = CalFileLine(1, 1, 2.0, 2, 2) - + updateEntry = CalFileLine(1, 1, 2.0, 2, 2) + # Run the algorithm and return the first line of the output merged cal file. firstLineOutput = self.do_execute(masterEntry=masterEntry, updateEntry=updateEntry, mergeOffsets=False, mergeSelect=True, mergeGroups=False) - + self.assertEqual(masterEntry.getOffset(), firstLineOutput.getOffset()) self.assertEqual(updateEntry.getSelect(), firstLineOutput.getSelect()) self.assertEqual(masterEntry.getGroup(), firstLineOutput.getGroup()) - + def test_replace_group_only(self): - + masterEntry = CalFileLine(1, 1, 1.0, 1, 1) - updateEntry = CalFileLine(1, 1, 2.0, 2, 2) - + updateEntry = CalFileLine(1, 1, 2.0, 2, 2) + # Run the algorithm and return the first line of the output merged cal file. firstLineOutput = self.do_execute(masterEntry=masterEntry, updateEntry=updateEntry, mergeOffsets=False, mergeSelect=False, mergeGroups=True) - + self.assertEqual(masterEntry.getOffset(), firstLineOutput.getOffset()) self.assertEqual(masterEntry.getSelect(), firstLineOutput.getSelect()) self.assertEqual(updateEntry.getGroup(), firstLineOutput.getGroup()) def test_replace_all(self): - + masterEntry = CalFileLine(1, 1, 1.0, 1, 1) - updateEntry = CalFileLine(1, 1, 2.0, 2, 2) - + updateEntry = CalFileLine(1, 1, 2.0, 2, 2) + # Run the algorithm and return the first line of the output merged cal file. firstLineOutput = self.do_execute(masterEntry=masterEntry, updateEntry=updateEntry, mergeOffsets=True, mergeSelect=True, mergeGroups=True) - + self.assertEqual(updateEntry.getOffset(), firstLineOutput.getOffset()) self.assertEqual(updateEntry.getSelect(), firstLineOutput.getSelect()) self.assertEqual(updateEntry.getGroup(), firstLineOutput.getGroup()) - + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PDDetermineCharacterizationsTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PDDetermineCharacterizationsTest.py index 49d42533087c..7c903af43030 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PDDetermineCharacterizationsTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/PDDetermineCharacterizationsTest.py @@ -40,7 +40,7 @@ def createTableWksp(self, full): # table columns labels = ["frequency", "wavelength", "bank", "vanadium", "container", "empty", "d_min", "d_max", "tof_min", "tof_max"] - types = ["double", "double", "int", "int", "int", + types = ["double", "double", "int", "int", "int", "int", "str", "str", "double", "double"] # create the table @@ -50,7 +50,7 @@ def createTableWksp(self, full): if full: rows = [[60., 0.533, 1, 17702, 17711, 0, "0.05", "2.20", 0000.00, 16666.67], - [60., 1.333, 3, 17703, 17712, 0, "0.43", "5.40", 12500.00, 29166.67], + [60., 1.333, 3, 17703, 17712, 0, "0.43", "5.40", 12500.00, 29166.67], [60., 2.665, 4, 17704, 17713, 0, "1.15", "9.20", 33333.33, 50000.00], [60., 4.797, 5, 17705, 17714, 0, "2.00", "15.35", 66666.67, 83333.67]] for row in rows: diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/RetrieveRunInfoTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/RetrieveRunInfoTest.py index 03bbbb057a87..4fbc13e0f323 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/RetrieveRunInfoTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/RetrieveRunInfoTest.py @@ -7,18 +7,18 @@ from testhelpers import run_algorithm class RetrieveRunInfoTest(unittest.TestCase): - + class_has_been_set_up = False - + def setUp(self): # Set up every time. config['default.instrument'] = 'IRIS' config["default.facility"] = "ISIS" - + # Only set up once. if not self.class_has_been_set_up: class_has_been_set_up = True - + # Create a workspace that is not a table workspace. pre_existing_matrix_workspace_alg = run_algorithm( "CreateWorkspace", @@ -27,28 +27,28 @@ def setUp(self): DataY='1') self.__pre_existing_matrix_workspace_name = \ pre_existing_matrix_workspace_alg.getPropertyValue("OutputWorkspace") - + # Create an empty table workspace. table_workspace_alg = run_algorithm( "CreateEmptyTableWorkspace", OutputWorkspace='__empty_table') self.__empty_table_workspace_name = \ table_workspace_alg.getPropertyValue("OutputWorkspace") - + self.__existing_range_of_run_files = '21360, 26173, 38633' self.__nonexistant_run_file = '99999' - + def test_wrong_facility_throws(self): ''' Dont expect to be able to support non-ISIS runs. ''' config["default.facility"] = "SNS" self.assertRaises( RuntimeError, run_algorithm, - 'RetrieveRunInfo', + 'RetrieveRunInfo', Runs = self.__existing_range_of_run_files, OutputWorkspace = "test", rethrow = True) - + def test_missing_run_file_throws(self): ''' Check that ALL files are present before proceeding. ''' self.assertRaises( @@ -58,7 +58,7 @@ def test_missing_run_file_throws(self): Runs = self.__nonexistant_run_file, OutputWorkspace = "test", rethrow = True) - + def test_pre_existing_non_table_workspace_throws(self): ''' Only allow TableWorkspaces. ''' self.assertRaises( @@ -68,32 +68,32 @@ def test_pre_existing_non_table_workspace_throws(self): Runs = self.__existing_range_of_run_files, OutputWorkspace = self.__pre_existing_matrix_workspace_name, rethrow = True) - + def test_existing_table_workspace_throws(self): ''' Dont bother trying to append. If it exists already, we throw. ''' self.assertRaises( RuntimeError, run_algorithm, - 'RetrieveRunInfo', + 'RetrieveRunInfo', Runs = self.__existing_range_of_run_files, OutputWorkspace = self.__empty_table_workspace_name, rethrow = True) - + def test_output_ws_correct_size(self): - ''' Does a standard example return a table with the right amount of + ''' Does a standard example return a table with the right amount of stuff in it? ''' run_algorithm( - 'RetrieveRunInfo', + 'RetrieveRunInfo', Runs = self.__existing_range_of_run_files, OutputWorkspace = 'test', rethrow = True) - + output_ws = mtd['test'] - + self.assertEqual(output_ws.columnCount(), 5) # Five log props. self.assertEqual(output_ws.rowCount(), 3) # Three runs. - + DeleteWorkspace(Workspace = 'test') - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SANSSubtractTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SANSSubtractTest.py index cfac75752b47..3bf5b093c5f8 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SANSSubtractTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SANSSubtractTest.py @@ -7,32 +7,32 @@ from testhelpers import run_algorithm class SANSSubtractTest(unittest.TestCase): - + def setUp(self): config['default.instrument'] = 'EQSANS' config["default.facility"] = "SNS" x = numpy.asarray([0,1,2,3,4,5]) y = numpy.asarray([1,2,3,4,5]) - + alg = run_algorithm('CreateWorkspace', DataX = x, DataY = y, OutputWorkspace='_test_iq_ws' ) self.test_ws = alg.getPropertyValue("OutputWorkspace") - + def test_simple_subtraction(self): run_algorithm( - 'SANSSubtract', + 'SANSSubtract', DataDistribution=self.test_ws, Background=self.test_ws, OutputWorkspace = 'test', rethrow = True) self.assertTrue(AnalysisDataService.doesExist('test')) - + y = AnalysisDataService.retrieve('test').readY(0) for value in y: self.assertAlmostEqual(value, 0, 2) - + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SANSWideAngleCorrectionTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SANSWideAngleCorrectionTest.py index 8e2ed4422338..1c3d16c98d7e 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SANSWideAngleCorrectionTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SANSWideAngleCorrectionTest.py @@ -1,9 +1,9 @@ import unittest import numpy -from mantid.kernel import * +from mantid.kernel import * from mantid.api import * -from mantid.simpleapi import (CreateWorkspace, LoadInstrument, - MoveInstrumentComponent, CropWorkspace, +from mantid.simpleapi import (CreateWorkspace, LoadInstrument, + MoveInstrumentComponent, CropWorkspace, SANSWideAngleCorrection, Min, Max, Transpose, Multiply) class SANSWideAngleCorrectionTest(unittest.TestCase): @@ -16,12 +16,12 @@ def setUp(self): yd = 10 data = numpy.random.normal(size=xd*yd*nb)/2.0 + 5.0 xvalues = numpy.linspace(3500,43500,nb+1) - tv = numpy.linspace(7e-2,6e-2,nb) - Sample = CreateWorkspace(xvalues,data,NSpec=xd*yd) + tv = numpy.linspace(7e-2,6e-2,nb) + Sample = CreateWorkspace(xvalues,data,NSpec=xd*yd) LoadInstrument(Sample, InstrumentName='SANS2D') Sample = CropWorkspace(Sample,StartWorkspaceIndex=8)#remove the monitors # create a transmission workspace - Trans = CropWorkspace(Sample,StartWorkspaceIndex=10,EndWorkspaceIndex=10) + Trans = CropWorkspace(Sample,StartWorkspaceIndex=10,EndWorkspaceIndex=10) x_v = Trans.dataX(0)[:-1] y_v = numpy.linspace(0.743139, 0.6,nb) e_v = y_v/58.0 @@ -41,7 +41,7 @@ def test_calculate_correction(self): lRange = Transpose(lRange) hRange = Transpose(hRange) self.assertTrue(97 > hRange.dataY(0).all()) - self.assertTrue(1 >= hRange.dataY(0).all()) + self.assertTrue(1 >= hRange.dataY(0).all()) def test_negative_trans_data(self): @@ -58,4 +58,4 @@ def test_no_instrument_associated(self): if __name__ == "__main__": unittest.main() - + diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SavePlot1DTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SavePlot1DTest.py index 8d68549588a8..a38545a0c13e 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SavePlot1DTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SavePlot1DTest.py @@ -4,18 +4,18 @@ class SavePlot1DTest(unittest.TestCase): def makeWs(self): mantid.simpleapi.CreateWorkspace(OutputWorkspace='test1',DataX='1,2,3,4,5,1,2,3,4,5',DataY='1,2,3,4,2,3,4,5',DataE='1,2,3,4,2,3,4,5',NSpec='2',UnitX='TOF',Distribution='1',YUnitlabel="S(q)") - mantid.simpleapi.CreateWorkspace(OutputWorkspace='test2',DataX='1,2,3,4,5,1,2,3,4,5',DataY='1,2,3,4,2,3,4,5',DataE='1,2,3,4,2,3,4,5',NSpec='2', + mantid.simpleapi.CreateWorkspace(OutputWorkspace='test2',DataX='1,2,3,4,5,1,2,3,4,5',DataY='1,2,3,4,2,3,4,5',DataE='1,2,3,4,2,3,4,5',NSpec='2', UnitX='Momentum',VerticalAxisUnit='TOF',VerticalAxisValues='1,2',Distribution='1',YUnitLabel='E',WorkspaceTitle='x') mantid.simpleapi.GroupWorkspaces("test1,test2",OutputWorkspace="group") self.plotfile=os.path.join(mantid.config.getString('defaultsave.directory'),'plot.png') - + def cleanup(self): mantid.api.AnalysisDataService.remove("group") mantid.api.AnalysisDataService.remove("test1") mantid.api.AnalysisDataService.remove("test2") if os.path.exists(self.plotfile): os.remove(self.plotfile) - + def testPlot(self): self.makeWs() ok2run='' @@ -31,7 +31,7 @@ def testPlot(self): if ok2run=='': mantid.simpleapi.SavePlot1D("group",self.plotfile) self.assertGreater(os.path.getsize(self.plotfile),1e4) - self.cleanup() + self.cleanup() if __name__=="__main__": - unittest.main() + unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortByQVectorsTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortByQVectorsTest.py index 935560c29690..a01c9732a0f4 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortByQVectorsTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortByQVectorsTest.py @@ -5,16 +5,16 @@ class SortByQVectorsTest(unittest.TestCase): - def test_output(self): + def test_output(self): ws = mantid.simpleapi.LoadSassena("outputSassena_1.4.1.h5", TimeUnit=1.0) - mantid.simpleapi.SortByQVectors('ws') - self.assertAlmostEqual(ws[0].getNumberHistograms(),5) - self.assertAlmostEqual(ws[0].dataY(0)[0],0.0) - self.assertAlmostEqual(ws[0].dataY(1)[0],0.00600600591861) - self.assertAlmostEqual(ws[0].dataY(2)[0],0.0120120118372) - self.assertAlmostEqual(ws[0].dataY(3)[0],0.0180180184543) - self.assertAlmostEqual(ws[0].dataY(4)[0],0.0240240236744) - mantid.api.AnalysisDataService.remove("ws") + mantid.simpleapi.SortByQVectors('ws') + self.assertAlmostEqual(ws[0].getNumberHistograms(),5) + self.assertAlmostEqual(ws[0].dataY(0)[0],0.0) + self.assertAlmostEqual(ws[0].dataY(1)[0],0.00600600591861) + self.assertAlmostEqual(ws[0].dataY(2)[0],0.0120120118372) + self.assertAlmostEqual(ws[0].dataY(3)[0],0.0180180184543) + self.assertAlmostEqual(ws[0].dataY(4)[0],0.0240240236744) + mantid.api.AnalysisDataService.remove("ws") if __name__=="__main__": - unittest.main() + unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortDetectorsTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortDetectorsTest.py index 032aee57c3b5..1043316f076c 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortDetectorsTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortDetectorsTest.py @@ -6,7 +6,7 @@ class SortDetectorsTest(unittest.TestCase): - + def testSortDetectors(self): w=WorkspaceCreationHelper.create2DWorkspaceWithFullInstrument(10,2,False,False) AnalysisDataService.add('w',w) @@ -17,6 +17,6 @@ def testSortDetectors(self): self.assertTrue(array_equal(x[1],array([7.]))) self.assertTrue(array_equal(x[2],array([0, 1, 3, 4, 5, 6, 7, 8, 9]))) self.assertTrue(x[3][0]==5.) - + if __name__ == '__main__': unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortXAxisTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortXAxisTest.py index bf8598669537..fbdec673003b 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortXAxisTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SortXAxisTest.py @@ -2,7 +2,7 @@ from mantid.kernel import * from mantid.api import * from mantid.simpleapi import * - + class SortXAxisTest(unittest.TestCase): def test_x_ascending(self): @@ -41,7 +41,7 @@ def test_x_descending(self): self.assertEqual(dataE, sortedE.tolist()) DeleteWorkspace(unsortedws) DeleteWorkspace(sortedws) - + def test_on_multiple_spectrum(self): dataX = [3, 2, 1, 3, 2, 1] # In descending order, so y and e will need to be reversed. dataY = [1, 2, 3, 1, 2, 3] @@ -50,7 +50,7 @@ def test_on_multiple_spectrum(self): dataY.reverse() dataE.reverse() # Run the algorithm - sortedws = SortXAxis(InputWorkspace=unsortedws) + sortedws = SortXAxis(InputWorkspace=unsortedws) # Check the resulting data values for 1st spectrum. sortedX = sortedws.readX(0) sortedY = sortedws.readY(0) @@ -67,10 +67,10 @@ def test_on_multiple_spectrum(self): self.assertEqual(dataE[3:], sortedE.tolist()) DeleteWorkspace(unsortedws) DeleteWorkspace(sortedws) - - + + def test_sorts_x_histogram_ascending(self): - dataX = [1, 2, 3, 4] + dataX = [1, 2, 3, 4] dataY = [1, 2, 3] dataE = [1, 2, 3] unsortedws = CreateWorkspace(DataX=dataX,DataY=dataY,DataE=dataE,UnitX='TOF',Distribution=False) @@ -83,12 +83,12 @@ def test_sorts_x_histogram_ascending(self): self.assertEqual(dataX, sortedX.tolist()) self.assertEqual(dataY, sortedY.tolist()) self.assertEqual(dataE, sortedE.tolist()) - + DeleteWorkspace(unsortedws) DeleteWorkspace(sortedws) - + def test_sorts_x_histogram_descending(self): - dataX = [4, 3, 2, 1] + dataX = [4, 3, 2, 1] dataY = [1, 2, 3] dataE = [1, 2, 3] unsortedws = CreateWorkspace(DataX=dataX,DataY=dataY,DataE=dataE,UnitX='TOF',Distribution=False) @@ -103,11 +103,11 @@ def test_sorts_x_histogram_descending(self): dataE.reverse() self.assertEqual(dataY, sortedY.tolist()) self.assertEqual(dataE, sortedE.tolist()) - + DeleteWorkspace(unsortedws) DeleteWorkspace(sortedws) - - - + + + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/Stitch1DManyTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/Stitch1DManyTest.py index aa4c26b171be..5589218c8e94 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/Stitch1DManyTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/Stitch1DManyTest.py @@ -5,13 +5,13 @@ from mantid.api import * class Stitch1DManyTest(unittest.TestCase): - + a = None b = None c = None x = None e = None - + def setUp(self): x = numpy.arange(-1, 1.2, 0.2) e = numpy.arange(-1, 1, 0.2) @@ -22,50 +22,50 @@ def setUp(self): b = CreateWorkspace(UnitX="1/q", DataX=x, DataY=[2.0,2.0,2.0,2.0,2.0,2.0,2.0,0.0,0.0,0.0], NSpec=1, DataE=e) self.a = a self.b = b - + def tearDown(self): # Cleanup DeleteWorkspace(self.a) DeleteWorkspace(self.b) - + def do_check_ydata(self, expectedYData, targetWS): print "expected" print expectedYData print "target" - print targetWS.readY(0) + print targetWS.readY(0) yDataRounded = [ round(elem, 4) for elem in targetWS.readY(0) ] same = all([(x == y) for x,y in zip(yDataRounded, expectedYData)]) self.assertTrue(same) - - + + def test_stitch_throws_with_too_few_workspaces(self): try: stitched = Stitch1DMany(InputWorkspaces='a', StartOverlaps=[-0.5], EndOverlaps=[0.5], Params=[0.1]) self.fail("Only one workspace. Should have thrown.") except RuntimeError: pass - + def test_stitch_throws_with_wrong_number_of_Start_overlaps(self): try: stitched = Stitch1DMany(InputWorkspaces='a, b', StartOverlaps=[-0.5, -0.6], EndOverlaps=[0.5], Params=[0.1]) self.fail("Two start overlaps, but only two workspaces. Should have thrown.") except RuntimeError: pass - + def test_stitch_throws_with_wrong_number_of_End_overlaps(self): try: stitched = Stitch1DMany(InputWorkspaces='a, b', StartOverlaps=[-0.5], EndOverlaps=[0.5, 0.6], Params=[0.1]) self.fail("Two end overlaps, but only two workspaces. Should have thrown.") except RuntimeError: pass - + def test_stich_throws_if_no_params(self): try: stitched = Stitch1DMany(InputWorkspaces='a, b') self.fail("No Params given. Should have thrown.") except RuntimeError: pass - + def test_workspace_types_differ_throws(self): tbl = CreateEmptyTableWorkspace() input_workspaces = "%s, %s" % (self.a.name(), tbl.name()) # One table workspace, one matrix workspace @@ -76,13 +76,13 @@ def test_workspace_types_differ_throws(self): pass finally: DeleteWorkspace(tbl) - + def test_workspace_group_size_differ_throws(self): ws1 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[3.0, 3.0, 3.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], NSpec=1, DataE=self.e) ws2 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 2.0, 0.0, 0.0, 0.0], NSpec=1, DataE=self.e) ws3 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], NSpec=1, DataE=self.e) input_group_1 = GroupWorkspaces(InputWorkspaces="%s,%s, %s" % (ws1.name(), ws2.name(), ws3.name())) - input_group_2 = GroupWorkspaces(InputWorkspaces="%s,%s" % (ws1.name(), ws2.name())) + input_group_2 = GroupWorkspaces(InputWorkspaces="%s,%s" % (ws1.name(), ws2.name())) try: stitched, sf = Stitch1DMany(InputWorkspaces='%s,%s' % (input_group_1.name(), input_group_2.name()), Params=0.2) self.fail("Differing number of sub-workspaces in workspace group. Should have thrown.") @@ -90,71 +90,71 @@ def test_workspace_group_size_differ_throws(self): pass finally: DeleteWorkspace(input_group_1) - - #Cross-check that the result of using Stitch1DMany with two workspaces is the same as using Stitch1D. - + + #Cross-check that the result of using Stitch1DMany with two workspaces is the same as using Stitch1D. + def test_stitches_two(self): stitchedViaStitchMany, scaleFactorMany = Stitch1DMany(InputWorkspaces='a, b', StartOverlaps=[-0.4], EndOverlaps=[0.4], Params=[0.2]) stitchedViaStitchTwo, scaleFactorTwo = Stitch1D(LHSWorkspace=self.a, RHSWorkspace=self.b, StartOverlap=-0.4, EndOverlap=0.4, Params=[0.2]) self.assertTrue(isinstance(scaleFactorMany, numpy.ndarray), "Should be returning a list of scale factors") self.assertEqual(1, scaleFactorMany.size) self.assertEquals(scaleFactorTwo, scaleFactorMany[0]) - + expectedYData = [0,0,0,3,3,3,3,0,0,0] self.do_check_ydata(expectedYData, stitchedViaStitchMany) - + # Do cross compare isSuccess = CheckWorkspacesMatch(Workspace1=stitchedViaStitchMany, Workspace2=stitchedViaStitchTwo) self.assertEquals("Success!", isSuccess); - + DeleteWorkspace(stitchedViaStitchMany) DeleteWorkspace(stitchedViaStitchTwo) - - + + def test_stitches_three(self): ws1 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[3.0, 3.0, 3.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], NSpec=1, DataE=self.e) ws2 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 2.0, 0.0, 0.0, 0.0], NSpec=1, DataE=self.e) ws3 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], NSpec=1, DataE=self.e) stitchedViaStitchMany, sfs = Stitch1DMany(InputWorkspaces='ws1, ws2, ws3', StartOverlaps=[-0.4,0.2], EndOverlaps=[-0.2,0.4], Params=0.2) - + expectedYData = [3,3,3,3,3,3,3,3,3,3] self.do_check_ydata(expectedYData, stitchedViaStitchMany) self.assertEqual(2, sfs.size) self.assertEquals(1.5, round(sfs[0], 6)) self.assertEquals(3.0, round(sfs[1], 6)) - + DeleteWorkspace(ws1) DeleteWorkspace(ws2) DeleteWorkspace(ws3) DeleteWorkspace(stitchedViaStitchMany) - + def test_stitches_three_no_overlaps_specified_should_still_work(self): ws1 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[3.0, 3.0, 3.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], NSpec=1, DataE=self.e) ws2 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 2.0, 0.0, 0.0, 0.0], NSpec=1, DataE=self.e) ws3 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], NSpec=1, DataE=self.e) stitchedViaStitchMany, sf = Stitch1DMany(InputWorkspaces='ws1, ws2, ws3', Params=0.2) - - + + def test_stitches_using_manual_scaling(self): stitchedViaStitchMany, sf = Stitch1DMany(InputWorkspaces='a, b', StartOverlaps=[-0.4], EndOverlaps=[0.4], Params=[0.2], UseManualScaleFactor=True, ManualScaleFactor=2.0) - + self.assertEquals(2.0, round(sf, 6)) DeleteWorkspace(stitchedViaStitchMany) - + def test_process_group_workspaces(self): ws1 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[3.0, 3.0, 3.0, 3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], NSpec=1, DataE=self.e) ws2 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 2.0, 0.0, 0.0, 0.0], NSpec=1, DataE=self.e) ws3 = CreateWorkspace(UnitX="1/q", DataX=self.x, DataY=[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0], NSpec=1, DataE=self.e) input_group_1 = GroupWorkspaces(InputWorkspaces="%s,%s,%s" % (ws1.name(), ws2.name(), ws3.name())) - input_group_2 = GroupWorkspaces(InputWorkspaces="%s,%s,%s" % (ws1.name(), ws2.name(), ws3.name())) + input_group_2 = GroupWorkspaces(InputWorkspaces="%s,%s,%s" % (ws1.name(), ws2.name(), ws3.name())) stitched, sfs = Stitch1DMany(InputWorkspaces='%s,%s' % (input_group_1.name(), input_group_2.name()), Params=0.2) self.assertTrue(isinstance(stitched, WorkspaceGroup), "Output should be a group workspace") self.assertEqual(stitched.size(), 3, "Output should contain 3 workspaces") self.assertEqual(stitched.name(), "stitched", "Output not named correctly") self.assertEquals(input_group_1.size(), sfs.size) DeleteWorkspace(input_group_1) - - - + + + if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SuggestTibCNCSTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SuggestTibCNCSTest.py index 060f0c466972..dcc680585dda 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SuggestTibCNCSTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SuggestTibCNCSTest.py @@ -3,13 +3,13 @@ class SuggestTibCNCSTest(unittest.TestCase): - def test_simple(self): - result=mantid.simpleapi.SuggestTibCNCS(3.) - self.assertAlmostEqual(result[0]*0.1,4491.5,0) - self.assertAlmostEqual(result[1]*0.1,4731.5,0) - result=mantid.simpleapi.SuggestTibCNCS(1.) - self.assertAlmostEqual(result[0]*0.1,9562.1,0) - self.assertAlmostEqual(result[1]*0.1,9902.1,0) + def test_simple(self): + result=mantid.simpleapi.SuggestTibCNCS(3.) + self.assertAlmostEqual(result[0]*0.1,4491.5,0) + self.assertAlmostEqual(result[1]*0.1,4731.5,0) + result=mantid.simpleapi.SuggestTibCNCS(1.) + self.assertAlmostEqual(result[0]*0.1,9562.1,0) + self.assertAlmostEqual(result[1]*0.1,9902.1,0) if __name__=="__main__": - unittest.main() + unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SuggestTibHYSPECTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SuggestTibHYSPECTest.py index 439603ac68d8..30e4d8c1040f 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SuggestTibHYSPECTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/SuggestTibHYSPECTest.py @@ -3,13 +3,13 @@ class SuggestTibHYSPECTest(unittest.TestCase): - def test_simple(self): - result=mantid.simpleapi.SuggestTibHYSPEC(5.) - self.assertAlmostEqual(result[0]*.1,3951.5,0) - self.assertAlmostEqual(result[1]*.1,4151.5,0) - result=mantid.simpleapi.SuggestTibHYSPEC(40.) - self.assertAlmostEqual(result[0]*.1,1189.8,0) - self.assertAlmostEqual(result[1]*.1,1389.8,0) + def test_simple(self): + result=mantid.simpleapi.SuggestTibHYSPEC(5.) + self.assertAlmostEqual(result[0]*.1,3951.5,0) + self.assertAlmostEqual(result[1]*.1,4151.5,0) + result=mantid.simpleapi.SuggestTibHYSPEC(40.) + self.assertAlmostEqual(result[0]*.1,1189.8,0) + self.assertAlmostEqual(result[1]*.1,1389.8,0) if __name__=="__main__": - unittest.main() + unittest.main() diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/UpdatePeakParameterTableValueTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/UpdatePeakParameterTableValueTest.py index fd8ee0b3a7fb..de997ef42340 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/UpdatePeakParameterTableValueTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/algorithms/UpdatePeakParameterTableValueTest.py @@ -27,7 +27,7 @@ def test_updateDouble(self): alg_test = run_algorithm("UpdatePeakParameterTableValue", InputWorkspace=alg_init.getPropertyValue("OutputWorkspace"), Column="Value", ParameterNames=["A"], NewFloatValue=1.00) - + self.assertTrue(alg_test.isExecuted()) newvalue_A = tablews.cell(0, 1) diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/DSFinterp1DFitTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/DSFinterp1DFitTest.py index 7485f524476a..51ac4dd1ba31 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/DSFinterp1DFitTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/DSFinterp1DFitTest.py @@ -9,11 +9,11 @@ class DSFinterp1DTestTest(unittest.TestCase): def generateWorkspaces(self, nf, startf, df, e=False): - '''Helper function. Generates input workspaces for testing - + '''Helper function. Generates input workspaces for testing + Generates a set of one-histogram workspaces, each containing a Lorentzian. Also generate a target lorentzian agains which we will fit - + Arguments: nf: number of InputWorkspaces startf: first theoretical HWHM diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/Example1DFunctionTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/Example1DFunctionTest.py index b7698ee68ee7..1ddf633fda3c 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/Example1DFunctionTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/Example1DFunctionTest.py @@ -10,7 +10,7 @@ def PyInit(self): self.declareProperty("A0", -1.0, validator=FloatBoundedValidator(lower=0)) self.declareProperty("A1", -1.0, validator=FloatBoundedValidator(lower=0)) self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output)) - + def PyExec(self): import random nbins=4000 @@ -19,17 +19,17 @@ def PyExec(self): a0 = self.getProperty("A0").value a1 = self.getProperty("A1").value - + # Noise parameter amplitude = 100 - + prog_reporter = Progress(self,start=0.0,end=1.0,nreports=nbins) for i in range(0,nbins): x_value = 5.0 + 5.5*i; nominal_y = a0 +a1*x_value # add some noise nominal_y += random.random()*amplitude - + wspace.dataX(0)[i] = x_value wspace.dataY(0)[i] = nominal_y wspace.dataE(0)[i] = 1 @@ -44,14 +44,14 @@ def test_function_has_been_registered(self): FunctionFactory.createFunction("ExamplePeakFunction") except RuntimeError, exc: self.fail("Could not create ExamplePeakFunction function: %s" % str(exc)) - + def test_fit_succeeds_with_expected_answer(self): AlgorithmFactory.subscribe(_InternalMakeLinear) alg = testhelpers.run_algorithm("_InternalMakeLinear", A0=1.0,A1=0.75,OutputWorkspace='_test_linear') - + func_string="name=Example1DFunction,A0=0.0,A1=0.0" Fit(Function=func_string,InputWorkspace="_test_linear",StartX=1000,EndX=6000,CreateOutput=1,MaxIterations=2) - + mtd.remove('_test_linear') mtd.remove('_test_linear_NormalisedCovarianceMatrix') mtd.remove('_test_linear_Parameters') diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/ExamplePeakFunctionTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/ExamplePeakFunctionTest.py index 0df8cb89f620..ba6e4419b4d3 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/ExamplePeakFunctionTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/ExamplePeakFunctionTest.py @@ -11,7 +11,7 @@ def PyInit(self): self.declareProperty("Centre", -1.0, validator=FloatBoundedValidator(lower=0)) self.declareProperty("Sigma", -1.0, validator=FloatBoundedValidator(lower=0)) self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", direction = Direction.Output)) - + def PyExec(self): import math import random @@ -22,14 +22,14 @@ def PyExec(self): sigma_sq = math.pow(self.getProperty("Sigma").value,2) # Noise parameter amplitude = 0.1*height - + prog_reporter = Progress(self,start=0.0,end=1.0,nreports=nbins) for i in range(1,nbins): x_value = 5.0 + 5.5*i; nominal_y = height * math.exp(-0.5*math.pow(x_value - centre, 2.)/sigma_sq) # add some noise nominal_y += random.random()*amplitude - + wspace.dataX(0)[i] = x_value wspace.dataY(0)[i] = nominal_y wspace.dataE(0)[i] = 1 @@ -44,14 +44,14 @@ def test_function_has_been_registered(self): FunctionFactory.createFunction("ExamplePeakFunction") except RuntimeError, exc: self.fail("Could not create ExamplePeakFunction function: %s" % str(exc)) - + def test_fit_succeeds_with_expected_answer(self): AlgorithmFactory.subscribe(_InternalMakeGaussian) alg = testhelpers.run_algorithm("_InternalMakeGaussian", Height=300,Centre=2100,Sigma=700,OutputWorkspace='_test_gauss') - + func_string="name=ExamplePeakFunction,NTerms=3,Height=309.92,PeakCentre=2105,Sigma=710.2" Fit(Function=func_string,InputWorkspace="_test_gauss",StartX=150,EndX=4310,CreateOutput=1,MaxIterations=2) - + mtd.remove('_test_gauss') mtd.remove('_test_gauss_NormalisedCovarianceMatrix') mtd.remove('_test_gauss_Parameters') diff --git a/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/StretchedExpFTTest.py b/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/StretchedExpFTTest.py index 638a8099e731..6ef9c2d2f8cb 100644 --- a/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/StretchedExpFTTest.py +++ b/Code/Mantid/Framework/PythonInterface/test/python/plugins/functions/StretchedExpFTTest.py @@ -28,7 +28,7 @@ def PyExec( self ): nhalfbins = self.getProperty( 'nhalfbins' ).value de = self.getProperty( 'de' ).value #bin width, in meV or ueV nbins = 2 * nhalfbins - xvals = de * np.arange( -nhalfbins, nhalfbins + 1) + de/2 # + xvals = de * np.arange( -nhalfbins, nhalfbins + 1) + de/2 # #Find the time domain M = 2 * nhalfbins + 1 @@ -91,7 +91,7 @@ def test_fit( self ): return from random import random - variation = lambda x: x * ( 1 + ( random() - 0.5 ) / 5. ) # range [x*0.9, x*1.1] should be bigger but not until parameter constraints have been exposed to python + variation = lambda x: x * ( 1 + ( random() - 0.5 ) / 5. ) # range [x*0.9, x*1.1] should be bigger but not until parameter constraints have been exposed to python #Generate a data workspace using random parameters around {'height':0.1,'tau':100,'beta':1} parms={ 'height' : variation( 0.1 ), 'tau' : variation( 100 ), 'beta' : variation( 1 ) } @@ -114,7 +114,7 @@ def test_fit( self ): value = row[ 'Value' ] elif name in parms.keys(): fitted += '{0}={1}, '.format( name, row[ 'Value' ] ) - target = ', '.join( '{0}={1}'.format( key, val ) for key, val in parms.items() ) + target = ', '.join( '{0}={1}'.format( key, val ) for key, val in parms.items() ) msg = 'Cost function {0} too high\nTargets were {1},\nbut obtained {2}'.format( value, target, fitted ) self.assertTrue( value < 5.0, msg ) msg='Cost function {0}\nStarted with height=0.1, tau=100, beta=1\nTargets were {1},\nobtained {2}'.format( value, target, fitted ) diff --git a/Code/Mantid/Framework/PythonInterface/test/testhelpers/__init__.py b/Code/Mantid/Framework/PythonInterface/test/testhelpers/__init__.py index 758e84d4fb9e..a8337655c3ff 100644 --- a/Code/Mantid/Framework/PythonInterface/test/testhelpers/__init__.py +++ b/Code/Mantid/Framework/PythonInterface/test/testhelpers/__init__.py @@ -24,7 +24,7 @@ def run_algorithm(name, **kwargs): def create_algorithm(name, **kwargs): """Create a named algorithm, set the properties given by the keywords and return the algorithm handle WITHOUT executing the algorithm - + Useful keywords: - child: Makes algorithm a child algorithm - rethrow: Causes exceptions to be rethrown on execution @@ -53,11 +53,11 @@ def create_algorithm(name, **kwargs): return alg # Case difference is to be consistent with the unittest module -def assertRaisesNothing(testobj, callable, *args, **kwargs): +def assertRaisesNothing(testobj, callable, *args, **kwargs): """ unittest does not have an assertRaisesNothing. This provides that functionality - + Parameters: testobj - A unittest object callable - A callable object @@ -67,7 +67,7 @@ def assertRaisesNothing(testobj, callable, *args, **kwargs): try: return callable(*args, **kwargs) except Exception, exc: - testobj.fail("Assertion error. An exception was caught where none was expected in %s. Message: %s" + testobj.fail("Assertion error. An exception was caught where none was expected in %s. Message: %s" % (callable.__name__, str(exc))) def can_be_instantiated(cls): diff --git a/Code/Mantid/Framework/PythonInterface/test/testhelpers/algorithm_decorator.py b/Code/Mantid/Framework/PythonInterface/test/testhelpers/algorithm_decorator.py index 91c0fd54546d..8c8d8efad0e9 100644 --- a/Code/Mantid/Framework/PythonInterface/test/testhelpers/algorithm_decorator.py +++ b/Code/Mantid/Framework/PythonInterface/test/testhelpers/algorithm_decorator.py @@ -5,45 +5,45 @@ def make_decorator(algorithm_to_decorate): """ Dynamically create a builder pattern style decorator around a Mantid algorithm. This allows you to separate out setting algorithm parameters from the actual method execution. Parameters may be reset multiple times. - + Usage: rebin = make_decorator(Rebin) rebin.set_Params([0, 0.1, 1]) .... rebin.execute() - + Arguments: algorithm_to_decorate: The mantid.simpleapi algorithm to decorate. - - - + + + """ - + class Decorator(object): - + def __init__(self, alg_subject): self.__alg_subject = alg_subject self.__parameters__ = dict() - + def execute(self, additional=None, verbose=False): if verbose: print "Algorithm Parameters:" print self.__parameters__ - print + print out = self.__alg_subject(**self.__parameters__) return out - + def set_additional(self, additional): self.__parameters__.update(**additional) def add_getter_setter(type, name): - + def setter(self, x): self.__parameters__[name] = x - + def getter(self): return self.__parameters__[name] - + setattr(type, "set_" + name, setter) setattr(type, "get_" + name, getter) @@ -58,4 +58,4 @@ def getter(self): parameter = m.group(0).strip() add_getter_setter(Decorator, m.group(0).strip()) - return Decorator(algorithm_to_decorate) + return Decorator(algorithm_to_decorate) diff --git a/Code/Mantid/Framework/UserAlgorithms/createAlg.py b/Code/Mantid/Framework/UserAlgorithms/createAlg.py index 5f163af114e2..3a5b550daa0d 100644 --- a/Code/Mantid/Framework/UserAlgorithms/createAlg.py +++ b/Code/Mantid/Framework/UserAlgorithms/createAlg.py @@ -21,7 +21,7 @@ cat = sys.argv[2] else: cat = "UserAlgorithms" - + hfilename = name + ".h" cppfilename = name + ".cpp" diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/test/EQSANSQ2DTest.py b/Code/Mantid/Framework/WorkflowAlgorithms/test/EQSANSQ2DTest.py index cd70ad2819cd..b479bca36524 100644 --- a/Code/Mantid/Framework/WorkflowAlgorithms/test/EQSANSQ2DTest.py +++ b/Code/Mantid/Framework/WorkflowAlgorithms/test/EQSANSQ2DTest.py @@ -4,18 +4,18 @@ class EQSANSQ2DTest(unittest.TestCase): def setUp(self): - + self.test_ws_name = "EQSANS_test_ws" x = [1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,11.] y = 491520*[0.1] CreateWorkspace(OutputWorkspace=self.test_ws_name,DataX=x,DataY=y,DataE=y,NSpec='49152',UnitX='Wavelength') LoadInstrument(Workspace=self.test_ws_name, InstrumentName="EQSANS") - + run = mtd[self.test_ws_name].mutableRun() - + run.addProperty("sample_detector_distance", 4000.0, 'mm', True) run.addProperty("beam_center_x", 96.0, 'pixel', True) - run.addProperty("beam_center_y", 128.0, 'pixel', True) + run.addProperty("beam_center_y", 128.0, 'pixel', True) run.addProperty("wavelength_min", 1.0, "Angstrom", True) run.addProperty("wavelength_max", 11.0, "Angstrom", True) run.addProperty("is_frame_skipping", 0, True) diff --git a/Code/Mantid/Framework/WorkflowAlgorithms/test/SANSBeamFluxCorrectionTest.py b/Code/Mantid/Framework/WorkflowAlgorithms/test/SANSBeamFluxCorrectionTest.py index 6b5e442138ec..9c47ba2b115f 100644 --- a/Code/Mantid/Framework/WorkflowAlgorithms/test/SANSBeamFluxCorrectionTest.py +++ b/Code/Mantid/Framework/WorkflowAlgorithms/test/SANSBeamFluxCorrectionTest.py @@ -5,10 +5,10 @@ class SANSBeamFluxCorrectionTest(unittest.TestCase): def setUp(self): - + self.test_ws_name = "EQSANS_test_ws" x = [1.,2.,3.,4.,5.,6.,7.,8.,9.,10.,11.] - y = 491520*[0.1] + y = 491520*[0.1] CreateWorkspace(OutputWorkspace=self.test_ws_name,DataX=x,DataY=y,DataE=y,NSpec='49152',UnitX='Wavelength') LoadInstrument(self.test_ws_name, InstrumentName="EQSANS") @@ -17,15 +17,15 @@ def setUp(self): def tearDown(self): if AnalysisDataService.doesExist(self.test_ws_name): - AnalysisDataService.remove(self.test_ws_name) + AnalysisDataService.remove(self.test_ws_name) if AnalysisDataService.doesExist(self.monitor): - AnalysisDataService.remove(self.monitor) + AnalysisDataService.remove(self.monitor) def test_simple(self): output = SANSBeamFluxCorrection(InputWorkspace=self.test_ws_name, InputMonitorWorkspace=self.monitor, ReferenceFluxFilename="SANSBeamFluxCorrectionMonitor.nxs") - + ref_value = 0.1/(49152*0.1)/(49152*0.1) output_y = output[0].readY(0) self.assertAlmostEqual(ref_value, output_y[0], 6) @@ -35,7 +35,7 @@ def test_in_place(self): InputMonitorWorkspace=self.monitor, ReferenceFluxFilename="SANSBeamFluxCorrectionMonitor.nxs", OutputWorkspace=self.test_ws_name) - + ref_value = 0.1/(49152*0.1)/(49152*0.1) output_y = output[0].readY(0) self.assertAlmostEqual(ref_value, output_y[0], 6)