def get_gui_algorithm_name(facility):
    if facility is SANSFacility.ISIS:
        algorithm_name = "SANSGuiDataProcessorAlgorithm"
        AlgorithmFactory.subscribe(SANSGuiDataProcessorAlgorithm)
    else:
        raise RuntimeError("The facility is currently not supported")
    return algorithm_name
Beispiel #2
0
    def test_python_alg_can_use_other_python_alg_through_simple_api(self):
        class SimpleAPIPythonAlgorithm1(PythonAlgorithm):
            def PyInit(self):
                pass
            def PyExec(self):
                from mantid.simpleapi import SimpleAPIPythonAlgorithm2
                SimpleAPIPythonAlgorithm2()
        class SimpleAPIPythonAlgorithm2(PythonAlgorithm):
            def PyInit(self):
                pass
            def PyExec(self):
                pass

        AlgorithmFactory.subscribe(SimpleAPIPythonAlgorithm1)
        AlgorithmFactory.subscribe(SimpleAPIPythonAlgorithm2)
        # ---------------------------------------------------------
        alg1 = SimpleAPIPythonAlgorithm1()
        alg1.initialize()
        # Puts function in simpleapi globals
        simpleapi_alg1_func = simpleapi._create_algorithm_function("SimpleAPIPythonAlgorithm1", 1, alg1)
        alg2 = SimpleAPIPythonAlgorithm1()
        alg2.initialize()
        # Puts function in simpleapi globals
        simpleapi._create_algorithm_function("SimpleAPIPythonAlgorithm2", 1, alg2)
        try:
            simpleapi_alg1_func()
        except RuntimeError as exc:
            self.fail("Running algorithm 2 from 1 failed: " + str(exc))
Beispiel #3
0
    def test_that_selector_is_refreshed_on_alg_load(self):
        widget = AlgorithmSelectorWidgetMock()
        widget.refresh = mock.MagicMock()
        widget.observeUpdate(True)
        AlgorithmFactory.subscribe(ToyAlgorithm)

        self.assertTrue(widget.refresh.call_count == 1,
                        "We expect the widget to be refreshed when the Algorithm Factory "
                        "subscribes to a new algorithm. refresh was called "
                        "{} times after subscription.".format(widget.refresh.call_count))
Beispiel #4
0
    def test_can_toggle_algorithm_factory_notifications(self):
        widget = AlgorithmSelectorWidgetMock()
        widget.refresh = mock.MagicMock()
        widget.observeUpdate(True)
        widget.observeUpdate(False)

        AlgorithmFactory.subscribe(ToyAlgorithm)

        self.assertTrue(widget.refresh.call_count == 0,
                        "We expect the widget to be refreshed when the Algorithm Factory "
                        "subscribes to a new algorithm. refresh was called "
                        "{} times after subscription.".format(widget.refresh.call_count))
    def test_class_can_override_standard_algorithm_methods(self):
        class TestDataProcessor(DataProcessorAlgorithm):
            def version(self):
                return 2
            def PyInit(self):
                pass
            def PyExec(self):
                pass
        # end v2 alg

        AlgorithmFactory.subscribe(TestDataProcessor)
        assertRaisesNothing(self, AlgorithmManager.createUnmanaged, "TestDataProcessor", 2)
 def setUp(self):
     if self.__class__._registered is None:
         self.__class__._registered = True
         AlgorithmFactory.subscribe(TestPyAlgDefaultAttrs)
         AlgorithmFactory.subscribe(TestPyAlgOverriddenAttrs)
         AlgorithmFactory.subscribe(TestPyAlgIsRunningReturnsNonBool)
         AlgorithmFactory.subscribe(CancellableAlg)
Beispiel #7
0
    def test_explicit_store_in_ADS(self):
        class SimpleAPIPythonAlgorithm5(PythonAlgorithm):
            def PyInit(self):
                pass

            def PyExec(self):
                from mantid.simpleapi import CreateSampleWorkspace
                workspaceInADS = CreateSampleWorkspace(StoreInADS=True)
                assert(workspaceInADS)
        AlgorithmFactory.subscribe(SimpleAPIPythonAlgorithm5)

        alg = SimpleAPIPythonAlgorithm5()
        alg.initialize()
        alg.execute()
        self.assertTrue('workspaceInADS' in mtd)
Beispiel #8
0
    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 
        """
        src = """
from mantid.api import PythonAlgorithm, AlgorithmFactory
import mantid.simpleapi as api
from mantid.simpleapi import *

class %(name)s(PythonAlgorithm):

    def PyInit(self):
        pass
    def PyExec(self):
        %(execline1)s
        %(execline2)s
        
