Beispiel #1
0
    def test_that_can_add_workspaces_to_WorkspaceGroup_when_not_in_ADS(self):
        ws1 = WorkspaceFactory.create("Workspace2D", 2, 2, 2)
        ws2 = WorkspaceFactory.create("Workspace2D", 2, 2, 2)

        ws_group = WorkspaceGroup()

        ws_group.addWorkspace(ws1)
        ws_group.addWorkspace(ws2)

        self.assertEqual(ws_group.size(), 2)
    def test_that_can_add_workspaces_to_WorkspaceGroup_when_not_in_ADS(self):
        ws1 = WorkspaceFactory.create("Workspace2D", 2, 2, 2)
        ws2 = WorkspaceFactory.create("Workspace2D", 2, 2, 2)

        ws_group = WorkspaceGroup()

        ws_group.addWorkspace(ws1)
        ws_group.addWorkspace(ws2)

        self.assertEqual(ws_group.size(), 2)
Beispiel #3
0
    def _loadFullprofPrfFile(self, prffilename):
        """ Load Fullprof .prf file
        """
        # 1. Parse the file to dictionary
        infodict, data = self._parseFullprofPrfFile(prffilename)

        # 2. Export information to table file
        tablews = WorkspaceFactory.createTable()
        tablews.addColumn("str", "Name")
        tablews.addColumn("double", "Value")
        for parname in infodict.keys():
            parvalue = infodict[parname]
            tablews.addRow([parname, parvalue])

        # 3. Export the data workspace
        datasize = len(data)
        print "Data Size = ", datasize
        dataws = WorkspaceFactory.create("Workspace2D", 4, datasize, datasize)
        for i in xrange(datasize):
            for j in xrange(4):
                dataws.dataX(j)[i] = data[i][0]
                dataws.dataY(j)[i] = data[i][j + 1]
                dataws.dataE(j)[i] = 1.0

        return (tablews, dataws)
Beispiel #4
0
    def _loadFullprofPrfFile(self, prffilename):
        """ Load Fullprof .prf file
        """
        # 1. Parse the file to dictionary
        infodict, data = self._parseFullprofPrfFile(prffilename)

        # 2. Export information to table file
        tablews = WorkspaceFactory.createTable()
        tablews.addColumn("str", "Name")
        tablews.addColumn("double", "Value")
        for parname in infodict.keys():
            parvalue = infodict[parname]
            tablews.addRow([parname, parvalue])

        # 3. Export the data workspace
        datasize = len(data)
        print "Data Size = ", datasize
        dataws = WorkspaceFactory.create("Workspace2D", 4, datasize, datasize)
        for i in xrange(datasize):
            for j in xrange(4):
                dataws.dataX(j)[i] = data[i][0]
                dataws.dataY(j)[i] = data[i][j+1]
                dataws.dataE(j)[i] = 1.0

        return (tablews, dataws)
    def test_remove_workspace_by_name_will_remove_a_fit_containing_a_specific_parameter_workspace(
            self):
        output_ws = WorkspaceFactory.create("Workspace2D",
                                            NVectors=3,
                                            YLength=5,
                                            XLength=5)
        table_workspace = WorkspaceFactory.createTable()

        output_ws_wrap1 = StaticWorkspaceWrapper("Output1", output_ws)
        parameter_ws_wrap1 = StaticWorkspaceWrapper("Parameter1",
                                                    table_workspace)
        covariance_ws_wrap1 = StaticWorkspaceWrapper("Covariance1",
                                                     table_workspace)
        output_ws_wrap2 = StaticWorkspaceWrapper("Output2", output_ws)
        parameter_ws_wrap2 = StaticWorkspaceWrapper("Parameter2",
                                                    table_workspace)
        covariance_ws_wrap2 = StaticWorkspaceWrapper("Covariance2",
                                                     table_workspace)

        fit1 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1],
                              parameter_ws_wrap1, covariance_ws_wrap1)
        fit2 = FitInformation(["Input2"], "GausOsc", [output_ws_wrap2],
                              parameter_ws_wrap2, covariance_ws_wrap2)

        self.fitting_context.active_fit_history = [fit1, fit2]

        self.fitting_context.remove_workspace_by_name("Parameter1")

        self.assertEqual(self.fitting_context.active_fit_history[0], fit2)
        self.assertEqual(self.fitting_context.all_latest_fits()[0], fit2)
 def test_creating_a_workspace_from_another_with_different_size(self):
     clean = self._create_clean_workspace(nhist=2, xlength=4, ylength=3)
     nhist = 4
     xlength = 6
     ylength = 5
     copy = WorkspaceFactory.create(clean, nhist, xlength, ylength)
     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
     xlength = 5
     ylength = 6
     copy = WorkspaceFactory.create(clean, nhist, xlength, ylength)
     self._verify(copy, nhist, xlength, ylength)
 def test_creating_a_workspace_from_another_gives_one_of_same_size(self):
     nhist = 2
     xlength = 3
     ylength = 4
     clean = self._create_clean_workspace(nhist, xlength, ylength)
     copy = WorkspaceFactory.create(clean)
     self._verify(copy, nhist, xlength, ylength)
