def PyExec(self):
        workspace = get_input_workspace_as_copy_if_not_same_as_output_workspace(
            self)

        progress = Progress(self, start=0.0, end=1.0, nreports=3)

        # Convert the units into wavelength
        progress.report("Converting workspace to wavelength units.")
        workspace = self._convert_units_to_wavelength(workspace)

        # Get the rebin option
        rebin_type = RebinType.from_string(self.getProperty("RebinMode").value)
        rebin_string = self._get_rebin_string(workspace)
        if rebin_type is RebinType.Rebin:
            rebin_options = {
                "InputWorkspace": workspace,
                "PreserveEvents": True,
                "Params": rebin_string
            }
        else:
            rebin_options = {
                "InputWorkspace": workspace,
                "Params": rebin_string
            }

        # Perform the rebin
        progress.report("Performing rebin.")
        workspace = self._perform_rebin(rebin_type, rebin_options, workspace)

        append_to_sans_file_tag(workspace, "_toWavelength")
        self.setProperty("OutputWorkspace", workspace)
        progress.report("Finished converting to wavelength.")
    def PyExec(self):
        workspace = get_input_workspace_as_copy_if_not_same_as_output_workspace(
            self)
        wavelength_pairs: List[Tuple[float, float]] = json.loads(
            self.getProperty(self.WAV_PAIRS).value)
        progress = Progress(self,
                            start=0.0,
                            end=1.0,
                            nreports=1 +
                            len(wavelength_pairs))  # 1 - convert units

        # Convert the units into wavelength
        progress.report("Converting workspace to wavelength units.")
        workspace = self._convert_units_to_wavelength(workspace)

        # Get the rebin option
        output_group = WorkspaceGroup()
        for pair in wavelength_pairs:
            rebin_string = self._get_rebin_string(workspace, *pair)
            progress.report(f"Converting wavelength range: {rebin_string}")

            # Perform the rebin
            rebin_options = self._get_rebin_params(rebin_string, workspace)
            out_ws = self._perform_rebin(rebin_options)

            append_to_sans_file_tag(out_ws, "_toWavelength")
            output_group.addWorkspace(out_ws)
        self.setProperty("OutputWorkspace", output_group)
    def _sample(self):
        sample_prog = Progress(self, start=0.01, end=0.03, nreports=2)
        sample_prog.report('Setting Sample Material for Sample')
        SetSampleMaterial(self._sample_ws_name,
                          ChemicalFormula=self._sample_chemical_formula,
                          SampleNumberDensity=self._sample_number_density)
        sample = mtd[self._sample_ws_name].sample()
        sam_material = sample.getMaterial()
        # total scattering x-section
        self._sig_s = np.zeros(self._number_can)
        self._sig_s[0] = sam_material.totalScatterXSection()
        # absorption x-section
        self._sig_a = np.zeros(self._number_can)
        self._sig_a[0] = sam_material.absorbXSection()
        # density
        self._density = np.zeros(self._number_can)
        self._density[0] = self._sample_number_density

        if self._use_can:
            sample_prog.report('Setting Sample Material for Container')
            SetSampleMaterial(InputWorkspace=self._can_ws_name,
                              ChemicalFormula=self._can_chemical_formula,
                              SampleNumberDensity=self._can_number_density)
            can_sample = mtd[self._can_ws_name].sample()
            can_material = can_sample.getMaterial()
            self._sig_s[1] = can_material.totalScatterXSection()
            self._sig_a[1] = can_material.absorbXSection()
            self._density[1] = self._can_number_density
Esempio n. 4
0
    def PyExec(self):
        # Read the state
        state_property_manager = self.getProperty("SANSState").value
        state = create_deserialized_sans_state_from_property_manager(
            state_property_manager)

        component = self._get_component()

        # Get the correct SANS masking strategy from create_masker
        workspace = self.getProperty("Workspace").value
        masker = create_masker(state, component)

        # 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 _sample(self):
        sample_prog = Progress(self, start=0.01, end=0.03, nreports=2)
        sample_prog.report('Setting Sample Material for Sample')

        sample_chemical_formula = self.getPropertyValue(
            'SampleChemicalFormula')

        sample_ws, self._sample_density = self._set_material(
            self._sample_ws_name, sample_chemical_formula,
            self._sample_density_type, self._sample_density)

        sample_material = sample_ws.sample().getMaterial()
        # total scattering x-section
        self._sig_s = np.zeros(self._number_can)
        self._sig_s[0] = sample_material.totalScatterXSection()
        # absorption x-section
        self._sig_a = np.zeros(self._number_can)
        self._sig_a[0] = sample_material.absorbXSection()
        # density
        self._density = np.zeros(self._number_can)
        self._density[0] = self._sample_density

        if self._use_can:
            sample_prog.report('Setting Sample Material for Container')

            can_chemical_formula = self.getPropertyValue('CanChemicalFormula')

            can_ws, self._can_density = self._set_material(
                self._can_ws_name, can_chemical_formula,
                self._can_density_type, self._can_density)

            can_material = can_ws.sample().getMaterial()
            self._sig_s[1] = can_material.totalScatterXSection()
            self._sig_a[1] = can_material.absorbXSection()
            self._density[1] = self._can_density
    def PyExec(self):
        """Executes the data reduction workflow."""
        progress = Progress(self, 0.0, 1.0, 4)
        self._subalgLogging = self.getProperty(
            common.PROP_SUBALG_LOGGING).value == common.SUBALG_LOGGING_ON
        wsNamePrefix = self.getProperty(common.PROP_OUTPUT_WS).valueAsStr
        cleanupMode = self.getProperty(common.PROP_CLEANUP_MODE).value
        self._names = utils.NameSource(wsNamePrefix, cleanupMode)
        self._cleanup = utils.Cleanup(cleanupMode, self._subalgLogging)

        progress.report('Loading inputs')
        mainWS = self._inputWS()

        # First subtract the background, then apply the absorption correction to sample
        progress.report('Subtracting EC')
        mainWS, subtracted = self._subtractEC(mainWS)

        progress.report('Applying self shielding corrections')
        mainWS, applied = self._applyCorrections(mainWS)

        if not applied and not subtracted:
            mainWS = self._cloneOnly(mainWS)

        self._finalize(mainWS)
        progress.report('Done')
 def PyExec(self):
     error = self.getProperty("Error").value
     if error:
         raise RuntimeError('Error in algorithm')
     progress = Progress(self, 0.0, 1.0, 2)
     progress.report('Half way')
     progress.report()