AlgorithmFactory.subscribe(%(name)s)
"""
        name1 = "SimpleAPIPythonAlgorithm1"
        name2 = "SimpleAPIPythonAlgorithm2"
        src1 = src % {"name":name1,"execline1":name2+"()","execline2":"api."+name2+"()"}
        src2 = src % {"name":name2,"execline1":"pass","execline2":"pass"}
        a = TemporaryPythonAlgorithm(name1,src1)
        b = TemporaryPythonAlgorithm(name2,src2)
        import subprocess
        # Try to use algorithm 1 to run algorithm 2
        cmd = sys.executable + ' -c "from mantid.simpleapi import %(name)s;%(name)s()"' % {'name':name1}
        try:
            subprocess.check_call(cmd,shell=True)
        except subprocess.CalledProcessError, exc:
            self.fail("Error occurred running one Python algorithm from another: %s" % str(exc))
Beispiel #9
0
 def test_validate_inputs_with_errors_stops_algorithm(self):
     class ValidateInputsTest(PythonAlgorithm):
         def PyInit(self):
             self.declareProperty("Prop1", 1.0)
             self.declareProperty("Prop2", 2.0)
         def validateInputs(self):
             return {"Prop1":"Value is less than Prop2"}
         def PyExec(self):
             pass
     AlgorithmFactory.subscribe(ValidateInputsTest)
     # ---------------------------------------------------------
     alg_obj = ValidateInputsTest()
     alg_obj.initialize()
     
     simpleapi_func = simpleapi._create_algorithm_function("ValidateInputsTest", 1, alg_obj)
     # call
     self.assertRaises(RuntimeError, simpleapi_func, Prop1=2.5, Prop2=3.5)
Beispiel #10
0
    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,
        )
        from mantid.kernel import Direction

        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)
        algm_object.initialize()
        simpleapi._create_algorithm_function(name, 1, algm_object)  # Create the wrapper

        # Call with no optional output specified
        result = simpleapi.OptionalWorkspace(RequiredWorkspace="required")
        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
Beispiel #11
0
    def test_later_store_in_ADS(self):
        from mantid.api import MatrixWorkspaceProperty
        from mantid.kernel import Direction

        class SimpleAPIPythonAlgorithm6(PythonAlgorithm):
            def PyInit(self):
                self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output))

            def PyExec(self):
                from mantid.simpleapi import CreateSampleWorkspace
                workspaceNotInADS = CreateSampleWorkspace(StoreInADS=False)
                assert(workspaceNotInADS)
                self.setProperty("OutputWorkspace", workspaceNotInADS)
        AlgorithmFactory.subscribe(SimpleAPIPythonAlgorithm6)

        alg = SimpleAPIPythonAlgorithm6()
        alg.initialize()
        alg.setPropertyValue("OutputWorkspace", "out")
        alg.execute()
        self.assertTrue('out' in mtd)
        mtd.remove('out')
Beispiel #12
0
                panel_pos = component.position(panel_index)
                panel_rel_pos = component.relativePosition(panel_index)
                # need to move detector in direction in x-z plane
                panel_offset = panel_rel_pos * (distance /
                                                panel_rel_pos.norm())
                panel_offset += panel_pos
                component.setPosition(panel_index, panel_offset)

    def __get_wavelength(self, exp_info):
        """
        Gets the wavelength from experiment info if provided, otherwise it will try to get the value
        from the algorithm property. Throws a RuntimeError if a wavelength cannot be found from either.
        :param exp_info: The experiment info of the run to lookup set wavelength value
        :return: wavelength value from experiment info if set, or from wavelength property
        """
        if exp_info.run().hasProperty("wavelength"):
            return exp_info.run().getProperty("wavelength").value
        else:
            # Set wavelength value from the backup property, if provided
            wl_prop = self.getProperty("Wavelength")
            if not wl_prop.isDefault:
                return wl_prop.value
            else:
                # If wavelength value not set, throw an error
                raise RuntimeError(
                    "Wavelength not found in sample log and was not provided as input to the algorithm"
                )


AlgorithmFactory.subscribe(HB3AAdjustSampleNorm)
Beispiel #13
0
            raise RuntimeError("Failed to determine IPTS directory " +
                               "from path '%s'" % filename)
        location = filename.find('/', location)
        direc = filename[0:location + 1]
        return direc

    def PyInit(self):
        self.declareProperty('RunNumber',
                             defaultValue=0,
                             direction=Direction.Input,
                             validator=IntBoundedValidator(lower=1),
                             doc="Extracts the IPTS number for a run")

        instruments = self.getValidInstruments()
        self.declareProperty('Instrument', '',
                             StringListValidator(instruments),
                             "Empty uses default instrument")

        self.declareProperty('Directory', '', direction=Direction.Output)

    def PyExec(self):
        instrument = self.getProperty('Instrument').value
        runnumber = self.getProperty('RunNumber').value

        direc = self.getIPTSLocal(instrument, runnumber)
        self.setPropertyValue('Directory', direc)
        self.log().notice('IPTS directory is: %s' % direc)


AlgorithmFactory.subscribe(GetIPTS)
Beispiel #14
0
                name=self._instrument_name)
        else:
            raise ValueError("Unknown instrument %s" % instrument_name)

        self._atoms = self.getProperty("Atoms").value
        self._sum_contributions = self.getProperty("SumContributions").value

        # conversion from str to int
        self._num_quantum_order_events = int(
            self.getProperty("QuantumOrderEventsNumber").value)

        self._scale_by_cross_section = self.getPropertyValue(
            'ScaleByCrossSection')
        self._out_ws_name = self.getPropertyValue('OutputWorkspace')
        self._calc_partial = (len(self._atoms) > 0)

        # Sampling mesh is determined by
        # AbinsModules.AbinsParameters.sampling['min_wavenumber']
        # AbinsModules.AbinsParameters.sampling['max_wavenumber']
        # and AbinsModules.AbinsParameters.sampling['bin_width']
        step = self._bin_width
        start = AbinsParameters.sampling['min_wavenumber']
        stop = AbinsParameters.sampling['max_wavenumber'] + step
        self._bins = np.arange(start=start,
                               stop=stop,
                               step=step,
                               dtype=AbinsModules.AbinsConstants.FLOAT_TYPE)


AlgorithmFactory.subscribe(Abins)
Beispiel #15
0
        Convert Euler angles to a quaternion
        """
        getV3D = {'X': V3D(1, 0, 0), 'Y': V3D(0, 1, 0), 'Z': V3D(0, 0, 1)}
        return (Quat(alpha, getV3D[convention[0]]) *
                Quat(beta, getV3D[convention[1]]) *
                Quat(gamma, getV3D[convention[2]]))

    def _eulerToAngleAxis(self, alpha, beta, gamma, convention):
        """
        Convert Euler angles to a angle rotation around an axis
        """
        quat = self._eulerToQuat(alpha, beta, gamma, convention)
        if quat[0] == 1:
            return 0, 0, 0, 1
        deg = math.acos(quat[0])
        scale = math.sin(deg)
        deg *= 360.0 / math.pi
        ax0 = quat[1] / scale
        ax1 = quat[2] / scale
        ax2 = quat[3] / scale
        return deg, ax0, ax1, ax2


try:
    from scipy.optimize import minimize
    AlgorithmFactory.subscribe(AlignComponents)
except ImportError:
    logger.debug(
        'Failed to subscribe algorithm AlignComponets; cannot import minimize from scipy.optimize'
    )
        crop_alg.setProperty("XMin", xmin)
        crop_alg.setProperty("XMax", xmax)
        crop_alg.execute()
        out_ws = crop_alg.getProperty("OutputWorkspace").value
        # add logs
        num_spectra = out_ws.getNumberHistograms()
        run_obj = out_ws.getRun()
        min_values = [xmin]*num_spectra
        max_values = [xmax]*num_spectra
        if run_obj.hasProperty('MDNorm_low'):
            #TODO: when handling of masking bins is implemented, number of spectra will be different
            #      than the number of limits
            try:
                min_values = numpy.maximum(min_values, run_obj.getProperty('MDNorm_low').value).tolist()
            except ValueError:
                raise RuntimeError("Could not compare old and new values for 'MDNorm_low' log. "+
                                   "Make sure the length of the old data is equal to the number of spectra")
        run_obj.addProperty('MDNorm_low', min_values, True)
        if run_obj.hasProperty('MDNorm_high'):
            try:
                max_values = numpy.minimum(max_values, run_obj.getProperty('MDNorm_high').value).tolist()
            except ValueError:
                raise RuntimeError("Could not compare old and new values for 'MDNorm_high' log. "+
                                   "Make sure the length of the old data is equal to the number of spectra")
        run_obj.addProperty('MDNorm_high', [xmax]*num_spectra, True)
        run_obj.addProperty('MDNorm_spectra_index', numpy.arange(num_spectra).tolist(), True)
        self.setProperty('OutputWorkspace', out_ws)

# Register algorithm with Mantid.
AlgorithmFactory.subscribe(CropWorkspaceForMDNorm)
        self.input_workspaces['SF_Background'] = self.getPropertyValue(
            "SFBkgrWorkspace")
        self.input_workspaces['NSF_Background'] = self.getPropertyValue(
            "NSFBkgrWorkspace")
        self.sf_outws_name = self.getPropertyValue("SFOutputWorkspace")
        self.nsf_outws_name = self.getPropertyValue("NSFOutputWorkspace")

        # check if possible to apply correction
        self._can_correct()

        # apply flipping ratio correction, retrieve the result
        self._fr_correction()
        nsf_outws = api.AnalysisDataService.retrieve(self.nsf_outws_name)
        sf_outws = api.AnalysisDataService.retrieve(self.sf_outws_name)

        # copy sample logs from data workspace to the output workspace
        api.CopyLogs(InputWorkspace=self.input_workspaces['SF_Data'],
                     OutputWorkspace=self.sf_outws_name,
                     MergeStrategy='MergeReplaceExisting')
        api.CopyLogs(InputWorkspace=self.input_workspaces['NSF_Data'],
                     OutputWorkspace=self.nsf_outws_name,
                     MergeStrategy='MergeReplaceExisting')
        self.setProperty("SFOutputWorkspace", sf_outws)
        self.setProperty("NSFOutputWorkspace", nsf_outws)

        return


# Register algorithm with Mantid
AlgorithmFactory.subscribe(DNSFlippingRatioCorr)
Beispiel #18
0
                if skip:
                    I = number_omega - I + 2
                else:
                    I += 1
        AAA += sum_1 * Area_y
        BBB += sum_2 * Area_y
        Area += Area_sum * Area_y
        return AAA, BBB, Area

#------------------------------------------------------------------------------

    def _distance(self, r1, radius, omega):
        r = r1
        distance = 0.
        b = r * math.sin(omega)
        if abs(b) < radius:
            t = r * math.cos(omega)
            c = radius * radius - b * b
            d = math.sqrt(c)
            if r <= radius:
                distance = t + d
            else:
                distance = d * (1.0 + math.copysign(1.0, t))
        return distance