Beispiel #9
0
    def _fill_s_1d_workspace(self,
                             s_points=None,
                             workspace=None,
                             protons_number=None,
                             nucleons_number=None):
        """
        Puts 1D S into workspace.
        :param protons_number: number of protons in the given type of atom
        :param nucleons_number: number of nucleons in the given type of atom
        :param s_points: dynamical factor for the given atom
        :param workspace: workspace to be filled with S
        """
        if protons_number is not None:
            s_points = s_points * self._scale * self.get_cross_section(
                scattering=self._scale_by_cross_section,
                protons_number=protons_number,
                nucleons_number=nucleons_number)
        dim = 1
        length = s_points.size

        wrk = WorkspaceFactory.create("Workspace2D",
                                      NVectors=dim,
                                      XLength=length + 1,
                                      YLength=length)
        for i in range(dim):
            wrk.getSpectrum(i).setDetectorID(i + 1)
        wrk.setX(0, self._bins)
        wrk.setY(0, s_points)
        AnalysisDataService.addOrReplace(workspace, wrk)

        # Set correct units on workspace
        self.set_workspace_units(workspace, layout="1D")
 def test_creating_a_workspace_from_another_gives_one_of_same_size(self):
     nhist = 2
     xlength = 4
     ylength = 3
     clean = self._create_clean_workspace(nhist, xlength, ylength)
     copy = WorkspaceFactory.create(clean)
     self._verify(copy, nhist, xlength, ylength)
    def test_that_all_latest_fits_will_return_the_two_most_recent_unique_fits(
            self):
        output_ws = WorkspaceFactory.create("Workspace2D",
                                            NVectors=3,
                                            YLength=5,
                                            XLength=5)
        table_workspace = WorkspaceFactory.createTable()

        output_ws_wrap1 = StaticWorkspaceWrapper("Output1", output_ws)
        parameter_ws_wrap1 = StaticWorkspaceWrapper("Parameter1",
                                                    table_workspace)
        covariance_ws_wrap1 = StaticWorkspaceWrapper("Covariance1",
                                                     table_workspace)
        output_ws_wrap2 = StaticWorkspaceWrapper("Output2", output_ws)
        parameter_ws_wrap2 = StaticWorkspaceWrapper("Parameter2",
                                                    table_workspace)
        covariance_ws_wrap2 = StaticWorkspaceWrapper("Covariance2",
                                                     table_workspace)

        fit1 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1],
                              parameter_ws_wrap1, covariance_ws_wrap1)
        fit2 = FitInformation(["Input2"], "GausOsc", [output_ws_wrap2],
                              parameter_ws_wrap2, covariance_ws_wrap2)
        fit3 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1],
                              parameter_ws_wrap1, covariance_ws_wrap1)

        self.fitting_context.active_fit_history = [fit1, fit2, fit3]

        self.assertEqual(self.fitting_context.active_fit_history[0], fit1)
        self.assertEqual(self.fitting_context.active_fit_history[1], fit2)
        self.assertEqual(self.fitting_context.active_fit_history[2], fit3)

        # fit3 == fit1 and fit3 is more recent, so 'all_latest_fits' will only return the most recent unique fits.
        self.assertEqual(self.fitting_context.all_latest_fits()[0], fit2)
        self.assertEqual(self.fitting_context.all_latest_fits()[1], fit3)
Beispiel #12
0
    def test_create_results_table_with_logs_selected(self):
        workspace = WorkspaceFactory.create("Workspace2D", NVectors=3, YLength=5, XLength=5)
        workspace.mutableRun().addProperty("sample_temp", 50, True)
        workspace.mutableRun().addProperty("sample_magn_field", 2, True)
        _, model = create_test_model(('ws1',), 'func1', self.parameters, [StaticWorkspaceWrapper('ws1', workspace)],
                                     self.logs)
        selected_results = [('ws1', 0)]
        table = model.create_results_table(self.log_names, selected_results)

        expected_cols = ['workspace_name'] + self.log_names + [
            'f0.Height', 'f0.HeightError', 'f0.PeakCentre',
            'f0.PeakCentreError', 'f0.Sigma', 'f0.SigmaError', 'f1.Height',
            'f1.HeightError', 'f1.PeakCentre', 'f1.PeakCentreError',
            'f1.Sigma', 'f1.SigmaError', 'Cost function value'
        ]
        expected_types = (TableColumnType.NoType, TableColumnType.X,
                          TableColumnType.X, TableColumnType.Y,
                          TableColumnType.YErr, TableColumnType.Y,
                          TableColumnType.YErr, TableColumnType.Y,
                          TableColumnType.YErr, TableColumnType.Y,
                          TableColumnType.YErr, TableColumnType.Y,
                          TableColumnType.YErr, TableColumnType.Y,
                          TableColumnType.YErr, TableColumnType.Y)
        avg_log_values = 50., 2.0
        expected_content = [
            ('ws1_Parameters', avg_log_values[0], avg_log_values[1],
             self.f0_height[0], self.f0_height[1], self.f0_centre[0],
             self.f0_centre[1], self.f0_sigma[0], self.f0_sigma[1],
             self.f1_height[0], self.f1_height[1], self.f1_centre[0],
             self.f1_centre[1], self.f1_sigma[0], self.f1_sigma[1],
             self.cost_function[0])
        ]
        self._assert_table_matches_expected(zip(expected_cols, expected_types),
                                            expected_content, table,
                                            model.results_table_name())
Beispiel #13
0
    def setUp(self):
        self.results_context = ResultsContext()
        self.result_table_names = ["Name1", "Name2"]

        workspace = WorkspaceFactory.create("Workspace2D", NVectors=3, YLength=5, XLength=5)
        add_ws_to_ads("Name1", workspace)
        add_ws_to_ads("Name2", workspace)