Esempio n. 8
0
    def _setup(self):
        setup_prog = Progress(self, start=0.00, end=0.01, nreports=2)
        setup_prog.report('Obtaining input properties')
        self._sample_ws_name = self.getPropertyValue('SampleWorkspace')
        self._sample_density_type = self.getPropertyValue('SampleDensityType')
        self._sample_density = self.getProperty('SampleDensity').value
        self._sample_inner_radius = self.getProperty('SampleInnerRadius').value
        self._sample_outer_radius = self.getProperty('SampleOuterRadius').value
        self._number_can = 1

        self._can_ws_name = self.getPropertyValue('CanWorkspace')
        self._use_can = self._can_ws_name != ''
        self._can_density_type = self.getPropertyValue('CanDensityType')
        self._can_density = self.getProperty('CanDensity').value
        self._can_outer_radius = self.getProperty('CanOuterRadius').value
        if self._use_can:
            self._number_can = 2

        self._step_size = self.getProperty('StepSize').value
        self._radii = np.zeros(self._number_can + 1)
        self._radii[0] = self._sample_inner_radius
        self._radii[1] = self._sample_outer_radius
        if (self._radii[1] - self._radii[0]) < 1e-4:
            raise ValueError('Sample outer radius not > inner radius')
        else:
            logger.information(
                'Sample : inner radius = %f ; outer radius = %f' %
                (self._radii[0], self._radii[1]))
            self._ms = int(
                (self._radii[1] - self._radii[0] + 0.0001) / self._step_size)
            if self._ms < 20:
                raise ValueError('Number of steps ( %i ) should be >= 20' %
                                 self._ms)
            else:
                if self._ms < 1:
                    self._ms = 1
                logger.information('Sample : ms = %i ' % self._ms)
        if self._use_can:
            self._radii[2] = self._can_outer_radius
            if (self._radii[2] - self._radii[1]) < 1e-4:
                raise ValueError('Can outer radius not > sample outer radius')
            else:
                logger.information(
                    'Can : inner radius = %f ; outer radius = %f' %
                    (self._radii[1], self._radii[2]))
        setup_prog.report('Obtaining beam values')
        beam_width = self.getProperty('BeamWidth').value
        beam_height = self.getProperty('BeamHeight').value
        self._beam = [
            beam_height, 0.5 * beam_width, -0.5 * beam_width, (beam_width / 2),
            -(beam_width / 2), 0.0, beam_height, 0.0, beam_height
        ]

        self._interpolate = self.getProperty('Interpolate').value
        self._number_wavelengths = self.getProperty('NumberWavelengths').value

        self._emode = self.getPropertyValue('Emode')
        self._efixed = self.getProperty('Efixed').value

        self._output_ws_name = self.getPropertyValue('OutputWorkspace')
Esempio n. 9
0
    def _wave_range(self):
        wave_range = '__wave_range'
        ExtractSingleSpectrum(InputWorkspace=self._sample_ws_name,
                              OutputWorkspace=wave_range,
                              WorkspaceIndex=0)

        Xin = mtd[wave_range].readX(0)
        wave_min = mtd[wave_range].readX(0)[0]
        wave_max = mtd[wave_range].readX(0)[len(Xin) - 1]
        number_waves = self._number_wavelengths
        wave_bin = (wave_max - wave_min) / (number_waves - 1)

        self._waves = list()
        wave_prog = Progress(self, start=0.07, end=0.10, nreports=number_waves)
        for idx in range(0, number_waves):
            wave_prog.report('Appending wave data: %i' % idx)
            self._waves.append(wave_min + idx * wave_bin)
        DeleteWorkspace(wave_range, EnableLogging=False)

        if self._emode == 'Elastic':
            self._elastic = self._waves[int(len(self._waves) / 2)]
        else:
            self._elastic = math.sqrt(81.787 /
                                      self._efixed)  # elastic wavelength

        logger.information('Elastic lambda : %f' % self._elastic)
        logger.information('Lambda : %i values from %f to %f' %
                           (len(self._waves), self._waves[0], self._waves[-1]))
Esempio n. 10
0
    def PyExec(self):
        from IndirectCommon import convertToElasticQ

        progress_tracker = Progress(self, start=0.05, end=0.95, nreports=2)

        # Convert sample workspace to elastic Q
        self._temporary_fit_name = '__fit_ws'
        self._crop_workspace(self._sample_workspace, self._temporary_fit_name,
                             self._e_min, self._e_max)

        self._convert_to_histogram(self._temporary_fit_name)
        convertToElasticQ(self._temporary_fit_name)

        # Perform fits
        progress_tracker.report('Fitting 1 peak...')
        self._fit('1L')
        progress_tracker.report('Fitting 2 peaks...')
        self._fit('2L')
        self._delete_workspace(self._temporary_fit_name)

        # Appends the chi workspaces and replaces the y labels
        self._append_chi_squared_workspaces()

        # Appends the result workspaces and replaces the y labels
        self._append_result_workspaces()