#------------------------------------------------------------------------------

# Register algorithm with Mantid
AlgorithmFactory.subscribe(CylinderPaalmanPingsCorrection)
            convert_alg.execute()
            workspace = convert_alg.getProperty("OutputWorkspace").value
            append_to_sans_file_tag(workspace, "_histogram")

        return workspace

    def _get_state(self):
        state_property_manager = self.getProperty("SANSState").value
        state = create_deserialized_sans_state_from_property_manager(state_property_manager)
        state.property_manager = state_property_manager
        return state

    def _get_monitor_workspace(self):
        monitor_workspace = self.getProperty("SampleScatterMonitorWorkspace").value
        return self._get_cloned_workspace(monitor_workspace)

    def _get_cloned_workspace(self, workspace):
        clone_name = "CloneWorkspace"
        clone_options = {"InputWorkspace": workspace,
                         "OutputWorkspace": EMPTY_NAME}
        clone_alg = create_child_algorithm(self, clone_name, **clone_options)
        clone_alg.execute()
        return clone_alg.getProperty("OutputWorkspace").value

    def _get_progress(self):
        return Progress(self, start=0.0, end=1.0, nreports=10)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSBeamCentreFinderMassMethod)
Beispiel #20
0
                             OutputWorkspace=correctedWSName,
                             EnableLogging=subalgLogging)
        wsCleanup.cleanup(mainWS)
        return correctedWS

    def _finalize(self, outWS, wsCleanup):
        """Do final cleanup and set the output property."""
        self.setProperty(common.PROP_OUTPUT_WS, outWS)
        wsCleanup.cleanup(outWS)
        wsCleanup.finalCleanup()

    def _inputWS(self, wsCleanup):
        """Return the raw input workspace."""
        mainWS = self.getProperty(common.PROP_INPUT_WS).value
        wsCleanup.protect(mainWS)
        return mainWS

    def _subtractEC(self, mainWS, wsNames, wsCleanup, subalgLogging):
        """Subtract the empty container workspace without self-shielding corrections."""
        if self.getProperty(common.PROP_EC_WS).isDefault:
            return mainWS
        ecWS = self.getProperty(common.PROP_EC_WS).value
        ecScaling = self.getProperty(common.PROP_EC_SCALING).value
        subtractedWS = _subtractEC(mainWS, ecWS, ecScaling, wsNames, wsCleanup,
                                   subalgLogging)
        wsCleanup.cleanup(mainWS)
        return subtractedWS


AlgorithmFactory.subscribe(DirectILLApplySelfShielding)
#pylint: disable=no-init
from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory
from mantid.kernel import Direction


# Create an empty table workspace to be populated by a python script.
class CreateEmptyTableWorkspace(PythonAlgorithm):
    def summary(self):
        return "Creates an empty TableWorkspace which can be populated with various "\
               "types of information."

    def category(self):
        return 'Utility\\Workspaces'

    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)
            ('Median', collections.OrderedDict()),
            ('Maximum', collections.OrderedDict()),
            ('Mean', collections.OrderedDict()),
        ])

        for index in indices_list:
            column_name = column_names[index]
            try:
                column_data = np.array([float(v) for v in in_ws.column(index)])
                col_stats = _stats_to_dict(Stats.getStatistics(column_data))
                for stat_name in stats:
                    stats[stat_name][column_name] = col_stats[stat_name]
                out_ws.addColumn('float', column_name)
            except RuntimeError:
                logger.notice('Column \'%s\' is not numerical, skipping' %
                              column_name)
            except:
                logger.notice('Column \'%s\' is not numerical, skipping' %
                              column_name)

        for index, stat_name in iteritems(stats):
            stat = collections.OrderedDict(stat_name)
            stat['Statistic'] = index
            out_ws.addRow(stat)

        self.setProperty('OutputWorkspace', out_ws)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(StatisticsOfTableWorkspace)
Beispiel #23
0
        quick_run_alg = self.createChildAlgorithm("IndirectQuickRun", 0.05,
                                                  0.95)
        for num in range(self._number_samples):
            first_run = self._run_first + num
            run_numbers = [
                str(first_run + idx * self._number_samples)
                for idx in range(self._number_runs)
            ]

            quick_run_alg.setProperty('InputFiles', run_numbers)
            quick_run_alg.setProperty('Instrument', self._instrument_name)
            quick_run_alg.setProperty('Analyser', self._analyser)
            quick_run_alg.setProperty('Reflection', self._reflection)
            quick_run_alg.setProperty('SpectraRange', self._spectra_range)
            quick_run_alg.setProperty('ElasticRange', self._elastic_range)
            quick_run_alg.setProperty('InelasticRange', self._inelastic_range)
            quick_run_alg.setProperty('TotalRange', self._total_range)
            quick_run_alg.setProperty('SampleEnvironmentLogName',
                                      self._sample_log_name)
            quick_run_alg.setProperty('SampleEnvironmentLogValue',
                                      self._sample_log_value)
            quick_run_alg.setProperty('MSDFit', self._msd_fit)
            quick_run_alg.setProperty('WidthFit', self._width_fit)
            quick_run_alg.setProperty('Plot', self._plot)
            quick_run_alg.setProperty('Save', self._save)
            quick_run_alg.execute()


AlgorithmFactory.subscribe(
    IndirectSampleChanger)  # Register algorithm with Mantid
Beispiel #24
0
        # ------------------------------------------------------------
        self.setProperty("OutputWorkspace", workspace)

        # ------------------------------------------------------------
        # Diagnostic output
        # ------------------------------------------------------------
        if sum_of_counts:
            self.setProperty("SumOfCounts", sum_of_counts)
        if sum_of_norms:
            self.setProperty("SumOfNormFactors", sum_of_norms)

        self.setProperty("CalculatedTransmissionWorkspace", calculated_transmission_workspace)
        self.setProperty("UnfittedTransmissionWorkspace", unfitted_transmission_workspace)

    def validateInputs(self):
        errors = dict()
        # Check that the input can be converted into the right state object
        try:
            state = self._get_state()
            state.validate()
        except ValueError as err:
            errors.update({"SANSSingleReduction": str(err)})
        return errors

    def _get_progress(self):
        return Progress(self, start=0.0, end=1.0, nreports=10)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSReductionCore)
                if skip:
                    I = number_omega - I + 2
                else:
                    I += 1
        AAA += sum_1 * Area_y
        BBB += sum_2 * Area_y
        Area += Area_sum * Area_y
        return AAA, BBB, Area

    # ------------------------------------------------------------------------------

    def _distance(self, r1, radius, omega):
        r = r1
        distance = 0.0
        b = r * math.sin(omega)
        if abs(b) < radius:
            t = r * math.cos(omega)
            c = radius * radius - b * b
            d = math.sqrt(c)
            if r <= radius:
                distance = t + d
            else:
                distance = d * (1.0 + math.copysign(1.0, t))
        return distance


# ------------------------------------------------------------------------------

# Register algorithm with Mantid
AlgorithmFactory.subscribe(CylinderPaalmanPingsCorrection)
Beispiel #26
0
                     'energy_min', 'energy_max', 'sample_binning']
        log_values = [self._res_name, str(self._background), str(self._elastic),
                      energy_min, energy_max, sample_binning]

        add_log = self.createChildAlgorithm('AddSampleLogMultiple', enableLogging=False)
        add_log.setProperty('Workspace', workspace)
        add_log.setProperty('LogNames', log_names)
        add_log.setProperty('LogValues', log_values)
        add_log.setProperty('ParseType', True)  # Should determine String/Number type
        add_log.execute()

    def _get_properties(self):
        self._sam_name = self.getPropertyValue('SampleWorkspace')
        self._sam_ws = self.getProperty('SampleWorkspace').value
        self._res_name = self.getPropertyValue('ResolutionWorkspace')
        self._e_min = self.getProperty('EMin').value
        self._e_max = self.getProperty('EMax').value
        self._sam_bins = self.getPropertyValue('SampleBins')
        self._elastic = self.getProperty('Elastic').value
        self._background = self.getPropertyValue('Background')
        self._nbet = self.getProperty('NumberBeta').value
        self._nsig = self.getProperty('NumberSigma').value
        self._loop = self.getProperty('Loop').value

        self._erange = [self._e_min, self._e_max]
        # [sample_bins, resNorm_bins=1]
        self._nbins = [self._sam_bins, 1]