def create_test_workspace(ws_name=None,
                          time_series_logs=None,
                          string_value_logs=None):
    """
    Create a test workspace.
    :param ws_name: An optional name for the workspace
    :param time_series_logs: A set of (name, (values,...))
    :param string_value_logs: A set of (name, value) pairs
    :return: The new workspace
    """
    fake_ws = WorkspaceFactory.create('Workspace2D', 1, 1, 1)
    run = fake_ws.run()
    if time_series_logs is not None:
        for name, values in time_series_logs:
            tsp = FloatTimeSeriesProperty(name)
            for item in values:
                try:
                    time, value = item[0], item[1]
                except TypeError:
                    time, value = "2000-05-01T12:00:00", item
                tsp.addValue(time, value)
            run.addProperty(name, tsp, replace=True)

    if string_value_logs is not None:
        for name, value in string_value_logs:
            run.addProperty(name,
                            StringPropertyWithValue(name, value),
                            replace=True)

    ws_name = ws_name if ws_name is not None else 'fitting_context_model_test'
    AnalysisDataService.Instance().addOrReplace(ws_name, fake_ws)
    return fake_ws
Beispiel #15
0
    def test_that_all_latest_fits_will_return_the_two_most_recent_unique_fits(self):
        output_ws = WorkspaceFactory.create("Workspace2D", NVectors=3, YLength=5, XLength=5)
        table_workspace = WorkspaceFactory.createTable()

        output_ws_wrap1 = StaticWorkspaceWrapper("Output1", output_ws)
        parameter_ws_wrap1 = StaticWorkspaceWrapper("Parameter1", table_workspace)
        covariance_ws_wrap1 = StaticWorkspaceWrapper("Covariance1", table_workspace)
        output_ws_wrap2 = StaticWorkspaceWrapper("Output2", output_ws)
        parameter_ws_wrap2 = StaticWorkspaceWrapper("Parameter2", table_workspace)
        covariance_ws_wrap2 = StaticWorkspaceWrapper("Covariance2", table_workspace)

        fit1 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1], parameter_ws_wrap1, covariance_ws_wrap1)
        fit2 = FitInformation(["Input2"], "GausOsc", [output_ws_wrap2], parameter_ws_wrap2, covariance_ws_wrap2)
        fit3 = FitInformation(["Input1"], "GausOsc", [output_ws_wrap1], parameter_ws_wrap1, covariance_ws_wrap1)

        self.fitting_context.tf_asymmetry_mode = True
        self.fitting_context.simultaneous_fitting_mode = True
        self.fitting_context.active_fit_history = [fit1, fit2, fit3]

        self.assertEqual(self.fitting_context.active_fit_history[0], fit1)
        self.assertEqual(self.fitting_context.active_fit_history[1], fit2)
        self.assertEqual(self.fitting_context.active_fit_history[2], fit3)

        self.assertEqual(self.fitting_context.all_latest_fits()[0], fit2)
        self.assertEqual(self.fitting_context.all_latest_fits()[1], fit3)

        self.fitting_context.tf_asymmetry_mode = False
        self.assertEqual(self.fitting_context.active_fit_history, [])
        self.assertEqual(self.fitting_context.all_latest_fits()[0], fit2)
        self.assertEqual(self.fitting_context.all_latest_fits()[1], fit3)
    def test_setting_spectra_from_array_using_incorrect_index_raises_error(self):
        nvectors = 2
        xlength = 11
        ylength = 10

        test_ws = WorkspaceFactory.create("Workspace2D", nvectors, xlength, ylength)
        xvalues = np.arange(xlength)
        self.assertRaises(RuntimeError, test_ws.setX, 3, xvalues)
Beispiel #17
0
 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!")
 def test_that_get_item_scope_works_not_in_ads(self):
     with self._HoldWsGroup() as group:
         # Note we want to create this inline so our ref is through getItem
         group.addWorkspace(WorkspaceFactory.create("Workspace2D", 1, 1, 1))
         ws = group.getItem(0)
         self.assertFalse(ws.name())  # Not in ADS so should be no name
         self.assertEqual(len(AnalysisDataService.getObjectNames()), 0)
     # Now the group should be deleted, this should continue to work now
     self.assertFalse(ws.name())