Esempio n. 11
0
 def _get_progress(self, number_of_reductions, overall_reduction_mode):
     number_from_merge = 1 if overall_reduction_mode is ReductionMode.Merged else 0
     number_of_progress_reports = number_of_reductions + number_from_merge + 1
     return Progress(self,
                     start=0.0,
                     end=1.0,
                     nreports=number_of_progress_reports)
Esempio n. 12
0
    def PyExec(self):
        # Read the state
        state_property_manager = self.getProperty("SANSState").value
        state = create_deserialized_sans_state_from_property_manager(state_property_manager)

        progress = Progress(self, start=0.0, end=1.0, nreports=3)
        input_workspace = self.getProperty("InputWorkspace").value

        data_type_as_string = self.getProperty("DataType").value
        data_type = DataType.from_string(data_type_as_string)

        slicer = SliceEventFactory.create_slicer(state, input_workspace, data_type)
        slice_info = state.slice

        # Perform the slicing
        progress.report("Starting to slice the workspace.")
        sliced_workspace, slice_factor = slicer.create_slice(input_workspace, slice_info)

        # Scale the monitor accordingly
        progress.report("Scaling the monitors.")
        self.scale_monitors(slice_factor)

        # Set the outputs
        append_to_sans_file_tag(sliced_workspace, "_sliced")
        self.setProperty("OutputWorkspace", sliced_workspace)
        self.setProperty("SliceEventFactor", slice_factor)
        progress.report("Finished slicing.")
Esempio n. 13
0
    def PyExec(self):
        """ Main execution body
        """

        # returns workspace instance
        self.vanaws = self.getProperty("VanadiumWorkspace").value
        # returns workspace name (string)
        eppws = self.getProperty("EPPTable").value
        nhist = self.vanaws.getNumberHistograms()
        prog_reporter = Progress(self, start=0.8, end=1.0, nreports=3)
        integrate = self.createChildAlgorithm("IntegrateEPP",
                                              startProgress=0.0,
                                              endProgress=0.8,
                                              enableLogging=False)
        integrate.setProperty("InputWorkspace", self.vanaws)
        integrate.setProperty("OutputWorkspace", "__unused_for_child")
        integrate.setProperty("EPPWorkspace", eppws)
        width = 3. * 2. * np.sqrt(2. * np.log(2.))
        integrate.setProperty("HalfWidthInSigmas", width)
        integrate.execute()
        prog_reporter.report("Computing DWFs")
        outws = integrate.getProperty("OutputWorkspace").value
        # calculate array of Debye-Waller factors
        prog_reporter.report("Applying DWFs")
        dwf = self.calculate_dwf()
        for idx in range(nhist):
            ys = outws.dataY(idx)
            ys /= dwf[idx]
            es = outws.dataE(idx)
            es /= dwf[idx]
        prog_reporter.report("Done")
        self.setProperty("OutputWorkspace", outws)
Esempio n. 14
0
    def PyExec(self):
        # Read the state
        state_property_manager = self.getProperty("SANSState").value
        state = create_deserialized_sans_state_from_property_manager(state_property_manager)

        # Run the appropriate SANSLoader and get the workspaces and the workspace monitors
        # Note that cache optimization is only applied to the calibration workspace since it is not available as a
        # return property and it is also something which is most likely not to change between different reductions.
        use_cached = self.getProperty("UseCached").value
        publish_to_ads = self.getProperty("PublishToCache").value

        data = state.data
        progress = self._get_progress_for_file_loading(data)

        # Get the correct SANSLoader from the SANSLoaderFactory
        load_factory = SANSLoadDataFactory()
        loader = load_factory.create_loader(state)

        workspaces, workspace_monitors = loader.execute(data_info=data, use_cached=use_cached,
                                                        publish_to_ads=publish_to_ads, progress=progress,
                                                        parent_alg=self)
        progress.report("Loaded the data.")

        progress_move = Progress(self, start=0.8, end=1.0, nreports=2)
        progress_move.report("Starting to move the workspaces.")
        self._perform_initial_move(workspaces, state)
        progress_move.report("Finished moving the workspaces.")

        # Set output workspaces
        for workspace_type, workspace in list(workspaces.items()):
            self.set_output_for_workspaces(workspace_type, workspace)

        # Set the output monitor workspaces
        for workspace_type, workspace in list(workspace_monitors.items()):
            self.set_output_for_monitor_workspaces(workspace_type, workspace)
Esempio n. 15
0
    def PyExec(self):
        """Executes the data reduction workflow."""
        progress = Progress(self, 0.0, 1.0, 9)
        report = common.Report()
        subalgLogging = False
        if self.getProperty(common.PROP_SUBALG_LOGGING).value == common.SUBALG_LOGGING_ON:
            subalgLogging = True
        wsNamePrefix = self.getProperty(common.PROP_OUTPUT_WS).valueAsStr
        cleanupMode = self.getProperty(common.PROP_CLEANUP_MODE).value
        wsNames = common.NameSource(wsNamePrefix, cleanupMode)
        wsCleanup = common.IntermediateWSCleanup(cleanupMode, subalgLogging)

        # The variables 'mainWS' and 'monWS shall hold the current main
        # data throughout the algorithm.

        # Get input workspace.
        progress.report('Loading inputs')
        mainWS = self._inputWS(wsNames, wsCleanup, subalgLogging)

        progress.report('Applying diagnostics')
        mainWS = self._applyDiagnostics(mainWS, wsNames, wsCleanup, subalgLogging)

        # Vanadium normalization.
        progress.report('Normalising to vanadium')
        mainWS = self._normalizeToVana(mainWS, wsNames, wsCleanup, report, subalgLogging)

        # Convert units from TOF to energy.
        progress.report('Converting to energy')
        mainWS = self._convertTOFToDeltaE(mainWS, wsNames, wsCleanup,
                                          subalgLogging)

        # KiKf conversion.
        mainWS = self._correctByKiKf(mainWS, wsNames,
                                     wsCleanup, subalgLogging)

        # Rebinning.
        progress.report('Rebinning in energy')
        mainWS = self._rebinInW(mainWS, wsNames, wsCleanup, report,
                                subalgLogging)

        # Divide the energy transfer workspace by bin widths.
        mainWS = self._convertToDistribution(mainWS, wsNames, wsCleanup, subalgLogging)

        # Detector efficiency correction.
        progress.report('Correcting detector efficiency')
        mainWS = self._correctByDetectorEfficiency(mainWS, wsNames,
                                                   wsCleanup, subalgLogging)

        progress.report('Grouping detectors')
        mainWS = self._groupDetectors(mainWS, wsNames, wsCleanup,
                                      subalgLogging)

        self._outputWSConvertedToTheta(mainWS, wsNames, wsCleanup,
                                       subalgLogging)

        progress.report('Converting to q')
        mainWS = self._sOfQW(mainWS, wsNames, wsCleanup, report, subalgLogging)
        mainWS = self._transpose(mainWS, wsNames, wsCleanup, subalgLogging)
        self._finalize(mainWS, wsCleanup, report)
        progress.report('Done')