AlgorithmFactory.subscribe(BayesStretch)  # Register algorithm with Mantid
        wavelength_options = {"InputWorkspace": workspace,
                              "WavelengthLow": wavelength_state.wavelength_low[0],
                              "WavelengthHigh": wavelength_state.wavelength_high[0],
                              "WavelengthStep": wavelength_state.wavelength_step,
                              "WavelengthStepType": RangeStepType.to_string(
                                  wavelength_state.wavelength_step_type),
                              "RebinMode": RebinType.to_string(wavelength_state.rebin_type)}
        wavelength_alg = create_unmanaged_algorithm(wavelength_name, **wavelength_options)
        wavelength_alg.setPropertyValue("OutputWorkspace", EMPTY_NAME)
        wavelength_alg.setProperty("OutputWorkspace", workspace)
        wavelength_alg.execute()
        converted_workspace = wavelength_alg.getProperty("OutputWorkspace").value
        append_to_sans_file_tag(converted_workspace, "_wavelength")
        self.setProperty("OutputWorkspace", converted_workspace)

    def validateInputs(self):
        errors = dict()
        # Check that the input can be converted into the right state object
        state_property_manager = self.getProperty("SANSState").value
        try:
            state = create_deserialized_sans_state_from_property_manager(state_property_manager)
            state.property_manager = state_property_manager
            state.validate()
        except ValueError as err:
            errors.update({"SANSSMove": str(err)})
        return errors


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSConvertToWavelength)
Beispiel #28
0
                    Goniometers=self.getProperty('Goniometers').value,
                    Axis0='{},0,1,0,1'.format(offset),
                    Axis1=self.getProperty('Axis0').value,
                    Axis2=self.getProperty('Axis1').value,
                    Axis3=self.getProperty('Axis2').value)
            else:
                SetGoniometer(Workspace=ws_name,
                              Axis0='{},0,1,0,1'.format(offset),
                              Axis1='omega,0,1,0,1',
                              Axis2='chi,0,0,1,1',
                              Axis3='phi,0,1,0,1')
        else:
            if self.getProperty('SetGoniometer').value:
                SetGoniometer(
                    Workspace=ws_name,
                    Goniometers=self.getProperty('Goniometers').value,
                    Axis0=self.getProperty('Axis0').value,
                    Axis1=self.getProperty('Axis1').value,
                    Axis2=self.getProperty('Axis2').value)

        ConvertUnits(InputWorkspace=ws_name,
                     OutputWorkspace=ws_name,
                     Target='Momentum')
        CropWorkspaceForMDNorm(InputWorkspace=ws_name,
                               OutputWorkspace=ws_name,
                               XMin=self.XMin,
                               XMax=self.XMax)


AlgorithmFactory.subscribe(SingleCrystalDiffuseReduction)
Beispiel #29
0
        return

    def PyExec(self):
        # Input
        input_list = self.getProperty("WorkspaceNames").value
        self.outws_name = self.getProperty("OutputWorkspace").valueAsStr
        self.xaxis = self.getProperty("HorizontalAxis").value

        self.workspace_names = self._expand_groups(input_list)
        self.log().information("Workspaces to merge: %i" %
                               (len(self.workspace_names)))
        # produce warnings is some optional sample logs do not match
        result = api.CompareSampleLogs(self.workspace_names,
                                       self.properties_to_compare, 1e-2)

        self._merge_workspaces()

        outws = api.AnalysisDataService.retrieve(self.outws_name)
        api.CopyLogs(self.workspace_names[0], outws)
        # remove logs which do not match
        if result:
            api.RemoveLogs(outws, result)

        self.setProperty("OutputWorkspace", outws)
        return


# Register algorithm with Mantid
AlgorithmFactory.subscribe(DNSMergeRuns)
        maxIndex = ws.getNumberHistograms() - 1
        foregroundYs = foregroundWS.dataY(0)
        foregroundEs = foregroundWS.dataE(0)
        numpy.square(foregroundEs, out=foregroundEs)
        for i in sumIndices:
            if i == beamPosIndex:
                continue
            if i < 0 or i > maxIndex:
                self.log().warning(
                    'Foreground partially out of the workspace.')
            ys = ws.readY(i)
            foregroundYs += ys
            es = ws.readE(i)
            foregroundEs += es**2
        numpy.sqrt(foregroundEs, out=foregroundEs)
        self._cleanup.cleanup(ws)
        AddSampleLog(Workspace=foregroundWS,
                     LogName=common.SampleLogs.SUM_TYPE,
                     LogText=SumType.IN_LAMBDA,
                     LogType='String',
                     EnableLogging=self._subalgLogging)
        ConvertToDistribution(Workspace=foregroundWS,
                              EnableLogging=self._subalgLogging)
        return foregroundWS

    def _sumType(self):
        return self.getProperty(Prop.SUM_TYPE).value


AlgorithmFactory.subscribe(ReflectometryILLSumForeground)
Beispiel #31
0
        api.AddSampleLog(outws, 'polarisation_comment', LogText=str(pol[1]), LogType='String')
        # slits
        api.AddSampleLog(outws, LogName='slit_i_upper_blade_position',
                         LogText=str(metadata.slit_i_upper_blade_position),
                         LogType='Number', LogUnit='mm')
        api.AddSampleLog(outws, LogName='slit_i_lower_blade_position',
                         LogText=str(metadata.slit_i_lower_blade_position),
                         LogType='Number', LogUnit='mm')
        api.AddSampleLog(outws, LogName='slit_i_left_blade_position',
                         LogText=str(metadata.slit_i_left_blade_position),
                         LogType='Number', LogUnit='mm')
        api.AddSampleLog(outws, 'slit_i_right_blade_position',
                         LogText=str(metadata.slit_i_right_blade_position),
                         LogType='Number', LogUnit='mm')
        # data normalization

        # add information whether the data are normalized (duration/monitor/no):
        api.AddSampleLog(outws, LogName='normalized', LogText=norm, LogType='String')

        outws.setYUnit(yunit)
        outws.setYUnitLabel(ylabel)

        self.setProperty("OutputWorkspace", outws)
        self.log().debug('LoadDNSLegacy: data are loaded to the workspace ' + outws_name)

        return


# Register algorithm with Mantid
AlgorithmFactory.subscribe(LoadDNSLegacy)
Beispiel #32
0
    def serialize_in_log(self, ws_name):
        r"""Save the serialization of the algorithm in the logs.

        Parameters
        ----------
        ws_name: str
            Name of the workspace from which to retrieve and modify the logs
        """
        def jsonify(value):
            r"""Cast non-standard objects to their closest standard
            representation to enable JSON serialiation"""
            if isinstance(value, np.ndarray):
                return value.tolist()
            return value
        if self._as_json is None:
            self._as_json = json.loads(str(self))
            # Force serialization of the following properties even if having
            # their default values
            forced = {name: jsonify(self.getProperty(name).value)
                      for name in ('DoIndividual', 'MonitorNorm',
                                   'NormalizeToFirst', 'ReflectionType',
                                   'EnergyBins', 'MomentumTransferBins',
                                   'MaskFile', 'DivideByVanadium')}
            self._as_json['properties'].update(forced)
        r = mtd[ws_name].mutableRun()
        r.addProperty('asString', json.dumps(self._as_json), True)