Beispiel #19
0
 def _create_dummy_workspace(self, name):
     wrk = WorkspaceFactory.create("Workspace2D",
                                   NVectors=1,
                                   XLength=2,
                                   YLength=1)
     wrk.setX(0, [0, 1])
     wrk.setY(0, [0])
     AnalysisDataService.addOrReplace(name, wrk)
     return wrk
    def test_setting_spectra_from_array_of_incorrect_length_raises_error(self):
        nvectors = 2
        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)
        self.assertRaises(ValueError, test_ws.setE, 0, values)
    def runTest(self):
        PDLoadCharacterizations(Filename=self.char_file, OutputWorkspace='characterizations',
                                SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0')

        self.wksp_mem = os.path.basename(self.data_file).split('.')[0]
        self.wksp_mem, self.wksp_file = self.wksp_mem + '_mem', self.wksp_mem + '_file'

        # load then process
        LoadEventAndCompress(Filename=self.data_file, OutputWorkspace=self.wksp_mem, MaxChunkSize=16, FilterBadPulses=0)
        LoadDiffCal(Filename=self.cal_file, InputWorkspace=self.wksp_mem, WorkspaceName='PG3')
        PDDetermineCharacterizations(InputWorkspace=self.wksp_mem, Characterizations='characterizations',
                                     ReductionProperties='__snspowderreduction_inner')

        # set-up the absorption calculation
        num_wl_bins = 200
        prop_manager = PropertyManagerDataService.retrieve('__snspowderreduction_inner')
        wl_min, wl_max = prop_manager['wavelength_min'].value, prop_manager['wavelength_max'].value  # 0.05, 2.20
        absorptionWS = WorkspaceFactory.create(mtd[self.wksp_mem],
                                               NVectors=mtd[self.wksp_mem].getNumberHistograms(), XLength=num_wl_bins+1,
                                               YLength=num_wl_bins)
        xaxis = np.arange(0., float(num_wl_bins + 1)) * (wl_max - wl_min) / (num_wl_bins) + wl_min
        for i in range(absorptionWS.getNumberHistograms()):
            absorptionWS.setX(i, xaxis)
        absorptionWS.getAxis(0).setUnit('Wavelength')
        mantid.api.AnalysisDataService.addOrReplace('V_abs', absorptionWS)
        SetSample(InputWorkspace='V_abs',
                  Material={'ChemicalFormula': 'V', 'SampleNumberDensity': 0.0721},
                  Geometry={'Shape': 'Cylinder', 'Height': 6.97, 'Radius': (0.63 / 2), 'Center': [0., 0., 0.]})
        self.assertEqual(absorptionWS.getNumberBins(), num_wl_bins)
        # calculate the absorption
        CylinderAbsorption(InputWorkspace='V_abs', OutputWorkspace='V_abs',
                           NumberOfSlices=20, NumberOfAnnuli=3)

        # do the work in memory
        ConvertUnits(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem, Target='Wavelength')
        Divide(LHSWorkspace=self.wksp_mem, RHSWorkspace='V_abs', OutputWorkspace=self.wksp_mem)
        ConvertUnits(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem, Target='TOF')
        AlignAndFocusPowder(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem,
                            GroupingWorkspace='PG3_group', CalibrationWorkspace='PG3_cal', MaskWorkspace='PG3_mask',
                            Params=-.0002, CompressTolerance=0.01,
                            PrimaryFlightPath=60, SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0',
                            ReductionProperties='__snspowderreduction_inner')
        NormaliseByCurrent(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem)
        ConvertUnits(InputWorkspace=self.wksp_mem, OutputWorkspace=self.wksp_mem, Target='dSpacing')

        # everything inside the algorithm
        AlignAndFocusPowderFromFiles(Filename=self.data_file, OutputWorkspace=self.wksp_file,
                                     GroupingWorkspace='PG3_group', CalibrationWorkspace='PG3_cal',
                                     MaskWorkspace='PG3_mask',
                                     AbsorptionWorkspace='V_abs',
                                     Params=-.0002, CompressTolerance=0.01,
                                     PrimaryFlightPath=60, SpectrumIDs='1', L2='3.18', Polar='90', Azimuthal='0',
                                     ReductionProperties='__snspowderreduction_inner')
        NormaliseByCurrent(InputWorkspace=self.wksp_file, OutputWorkspace=self.wksp_file)
        ConvertUnits(InputWorkspace=self.wksp_file, OutputWorkspace=self.wksp_file, Target='dSpacing')
Beispiel #22
0
def create_test_workspace(model, num_bins):
    workspace = WorkspaceFactory.create("Workspace2D", NVectors=1,
                                        XLength=num_bins, YLength=num_bins)

    for i in range(1, num_bins):
        noise = random.uniform(0.8, 1.2)
        x_value = i * 1.2
        workspace.dataX(0)[i] = x_value
        workspace.dataY(0)[i] = noise * model(x_value)
        workspace.dataE(0)[i] = 1
    return workspace
Beispiel #23
0
    def test_setting_spectra_from_array_of_incorrect_shape_raises_error(self):
        nvectors = 2
        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)
        self.assertRaises(ValueError, test_ws.setY, 0, values)
        self.assertRaises(ValueError, test_ws.setE, 0, values)
Beispiel #24
0
    def test_setting_spectra_from_array_of_incorrect_shape_raises_error(self):
        nvectors = 2
        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)
        self.assertRaises(ValueError, test_ws.setY, 0, values)
        self.assertRaises(ValueError, test_ws.setE, 0, values)