Esempio n. 16
0
    def PyExec(self):
        # Progress reporter for algorithm initialization
        prog_reporter = Progress(self, start=0.0, end=0.1, nreports=4)

        raw_xvals, raw_yvals, raw_error, error_ws = self.load_data(
            prog_reporter)

        # Convert the data to point data
        prog_reporter.report('Converting to point data')
        raw_data_ws = ConvertToPointData(error_ws, StoreInADS=False)
        raw_xvals = raw_data_ws.readX(0).copy()
        raw_yvals = raw_data_ws.readY(0).copy()

        raw_xvals, raw_yvals, raw_error = self.crop_data(
            raw_xvals, raw_yvals, raw_error, prog_reporter)

        # Find the best peaks
        (peakids, peak_table, refit_peak_table), baseline = self.process(
            raw_xvals,
            raw_yvals,
            raw_error,
            acceptance=self._acceptance,
            average_window=self._smooth_window,
            bad_peak_to_consider=self._bad_peak_to_consider,
            use_poisson=self._use_poisson_cost,
            peak_width_estimate=self._estimate_peak_sigma,
            fit_to_baseline=self._fit_to_baseline,
            prog_reporter=prog_reporter)

        if self._plot_peaks:
            self.plot_peaks(raw_xvals, raw_yvals, baseline, peakids)

        self.set_output_properties(peak_table, refit_peak_table)
Esempio n. 17
0
 def setUp(self):
     self.sample = self.getPropertyValue('SampleRuns').split(',')
     self.absorber = self.getPropertyValue('AbsorberRuns').split(',')
     self.beam = self.getPropertyValue('BeamRuns').split(',')
     self.flux = self.getPropertyValue('FluxRuns').split(',')
     self.container = self.getPropertyValue('ContainerRuns').split(',')
     self.stransmission = self.getPropertyValue('SampleTransmissionRuns')
     self.ctransmission = self.getPropertyValue('ContainerTransmissionRuns')
     self.btransmission = self.getPropertyValue('TransmissionBeamRuns')
     self.atransmission = self.getPropertyValue('TransmissionAbsorberRuns')
     self.sensitivity = self.getPropertyValue('SensitivityMaps') \
         .replace(' ', '').split(',')
     self.default_mask = self.getPropertyValue('DefaultMaskFile')
     self.mask = self.getPropertyValue('MaskFiles') \
         .replace(' ', '').split(',')
     self.reference = self.getPropertyValue('ReferenceFiles') \
         .replace(' ', '').split(',')
     self.output = self.getPropertyValue('OutputWorkspace')
     self.output_panels = self.output + "_panels"
     self.output_sens = self.getPropertyValue('SensitivityOutputWorkspace')
     self.normalise = self.getPropertyValue('NormaliseBy')
     self.theta_dependent = self.getProperty('ThetaDependent').value
     self.radius = self.getProperty('BeamRadius').value
     self.dimensionality = len(self.sample)
     self.progress = Progress(self, start=0.0, end=1.0, nreports=10 * self.dimensionality)
     self.cleanup = self.getProperty('ClearCorrected2DWorkspace').value
     self.n_wedges = self.getProperty('NumberOfWedges').value
     self.maxqxy = self.getPropertyValue('MaxQxy').split(',')
     self.deltaq = self.getPropertyValue('DeltaQ').split(',')
     self.output_type = self.getPropertyValue('OutputType')
Esempio n. 18
0
    def PyExec(self):
        # Get the correct SANS move strategy from the SANSMaskFactory
        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")