# Register algorithm with Mantid.
AlgorithmFactory.subscribe(BASISReduction)
Beispiel #33
0
                             b=self._b,
                             c=self._c,
                             alpha=self._alpha,
                             beta=self._beta,
                             gamma=self._gamma,
                             StoreInADS=False)

            # new linked predicted peaks
            linked_peaks_predicted = PredictPeaks(
                InputWorkspace=linked_peaks,
                WavelengthMin=self._wavelength_min,
                WavelengthMax=self._wavelength_max,
                MinDSpacing=self._min_dspacing,
                MaxDSpacing=self._max_dspacing,
                ReflectionCondition=self._reflection_condition,
                StoreInADS=False)

        # clean up
        self.setProperty("LinkedPeaks", linked_peaks)
        self.setProperty("LinkedPredictedPeaks", linked_peaks_predicted)
        if mtd.doesExist("linked_peaks"):
            DeleteWorkspace(linked_peaks)
        if mtd.doesExist("linked_peaks_predicted"):
            DeleteWorkspace(linked_peaks_predicted)
        if self._delete_ws:
            DeleteWorkspace(self._workspace)


# register algorithm with mantid
AlgorithmFactory.subscribe(LinkedUBs)
    except:
        raise RuntimeError('Could not find run number for workspace ' +
                           workspace.getName())


def _hasWorkspaceID(workspace_name, workspace_id):
    """Check that a workspace has the given type"""
    workspace = AnalysisDataService.retrieve(workspace_name)
    if isinstance(workspace, WorkspaceGroup):
        return workspace[0].id() == workspace_id
    else:
        return workspace.id() == workspace_id


def _removeWorkspace(workspace_name):
    """Remove the workspace with the given name, including any child workspaces if it
    is a group. If a corresponding monitors workspace exists, remove that too."""
    if AnalysisDataService.doesExist(workspace_name):
        workspace = AnalysisDataService.retrieve(workspace_name)
        if isinstance(workspace, WorkspaceGroup):
            # Remove child workspaces first
            while workspace.getNumberOfEntries():
                _removeWorkspace(workspace[0].name())
        AnalysisDataService.remove(workspace_name)
    # If a corresponding monitors workspace also exists, remove that too
    if AnalysisDataService.doesExist(_monitorWorkspace(workspace_name)):
        _removeWorkspace(_monitorWorkspace(workspace_name))


AlgorithmFactory.subscribe(ReflectometryISISLoadAndProcess)
        transmission_workspace = self.getProperty(
            "TransmissionWorkspace").value
        return self._get_cloned_workspace(
            transmission_workspace) if transmission_workspace else None

    def _get_direct_workspace(self):
        direct_workspace = self.getProperty("DirectWorkspace").value
        return self._get_cloned_workspace(
            direct_workspace) if direct_workspace else None

    def _get_monitor_workspace(self):
        monitor_workspace = self.getProperty("ScatterMonitorWorkspace").value
        return self._get_cloned_workspace(monitor_workspace)

    def _get_cloned_workspace(self, workspace):
        clone_name = "CloneWorkspace"
        clone_options = {
            "InputWorkspace": workspace,
            "OutputWorkspace": EMPTY_NAME
        }
        clone_alg = create_child_algorithm(self, clone_name, **clone_options)
        clone_alg.execute()
        return clone_alg.getProperty("OutputWorkspace").value

    def _get_progress(self):
        return Progress(self, start=0.0, end=1.0, nreports=10)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSBeamCentreFinderCore)
	#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())
    
AlgorithmFactory.subscribe(DakotaChiSquared)
            issues['Height'] = 'Please enter a non-zero number for height'

        if self._shape == 'FlatPlate':
            if not self._width:
                issues['Width'] = 'Please enter a non-zero number for width'
            if not self._thickness:
                issues[
                    'Thickness'] = 'Please enter a non-zero number for thickness'

        if self._shape == 'Cylinder':
            if not self._radius:
                issues['Radius'] = 'Please enter a non-zero number for radius'

        if self._shape == 'Annulus':
            if not self._inner_radius:
                issues[
                    'InnerRadius'] = 'Please enter a non-zero number for inner radius'
            if not self._outer_radius:
                issues[
                    'OuterRadius'] = 'Please enter a non-zero number for outer radius'

            # Geometry validation: outer radius > inner radius
            if not self._outer_radius > self._inner_radius:
                issues['OuterRadius'] = 'Must be greater than InnerRadius'

        return issues


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SimpleShapeMonteCarloAbsorption)
    def validateInputs(self):
        """
        Validate algorithm options.
        """

        self._setup()
        issues = dict()

        if self._use_can_corrections and self._can_chemical_formula == '':
            issues['CanChemicalFormula'] = 'Must be set to use can corrections'

        if self._use_can_corrections and self._can_ws_name is None:
            issues['UseCanCorrections'] = 'Must specify a can workspace to use can corrections'

        # Geometry validation: can inner < sample inner < sample outer < can outer
        if self._sample_inner_radius < self._can_inner_radius:
            issues['SampleInnerRadius'] = 'Must be greater than CanInnerRadius'

        if self._sample_outer_radius < self._sample_inner_radius:
            issues['SampleOuterRadius'] = 'Must be greater than SampleInnerRadius'

        if self._can_outer_radius < self._sample_outer_radius:
            issues['CanOuterRadius'] = 'Must be greater than SampleOuterRadius'

        return issues


# Register algorithm with Mantid
AlgorithmFactory.subscribe(IndirectAnnulusAbsorption)
Beispiel #39
0
            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
        # of loading files and then deleting the resulting workspaces in turn
        # when we are finished with them.
        ws_iter = FileBackedWsIterator(filenames)
        for ws in ws_iter:
            # Create a single row table for each file.
            temp_table_name = ws.getName() + "_INFO"
            CreateLogPropertyTable(
                InputWorkspaces=ws.getName(),
                LogPropertyNames=', '.join(PROP_NAMES),
                GroupPolicy="First",  # Include only the 1st child of any groups.
                OutputWorkspace=temp_table_name)
            # Add its contents to the output before deleting it.
            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.
AlgorithmFactory.subscribe(RetrieveRunInfo)
Beispiel #40
0
            o_el = 1
        else:
            o_el = 0
        fitOp = [o_el, bgd, 0, 0]
        loopOp = self.getProperty('Sequence').value
        verbOp = self.getProperty('Verbose').value
        plotOp = self.getPropertyValue('Plot')
        saveOp = self.getProperty('Save').value

        workdir = config['defaultsave.directory']
        if inType == 'File':
            spath = os.path.join(workdir, sname+'.nxs')        # path name for sample nxs file
            LoadNexusProcessed(Filename=spath, OutputWorkspace=sname)
            Smessage = 'Sample from File : '+spath
        else:
            Smessage = 'Sample from Workspace : '+sname

        if rinType == 'File':
            rpath = os.path.join(workdir, rname+'.nxs')        # path name for res nxs file
            LoadNexusProcessed(Filename=rpath, OutputWorkspace=rname)
            Rmessage = 'Resolution from File : '+rpath
        else:
            Rmessage = 'Resolution from Workspace : '+rname

        if verbOp:
            logger.notice(Smessage)
            logger.notice(Rmessage)
        Main.QuestRun(sname,rname,nbs,erange,nbins,fitOp,loopOp,plotOp,saveOp)