Beispiel #25
0
    def PyExec(self):
        input_ws = self.getProperty("InputWorkspace").value
        output_ws_name = self.getProperty('OutputWorkspace').valueAsStr
        from_quantity = self.getProperty("From").value
        to_quantity = self.getProperty("To").value

        if input_ws.name() == output_ws_name:
            output_ws = input_ws
        else:
            output_ws = WorkspaceFactory.create(input_ws)

        self.setProperty('OutputWorkspace', output_ws)
        if from_quantity == to_quantity:
            logger.warning(
                'The input and output functions are the same. Nothing to be done'
            )
            return

        c = Converter()
        transformation = {
            Gr: {
                GKr: c.G_to_GK,
                gr: c.G_to_g
            },
            GKr: {
                Gr: c.GK_to_G,
                gr: c.GK_to_g
            },
            gr: {
                Gr: c.g_to_G,
                GKr: c.g_to_GK
            }
        }

        sample_kwargs = {
            "<b_coh>^2":
            input_ws.sample().getMaterial().cohScatterLengthSqrd(),
            "<b_tot^2>":
            input_ws.sample().getMaterial().totalScatterLengthSqrd(),
            "rho": input_ws.sample().getMaterial().numberDensity
        }

        for sp_num in range(input_ws.getNumberHistograms()):
            x = input_ws.readX(sp_num)
            output_ws.setX(sp_num, x)
            y = input_ws.readY(sp_num)
            e = input_ws.readE(sp_num)
            if len(x) == len(y) + 1:
                x = 0.5 * (x[:-1] + x[1:])

            new_y, new_e = transformation[from_quantity][to_quantity](
                x, y, e, **sample_kwargs)
            output_ws.setY(sp_num, new_y)
            output_ws.setE(sp_num, new_e)
Beispiel #26
0
def __create_outputws(donor: Union[str, Workspace2D], numSpec, numPeaks):
    '''The resulting workspace needs to be added to the ADS'''
    # convert the d-space table to a Workspace2d
    if donor:
        donor = mtd[str(donor)]
    else:
        donor = 'Workspace2D'
    output = WorkspaceFactory.create(donor,
                                     NVectors=numSpec,
                                     XLength=numPeaks,
                                     YLength=numPeaks)
    output.getAxis(0).setUnit('dSpacing')
    return output
    def test_setxy_data_coerced_correctly_to_float64(self):
        nbins = 10
        nspec = 2
        xdata = np.arange(nbins+1)
        ydata = np.arange(nbins)
        ws = WorkspaceFactory.create("Workspace2D", NVectors=nspec, XLength=nbins+1, YLength=nbins)
        for i in range(nspec):
            ws.setX(i, xdata)
            ws.setY(i, ydata)

        # Verify
        x_expected, y_expected = np.vstack((xdata, xdata)), np.vstack((ydata, ydata))
        x_extracted, y_extracted = ws.extractX(), ws.extractY()
        self.assertTrue(np.array_equal(x_expected, x_extracted))
        self.assertTrue(np.array_equal(y_expected, y_extracted))
    def test_setxy_accepts_python_list(self):
        nbins = 10
        nspec = 2
        xdata = list(range(nbins+1))
        ydata = list(range(nbins))
        ws = WorkspaceFactory.create("Workspace2D", NVectors=nspec, XLength=nbins+1, YLength=nbins)
        for i in range(nspec):
            ws.setX(i, xdata)
            ws.setY(i, ydata)

        # Verify
        xdata, ydata = np.array(xdata), np.array(ydata)
        x_expected, y_expected = np.vstack((xdata, xdata)), np.vstack((ydata, ydata))
        x_extracted, y_extracted = ws.extractX(), ws.extractY()
        self.assertTrue(np.array_equal(x_expected, x_extracted))
        self.assertTrue(np.array_equal(y_expected, y_extracted))
    def test_rebinnedOutput(self):
        rebin = WorkspaceFactory.create("RebinnedOutput", 2, 3, 2)
        self.assertFalse(rebin.nonZeroF())
        fv = rebin.readF(1)
        rebin.dataY(1)[:] = 10.0
        rebin.dataE(1)[:] = 1.0
        twos = np.ones(len(fv)) * 2.0
        rebin.setF(1, twos)
        self.assertTrue(rebin.nonZeroF())
        rebin.setFinalized(False)
        rebin.setSqrdErrors(False)
        rebin.unfinalize()
        self.assertFalse(rebin.isFinalized())
        yv = rebin.readY(1)
        ev = rebin.readE(1)
        self.assertAlmostEqual(yv[0], 10.0)
        self.assertAlmostEqual(ev[0], 1.0)

        rebin.finalize(True)
        self.assertTrue(rebin.isFinalized())
        self.assertTrue(rebin.hasSqrdErrors())
        yv = rebin.readY(1)
        ev = rebin.readE(1)
        self.assertAlmostEqual(yv[0], 5.0)
        self.assertAlmostEqual(ev[0], 0.25)

        rebin.finalize(False)
        self.assertTrue(rebin.isFinalized())
        self.assertFalse(rebin.hasSqrdErrors())
        yv = rebin.readY(1)
        ev = rebin.readE(1)
        self.assertAlmostEqual(yv[0], 5.0)
        self.assertAlmostEqual(ev[0], 0.5)

        rebin.unfinalize()
        self.assertFalse(rebin.isFinalized())
        yv = rebin.readY(1)
        ev = rebin.readE(1)
        self.assertAlmostEqual(yv[0], 10.0)
        self.assertAlmostEqual(ev[0], 1.0)

        rebin.scaleF(2.0)
        fv = rebin.readF(1)
        self.assertAlmostEqual(fv[0], 4.0)