Esempio n. 19
0
    def PyExec(self):

        self.setUp()

        # total number of (unsummed) runs
        total = self._sample_files.count(',')+self._background_files.count(',')+self._calibration_files.count(',')

        self._progress = Progress(self, start=0.0, end=1.0, nreports=total)

        self._reduce_multiple_runs(self._sample_files, self._SAMPLE)

        if self._background_files:

            self._reduce_multiple_runs(self._background_files, self._BACKGROUND)

            back_ws = self._red_ws + '_' + self._BACKGROUND

            Scale(InputWorkspace=back_ws, Factor=self._back_scaling, OutputWorkspace=back_ws)

            if self._back_option == 'Sum':
                self._integrate(self._BACKGROUND, self._SAMPLE)
            else:
                self._interpolate(self._BACKGROUND, self._SAMPLE)

            self._subtract_background(self._BACKGROUND, self._SAMPLE)

            DeleteWorkspace(back_ws)

        if self._calibration_files:

            self._reduce_multiple_runs(self._calibration_files, self._CALIBRATION)

            if self._background_calib_files:
                self._reduce_multiple_runs(self._background_calib_files, self._BACKCALIB)

                back_calib_ws = self._red_ws + '_' + self._BACKCALIB

                Scale(InputWorkspace=back_calib_ws, Factor=self._back_calib_scaling, OutputWorkspace=back_calib_ws)

                if self._back_calib_option == 'Sum':
                    self._integrate(self._BACKCALIB, self._CALIBRATION)
                else:
                    self._interpolate(self._BACKCALIB, self._CALIBRATION)

                self._subtract_background(self._BACKCALIB, self._CALIBRATION)

                DeleteWorkspace(back_calib_ws)

            if self._calib_option == 'Sum':
                self._integrate(self._CALIBRATION, self._SAMPLE)
            else:
                self._interpolate(self._CALIBRATION, self._SAMPLE)

            self._calibrate()

            DeleteWorkspace(self._red_ws + '_' + self._CALIBRATION)

        self.log().debug('Run files map is :'+str(self._all_runs))

        self.setProperty('OutputWorkspace',self._red_ws)
    def PyExec(self):
        """Executes the data reduction workflow."""
        progress = Progress(self, 0.0, 1.0, 4)
        subalgLogging = False
        if self.getProperty(
                common.PROP_SUBALG_LOGGING).value == common.SUBALG_LOGGING_ON:
            subalgLogging = True
        wsNamePrefix = self.getProperty(common.PROP_OUTPUT_WS).valueAsStr
        cleanupMode = self.getProperty(common.PROP_CLEANUP_MODE).value
        wsNames = common.NameSource(wsNamePrefix, cleanupMode)
        wsCleanup = common.IntermediateWSCleanup(cleanupMode, subalgLogging)

        progress.report('Loading inputs')
        mainWS = self._inputWS(wsCleanup)

        progress.report('Applying self shielding corrections')
        mainWS, applied = self._applyCorrections(mainWS, wsNames, wsCleanup,
                                                 subalgLogging)

        progress.report('Subtracting EC')
        mainWS, subtracted = self._subtractEC(mainWS, wsNames, wsCleanup,
                                              subalgLogging)

        if not applied and not subtracted:
            mainWS = self._cloneOnly(mainWS, wsNames, wsCleanup, subalgLogging)

        self._finalize(mainWS, wsCleanup)
        progress.report('Done')
Esempio n. 21
0
    def _perform_two_peak_fits(self, workspace_names, x_min, x_max):
        result_workspaces = []
        chi_workspaces = []
        run_numbers = []
        for workspace_name in workspace_names:
            number_of_histograms = mtd[workspace_name].getNumberHistograms()

            progress_tracker = Progress(self, 0.3, 1.0,
                                        number_of_histograms + 1)
            progress_tracker.report(
                'Finding temperature for {0}...'.format(workspace_name))

            if self._temperatures is None:
                run_number = str(mtd[workspace_name].getRunNumber())
                run_numbers.append(run_number)

            result = workspace_name[:-3] + 'fit'

            for index in range(number_of_histograms):
                progress_tracker.report('Fitting {0}-sp{1}...'.format(
                    workspace_name, index))
                IndirectTwoPeakFit(SampleWorkspace=workspace_name,
                                   EnergyMin=x_min,
                                   EnergyMax=x_max,
                                   OutputName=result)

            result_workspaces.append(result + '_Result')
            chi_workspaces.append(result + '_ChiSq')
        return result_workspaces, chi_workspaces, run_numbers
Esempio n. 22
0
    def PyExec(self):
        """Execute the data collection workflow."""
        progress = Progress(self, 0.0, 1.0, 9)
        report = common.Report()
        subalgLogging = self.getProperty(
            common.PROP_SUBALG_LOGGING).value == common.SUBALG_LOGGING_ON
        wsNamePrefix = self.getProperty(common.PROP_OUTPUT_WS).valueAsStr
        cleanupMode = self.getProperty(common.PROP_CLEANUP_MODE).value
        wsNames = common.NameSource(wsNamePrefix, cleanupMode)
        wsCleanup = common.IntermediateWSCleanup(cleanupMode, subalgLogging)

        # The variables 'mainWS' and 'monWS shall hold the current main
        # data throughout the algorithm.

        # Get input workspace.
        progress.report('Loading inputs')
        mainWS = self._inputWS(wsNames, wsCleanup, subalgLogging)

        # Extract monitors to a separate workspace.
        progress.report('Extracting monitors')
        mainWS, monWS = self._separateMons(mainWS, wsNames, wsCleanup,
                                           subalgLogging)

        # Save the main workspace for later use, if needed.
        rawWS = None
        if not self.getProperty(common.PROP_OUTPUT_RAW_WS).isDefault:
            rawWS = mainWS
            wsCleanup.protect(rawWS)

        # Normalisation to monitor/time, if requested.
        progress.report('Normalising to monitor/time')
        monWS = self._flatBkgMon(monWS, wsNames, wsCleanup, subalgLogging)
        monEPPWS = self._createEPPWSMon(monWS, wsNames, wsCleanup,
                                        subalgLogging)
        mainWS = self._normalize(mainWS, monWS, monEPPWS, wsNames, wsCleanup,
                                 report, subalgLogging)

        # Time-independent background.
        progress.report('Calculating backgrounds')
        mainWS = self._flatBkgDet(mainWS, wsNames, wsCleanup, report,
                                  subalgLogging)

        # Calibrate incident energy, if requested.
        progress.report('Calibrating incident energy')
        mainWS, monWS = self._calibrateEi(mainWS, monWS, monEPPWS, wsNames,
                                          wsCleanup, report, subalgLogging)
        wsCleanup.cleanup(monWS, monEPPWS)

        progress.report('Correcting TOF')
        mainWS = self._correctTOFAxis(mainWS, wsNames, wsCleanup, report,
                                      subalgLogging)
        self._outputRaw(mainWS, rawWS, subalgLogging)

        # Find elastic peak positions.
        progress.report('Calculating EPPs')
        self._outputDetEPPWS(mainWS, wsNames, wsCleanup, report, subalgLogging)

        self._finalize(mainWS, wsCleanup, report)
        progress.report('Done')