AlgorithmFactory.subscribe(Quest)         # Register algorithm with Mantid
Beispiel #41
0
        @param workspace_suffix Suffix of result workspace name
        """

        if workspace_suffix is None:
            workspace_suffix = parameter_name

        col_names = fit_params.getColumnNames()

        y_values = []
        e_values = []

        y_values = fit_params.column(col_names.index(parameter_name))
        e_values = fit_params.column(col_names.index(parameter_name + '_Err'))

        ws_name = self._out_ws + '_' + workspace_suffix

        CreateWorkspace(OutputWorkspace=ws_name,
                        DataX=x_axis,
                        DataY=y_values,
                        DataE=e_values,
                        NSpec=1,
                        UnitX=x_unit,
                        VerticalAxisUnit='Text',
                        VerticalAxisValues=[parameter_name])

        return ws_name


# Register algorithm with Mantid
AlgorithmFactory.subscribe(ResNorm)
        out_ws.addColumn('str', 'statistic')

        stats = {
            'standard_deviation': dict(),
            'maximum': dict(),
            'minimum': dict(),
            'mean': dict(),
            'median': dict(),
        }

        for name in in_ws.getColumnNames():
            try:
                col_stats = _stats_to_dict(Stats.getStatistics(np.array([float(v) for v in in_ws.column(name)])))
                for statname in stats:
                    stats[statname][name] = col_stats[statname]
                out_ws.addColumn('float', name)
            except ValueError:
                logger.notice('Column \'%s\' is not numerical, skipping' % name)

        for name, stat in iteritems(stats):
            stat1 = dict(stat)
            stat1['statistic'] = name
            out_ws.addRow(stat1)

        self.setProperty('OutputWorkspace', out_ws)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(StatisticsOfTableWorkspace)
Beispiel #43
0
import unittest
from mantid.simpleapi import CreateWorkspace, set_properties
from mantid.api import (MatrixWorkspaceProperty, AlgorithmFactory, AlgorithmManager,
                        DataProcessorAlgorithm, PythonAlgorithm)
from mantid.kernel import Direction
from six import iteritems

class ChildAlg(PythonAlgorithm):

    def PyInit(self):
        pass

    def PyExec(self):
        pass

AlgorithmFactory.subscribe(ChildAlg)


class ParentAlg(DataProcessorAlgorithm):
    """Dummy workflow algorithm for testing purposes.
    This just creates an output workspace and runs a child algorithm.
    """

    def PyInit(self):
        self.declareProperty(MatrixWorkspaceProperty('Workspace', '', Direction.InOut),
                             doc="Name to give the input workspace.")

    def PyExec(self):

        alg = self.createChildAlgorithm('ChildAlg')
        alg.initialize()
        """
        Correct for sample and container.
        """

        logger.information('Correcting sample and container')

        factor_workspaces_wavelength = {factor: self._convert_units_wavelength(workspace) for factor, workspace
                                        in factor_workspaces.items()}

        if self._rebin_container_ws:
            container_workspace = s_api.RebinToWorkspace(WorkspaceToRebin=container_workspace,
                                                         WorkspaceToMatch=factor_workspaces_wavelength['acc'],
                                                         OutputWorkspace="rebinned",
                                                         StoreInADS=False)
        return self._corrections_approximation(sample_workspace, container_workspace, factor_workspaces_wavelength)

    def _three_factor_corrections_approximation(self, sample_workspace, container_workspace, factor_workspaces):
        acc = factor_workspaces['acc']
        acsc = factor_workspaces['acsc']
        assc = factor_workspaces['assc']
        return (sample_workspace - container_workspace * (acsc / acc)) / assc

    def _two_factor_corrections_approximation(self, sample_workspace, container_workspace, factor_workspaces):
        acc = factor_workspaces['acc']
        ass = factor_workspaces['ass']
        return (sample_workspace / ass) - (container_workspace / acc)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(ApplyPaalmanPingsCorrection)
        correctionWSName = wsNames.withSuffix('correction')
        useFullInstrument = self.getProperty(common.PROP_SIMULATION_INSTRUMENT).value == common.SIMULATION_INSTRUMENT_FULL
        if useFullInstrument:
            correctionWS = MonteCarloAbsorption(InputWorkspace=wavelengthWS,
                                                OutputWorkspace=correctionWSName,
                                                SparseInstrument=False,
                                                NumberOfWavelengthPoints=wavelengthPoints,
                                                Interpolation='CSpline',
                                                EnableLogging=subalgLogging)
        else:
            rows = self.getProperty(common.PROP_SPARSE_INSTRUMENT_ROWS).value
            columns = self.getProperty(common.PROP_SPARSE_INSTRUMENT_COLUMNS).value
            correctionWS = MonteCarloAbsorption(InputWorkspace=wavelengthWS,
                                                OutputWorkspace=correctionWSName,
                                                SparseInstrument=True,
                                                NumberOfDetectorRows=rows,
                                                NumberOfDetectorColumns=columns,
                                                NumberOfWavelengthPoints=wavelengthPoints,
                                                Interpolation='CSpline',
                                                EnableLogging=subalgLogging)
        wsCleanup.cleanup(wavelengthWS)
        correctionWS = ConvertUnits(InputWorkspace=correctionWS,
                                    OutputWorkspace=correctionWSName,
                                    Target='TOF',
                                    EMode='Direct',
                                    EnableLogging=subalgLogging)
        return correctionWS


AlgorithmFactory.subscribe(DirectILLSelfShielding)
from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty, WorkspaceFactory
from mantid.kernel import Direction

# Create an empty table workspace to be populated by a python script.
class CreateEmptyTableWorkspace(PythonAlgorithm):

    def summary(self):
        return "Creates an empty TableWorkspace which can be populated with various types of information."

    def PyInit(self):
        # Declare properties
        self.declareProperty(ITableWorkspaceProperty("OutputWorkspace", "", Direction.Output), "The name of the table workspace that will be created.")
 
    def PyExec(self):
        tableWS = WorkspaceFactory.createTable()

        self.setProperty("OutputWorkspace", tableWS)
 
# Register algorithm with Mantid
AlgorithmFactory.subscribe(CreateEmptyTableWorkspace)
            save_alg.setProperty("Filename", path)
            save_alg.execute()

    def _plot_result(self, workspaces):
        from IndirectImport import import_mantidplot
        mp = import_mantidplot()
        mp.plotSpectrum(workspaces,0)

    def _create_ws(self, output_ws, x, y, unit):
        create_alg = self.createChildAlgorithm("CreateWorkspace", enableLogging = False)
        create_alg.setProperty("OutputWorkspace", output_ws)
        create_alg.setProperty("DataX", x)
        create_alg.setProperty("DataY", y)
        create_alg.setProperty("Nspec", 1)
        create_alg.setProperty("UnitX", 'MomentumTransfer')
        create_alg.execute()
        mtd.addOrReplace(output_ws, create_alg.getProperty("OutputWorkspace").value)
        if unit == 'angle':
            unitx = mtd[output_ws].getAxis(0).setUnit("Label")
            unitx.setLabel('2theta', 'deg')

    def _group_ws(self, input_ws, output_ws):
        group_alg = self.createChildAlgorithm("GroupWorkspaces", enableLogging=False)
        group_alg.setProperty("InputWorkspaces", input_ws)
        group_alg.setProperty("OutputWorkspace", output_ws)
        group_alg.execute()
        mtd.addOrReplace(output_ws, group_alg.getProperty("OutputWorkspace").value)


AlgorithmFactory.subscribe(MuscatElasticReactor)          # Register algorithm with Mantid
Beispiel #48
0
        # list of run_numbers
        api.AddSampleLog(Workspace=wsOutput,
                         LogName='run_number',
                         LogText=str(pdict['run_number']),
                         LogType='String')

        self.setProperty("OutputWorkspace", wsOutput)

    def timingsMatch(self, wsNames):
        """
        :param wsNames:
        :return:
        """
        for i in range(len(wsNames)):
            leftWorkspace = wsNames[i]
            rightWorkspace = wsNames[i + 1]
            leftXData = api.mtd[leftWorkspace].dataX(0)
            rightXData = api.mtd[rightWorkspace].dataX(0)
            leftDeltaX = leftXData[0] - leftXData[1]
            rightDeltaX = rightXData[0] - rightXData[1]
            if abs(leftDeltaX -
                   rightDeltaX) >= 1e-4 or abs(rightXData[0] -
                                               leftXData[0]) >= 1e-4:
                raise RuntimeError("Timings don't match")
            else:
                return True


# Register algorithm with Mantid.
AlgorithmFactory.subscribe(TOFTOFMergeRuns)
Beispiel #49
0
        for i in range(10):
            ndens = (self._number_density/total_mass)*1e6
            xst = self.free_xst(self._masses, scatter_length)
            attenuation_length = ndens*xst*1e-28

            dmur = 2*attenuation_length*self._thickness
            trans_guess = math.exp(-dmur)
            self._number_density = ((1-self._transmission_guess)/(1-trans_guess))*self._number_density
            # Add guesses to output workspaces
            density_guesses_tbl_ws.addRow([str(i+1), self._number_density])
            trans_guesses_tbl_ws.addRow([str(i+1), trans_guess])

        self.setProperty("DensityWorkspace", density_guesses_tbl_ws)
        self.setProperty("TransmissionWorkspace", trans_guesses_tbl_ws)


    def free_xst(self, Mass, scatter_length):
        """
        Analytic expression for integration of PDCS over E1 and solid angle
        """
        # Neutron rest mass(u) / Mass
        xs_masses = 1.00867/Mass
        scatter_len_sq = np.square(scatter_length)
        cross_section = np.divide((self.FOUR_PI * scatter_len_sq),(np.square(xs_masses+1)))
        xs_sum = sum(cross_section)
        return xs_sum


AlgorithmFactory.subscribe(VesuvioThickness)
            peaks = run.getNumberPeaks()
            if peaks == 0:
                AnalysisDataService.remove(str(run))
            else:
                group.append(str(run))
        GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=ws_group)
        OptimizeCrystalPlacement(PeaksWorkspace=ws_group,
                                 ModifiedPeaksWorkspace=ws_group,
                                 AdjustSampleOffsets=True,
                                 MaxSamplePositionChangeMeters=0.005,
                                 MaxIndexingError=tolerance)
        RenameWorkspace(InputWorkspace=str(minR), OutputWorkspace=ws_append)
        for run in range(minR + 1, maxR):
            if AnalysisDataService.doesExist(str(run)):
                CombinePeaksWorkspaces(LHSWorkspace=ws_append,
                                       RHSWorkspace=str(run),
                                       OutputWorkspace=ws_append)
                logger.notice(
                    'Optimized %s sample position: %s\n' %
                    (str(run), mtd[str(run)].getPeak(0).getSamplePos()))
                AnalysisDataService.remove(str(run))
        result = IndexPeaks(PeaksWorkspace=ws_append, Tolerance=tolerance)
        logger.notice('After Optimization Number indexed: %s error: %s\n' %
                      (result[0], result[1]))
        AnalysisDataService.remove(ws_group)
        self.setProperty("OutputWorkspace", ws_append)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(OptimizeCrystalPlacementByRun)
Beispiel #51
0
        # Perform the masking
        number_of_masking_options = 7
        progress = Progress(self, start=0.0, end=1.0, nreports=number_of_masking_options)
        mask_info = state.mask
        workspace = masker.mask_workspace(mask_info, workspace, component, progress)

        append_to_sans_file_tag(workspace, "_masked")
        self.setProperty("Workspace", workspace)
        progress.report("Completed masking the workspace")

    def _get_component(self):
        component_as_string = self.getProperty("Component").value
        return DetectorType.from_string(component_as_string)

    def validateInputs(self):
        errors = dict()
        # Check that the input can be converted into the right state object
        state_property_manager = self.getProperty("SANSState").value
        try:
            state = create_deserialized_sans_state_from_property_manager(state_property_manager)
            state.property_manager = state_property_manager
            state.validate()
        except ValueError as err:
            errors.update({"SANSSMask": str(err)})
        return errors


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSMaskWorkspace)
                Scale(InputWorkspace=convertedToQName,
                      OutputWorkspace=convertedToQName,
                      Factor=scaleFactor)
            to_group.append(convertedToQName)
            self._autoCleanup.protect(convertedToQName)
            progress.report()

        if len(to_group) > 1:
            try:
                stitched = self._outWS + '_stitched'
                use_manual = self.getProperty(
                    PropertyNames.USE_MANUAL_SCALE_FACTORS).value
                scale_factors = self.getProperty(
                    PropertyNames.MANUAL_SCALE_FACTORS).value
                Stitch1DMany(InputWorkspaces=to_group,
                             OutputWorkspace=stitched,
                             UseManualScaleFactors=use_manual,
                             ManualScaleFactors=scale_factors)
                to_group.append(stitched)
            except RuntimeError as re:
                self.log().warning(
                    'Unable to stitch automatically, consider stitching manually: '
                    + str(re))

        GroupWorkspaces(InputWorkspaces=to_group, OutputWorkspace=self._outWS)
        self.setProperty(Prop.OUTPUT_WS, self._outWS)
        self._autoCleanup.finalCleanup()


AlgorithmFactory.subscribe(ReflectometryILLAutoProcess)
Beispiel #53
0
        workspace = self.getProperty("InputWorkspace").value

        # Component to crop
        component = self._get_component(workspace)

        progress = Progress(self, start=0.0, end=1.0, nreports=2)
        progress.report("Starting to crop component {0}".format(component))

        # Crop to the component
        crop_name = "CropToComponent"
        crop_options = {"InputWorkspace": workspace,
                        "OutputWorkspace": EMPTY_NAME,
                        "ComponentNames": component}
        crop_alg = create_unmanaged_algorithm(crop_name, **crop_options)
        crop_alg.execute()
        output_workspace = crop_alg.getProperty("OutputWorkspace").value

        # Change the file tag and set the output
        append_to_sans_file_tag(output_workspace, "_cropped")
        self.setProperty("OutputWorkspace", output_workspace)
        progress.report("Finished cropping")

    def _get_component(self, workspace):
        component_as_string = self.getProperty("Component").value
        component = DetectorType.from_string(component_as_string)
        return get_component_name(workspace, component)


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSCrop)
Beispiel #54
0
    def doIterativeSmoothing(self, y, nwindow, maxdepth, depth=0):
        """
        Iterative smoothing procedure to estimate the background in powder diffraction as published in
        Bruckner J. Appl. Cryst. (2000). 33, 977-979
        :param y: signal to smooth
        :param n: size of window for convolution
        :param maxdepth: max depth of recursion (i.e. number of iterations)
        :param depth: current iteration
        :return:
        """
        # smooth with hat function
        yy = np.copy(y)
        yy = np.convolve(yy, np.ones(nwindow) / nwindow, mode="same")
        # normalise end values effected by convolution
        ends = np.convolve(np.ones(nwindow),
                           np.ones(nwindow) / nwindow,
                           mode='same')
        yy[0:nwindow // 2] = yy[0:nwindow // 2] / ends[0:nwindow // 2]
        yy[-nwindow // 2:] = yy[-nwindow // 2:] / ends[-nwindow // 2:]
        if depth < maxdepth:
            # compare pt by pt with original and keep lowest
            idx = yy > y
            yy[idx] = y[idx]
            return self.doIterativeSmoothing(yy, nwindow, maxdepth, depth + 1)
        else:
            return yy


# register algorithm with mantid
AlgorithmFactory.subscribe(EnggEstimateFocussedBackground)
Beispiel #55
0
            if selected_detector is None:
                selected_detector = detectors[DetectorType.to_string(DetectorType.LAB)]
            pos1 = selected_detector.sample_centre_pos1
            pos2 = selected_detector.sample_centre_pos2
            coordinates = [pos1, pos2]
        return coordinates

    def validateInputs(self):
        errors = dict()
        # Check that the input can be converted into the right state object
        state_property_manager = self.getProperty("SANSState").value
        try:
            state = create_deserialized_sans_state_from_property_manager(state_property_manager)
            state.property_manager = state_property_manager
            state.validate()
        except ValueError as err:
            errors.update({"SANSSMove": str(err)})

        # Check that if the MoveType is either InitialMove or ElementaryDisplacement, then there are beam coordinates
        # supplied. In the case of SetToZero these coordinates are ignored if they are supplied
        coordinates = self.getProperty("BeamCoordinates").value
        selected_move_type = self._get_move_type()
        if len(coordinates) == 0 and (selected_move_type is MoveType.ElementaryDisplacement):
            errors.update({"BeamCoordinates": "Beam coordinates were not specified. An elementary displacement "
                                              "requires beam coordinates."})
        return errors


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSMove)
Beispiel #56
0
        """Create a new workspace with Y and E from directForegroundWS and X and DX data from ws."""
        qWSName = self._names.withSuffix(extraLabel + 'in_momentum_transfer')
        qWS = CreateWorkspace(
            OutputWorkspace=qWSName,
            DataX=ws.readX(0),
            DataY=directForegroundWS.readY(0)
            [::
             -1],  # Invert data because wavelength is inversely proportional to Q.
            DataE=directForegroundWS.readE(0)[::-1],
            Dx=ws.readDx(0),
            UnitX=ws.getAxis(0).getUnit().unitID(),
            ParentWorkspace=directForegroundWS,
            EnableLogging=self._subalgLogging)
        return qWS

    def _TOFChannelWidth(self, sampleLogs):
        """Return the time of flight bin width."""
        return sampleLogs.getProperty('PSD.time_of_flight_0').value

    def _toPointData(self, ws, extraLabel=''):
        """Convert ws from binned to point data."""
        pointWSName = self._names.withSuffix(extraLabel + 'as_points')
        pointWS = ConvertToPointData(InputWorkspace=ws,
                                     OutputWorkspace=pointWSName,
                                     EnableLogging=self._subalgLogging)
        self._cleanup.cleanup(ws)
        return pointWS


AlgorithmFactory.subscribe(ReflectometryILLConvertToQ)
Beispiel #57
0
                              "C_a", "C_b", "C_c", "C_z", "polarisation", "polarisation_comment"])
        logs["values"].extend([metadata.flipper_precession_current,
                               metadata.flipper_z_compensation_current, flipper_status,
                               metadata.a_coil_current, metadata.b_coil_current,
                               metadata.c_coil_current, metadata.z_coil_current,
                               str(pol[0]), str(pol[1])])
        logs["units"].extend(["A", "A", "", "A", "A", "A", "A", "", ""])

        # slits
        logs["names"].extend(["slit_i_upper_blade_position", "slit_i_lower_blade_position",
                              "slit_i_left_blade_position", "slit_i_right_blade_position"])
        logs["values"].extend([metadata.slit_i_upper_blade_position, metadata.slit_i_lower_blade_position,
                               metadata.slit_i_left_blade_position, metadata.slit_i_right_blade_position])
        logs["units"].extend(["mm", "mm", "mm", "mm"])

        # add information whether the data are normalized (duration/monitor/no):
        api.AddSampleLog(outws, LogName='normalized', LogText=norm, LogType='String')
        api.AddSampleLogMultiple(outws, LogNames=logs["names"], LogValues=logs["values"], LogUnits=logs["units"])

        outws.setYUnit(yunit)
        outws.setYUnitLabel(ylabel)

        self.setProperty("OutputWorkspace", outws)
        self.log().debug('LoadDNSLegacy: data are loaded to the workspace ' + outws_name)

        return


# Register algorithm with Mantid
AlgorithmFactory.subscribe(LoadDNSLegacy)
Beispiel #58
0
                move_component(component_name="",
                               move_info=state.move,
                               workspace=workspace,
                               move_type=MoveTypes.RESET_POSITION)

                move_component(component_name="LAB",
                               move_info=state.move,
                               beam_coordinates=beam_coordinates,
                               move_type=MoveTypes.INITIAL_MOVE,
                               workspace=workspace,
                               is_transmission_workspace=is_trans)

    def _get_progress_for_file_loading(self, data, state_adjustment):
        # Get the number of workspaces which are to be loaded
        number_of_files_to_load = sum(x is not None for x in [
            data.sample_scatter, data.sample_transmission, data.sample_direct,
            data.can_transmission, data.can_transmission, data.can_direct,
            state_adjustment.calibration
        ])
        progress_steps = number_of_files_to_load + 1
        # Check if there is a move operation to be performed

        # The partitioning of the progress bar is 80% for loading if there is a move else 100%
        end = 1.0
        progress = Progress(self, start=0.0, end=end, nreports=progress_steps)
        return progress


# Register algorithm with Mantid
AlgorithmFactory.subscribe(SANSLoad)
Beispiel #59
0
        # Outputs the calculated density of states to another workspace
        dos2d = CloneWorkspace(inws)
        if iqq == 1:
            dos2d = Transpose(dos2d)
        for i in range(len(y)):
            dos2d.setY(i, y[i,:])
            dos2d.setE(i, e[i,:])
        dos2d.setYUnitLabel(ylabel)

        # Make a 1D (energy dependent) cut
        dos1d = Rebin2D(dos2d, [dq[0], dq[1]-dq[0], dq[1]], dosebin, True, True)
        if cm and input_en_in_meV:
            dos1d.getAxis(0).setUnit('DeltaE_inWavenumber')
            dos1d = ScaleX(dos1d, mev2cm)
        elif not cm and not input_en_in_meV:
            dos1d.getAxis(0).setUnit('DeltaE')
            dos1d = ScaleX(dos1d, 1/mev2cm)

        if absunits:
            print("Converting to states/energy")
            # cross-section information is given in barns, but data is in milibarns.
            sigma = atoms[0].neutron()['tot_scatt_xs'] * 1000
            mass = atoms[0].mass
            dos1d = dos1d * (mass/sigma) * 4 * np.pi

        self.setProperty("OutputWorkspace", dos1d)
        DeleteWorkspace(dos2d)
        DeleteWorkspace(dos1d)

AlgorithmFactory.subscribe(ComputeIncoherentDOS)
            LHSWorkspace=ws,
            RHSWorkspace=rebinnedWaterWS,
            OutputWorkspace=calibratedWSName,
            EnableLogging=self._subalgLogging
        )
        self._cleanup.cleanup(waterWS)
        self._cleanup.cleanup(rebinnedWaterWS)
        self._cleanup.cleanup(ws)
        return calibratedWS

    def _calibrateDetectorAngleByDirectBeam(self, ws):
        """Perform detector position correction for reflected beams."""
        direct_line = self.getProperty('DirectBeamForegroundCentre').value
        calibratedWSName = self._names.withSuffix('reflected_beam_calibration')
        calibratedWS = SpecularReflectionPositionCorrect(
            InputWorkspace=ws,
            OutputWorkspace=calibratedWSName,
            DetectorComponentName='detector',
            LinePosition=direct_line, # yes, this is the direct line position!
            TwoTheta=2*self._theta_from_detector_angles(),
            PixelSize=common.pixelSize(self._instrumentName),
            DetectorCorrectionType='RotateAroundSample',
            DetectorFacesSample=True,
            EnableLogging=self._subalgLogging
        )
        self._cleanup.cleanup(ws)
        return calibratedWS


AlgorithmFactory.subscribe(ReflectometryILLPreprocess)