Beispiel #30
0
def extract_peak_info(wksp: Union[str, Workspace2D], outputname: str,
                      peak_position: float):
    """
    Extract information about a single peak from a Workspace2D. The input workspace is expected to have
    common x-axis of observed d-spacing. The y-values and errors are extracted.

    The output workspace will be a single spectra with the x-axis being the detector-id. The y-values
    and errors are extracted from the input workspace.
    """
    # confirm that the input is a workspace pointer
    wksp = mtd[str(wksp)]
    numSpec = wksp.getNumberHistograms()

    # get the index into the x/y arrays of the peak position
    peak_index = wksp.readX(0).searchsorted(peak_position)

    # create a workspace to put the result into
    single = WorkspaceFactory.create('Workspace2D',
                                     NVectors=1,
                                     XLength=wksp.getNumberHistograms(),
                                     YLength=wksp.getNumberHistograms())
    single.setTitle('d-spacing={}\\A'.format(wksp.readX(0)[peak_index]))

    # get a handle to map the detector positions
    detids = wksp.detectorInfo().detectorIDs()
    have_detids = bool(len(detids) > 0)

    # fill in the data values
    x = single.dataX(0)
    y = single.dataY(0)
    e = single.dataE(0)
    start_detid = np.searchsorted(detids, 0)
    for wksp_index in range(numSpec):
        if have_detids:
            x[wksp_index] = detids[start_detid + wksp_index]
        else:
            x[wksp_index] = wksp_index
        y[wksp_index] = wksp.readY(wksp_index)[peak_index]
        e[wksp_index] = wksp.readE(wksp_index)[peak_index]

    # add the workspace to the AnalysisDataService
    mtd.addOrReplace(outputname, single)
    return mtd[outputname]
Beispiel #31
0
    def _fill_s_2d_workspace(self,
                             s_points=None,
                             workspace=None,
                             protons_number=None,
                             nucleons_number=None):
        from mantid.api import NumericAxis
        from abins.constants import MILLI_EV_TO_WAVENUMBER

        if protons_number is not None:
            s_points = s_points * self.get_cross_section(
                scattering=self._scale_by_cross_section,
                protons_number=protons_number,
                nucleons_number=nucleons_number)

        n_q_values, n_freq_bins = s_points.shape
        n_q_bins = self._q_bins.size
        assert n_q_values + 1 == n_q_bins

        if self._energy_units == 'meV':
            energy_bins = self._bins / MILLI_EV_TO_WAVENUMBER
        else:
            energy_bins = self._bins

        wrk = WorkspaceFactory.create("Workspace2D",
                                      NVectors=n_freq_bins,
                                      XLength=n_q_bins,
                                      YLength=n_q_values)

        freq_axis = NumericAxis.create(n_freq_bins)
        freq_offset = (energy_bins[1] - energy_bins[0]) / 2
        for i, freq in enumerate(energy_bins[1:]):
            wrk.setX(i, self._q_bins)
            wrk.setY(i, s_points[:, i].T)
            freq_axis.setValue(i, freq + freq_offset)
        wrk.replaceAxis(1, freq_axis)

        AnalysisDataService.addOrReplace(workspace, wrk)

        self.set_workspace_units(workspace,
                                 layout="2D",
                                 energy_units=self._energy_units)
Beispiel #32
0
def create_test_fits(input_workspaces,
                     function_name,
                     parameters,
                     output_workspace_names=None,
                     global_parameters=None):
    """
    Create a list of fits
    :param input_workspaces: The input workspaces
    :param function_name: The name of the function
    :param parameters: The parameters list
    :param output_workspace_names: A list of workspace names
    :param global_parameters: An optional list of tied parameters
    :return: A list of Fits
    """
    workspace = WorkspaceFactory.create("Workspace2D",
                                        NVectors=3,
                                        YLength=5,
                                        XLength=5)

    output_workspace_names = output_workspace_names if output_workspace_names is not None else [
        StaticWorkspaceWrapper('test-output-ws', workspace)
    ]
    # Convert parameters to fit table-like structure
    fit_table = [{
        'Name': name,
        'Value': value,
        'Error': error
    } for name, (value, error) in parameters.items()]

    fits = []
    for name in input_workspaces:
        parameter_workspace = mock.NonCallableMagicMock()
        parameter_workspace.workspace.__iter__.return_value = fit_table
        parameter_workspace.workspace_name = name + '_Parameters'
        fits.append(
            FitInformation([name], function_name,
                           output_workspace_names, parameter_workspace,
                           mock.Mock(), global_parameters))

    return fits
    def test_setting_spectra_from_array_sets_expected_values(self):
        nvectors = 2
        xlength = 11
        ylength = 10

        test_ws = WorkspaceFactory.create("Workspace2D", nvectors, xlength, ylength)
        ws_index = 1

        values = np.linspace(0, 1, xlength)
        test_ws.setX(ws_index, values)
        ws_values = test_ws.readX(ws_index)
        self.assertTrue(np.array_equal(values, ws_values))

        values = np.ones(ylength)
        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)
        self.assertTrue(np.array_equal(values, ws_values))