Esempio n. 23
0
    def PyExec(self):
        # setup progress bar
        prog_reporter = Progress(self, start=0.0, end=1.0, nreports=3)
        # Get input
        ws_list = self.getProperty("PeakWorkspaces").value
        a = self.getProperty('a').value
        b = self.getProperty('b').value
        c = self.getProperty('c').value
        alpha = self.getProperty('alpha').value
        beta = self.getProperty('beta').value
        gamma = self.getProperty('gamma').value
        self.tol = self.getProperty('Tolerance').value

        # Find initial UB and use to index peaks in all runs
        prog_reporter.report(1, "Find initial UB for peak indexing")
        self.find_initial_indexing(
            a, b, c, alpha, beta, gamma,
            ws_list)  # removes runs from ws_list if can't index

        # optimize the lattice parameters across runs (i.e. B matrix)
        prog_reporter.report(2, "Optimize B")

        def fobj(x):
            return self.calcResiduals(x, ws_list)

        alatt0 = [a, b, c, alpha, beta, gamma]
        try:
            alatt, cov, info, msg, ier = leastsq(fobj,
                                                 x0=alatt0,
                                                 full_output=True)
            # eval the fobj at optimal solution to set UB (leastsq iteration stops at a next sub-optimal solution)
            fobj(alatt)
        except ValueError:
            logger.error(
                "CalculateUMatrix failed - check initial lattice parameters and tolerance provided."
            )
            return

        success = ier in [
            1, 2, 3, 4
        ] and cov is not None  # cov is None when matrix is singular
        if success:
            # calculate errors
            dof = sum(
                [self.child_IndexPeaks(ws, RoundHKLs=True)
                 for ws in ws_list]) - len(alatt0)
            err = np.sqrt(abs(np.diag(cov)) * (info['fvec']**2).sum() / dof)
            for wsname in ws_list:
                ws = AnalysisDataService.retrieve(wsname)
                ws.sample().getOrientedLattice().setError(*err)
            logger.notice(
                f"Lattice parameters successfully refined for workspaces: {ws_list}\n"
                f"Lattice Parameters: {np.array2string(alatt, precision=6)}\n"
                f"Parameter Errors  : {np.array2string(err, precision=6)}")
        else:
            logger.warning(
                f"Error in optimization of lattice parameters: {msg}")
        # complete progress
        prog_reporter.report(3, "Done")
    def _setup(self):
        setup_prog = Progress(self, start=0.00, end=0.01, nreports=2)
        setup_prog.report('Obtaining input properties')
        self._sample_ws_name = self.getPropertyValue('SampleWorkspace')
        self._sample_density_type = self.getPropertyValue('SampleDensityType')
        self._sample_density = self.getProperty('SampleDensity').value
        self._sample_inner_radius = self.getProperty('SampleInnerRadius').value
        self._sample_outer_radius = self.getProperty('SampleOuterRadius').value
        self._number_can = 1

        self._can_ws_name = self.getPropertyValue('CanWorkspace')
        self._use_can = self._can_ws_name != ''
        self._can_density_type = self.getPropertyValue('CanDensityType')
        self._can_density = self.getProperty('CanDensity').value
        self._can_outer_radius = self.getProperty('CanOuterRadius').value
        if self._use_can:
            self._number_can = 2

        self._step_size = self.getProperty('StepSize').value
        self._radii = np.zeros(self._number_can + 1)
        self._radii[0] = self._sample_inner_radius
        self._radii[1] = self._sample_outer_radius
        if self._use_can:
            self._radii[2] = self._can_outer_radius

        setup_prog.report('Obtaining beam values')
        beam_width = self.getProperty('BeamWidth').value
        beam_height = self.getProperty('BeamHeight').value
        self._beam = [
            beam_height, 0.5 * beam_width, -0.5 * beam_width, (beam_width / 2),
            -(beam_width / 2), 0.0, beam_height, 0.0, beam_height
        ]

        self._interpolate = self.getProperty('Interpolate').value
        self._number_wavelengths = self.getProperty('NumberWavelengths').value

        self._emode = self.getPropertyValue('Emode')
        self._efixed = self.getProperty('Efixed').value

        if self._emode == 'Efixed':
            logger.information('No interpolation is possible in Efixed mode.')
            self._interpolate = False

        if self._efixed == 0. and self._emode != 'Elastic':
            # In all the modes other than elastic, efixed is needed.
            # So try to get from instrument if the input is not set.
            try:
                self._efixed = self._getEfixed()
                logger.information('Found Efixed = {0}'.format(self._efixed))
            except ValueError:
                raise RuntimeError(
                    'Could not find the Efixed parameter in the instrument. '
                    'Please specify manually.')

        # purge the lists
        self._angles = list()
        self._waves = list()

        self._output_ws_name = self.getPropertyValue('OutputWorkspace')
Esempio n. 25
0
    def PyExec(self):

        self.setUp()

        self._filter_all_input_files()

        if self._background_file:
            background = '__background_'+self._red_ws
            IndirectILLEnergyTransfer(Run = self._background_file, OutputWorkspace = background, **self._common_args)
            Scale(InputWorkspace=background ,Factor=self._back_scaling,OutputWorkspace=background)

        if self._calibration_file:
            calibration = '__calibration_'+self._red_ws
            IndirectILLEnergyTransfer(Run = self._calibration_file, OutputWorkspace = calibration, **self._common_args)

            if self._background_calib_files:
                back_calibration = '__calibration_back_'+self._red_ws
                IndirectILLEnergyTransfer(Run = self._background_calib_files, OutputWorkspace = back_calibration, **self._common_args)
                Scale(InputWorkspace=back_calibration, Factor=self._back_calib_scaling, OutputWorkspace=back_calibration)
                Minus(LHSWorkspace=calibration, RHSWorkspace=back_calibration, OutputWorkspace=calibration)

            # MatchPeaks does not play nicely with the ws groups
            for ws in mtd[calibration]:
                MatchPeaks(InputWorkspace=ws.getName(), OutputWorkspace=ws.getName(), MaskBins=True, BinRangeTable = '')

            Integration(InputWorkspace=calibration,RangeLower=self._peak_range[0],RangeUpper=self._peak_range[1],
                        OutputWorkspace=calibration)
            self._warn_negative_integral(calibration,'in calibration run.')

        if self._unmirror_option == 5 or self._unmirror_option == 7:
            alignment = '__alignment_'+self._red_ws
            IndirectILLEnergyTransfer(Run = self._alignment_file, OutputWorkspace = alignment, **self._common_args)

        runs = self._sample_file.split(',')

        self._progress = Progress(self, start=0.0, end=1.0, nreports=len(runs))

        for run in runs:
            self._reduce_run(run)

        if self._background_file:
            DeleteWorkspace(background)

        if self._calibration_file:
            DeleteWorkspace(calibration)

        if self._background_calib_files:
            DeleteWorkspace(back_calibration)

        if self._unmirror_option == 5 or self._unmirror_option == 7:
            DeleteWorkspace(alignment)

        GroupWorkspaces(InputWorkspaces=self._ws_list,OutputWorkspace=self._red_ws)

        # unhide the final workspaces, i.e. remove __ prefix
        for ws in mtd[self._red_ws]:
            RenameWorkspace(InputWorkspace=ws,OutputWorkspace=ws.getName()[2:])

        self.setProperty('OutputWorkspace',self._red_ws)
Esempio n. 26
0
 def setUp(self):
     self.runs = self.getPropertyValue('SampleRuns').split(',')
     self.scan_parameter = self.getPropertyValue('Observable')
     self.mask_start_pixels = self.getProperty('MaskPixelsFromStart').value
     self.mask_end_pixels = self.getProperty('MaskPixelsFromEnd').value
     self.transpose = self.getProperty("Transpose").value
     self.output = self.getPropertyValue('OutputWorkspace')
     self.progress = Progress(self, start=0.0, end=1.0, nreports=10)
Esempio n. 27
0
    def PyExec(self):
        """ Main execution body
        """

        self.vanaws = self.getProperty(
            "VanadiumWorkspace").value  # returns workspace instance
        outws_name = self.getPropertyValue(
            "OutputWorkspace")  # returns workspace name (string)
        eppws = self.getProperty("EPPTable").value
        nhist = self.vanaws.getNumberHistograms()
        prog_reporter = Progress(self, start=0.0, end=1.0, nreports=nhist + 1)

        # calculate array of Debye-Waller factors
        dwf = self.calculate_dwf()

        # for each detector: fit gaussian to get peak_centre and fwhm
        # sum data in the range [peak_centre - 3*fwhm, peak_centre + 3*fwhm]
        dataX = self.vanaws.readX(0)
        coefY = np.zeros(nhist)
        coefE = np.zeros(nhist)
        instrument = self.vanaws.getInstrument()
        detID_offset = self.get_detID_offset()
        peak_centre = eppws.column('PeakCentre')
        sigma = eppws.column('Sigma')

        for idx in range(nhist):
            prog_reporter.report("Setting %dth spectrum" % idx)
            dataY = self.vanaws.readY(idx)
            det = instrument.getDetector(idx + detID_offset)
            if np.max(dataY) == 0 or det.isMasked():
                coefY[idx] = 0.
                coefE[idx] = 0.
            else:
                dataE = self.vanaws.readE(idx)
                fwhm = sigma[idx] * 2. * np.sqrt(2. * np.log(2.))
                idxmin = (np.fabs(dataX - peak_centre[idx] +
                                  3. * fwhm)).argmin()
                idxmax = (np.fabs(dataX - peak_centre[idx] -
                                  3. * fwhm)).argmin()
                coefY[idx] = dwf[idx] * sum(dataY[idxmin:idxmax + 1])
                coefE[idx] = dwf[idx] * sum(dataE[idxmin:idxmax + 1])

        # create X array, X data are the same for all detectors, so
        coefX = np.zeros(nhist)
        coefX.fill(dataX[0])

        create = self.createChildAlgorithm("CreateWorkspace")
        create.setPropertyValue('OutputWorkspace', outws_name)
        create.setProperty('ParentWorkspace', self.vanaws)
        create.setProperty('DataX', coefX)
        create.setProperty('DataY', coefY)
        create.setProperty('DataE', coefE)
        create.setProperty('NSpec', nhist)
        create.setProperty('UnitX', 'TOF')
        create.execute()
        outws = create.getProperty('OutputWorkspace').value

        self.setProperty("OutputWorkspace", outws)