Beispiel #34
0
    def test_create_results_table_with_logs_missing_from_some_workspaces_raises(self):
        workspace = WorkspaceFactory.create("Workspace2D", NVectors=3, YLength=5, XLength=5)

        parameters = OrderedDict([('f0.Height', (100, 0.1))])
        logs = [('log1', (1., 2.)), ('log2', (3., 4.)), ('log3', (4., 5.)),
                ('log4', (5., 6.))]
        fits_logs1 = create_test_fits(('ws1',), 'func1', parameters,
                                      output_workspace_names=[StaticWorkspaceWrapper('test-ws1-ws', workspace)])
        add_logs(fits_logs1[0].input_workspaces[0], logs[:2])

        fits_logs2 = create_test_fits(('ws2',), 'func1', parameters,
                                      output_workspace_names=[StaticWorkspaceWrapper('test-ws2-ws', workspace)])
        add_logs(fits_logs2[0].input_workspaces[0], logs[2:])

        fitting_context = TFAsymmetryFittingContext()
        fitting_context.fit_list = fits_logs1 + fits_logs2
        model = ResultsTabModel(fitting_context, ResultsContext())

        selected_results = [('ws1', 0), ('ws2', 1)]
        selected_logs = ['log1', 'log3']
        self.assertRaises(IndexError, model.create_results_table,
                          selected_logs, selected_results)
    def PyExec(self):
        input_ws = self.getProperty("InputWorkspace").value
        output_ws_name = self.getProperty('OutputWorkspace').valueAsStr
        from_quantity = self.getProperty("From").value
        to_quantity = self.getProperty("To").value

        if input_ws.name() == output_ws_name:
            output_ws = input_ws
        else:
            output_ws = WorkspaceFactory.create(input_ws)

        self.setProperty('OutputWorkspace', output_ws)
        if from_quantity == to_quantity:
            logger.warning('The input and output functions are the same. Nothing to be done')
            return
        c = Converter()
        transformation = {SQ: {FQ: c.S_to_F, FKQ: c.S_to_FK, DCS: c.S_to_DCS},
                          FQ: {SQ: c.F_to_S, FKQ: c.F_to_FK, DCS: c.F_to_DCS},
                          FKQ: {SQ: c.FK_to_S, FQ: c.FK_to_F, DCS: c.FK_to_DCS},
                          DCS: {SQ: c.DCS_to_S, FQ: c.DCS_to_F, FKQ: c.DCS_to_FK}}

        if input_ws.sample().getMaterial():
            sample_kwargs = {"<b_coh>^2": input_ws.sample().getMaterial().cohScatterLengthSqrd(),
                             "<b_tot^2>": input_ws.sample().getMaterial().totalScatterLengthSqrd(),
                             "rho": input_ws.sample().getMaterial().numberDensity}
        else:
            sample_kwargs = dict()

        for sp_num in range(input_ws.getNumberHistograms()):
            x = input_ws.readX(sp_num)
            output_ws.setX(sp_num, x)
            y = input_ws.readY(sp_num)
            e = input_ws.readE(sp_num)
            if len(x) == len(y) + 1:
                x = 0.5 * (x[:-1] + x[1:])

            new_y, new_e = transformation[from_quantity][to_quantity](x, y, e, **sample_kwargs)
            output_ws.setY(sp_num, new_y)
            output_ws.setE(sp_num, new_e)
Beispiel #36
0
    def _fill_s_1d_workspace(self, s_points=None, workspace=None, protons_number=None, nucleons_number=None):
        """
        Puts 1D S into workspace.
        :param protons_number: number of protons in the given type fo atom
        :param nucleons_number: number of nucleons in the given type of atom
        :param s_points: dynamical factor for the given atom
        :param workspace: workspace to be filled with S
        """
        if protons_number is not None:
            s_points = s_points * self._scale * self._get_cross_section(protons_number=protons_number,
                                                                        nucleons_number=nucleons_number)

        dim = 1
        length = s_points.size
        wrk = WorkspaceFactory.create("Workspace2D", NVectors=dim, XLength=length + 1, YLength=length)
        for i in range(dim):
            wrk.getSpectrum(i).setDetectorID(i + 1)
        wrk.setX(0, self._bins)
        wrk.setY(0, s_points)
        AnalysisDataService.addOrReplace(workspace, wrk)

        # Set correct units on workspace
        self._set_workspace_units(wrk=workspace)
Beispiel #37
0
    def PyExec(self):
        input_ws = self.getProperty("InputWorkspace").value
        output_ws_name = self.getProperty('OutputWorkspace').valueAsStr
        from_quantity = self.getProperty("From").value
        to_quantity = self.getProperty("To").value

        if(input_ws.name()==output_ws_name):
            output_ws=input_ws
        else:
            output_ws=WorkspaceFactory.create(input_ws)

        self.setProperty('OutputWorkspace', output_ws)
        if(from_quantity==to_quantity):
            logger.warning('The input and output functions are the same. Nothing to be done')
            return
        c=Converter()
        transformation={'G(r)':{'GK(r)':c.G_to_GK, 'g(r)':c.G_to_g},
                        'GK(r)':{'G(r)':c.GK_to_G, 'g(r)':c.GK_to_g},
                        'g(r)':{'G(r)':c.g_to_G, 'GK(r)':c.g_to_GK}}
        sample_kwargs={"<b_coh>^2":input_ws.sample().getMaterial().cohScatterLengthSqrd(),
                       "<b_tot^2>":input_ws.sample().getMaterial().totalScatterLengthSqrd(),
                       "rho":input_ws.sample().getMaterial().numberDensity}
        if ((sample_kwargs["<b_coh>^2"]<=0) or (sample_kwargs["<b_tot^2>"]<=0) or
           (sample_kwargs["rho"]<=0)):
            raise RuntimeError('Please run SetSampleMaterial algorithm before running'+
                               ' this algorithm')
        for sp_num in range(input_ws.getNumberHistograms()):
            x = input_ws.readX(sp_num)
            output_ws.setX(sp_num,x)
            y = input_ws.readY(sp_num)
            e = input_ws.readE(sp_num)
            if len(x)==len(y)+1:
                x = 0.5*(x[:-1]+x[1:])

            new_y, new_e=transformation[from_quantity][to_quantity](x,y,e,**sample_kwargs)
            output_ws.setY(sp_num,new_y)
            output_ws.setE(sp_num,new_e)