Esempio n. 28
0
    def PyExec(self):
        self.setUp()
        sample_runs = self.getPropertyValue('Runs').split(',')
        processes = ['Cadmium', 'Empty', 'Vanadium', 'Sample']
        nReports = np.array([3, 3, 3, 3])
        nReports *= len(sample_runs)
        nReports += 1  # for the wrapping up report
        if self.masking:
            nReports += 1
        progress = Progress(self,
                            start=0.0,
                            end=1.0,
                            nreports=int(nReports[processes.index(
                                self.process)]))
        output_samples = []
        for sample_no, sample in enumerate(sample_runs):
            progress.report("Collecting data")
            ws = self._collect_data(sample,
                                    vanadium=self.process == 'Vanadium')
            if self.cadmium:
                self._subtract_cadmium(ws)
            if self.masking and sample_no == 0:  # prepares masks once, and when the instrument is known
                progress.report("Preparing masks")
                self.mask_ws = self._prepare_masks()
            if self.process == 'Vanadium':
                progress.report("Processing vanadium")
                ws_sofq, ws_softw, ws_diag, ws_integral = self._process_vanadium(
                    ws)
                current_output = [ws_sofq, ws_softw, ws_diag, ws_integral]
                progress.report("Renaming output")
                current_output = self._rename_workspaces(current_output)
                output_samples.extend(current_output)
            elif self.process == 'Sample':
                progress.report("Processing sample")
                sample_sofq, sample_softw = self._process_sample(ws, sample_no)
                current_output = np.array([sample_sofq, sample_softw])
                current_output = current_output[[
                    isinstance(elem, str) for elem in current_output
                ]]
                progress.report("Renaming output")
                current_output = self._rename_workspaces(current_output)
                output_samples.extend(current_output)
            else:  # Empty or Cadmium
                progress.report("Renaming output")
                current_output = [ws]
                current_output = self._rename_workspaces(current_output)
                self._group_detectors(current_output)
                output_samples.extend(current_output)
            if self.save_output:
                self._save_output(current_output)

        progress.report("Grouping outputs")
        GroupWorkspaces(InputWorkspaces=output_samples,
                        OutputWorkspace=self.output)
        if self.clear_cache:  # final clean up
            self._clean_up(self.to_clean)
        self._print_report()
        self.setProperty('OutputWorkspace', mtd[self.output])
Esempio n. 29
0
    def PyExec(self):

        # get input
        inws = self.getProperty("InputWorkspace").value
        niter = self.getProperty("NIterations").value
        xwindow = self.getProperty("XWindow").value
        doSGfilter = self.getProperty('ApplyFilterSG').value

        # make output workspace
        clone_alg = self.createChildAlgorithm("CloneWorkspace",
                                              enableLogging=False)
        clone_alg.setProperty("InputWorkspace", inws)
        clone_alg.setProperty("OutputWorkspace",
                              self.getProperty("OutputWorkspace").valueAsStr)
        clone_alg.execute()
        outws = clone_alg.getProperty("OutputWorkspace").value

        # loop over all spectra
        nbins = inws.blocksize()
        nspec = inws.getNumberHistograms()
        prog_reporter = Progress(self, start=0.0, end=1.0, nreports=nspec)
        for ispec in range(0, nspec):
            prog_reporter.report()

            # get n points in convolution window
            binwidth = np.mean(np.diff(inws.readX(ispec)))
            nwindow = int(np.ceil(xwindow / binwidth))
            if not nwindow % 2:
                nwindow += 1

            if nwindow < self.MIN_WINDOW_SIZE:
                raise RuntimeError(
                    'Convolution window must have at least three points')
            elif not nwindow < nbins:
                # not effective due to edge effects of the convolution
                raise RuntimeError(
                    "Data has must have at least the number of points as the convolution window"
                )

            # do initial filter to remove very high intensity points
            if doSGfilter:
                ybg = savgol_filter(inws.readY(ispec), nwindow, polyorder=1)
            else:
                ybg = np.copy(inws.readY(ispec))
            Ibar = np.mean(ybg)
            Imin = np.min(ybg)
            ybg[ybg > (Ibar + 2 * (Ibar - Imin))] = (Ibar + 2 * (Ibar - Imin))

            # perform iterative smoothing
            ybg = self.doIterativeSmoothing(ybg, nwindow, niter)

            # replace intensity in output spectrum with background
            outws.setY(ispec, ybg)
            outws.setE(ispec, np.zeros(ybg.shape))

        # set output
        self.setProperty("OutputWorkspace", outws)
Esempio n. 30
0
    def PyExec(self):

        self.setUp()

        self._progress = Progress(self,
                                  start=0.0,
                                  end=1.0,
                                  nreports=self._run_file.count('+'))

        LoadAndMerge(Filename=self._run_file,
                     OutputWorkspace=self._red_ws,
                     LoaderName='LoadILLIndirect')

        self._instrument = mtd[self._red_ws].getInstrument()

        self._load_map_file()

        run = str(
            mtd[self._red_ws].getRun().getLogData('run_number').value)[:6]

        self._ws = self._red_ws + '_' + run

        if self._run_file.count('+') > 0:  # multiple summed files
            self._ws += '_multiple'

        RenameWorkspace(InputWorkspace=self._red_ws, OutputWorkspace=self._ws)

        LoadParameterFile(Workspace=self._ws, Filename=self._parameter_file)

        self._efixed = self._instrument.getNumberParameter('Efixed')[0]

        self._setup_run_properties()

        if self._reduction_type == 'BATS':
            self._reduce_bats(self._ws)
        else:
            if self._mirror_sense == 14:  # two wings, extract left and right

                size = mtd[self._ws].blocksize()
                left = self._ws + '_left'
                right = self._ws + '_right'
                _extract_workspace(self._ws, left, 0, int(size / 2))
                _extract_workspace(self._ws, right, int(size / 2), size)
                DeleteWorkspace(self._ws)
                self._reduce_one_wing(left)
                self._reduce_one_wing(right)
                GroupWorkspaces(InputWorkspaces=[left, right],
                                OutputWorkspace=self._red_ws)

            elif self._mirror_sense == 16:  # one wing

                self._reduce_one_wing(self._ws)
                GroupWorkspaces(InputWorkspaces=[self._ws],
                                OutputWorkspace=self._red_ws)

        self.setProperty('OutputWorkspace', self._red_ws)