Beispiel #38
0
    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:
                    # 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
        datasize = len(vecx)
        dataws = WorkspaceFactory.create("Workspace2D", 1, datasize, datasize)
        for i in xrange(datasize):
            dataws.dataX(0)[i] = vecx[i]
            dataws.dataY(0)[i] = vecy[i]
            dataws.dataE(0)[i] = vece[i]

        return (tablews, dataws)
Beispiel #39
0
 def _create_clean_workspace(self, nhist, xlength, ylength):
     return WorkspaceFactory.create("Workspace2D", NVectors=nhist, XLength=xlength, YLength=ylength)
Beispiel #40
0
    def PyExec(self):
        fn = self.getPropertyValue("Filename")
        wsn = self.getPropertyValue("OutputWorkspace")
        monitor_workspace_name = self.getPropertyValue("OutputMonitorWorkspace")
        if monitor_workspace_name == "":
            self.setPropertyValue("OutputMonitorWorkspace", wsn+'_Monitors')
        #print (fn, wsn)
        self.override_angle = self.getPropertyValue("AngleOverride")
        self.fxml = self.getPropertyValue("InstrumentXML")

        #load data

        parms_dict, det_udet, det_count, det_tbc, data = self.read_file(fn)
        nrows=int(parms_dict['NDET'])
        #nbins=int(parms_dict['NTC'])
        xdata = np.array(det_tbc)
        xdata_mon = np.linspace(xdata[0],xdata[-1], len(xdata))
        ydata=data.astype(np.float)
        ydata=ydata.reshape(nrows,-1)
        edata=np.sqrt(ydata)
        #CreateWorkspace(OutputWorkspace=wsn,DataX=xdata,DataY=ydata,DataE=edata,
        #                NSpec=nrows,UnitX='TOF',WorkspaceTitle='Data',YUnitLabel='Counts')
        nr,nc=ydata.shape
        ws = WorkspaceFactory.create("Workspace2D", NVectors=nr,
                                     XLength=nc+1, YLength=nc)
        for i in range(nrows):
            ws.setX(i, xdata)
            ws.setY(i, ydata[i])
            ws.setE(i, edata[i])
        ws.getAxis(0).setUnit('tof')
        AnalysisDataService.addOrReplace(wsn,ws)

        #self.setProperty("OutputWorkspace", wsn)
        #print ("ws:", wsn)
        #ws=mtd[wsn]

        # fix the x values for the monitor
        for i in range(nrows-2,nrows):
            ws.setX(i,xdata_mon)
        self.log().information("set detector IDs")
        #set detetector IDs
        for i in range(nrows):
            ws.getSpectrum(i).setDetectorID(det_udet[i])
        #Sample_logs the header values are written into the sample logs
        log_names=[str(sl.encode('ascii','ignore').decode()) for sl in parms_dict.keys()]
        log_values=[str(sl.encode('ascii','ignore').decode()) if isinstance(sl,UnicodeType) else str(sl) for sl in parms_dict.values()]
        for i in range(len(log_values)):
            if ('nan' in log_values[i]) or ('NaN' in log_values[i]):
                log_values[i] = '-1.0'
        AddSampleLogMultiple(Workspace=wsn, LogNames=log_names,LogValues=log_values)
        SetGoniometer(Workspace=wsn, Goniometers='Universal')
        if (self.fxml == ""):
            LoadInstrument(Workspace=wsn, InstrumentName = "Exed", RewriteSpectraMap= True)
        else:
            LoadInstrument(Workspace=wsn, Filename = self.fxml, RewriteSpectraMap= True)
        try:
            RotateInstrumentComponent(Workspace=wsn,
                                      ComponentName='Tank',
                                      Y=1,
                                      Angle=-float(parms_dict['phi'].encode('ascii','ignore')),
                                      RelativeRotation=False)
        except:
            self.log().warning("The instrument does not contain a 'Tank' component. "
                               "This means that you are using a custom XML instrument definition. "
                               "OMEGA_MAG will be ignored.")
            self.log().warning("Please make sure that the detector positions in the instrument definition are correct.")
        # Separate monitors into seperate workspace
        __temp_monitors = ExtractSpectra(InputWorkspace = wsn, WorkspaceIndexList = ','.join([str(s) for s in range(nrows-2, nrows)]),
                                         OutputWorkspace = self.getPropertyValue("OutputMonitorWorkspace"))
        # ExtractSpectra(InputWorkspace = wsn, WorkspaceIndexList = ','.join([str(s) for s in range(nrows-2, nrows)]),
                       # OutputWorkspace = wsn + '_Monitors')
        MaskDetectors(Workspace = wsn, WorkspaceIndexList = ','.join([str(s) for s in range(nrows-2, nrows)]))
        RemoveMaskedSpectra(InputWorkspace = wsn, OutputWorkspace = wsn)

        self.setProperty("OutputWorkspace", wsn)
        self.setProperty("OutputMonitorWorkspace", __temp_monitors)
Beispiel #41
0
 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!")
Beispiel #42
0
    def _makeEmptyDataWorkspace(self):
        """ Make an empty data workspace (Workspace2D)
        """
        dataws = WorkspaceFactory.create("Workspace2D", 1, 1, 1)

        return dataws