Example #1
0
    def pre_process(self):
        self._reduction_steps = []

        loadData = steps.LoadData()
        loadData.set_ws_list(self._data_files)
        loadData.set_sum(self._sum)
        loadData.set_load_logs(self._load_logs)
        loadData.set_detector_range(self._detector_range[0],
                                    self._detector_range[1])
        loadData.set_parameter_file(self._parameter_file)
        loadData.set_extra_load_opts(self._extra_load_opts)
        loadData.execute(self, None)

        if loadData.contains_event_data and (self._rebin_string is None
                                             or self._rebin_string is ''):
            logger.warning(
                'Reductins of event data without rebinning may give bad data!')

        self._multiple_frames = loadData.is_multiple_frames()

        if (self._info_table_props is not None):
            wsNames = loadData.get_ws_list().keys()
            wsNameList = ", ".join(wsNames)
            propsList = ", ".join(self._info_table_props)
            CreateLogPropertyTable(OutputWorkspace="RunInfo",
                                   InputWorkspaces=wsNameList,
                                   LogPropertyNames=propsList,
                                   GroupPolicy="First")

        if (self._sum):
            self._data_files = loadData.get_ws_list()

        self._setup_steps()
Example #2
0
def generate_and_save_focus_output(instrument, processed_spectra, run_details,
                                   attenuation_filepath, focus_mode):
    output_file_paths = instrument._generate_out_file_paths(
        run_details=run_details)
    if instrument._inst_settings.tt_mode == "custom" and len(
            processed_spectra) != 14:
        logger.warning(
            'Custom grouping file does not contain 14 groups so switching to focus_mode=Mods'
        )
        processed_nexus_files = _focus_mode_mods(
            output_file_paths=output_file_paths,
            calibrated_spectra=processed_spectra)
    elif focus_mode == "all":
        processed_nexus_files = _focus_mode_all(
            output_file_paths=output_file_paths,
            processed_spectra=processed_spectra,
            attenuation_filepath=attenuation_filepath)
    elif focus_mode == "groups":
        processed_nexus_files = _focus_mode_groups(
            output_file_paths=output_file_paths,
            calibrated_spectra=processed_spectra)
    elif focus_mode == "trans":
        processed_nexus_files = _focus_mode_trans(
            output_file_paths=output_file_paths,
            calibrated_spectra=processed_spectra,
            attenuation_filepath=attenuation_filepath)
    elif focus_mode == "mods":
        processed_nexus_files = _focus_mode_mods(
            output_file_paths=output_file_paths,
            calibrated_spectra=processed_spectra)
    else:
        raise ValueError("Focus mode '" + str(focus_mode) + "' unknown.")

    return processed_nexus_files
Example #3
0
        def create_table_item(column, itemname, invalid_value_count, log_size,
                              callable, *args):
            item = QStandardItem()
            item.setEditable(False)
            #format if there is invalid data entries
            if invalid_value_count == -1:
                item.setData(DEEP_RED, Qt.BackgroundRole)
                item.setToolTip(
                    "All of the values in the log are marked invalid, none of them are filtered."
                )
            elif invalid_value_count > 0:
                saturation = 10 + (170 * (invalid_value_count /
                                          (log_size + invalid_value_count)))
                item.setData(QColor.fromHsv(0, saturation, 255),
                             Qt.BackgroundRole)
                aux_verb = "is" if invalid_value_count == 1 else "are"
                item.setToolTip(
                    f"{invalid_value_count}/{log_size+invalid_value_count} of the values in the log"
                    f" {aux_verb} marked invalid, and {aux_verb} filtered.")
            try:
                item.setText(callable(*args))
            except Exception as exc:
                logger.warning("Error setting column {} for log {}: {}".format(
                    column, itemname, str(exc)))

            return item
Example #4
0
 def open_files_in_new_tabs(self, filepaths, startup=False):
     for filepath in filepaths:
         try:
             self.open_file_in_new_tab(filepath, startup)
         except IOError as io_error:
             logger.warning("Could not load file:\n  {}"
                            "".format(io_error))
Example #5
0
    def populate_interfaces_menu(self):
        interface_dir = ConfigService['mantidqt.python_interfaces_directory']
        items = ConfigService['mantidqt.python_interfaces'].split()

        # list of custom interfaces that are not qt4/qt5 compatible
        GUI_BLACKLIST = ['ISIS_Reflectometry_Old.py',
                         'ISIS_SANS_v2_experimental.py',
                         'Frequency_Domain_Analysis.py',
                         'Elemental_Analysis.py']

        # detect the python interfaces
        interfaces = {}
        for item in items:
            key, scriptname = item.split('/')
            if not os.path.exists(os.path.join(interface_dir, scriptname)):
                logger.warning('Failed to find script "{}" in "{}"'.format(scriptname, interface_dir))
                continue
            if scriptname in GUI_BLACKLIST:
                logger.information('Not adding gui "{}"'.format(scriptname))
                continue
            temp = interfaces.get(key, [])
            temp.append(scriptname)
            interfaces[key] = temp

        # add the interfaces to the menu
        keys = list(interfaces.keys())
        keys.sort()
        for key in keys:
            submenu = self.interfaces_menu.addMenu(key)
            names = interfaces[key]
            names.sort()
            for name in names:
                action = submenu.addAction(name.replace('.py', '').replace('_', ' '))
                script = os.path.join(interface_dir, name)
                action.triggered.connect(lambda checked, script=script: self.launch_custom_gui(script))
Example #6
0
 def load_existing_calibration_files(self, file_path):
     if not path.exists(file_path):
         msg = "Could not open GSAS calibration file: " + file_path
         logger.warning(msg)
         raise
     try:
         instrument, ceria_no, params_table = self.get_info_from_file(
             file_path)
         self.update_calibration_params_table(params_table)
     except RuntimeError:
         logger.error("Invalid file selected: " + file_path)
         raise
     try:
         bank = EnggUtils.load_relevant_calibration_files(file_path)
     except Exception as e:
         logger.error(
             "Unable to loading calibration files corresponding to " +
             file_path + ". Error: " + str(e))
         raise
     try:
         grp_ws_name, roi_text = EnggUtils.load_custom_grouping_workspace(
             file_path)
     except Exception as e:
         logger.error(
             "Unable to load grouping workspace corresponding to " +
             file_path + ". Error: " + str(e))
         raise
     return instrument, ceria_no, grp_ws_name, roi_text, bank
Example #7
0
    def check_for_recover_checkpoint(self):
        """
        Should a recovery attempt/offer occur?
        :return: Boolean; True if recover else False
        """
        try:
            # Clean directory first
            self._remove_empty_folders_from_dir(
                self.recovery_directory_hostname)

            # One pid_checkpoint equals one mantid process. If the number of checkpoints is less than the number of
            # (other) mantid processes then a recovery should occur.
            pid_checkpoints = self.listdir_fullpath(
                self.recovery_directory_hostname)
            num_of_other_mantid_processes = self._number_of_other_workbench_processes(
            )
            return len(pid_checkpoints) != 0 and len(
                pid_checkpoints) > num_of_other_mantid_processes
        except Exception as exc:
            if isinstance(exc, KeyboardInterrupt):
                raise

            # log and return no recovery possible
            logger.warning(
                "Error checking if project can be recovered: {}".format(
                    str(exc)))
            return False
Example #8
0
    def get_cross_section(scattering: str = 'Total',
                          nucleons_number: Optional[int] = None,
                          *,
                          protons_number: int) -> float:
        """
        Calculates cross section for the given element.
        :param scattering: Type of cross-section: 'Incoherent', 'Coherent' or 'Total'
        :param protons_number: number of protons in the given type fo atom
        :param nucleons_number: number of nucleons in the given type of atom
        :returns: cross section for that element
        """
        if nucleons_number is not None:
            try:
                atom = Atom(a_number=nucleons_number, z_number=protons_number)
            # isotopes are not implemented for all elements so use different constructor in that cases
            except RuntimeError:
                logger.warning(
                    f"Could not find data for isotope {nucleons_number}, "
                    f"using default values for {protons_number} protons.")
                atom = Atom(z_number=protons_number)
        else:
            atom = Atom(z_number=protons_number)

        scattering_keys = {
            'Incoherent': 'inc_scatt_xs',
            'Coherent': 'coh_scatt_xs',
            'Total': 'tot_scatt_xs'
        }
        return atom.neutron()[scattering_keys[scattering]]
Example #9
0
 def create_total_scattering_pdf(self, **kwargs):
     if 'pdf_type' not in kwargs or kwargs['pdf_type'] not in [
             'G(r)', 'g(r)', 'RDF(r)'
     ]:
         kwargs['pdf_type'] = 'G(r)'
         logger.warning(
             'PDF type not specified or is invalid, defaulting to G(r)')
     self._inst_settings.update_attributes(kwargs=kwargs)
     # Generate pdf
     run_details = self._get_run_details(self._inst_settings.run_number)
     focus_file_path = self._generate_out_file_paths(
         run_details)["nxs_filename"]
     cal_file_name = os.path.join(self._inst_settings.calibration_dir,
                                  self._inst_settings.grouping_file_name)
     pdf_output = polaris_algs.generate_ts_pdf(
         run_number=self._inst_settings.run_number,
         focus_file_path=focus_file_path,
         merge_banks=self._inst_settings.merge_banks,
         q_lims=self._inst_settings.q_lims,
         cal_file_name=cal_file_name,
         sample_details=self._sample_details,
         delta_r=self._inst_settings.delta_r,
         delta_q=self._inst_settings.delta_q,
         pdf_type=self._inst_settings.pdf_type,
         lorch_filter=self._inst_settings.lorch_filter,
         freq_params=self._inst_settings.freq_params,
         debug=self._inst_settings.debug)
     return pdf_output
Example #10
0
    def _transform(self):
        """
        Run TransformToIqt.
        """
        from IndirectCommon import CheckHistZero, CheckHistSame, CheckAnalysers
        try:
            CheckAnalysers(self._sample, self._resolution)
        except ValueError:
            # A genuine error the shows that the two runs are incompatible
            raise
        except:
            # Checking could not be performed due to incomplete or no instrument
            logger.warning(
                'Could not check for matching analyser and reflection')

        # Process resolution data
        num_res_hist = CheckHistZero(self._resolution)[0]
        if num_res_hist > 1:
            CheckHistSame(self._sample, 'Sample', self._resolution,
                          'Resolution')

        iqt = CalculateIqt(InputWorkspace=self._sample,
                           ResolutionWorkspace=self._resolution,
                           EnergyMin=self._e_min,
                           EnergyMax=self._e_max,
                           EnergyWidth=self._e_width,
                           NumberOfIterations=self._number_of_iterations,
                           SeedValue=self._seed,
                           StoreInADS=False,
                           OutputWorkspace="__ciqt")

        # Set Y axis unit and label
        iqt.setYUnit('')
        iqt.setYUnitLabel('Intensity')
        return iqt
Example #11
0
    def readSettings(self, settings):
        qapp = QApplication.instance()

        # get the saved window geometry
        window_size = settings.get('MainWindow/size')
        if not isinstance(window_size, QSize):
            window_size = QSize(*window_size)
        window_pos = settings.get('MainWindow/position')
        if not isinstance(window_pos, QPoint):
            window_pos = QPoint(*window_pos)
        if settings.has('MainWindow/font'):
            font_string = settings.get('MainWindow/font').split(',')
            font = QFontDatabase().font(font_string[0], font_string[-1],
                                        int(font_string[1]))
            qapp.setFont(font)

        # reset font for ipython console to ensure it stays monospace
        self.ipythonconsole.console.reset_font()

        # make sure main window is smaller than the desktop
        desktop = QDesktopWidget()

        # this gives the maximum screen number if the position is off screen
        screen = desktop.screenNumber(window_pos)

        # recalculate the window size
        desktop_geom = desktop.availableGeometry(screen)
        w = min(desktop_geom.size().width(), window_size.width())
        h = min(desktop_geom.size().height(), window_size.height())
        window_size = QSize(w, h)

        # and position it on the supplied desktop screen
        x = max(window_pos.x(), desktop_geom.left())
        y = max(window_pos.y(), desktop_geom.top())
        if x + w > desktop_geom.right():
            x = desktop_geom.right() - w
        if y + h > desktop_geom.bottom():
            y = desktop_geom.bottom() - h
        window_pos = QPoint(x, y)

        # set the geometry
        self.resize(window_size)
        self.move(window_pos)

        # restore window state
        if settings.has('MainWindow/state'):
            if not self.restoreState(settings.get('MainWindow/state'),
                                     SAVE_STATE_VERSION):
                logger.warning(
                    "The previous layout of workbench is not compatible with this version, reverting to default layout."
                )
        else:
            self.setWindowState(Qt.WindowMaximized)

        # read in settings for children
        AlgorithmInputHistory().readSettings(settings)
        for widget in self.widgets:
            if hasattr(widget, 'readSettingsIfNotDone'):
                widget.readSettingsIfNotDone(settings)
Example #12
0
 def _do_show_algorithm_history(self, names):
     for name in names:
         if not isinstance(self._ads.retrieve(name), WorkspaceGroup):
             try:
                 AlgorithmHistoryWindow(self, name).show()
             except Exception as exception:
                 logger.warning("Could not open history of '{}'. " "".format(name))
                 logger.warning("{}: {}".format(type(exception).__name__, exception))
Example #13
0
    def _calculate_parameters(self):
        """
        Calculates the TransformToIqt parameters and saves in a table workspace.
        """
        CropWorkspace(InputWorkspace=self._sample,
                      OutputWorkspace='__TransformToIqt_sample_cropped',
                      Xmin=self._e_min,
                      Xmax=self._e_max)
        x_data = mtd['__TransformToIqt_sample_cropped'].readX(0)
        number_input_points = len(x_data) - 1
        num_bins = int(number_input_points / self._number_points_per_bin)
        self._e_width = (abs(self._e_min) + abs(self._e_max)) / num_bins

        try:
            instrument = mtd[self._sample].getInstrument()

            analyserName = instrument.getStringParameter('analyser')[0]
            analyser = instrument.getComponentByName(analyserName)

            if analyser is not None:
                logger.debug('Found %s component in instrument %s, will look for resolution there'
                             % (analyserName, instrument))
                resolution = analyser.getNumberParameter('resolution')[0]
            else:
                logger.debug('No %s component found on instrument %s, will look for resolution in top level instrument'
                             % (analyserName, instrument))
                resolution = instrument.getNumberParameter('resolution')[0]

            logger.information('Got resolution from IPF: %f' % resolution)

        except (AttributeError, IndexError):
            resolution = 0.0175
            logger.warning('Could not get resolution from IPF, using default value: %f' % (resolution))

        resolution_bins = int(round((2 * resolution) / self._e_width))

        if resolution_bins < 5:
            logger.warning('Resolution curve has <5 points. Results may be unreliable.')

        param_table = CreateEmptyTableWorkspace(OutputWorkspace=self._parameter_table)

        param_table.addColumn('int', 'SampleInputBins')
        param_table.addColumn('float', 'BinReductionFactor')
        param_table.addColumn('int', 'SampleOutputBins')
        param_table.addColumn('float', 'EnergyMin')
        param_table.addColumn('float', 'EnergyMax')
        param_table.addColumn('float', 'EnergyWidth')
        param_table.addColumn('float', 'Resolution')
        param_table.addColumn('int', 'ResolutionBins')

        param_table.addRow([number_input_points, self._number_points_per_bin, num_bins,
                            self._e_min, self._e_max, self._e_width,
                            resolution, resolution_bins])

        DeleteWorkspace('__TransformToIqt_sample_cropped')

        self.setProperty('ParameterWorkspace', param_table)
Example #14
0
 def _do_show_algorithm_history(self, names):
     for name in names:
         if not isinstance(self._ads.retrieve(name), WorkspaceGroup):
             try:
                 AlgorithmHistoryWindow(self, name).show()
             except Exception as exception:
                 logger.warning("Could not open history of '{}'. "
                                "".format(name))
                 logger.warning("{}: {}".format(type(exception).__name__, exception))
Example #15
0
    def get_compatible_workspaces(workspaces):
        matrix_workspaces = []
        for ws in workspaces:
            if isinstance(ws, MatrixWorkspace):
                matrix_workspaces.append(ws)
            else:
                # Log an error but carry on so valid workspaces can be plotted.
                logger.warning("{}: Expected MatrixWorkspace, found {}".format(ws.name(), ws.__class__.__name__))

        return matrix_workspaces
Example #16
0
 def _do_show_algorithm_history(self, names):
     for name in names:
         if any(
                 isinstance(self._ads.retrieve(name), ws_type)
                 for ws_type in [MatrixWorkspace, ITableWorkspace]):
             AlgorithmHistoryWindow(self, name).show()
         else:
             logger.warning("Could not open history of '{}'. "
                            "Not a MatrixWorkspace or ITableWorkspace"
                            "".format(name))
Example #17
0
 def dropEvent(self, event):
     data = event.mimeData()
     for url in data.urls():
         filepath = url.toLocalFile()
         if osp.splitext(filepath)[1] in ACCEPTED_FILE_EXTENSIONS:
             try:
                 self.open_file_in_new_tab(filepath)
             except IOError as io_error:
                 logger.warning("Could not load file:\n  '{}'"
                                "".format(io_error))
Example #18
0
        def create_table_item(column, itemname, callable, *args):
            item = QStandardItem()
            item.setEditable(False)
            try:
                item.setText(callable(*args))
            except Exception as exc:
                logger.warning("Error setting column {} for log {}: {}".format(
                    column, itemname, str(exc)))

            return item
Example #19
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)
Example #20
0
def fast_fourier_filter(ws, freq_params=None, bw_order=None):
    if not freq_params:
        if bw_order:
            logger.warning(
                'bw_order set but no freq_params, freq_params must be set for filter to be performed.'
            )
        return
    # This is a simple fourier filter using the FFTSmooth to get a WS with only the low radius components, then
    # subtracting that from the merged WS
    x_range = ws.dataX(0)
    # The param p in FFTSmooth defined such that if the input ws has Nx bins then in the fourier space ws it will cut of
    # all frequencies in bins nk=Nk/p and above, calculated by p = pi/(k_c*dQ) when k_c is the cutoff frequency desired.
    # The input ws of FFTSmooth has binning [x_min, dx, x_max], with Nx bins.
    # FFTSmooth doubles the length of the input ws and preforms an FFT with output ws binning
    # [0, dk, k_max]=[0, 1/2*(x_max-x_min), 1/(2*dx)], and Nk=Nx bins.
    # k_max/k_c = Nk/nk
    # 1/(k_c*2*dx) = p
    # because FFT uses sin(2*pi*k*x) while PDFFourierTransform uses sin(Q*r) we need to include a factor of 2*pi
    # p = pi/(k_c*dQ)
    lower_freq_param = round(np.pi / (freq_params[0] *
                                      (x_range[1] - x_range[0])))
    # This is giving the FFTSmooth the data in the form of S(Q)-1, later we use PDFFourierTransform with Q(S(Q)-1)
    # it does not matter which we use in this case.
    if bw_order:
        tmp = mantid.FFTSmooth(InputWorkspace=ws,
                               Filter="Butterworth",
                               Params=str(lower_freq_param) + ',' +
                               str(bw_order),
                               StoreInADS=False,
                               IgnoreXBins=True)
    else:
        tmp = mantid.FFTSmooth(InputWorkspace=ws,
                               Filter="Zeroing",
                               Params=str(lower_freq_param),
                               StoreInADS=False,
                               IgnoreXBins=True)
    mantid.Minus(LHSWorkspace=ws, RHSWorkspace=tmp, OutputWorkspace=ws)

    if len(freq_params) > 1:
        upper_freq_param = round(np.pi / (freq_params[1] *
                                          (x_range[1] - x_range[0])))
        if bw_order:
            mantid.FFTSmooth(InputWorkspace=ws,
                             OutputWorkspace=ws,
                             Filter="Butterworth",
                             Params=str(upper_freq_param) + ',' +
                             str(bw_order),
                             IgnoreXBins=True)
        else:
            mantid.FFTSmooth(InputWorkspace=ws,
                             OutputWorkspace=ws,
                             Filter="Zeroing",
                             Params=str(upper_freq_param),
                             IgnoreXBins=True)
Example #21
0
 def _frame_to_slice_fn(self, frame):
     """
     Return the appropriate function to retrieve the peak coordinates in the given frame
     :param frame: The frame of the data workspace
     """
     try:
         peak_center_getter = FRAME_TO_PEAK_CENTER_ATTR[frame]
     except KeyError:
         logger.warning("Unknown frame {}. Assuming QLab.".format(frame))
         peak_center_getter = FRAME_TO_PEAK_CENTER_ATTR[SpecialCoordinateSystem.QLab]
     return peak_center_getter
Example #22
0
 def _superplot_show(self):
     """Show the superplot"""
     self.superplot = Superplot(self.canvas, self.window)
     if not self.superplot.is_valid():
         logger.warning("Superplot cannot be opened on data not linked "
                        "to a workspace.")
         self.superplot = None
         self.toolbar._actions["toggle_superplot"].setChecked(False)
     else:
         self.superplot.show()
         self.toolbar._actions["toggle_superplot"].setChecked(True)
Example #23
0
 def load_existing_gsas_parameters(self, file_path):
     if not path.exists(file_path):
         logger.warning("Could not open GSAS calibration file: ", file_path)
         return
     try:
         instrument, van_no, sample_no, params_table = self.get_info_from_file(file_path)
         self.update_calibration_params_table(params_table)
     except RuntimeError:
         logger.error("Invalid file selected: ", file_path)
         return
     vanadium_corrections.fetch_correction_workspaces(instrument+van_no, instrument)
     return instrument, van_no, sample_no
Example #24
0
    def PyExec(self):
        use_zero_error_free = self.getProperty("UseZeroErrorFree").value
        file_formats = self._get_file_formats()
        file_name = self.getProperty("Filename").value
        workspace = self.getProperty("InputWorkspace").value

        transmission = self.getProperty("Transmission").value
        transmission_can = self.getProperty("TransmissionCan").value

        if use_zero_error_free:
            workspace = get_zero_error_free_workspace(workspace)
            if transmission:
                transmission = get_zero_error_free_workspace(transmission)
            if transmission_can:
                transmission_can = get_zero_error_free_workspace(
                    transmission_can)
        transmission_workspaces = {
            "Transmission": transmission,
            "TransmissionCan": transmission_can
        }

        additional_run_numbers = {
            "SampleTransmissionRunNumber":
            self.getProperty("SampleTransmissionRunNumber").value,
            "SampleDirectRunNumber":
            self.getProperty("SampleDirectRunNumber").value,
            "CanScatterRunNumber":
            self.getProperty("CanScatterRunNumber").value,
            "CanDirectRunNumber":
            self.getProperty("CanDirectRunNumber").value
        }

        progress = Progress(self,
                            start=0.0,
                            end=1.0,
                            nreports=len(file_formats) + 1)
        for file_format in file_formats:
            progress_message = "Saving to {0}.".format(
                file_format.file_format.value)
            progress.report(progress_message)
            progress.report(progress_message)
            try:
                save_to_file(workspace, file_format, file_name,
                             transmission_workspaces, additional_run_numbers)
            except (RuntimeError, ValueError) as e:
                logger.warning(
                    f"Cannot save workspace using SANSSave. "
                    "This workspace needs to be the result of a SANS reduction, "
                    "and must be appropriate for saving 1D or 2D reduced data."
                )
                raise e
        progress.report("Finished saving workspace to files.")
Example #25
0
    def _check_analysers_and_reflection(self):
        from IndirectCommon import CheckAnalysersOrEFixed

        try:
            CheckAnalysersOrEFixed(self._sample, self._resolution)
        except ValueError:
            # A genuine error the shows that the two runs are incompatible
            raise
        except BaseException:
            # Checking could not be performed due to incomplete or no
            # instrument
            logger.warning(
                'Could not check for matching analyser and reflection')
Example #26
0
def load_from_file(filepath):
    """
        Loads the plugin file. Any code present at the top-level will
        be executed on loading
        @param filepath :: A path that must point to a file
    """
    loaded = []
    try:
        if contains_newapi_algorithm(filepath):
            name, module = load_plugin(filepath)
            loaded.append(module)
    except Exception, exc:
        logger.warning("Failed to load plugin %s. Error: %s" % (filepath, str(exc)))
Example #27
0
def load_from_file(filepath):
    """
        Loads the plugin file. Any code present at the top-level will
        be executed on loading
        @param filepath :: A path that must point to a file
    """
    loaded = []
    try:
        if contains_newapi_algorithm(filepath):
            name, module = load_plugin(filepath)
            loaded.append(module)
    except Exception, exc:
        logger.warning("Failed to load plugin %s. Error: %s" % (filepath, str(exc)))
Example #28
0
def load_from_file(filepath):
    """
        If the algorithm is a new API algorithm then load it
        
        @param filepath :: A path that must point to a file
    """
    loaded = []
    try:
        if contains_newapi_algorithm(filepath):
            name, module = load_plugin(filepath)
            loaded.append(module)
    except Exception, exc:
        logger.warning("Failed to load plugin %s. Error: %s" % (filepath, str(exc)))
Example #29
0
    def _check_analysers_and_reflection(self):
        from IndirectCommon import CheckAnalysersOrEFixed

        try:
            CheckAnalysersOrEFixed(self._sample, self._resolution)
        except ValueError:
            # A genuine error the shows that the two runs are incompatible
            raise
        except BaseException:
            # Checking could not be performed due to incomplete or no
            # instrument
            logger.warning(
                'Could not check for matching analyser and reflection')
Example #30
0
    def _do_sample_logs(self, names):
        """
        Show the sample log window for the given workspaces

        :param names: A list of workspace names
        """
        for ws in self._ads.retrieveWorkspaces(names, unrollGroups=True):
            try:
                SampleLogs(ws=ws, parent=self)
            except Exception as exception:
                logger.warning("Could not open sample logs for workspace '{}'."
                               "".format(ws.name()))
                logger.warning("{}: {}".format(
                    type(exception).__name__, exception))
Example #31
0
    def _do_slice_viewer(self, names):
        """
        Show the sliceviewer window for the given workspaces

        :param names: A list of workspace names
        """
        for ws in self._ads.retrieveWorkspaces(names, unrollGroups=True):
            try:
                SliceViewer(ws=ws, parent=self)
            except Exception as exception:
                logger.warning("Could not open slice viewer for workspace '{}'."
                               "".format(ws.name()))
                logger.debug("{}: {}".format(type(exception).__name__,
                                             exception))
Example #32
0
 def save_grouping_workspace(self, directory: str) -> None:
     """
     Save grouping workspace created for custom spectra or .cal cropping.
     :param directory: directory in which to save grouping workspace
     """
     if self.group and not self.group.banks:
         filename = self.generate_output_file_name(ext='.xml')
         SaveDetectorsGrouping(InputWorkspace=self.group_ws,
                               OutputFile=path.join(directory, filename))
     else:
         logger.warning(
             "Only save grouping workspace for custom or cropped groupings."
         )
     return
Example #33
0
def load_existing_calibration_files(calibration):
    # load prm
    prm_filepath = calibration.prm_filepath
    if not path.exists(prm_filepath):
        msg = f"Could not open GSAS calibration file: {prm_filepath}"
        logger.warning(msg)
        return
    try:
        # read diff constants from prm
        write_diff_consts_to_table_from_prm(prm_filepath)
    except RuntimeError:
        logger.error(f"Invalid file selected: {prm_filepath}")
        return
    calibration.load_relevant_calibration_files()
Example #34
0
    def _transform(self):
        """
        Run TransformToIqt.
        """
        from IndirectCommon import CheckHistZero, CheckHistSame, CheckAnalysers

        try:
            CheckAnalysers(self._sample, self._resolution)
        except ValueError:
            # A genuine error the shows that the two runs are incompatible
            raise
        except BaseException:
            # Checking could not be performed due to incomplete or no
            # instrument
            logger.warning(
                'Could not check for matching analyser and reflection')

        # Process resolution data
        num_res_hist = CheckHistZero(self._resolution)[0]
        if num_res_hist > 1:
            CheckHistSame(self._sample, 'Sample', self._resolution,
                          'Resolution')

        calculateiqt_alg = self.createChildAlgorithm(name='CalculateIqt',
                                                     startProgress=0.3,
                                                     endProgress=1.0,
                                                     enableLogging=True)
        calculateiqt_alg.setAlwaysStoreInADS(False)
        args = {
            "InputWorkspace": self._sample,
            "OutputWorkspace": "iqt",
            "ResolutionWorkspace": self._resolution,
            "EnergyMin": self._e_min,
            "EnergyMax": self._e_max,
            "EnergyWidth": self._e_width,
            "CalculateErrors": self._calculate_errors,
            "NumberOfIterations": self._number_of_iterations,
            "SeedValue": self._seed
        }
        for key, value in args.items():
            calculateiqt_alg.setProperty(key, value)
        calculateiqt_alg.execute()

        iqt = calculateiqt_alg.getProperty("OutputWorkspace").value

        # Set Y axis unit and label
        iqt.setYUnit('')
        iqt.setYUnitLabel('Intensity')
        return iqt
Example #35
0
 def _superplot_show(self):
     """Show the superplot"""
     self.superplot = Superplot(self.canvas, self.window)
     if not self.superplot.is_valid():
         logger.warning("Superplot cannot be opened on data not linked "
                        "to a workspace.")
         self.superplot = None
         self.toolbar._actions["toggle_superplot"].setChecked(False)
     else:
         self.window.addDockWidget(Qt.LeftDockWidgetArea,
                                   self.superplot.get_side_view())
         self.window.addDockWidget(Qt.BottomDockWidgetArea,
                                   self.superplot.get_bottom_view())
         self.toolbar._actions["toggle_superplot"].setChecked(True)
         self.superplot.get_bottom_view().setFocus()
Example #36
0
    def _do_slice_viewer(self, names):
        """
        Show the sliceviewer window for the given workspaces

        :param names: A list of workspace names
        """
        parent, flags = get_window_config()
        for ws in self._ads.retrieveWorkspaces(names, unrollGroups=True):
            try:
                presenter = SliceViewer(ws=ws, conf=CONF, parent=parent, window_flags=flags)
                presenter.view.show()
            except Exception as exception:
                logger.warning("Could not open slice viewer for workspace '{}'."
                               "".format(ws.name()))
                logger.warning("{}: {}".format(type(exception).__name__, exception))
Example #37
0
    def remove_oldest_checkpoints(self):
        """
        Removes the oldest checkpoint in the currently running programs' directory if it has hit the max number of
        checkpoints
        """
        paths = self.listdir_fullpath(self.recovery_directory_pid)

        if len(paths) > self.maximum_num_checkpoints:
            # Order paths in reverse and remove the last folder
            paths.sort(reverse=True)
            for ii in range(self.maximum_num_checkpoints, len(paths)):
                try:
                    self._remove_directory_and_directory_trees(paths[ii])
                except OSError as exc:
                    logger.warning(f"Unable to remove project recovery checkpoint '{paths[ii]}': {str(exc)}")
Example #38
0
    def setup(self):
        # menus must be done first so they can be filled by the
        # plugins in register_plugin
        self.create_menus()

        # widgets
        # Log message display must be imported first
        self.set_splash("Loading message display")
        from workbench.plugins.logmessagedisplay import LogMessageDisplay
        self.messagedisplay = LogMessageDisplay(self)
        # this takes over stdout/stderr
        self.messagedisplay.register_plugin()
        self.widgets.append(self.messagedisplay)

        self.set_splash("Loading Algorithm Selector")
        from workbench.plugins.algorithmselectorwidget import AlgorithmSelector
        self.algorithm_selector = AlgorithmSelector(self)
        self.algorithm_selector.register_plugin()
        self.widgets.append(self.algorithm_selector)

        self.set_splash("Loading Plot Selector")
        from workbench.plugins.plotselectorwidget import PlotSelector
        self.plot_selector = PlotSelector(self)
        self.plot_selector.register_plugin()
        self.widgets.append(self.plot_selector)

        self.set_splash("Loading code editing widget")
        from workbench.plugins.editor import MultiFileEditor
        self.editor = MultiFileEditor(self)
        self.editor.register_plugin()
        self.widgets.append(self.editor)

        self.set_splash("Loading IPython console")
        from workbench.plugins.jupyterconsole import JupyterConsole
        self.ipythonconsole = JupyterConsole(self)
        self.ipythonconsole.register_plugin()
        self.widgets.append(self.ipythonconsole)

        from workbench.plugins.workspacewidget import WorkspaceWidget
        self.workspacewidget = WorkspaceWidget(self)
        self.workspacewidget.register_plugin()
        self.widgets.append(self.workspacewidget)

        # Set up the project, recovery and interface manager objects
        self.project = Project(GlobalFigureManager, find_all_windows_that_are_savable)
        self.project_recovery = ProjectRecovery(globalfiguremanager=GlobalFigureManager,
                                                multifileinterpreter=self.editor.editors,
                                                main_window=self)

        self.interface_executor = PythonCodeExecution()
        self.interface_executor.sig_exec_error.connect(lambda errobj: logger.warning(str(errobj)))
        self.interface_manager = InterfaceManager()

        # uses default configuration as necessary
        self.readSettings(CONF)
        self.config_updated()

        self.setup_layout()
        self.create_actions()
Example #39
0
    def _do_show_instrument(self, names):
        """
        Show an instrument widget for the given workspaces

        :param names: A list of workspace names
        """
        for ws in self._ads.retrieveWorkspaces(names, unrollGroups=True):
            if ws.getInstrument().getName():
                try:
                    presenter = InstrumentViewPresenter(ws, parent=self)
                    presenter.show_view()
                except Exception as exception:
                    logger.warning("Could not show instrument for workspace "
                                   "'{}':\n{}.\n".format(ws.name(), exception))
            else:
                logger.warning("Could not show instrument for workspace '{}':"
                               "\nNo instrument available.\n"
                               "".format(ws.name()))
Example #40
0
    def _discover_python_interfaces(self, interface_dir):
        """Return a dictionary mapping a category to a set of named Python interfaces"""
        items = ConfigService['mantidqt.python_interfaces'].split()
        # list of custom interfaces that are not qt4/qt5 compatible
        GUI_BLACKLIST = ['ISIS_Reflectometry_Old.py',
                         'Frequency_Domain_Analysis_Old.py',
                         'Frequency_Domain_Analysis.py',
                         'Elemental_Analysis.py']

        # detect the python interfaces
        interfaces = {}
        for item in items:
            key, scriptname = item.split('/')
            if not os.path.exists(os.path.join(interface_dir, scriptname)):
                logger.warning('Failed to find script "{}" in "{}"'.format(scriptname, interface_dir))
                continue
            if scriptname in GUI_BLACKLIST:
                logger.information('Not adding gui "{}"'.format(scriptname))
                continue
            interfaces.setdefault(key, []).append(scriptname)

        return interfaces
    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)
Example #42
0
    def _calculate_parameters(self):
        """
        Calculates the TransformToIqt parameters and saves in a table workspace.
        """
        from IndirectCommon import getEfixed

        end_prog = 0.3 if self._calculate_errors else 0.9
        workflow_prog = Progress(self, start=0.0, end=end_prog, nreports=8)
        workflow_prog.report('Cropping Workspace')
        CropWorkspace(InputWorkspace=self._sample,
                      OutputWorkspace='__TransformToIqt_sample_cropped',
                      Xmin=self._e_min,
                      Xmax=self._e_max)
        workflow_prog.report('Calculating table properties')
        x_data = mtd['__TransformToIqt_sample_cropped'].readX(0)
        number_input_points = len(x_data) - 1
        num_bins = int(number_input_points / self._number_points_per_bin)
        self._e_width = (abs(self._e_min) + abs(self._e_max)) / num_bins

        workflow_prog.report('Attempting to Access IPF')
        try:
            workflow_prog.report('Access IPF')
            instrument = mtd[self._sample].getInstrument()

            analyserName = instrument.getStringParameter('analyser')[0]
            analyser = instrument.getComponentByName(analyserName)

            if analyser is not None:
                logger.debug('Found %s component in instrument %s, will look for resolution there'
                             % (analyserName, instrument))
                resolution = analyser.getNumberParameter('resolution')[0]
            else:
                logger.debug('No %s component found on instrument %s, will look for resolution in top level instrument'
                             % (analyserName, instrument))
                resolution = instrument.getNumberParameter('resolution')[0]

            logger.information('Got resolution from IPF: %f' % resolution)
            workflow_prog.report('IPF resolution obtained')
        except (AttributeError, IndexError):
            workflow_prog.report('Resorting to Default')
            resolution = getEfixed(self._sample) * 0.01
            logger.warning('Could not get the resolution from the IPF, using 1% of the E Fixed value for the '
                           'resolution: {0}'.format(resolution))

        resolution_bins = int(round((2 * resolution) / self._e_width))

        if resolution_bins < 5:
            logger.warning(
                'Resolution curve has <5 points. Results may be unreliable.')

        workflow_prog.report('Creating Parameter table')
        param_table = CreateEmptyTableWorkspace(
            OutputWorkspace=self._parameter_table)

        workflow_prog.report('Populating Parameter table')
        param_table.addColumn('int', 'SampleInputBins')
        param_table.addColumn('float', 'BinReductionFactor')
        param_table.addColumn('int', 'SampleOutputBins')
        param_table.addColumn('float', 'EnergyMin')
        param_table.addColumn('float', 'EnergyMax')
        param_table.addColumn('float', 'EnergyWidth')
        param_table.addColumn('float', 'Resolution')
        param_table.addColumn('int', 'ResolutionBins')

        param_table.addRow([number_input_points, self._number_points_per_bin, num_bins,
                            self._e_min, self._e_max, self._e_width,
                            resolution, resolution_bins])

        workflow_prog.report('Deleting temp Workspace')
        if mtd.doesExist('__TransformToIqt_sample_cropped'):
            DeleteWorkspace('__TransformToIqt_sample_cropped')

        self.setProperty('ParameterWorkspace', param_table)
Example #43
0
    def parseto(self,tag,value):
        if tag == 'scantype':
            tstring = value[0:2].lower()
            if tstring == 'si':
                return 'single'
            elif tstring == 'st':
                return 'step'
            elif tstring == 'sw':
                return 'sweep'
            else:
                raise ValueError("scantype not understood (single, step or sweep).")
                

        if tag in ['t0','efixed','emin','emax','ebin','qstep','tibgstart','tibgstop','vanmin','vanmax',
                   'logvaluemin','logvaluemax','logvaluestep','powderanglestep']:
            return float(value)

        if tag in ['runs','vanruns','pixel','tube','bank']:
            #create empty list to put the runs in
            runs = []
            #split the commas
            parts = value.split(',')
            #now deal with the hyphens
            for p in parts:
                if len(p) > 0:
                    elem = p.split("-")
                if len(elem) == 1:
                    runs.append(int(elem[0]))
                if len(elem) == 2:
                    startelem = int(elem[0])
                    endelem   = int(elem[1])
                    if endelem < startelem:
                        raise ValueError("The element after the hyphen needs to be greater or equal than the first element")
                    elemlist  = range(startelem,endelem+1)
                    runs.extend(elemlist)
            return runs
        if tag in ['calce','kiokf','tibg','normalizedcalibration','filterbadpulses']:
            return (value.lower() in ("yes", "true", "t", "1", "tru", "tr", "y"))
        if tag=='units':
            #replace all whitespace with nothing
            value.replace(' ', '')
            #this is a list of strings of the supported filetypes
            unittypesexist = ['DeltaE', 'DeltaE_inWavenumber', 'Energy', 'Energy_inWavenumber',
                              'Momentum', 'MomentumTransfer', 'QSquared', 'TOF', 'Wavelength',
                              'dspacing']
            #get a string all lowercase.
            unitlower = []
            for u in unittypesexist:
                unitlower.append(u.lower())
            #Find the matching value of the unit list.
            i = unitlower.index(value.lower())
            return unittypesexist[i]
        if tag=='save':
            #replace all whitespace with commas
            value.replace(' ', ',')
            #split up parts by comma delimited values
            parts = value.split(',')
            #this is a list of strings of the supported filetypes
            filetypesexist = ['phx', 'spe', 'nxspe', 'par', 'jpg', 'nxs', 'iofq','iofe','summary']
            #loop over the elements and fill up a list of the
            #filetypes to return.
            filestoprocess = []
            for p in parts:
                p = p.strip(' "')
                if p.lower() in filetypesexist:
                    filestoprocess.append(p.lower())
                else:
                    if len(p) > 0:
                        logger.warning("*****FILETYPE "+p+" DOES NOT EXIST. This file will be ignored.*****")
            return filestoprocess
        if tag=='friendlynamelogs':
            #convert to an arry of strings, split by the commas
            parts = value.replace(' ', '').split(',')
            return parts
        if tag in ['goniometermotor','goniometermotoraxis','goniometermotoroffset','goniometermotordirection']:
            try:
                return eval(value)
            except:
                return value            
        return value
Example #44
0
def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max,  background_min, background_max, int_min, int_max,
                   point_detector_start=0, point_detector_stop=0, multi_detector_start=0, theta=None,
                   pointdet=True,roi=[0,0], db=[0,0], trans='', debug=False, correction_strategy=NullCorrectionStrategy(),
                   stitch_start_overlap=None, stitch_end_overlap=None, stitch_params=None,
                   polcorr=False, crho=None, calpha=None, cAp=None, cPp=None, detector_component_name='point-detector',
                   sample_component_name='some-surface-holder', correct_positions=True ):

    '''
    Version of quick where all parameters are explicitly provided.
    '''

    _sample_ws = ConvertToWavelength.to_single_workspace(run)
    nHist =  _sample_ws.getNumberHistograms()
    to_lam = ConvertToWavelength(run)

    if pointdet:
        detector_index_ranges = (point_detector_start, point_detector_stop)
    else:
        detector_index_ranges = (multi_detector_start, nHist-1)


    _monitor_ws, _detector_ws = to_lam.convert(wavelength_min=lambda_min, wavelength_max=lambda_max, detector_workspace_indexes=detector_index_ranges, monitor_workspace_index=i0_monitor_index, correct_monitor=True, bg_min=background_min, bg_max=background_max )

    inst = _sample_ws.getInstrument()
    # Some beamline constants from IDF

    print i0_monitor_index
    print nHist

    if (run=='0'):
        RunNumber = '0'
    else:
        RunNumber = groupGet(_sample_ws.getName(),'samp','run_number')

    if not pointdet:
        # Proccess Multi-Detector; assume MD goes to the end:
        # if roi or db are given in the function then sum over the apropriate channels
        print "This is a multidetector run."

        _I0M = RebinToWorkspace(WorkspaceToRebin=_monitor_ws,WorkspaceToMatch=_detector_ws)
        IvsLam = _detector_ws / _I0M
        if (roi != [0,0]) :
            ReflectedBeam = SumSpectra(InputWorkspace=IvsLam, StartWorkspaceIndex=roi[0], EndWorkspaceIndex=roi[1])
        if (db != [0,0]) :
            DirectBeam = SumSpectra(InputWorkspace=_detector_ws, StartWorkspaceIndex=db[0], EndWorkspaceIndex=db[1])
            ReflectedBeam = ReflectedBeam / DirectBeam
        polCorr(polcorr, IvsLam, crho, calpha, cAp, cPp)
        if (theta and correct_positions):
            IvsQ = l2q(ReflectedBeam, detector_component_name, theta, sample_component_name)
        else:
            IvsQ = ConvertUnits(InputWorkspace=ReflectedBeam, Target="MomentumTransfer")


    # Single Detector processing-------------------------------------------------------------
    else:
        print "This is a Point-Detector run."
        # handle transmission runs
        # process the point detector reflectivity
        _I0P = RebinToWorkspace(WorkspaceToRebin=_monitor_ws,WorkspaceToMatch=_detector_ws)
        IvsLam = Scale(InputWorkspace=_detector_ws,Factor=1)

        if not trans:
            print "No transmission file. Trying default exponential/polynomial correction..."
            IvsLam = correction_strategy.apply(_detector_ws)
            IvsLam = Divide(LHSWorkspace=IvsLam, RHSWorkspace=_I0P)
        else: # we have a transmission run
            _monInt = Integration(InputWorkspace=_I0P,RangeLower=int_min,RangeUpper=int_max)
            IvsLam = Divide(LHSWorkspace=_detector_ws,RHSWorkspace=_monInt)
            names = mtd.getObjectNames()

            IvsLam = transCorr(trans, IvsLam, lambda_min, lambda_max, background_min, background_max,
                               int_min, int_max, detector_index_ranges, i0_monitor_index, stitch_start_overlap,
                               stitch_end_overlap, stitch_params )


        IvsLam = polCorr(polcorr, IvsLam, crho, calpha, cAp, cPp)



        # Convert to I vs Q
        # check if detector in direct beam
        if (theta == None or theta == 0 or theta == ''):
            inst = groupGet('IvsLam','inst')
            detLocation=inst.getComponentByName(detector_component_name).getPos()
            sampleLocation=inst.getComponentByName(sample_component_name).getPos()
            detLocation=inst.getComponentByName(detector_component_name).getPos()
            sample2detector=detLocation-sampleLocation    # metres
            source=inst.getSource()
            beamPos = sampleLocation - source.getPos()
            theta = groupGet(str(_sample_ws),'samp','theta')
            if not theta:
                theta = inst.getComponentByName(detector_component_name).getTwoTheta(sampleLocation, beamPos)*180.0/math.pi/2.0
            print "Det location: ", detLocation, "Calculated theta = ",theta
            if correct_positions:  # detector is not in correct place
                # Get detector angle theta from NeXuS
                logger.information('The detectorlocation is not at Y=0')
                print 'Nexus file theta =', theta
                IvsQ = l2q(IvsLam, detector_component_name, theta, sample_component_name)
            else:
                IvsQ = ConvertUnits(InputWorkspace=IvsLam,OutputWorkspace="IvsQ",Target="MomentumTransfer")

        else:
            if correct_positions:
                theta = float(theta)
                try:
                    IvsQ = l2q(IvsLam, detector_component_name, theta, sample_component_name)
                except AttributeError:
                    logger.warning("detector_component_name " + detector_component_name + " is unknown")
                    IvsQ = ConvertUnits(InputWorkspace=IvsLam,OutputWorkspace="IvsQ",Target="MomentumTransfer")
            else:
                IvsQ = ConvertUnits(InputWorkspace=IvsLam,OutputWorkspace="IvsQ",Target="MomentumTransfer")

    RenameWorkspace(InputWorkspace=IvsLam,OutputWorkspace=RunNumber+'_IvsLam')
    if isinstance(IvsLam, WorkspaceGroup):
        counter = 0
        for ws in IvsLam:
            RenameWorkspace(ws, OutputWorkspace=RunNumber+'_IvsLam_'+str(counter))
            counter += 1
    RenameWorkspace(InputWorkspace=IvsQ,OutputWorkspace=RunNumber+'_IvsQ')

    # delete all temporary workspaces unless in debug mode (debug=1)

    if not debug:
        cleanup()
        if mtd.doesExist('IvsLam'):
            DeleteWorkspace('IvsLam')
    return  mtd[RunNumber+'_IvsLam'], mtd[RunNumber+'_IvsQ'], theta
Example #45
0
    def parseto(self,tag,value):
        if tag == 'ScanType':
            tstring = value[0:2].lower()
            if tstring == 'si':
                return 'single'
            elif tstring == 'st':
                return 'step'
            elif tstring == 'sw':
                return 'sweep'
            else:
                raise ValueError("scantype not understood (single, step, sweep or vannorm).")
                
        #We choose not to convert to floats for the variables, but keep as strings.
        #if tag in ['t0','efixed','emin','emax','ebin','qmin','qmax','qstep','tibgstart','tibgstop','vanmin','vanmax',
        #           'logvaluemin','logvaluemax','logvaluestep','powderanglestep','powderanglemin','powderanglemax',
        #           'vanmine','vanmaxe','vanminangle','vanmaxangle','vanmass','samplemass','samplermm','scalefactor']:
        #    return float(value)

        if tag in ['Runs','VanRuns']:
            return _parseBTPlist(value)

        if tag in ['UseIncidentEnergyGuess','CorrectKiKf','TimeIndepBackgroundSub','NormalizedCalibration','FilterBadPulses','MedianTestCorrectForSolidAngle']:
            return (value.lower() in ("yes", "true", "t", "1", "tru", "tr", "y"))

        if tag=='DetVanIntRangeUnits':
            #replace all whitespace with nothing
            value.replace(' ', '')
            #this is a list of strings of the supported filetypes
            unittypesexist = ['DeltaE', 'DeltaE_inWavenumber', 'Energy', 'Energy_inWavenumber',
                              'Momentum', 'MomentumTransfer', 'QSquared', 'TOF', 'Wavelength',
                              'dspacing']
            #get a string all lowercase.
            unitlower = []
            for u in unittypesexist:
                unitlower.append(u.lower())
            #Find the matching value of the unit list.
            i = unitlower.index(value.lower())
            return unittypesexist[i]

        if tag=='Save':
            #replace all whitespace with commas
            value.replace(' ', ',')
            #split up parts by comma delimited values
            parts = value.split(',')
            #this is a list of strings of the supported filetypes
            filetypesexist = ['phx', 'spe', 'nxspe', 'par', 'jpg', 'nxs', 'mdnxs', 'iofq','iofe',
                            'iofphiecolumn','iofphiearray','iofqecolumn','iofqearray','summary',
                            'sqw','vannorm']
            #loop over the elements and fill up a list of the
            #filetypes to return.
            filestoprocess = []
            for p in parts:
                p = p.strip(' "')
                if p.lower() in filetypesexist:
                    filestoprocess.append(p.lower())
                else:
                    if len(p) > 0:
                        logger.warning("*****FILETYPE "+p+" DOES NOT EXIST. This file will be ignored.*****")
            return filestoprocess

        if tag=='FriendlyNameLogs':
            #convert to an arry of strings, split by the commas#
            parts = value.replace(' ', '').split(',')
            return parts

        if tag=='FilterNames':
            parts = value.replace(' ', '').split(',')
            return parts

        if tag=='FilterMin':
            parts = value.replace(' ', '').split(',')
            return parts

        if tag=='FilterMax':
            parts = value.replace(' ', '').split(',')
            return parts

        if tag in ['GoniometerMotor','GoniometerMotororAxis','GoniometerMotorOffset','GoniometerMotorDirection']:
            try:
                return eval(value)
            except:
                return value            

        return value
Example #46
0
    def PyExec(self):
        self._setup()
        self._sample()
        self._wave_range()
        self._get_angles()
        self._transmission()

        dataA1 = []
        dataA2 = []
        dataA3 = []
        dataA4 = []

        for angle in self._angles:
            (A1, A2, A3, A4) = self._cyl_abs(angle)
            logger.information('Angle : %f * successful' % (angle))

            dataA1 = np.append(dataA1, A1)
            dataA2 = np.append(dataA2, A2)
            dataA3 = np.append(dataA3, A3)
            dataA4 = np.append(dataA4, A4)

        dataX = self._waves * len(self._angles)

        # Create the output workspaces
        ass_ws = self._output_ws_name + '_ass'
        CreateWorkspace(OutputWorkspace=ass_ws, DataX=dataX, DataY=dataA1,
                    NSpec=len(self._angles), UnitX='Wavelength')
        workspaces = [ass_ws]

        if self._use_can:
            assc_ws = self._output_ws_name + '_assc'
            workspaces.append(assc_ws)
            CreateWorkspace(OutputWorkspace=assc_ws, DataX=dataX, DataY=dataA2,
                            NSpec=len(self._angles), UnitX='Wavelength')

            acsc_ws = self._output_ws_name + '_acsc'
            workspaces.append(acsc_ws)
            CreateWorkspace(OutputWorkspace=acsc_ws, DataX=dataX, DataY=dataA3,
                            NSpec=len(self._angles), UnitX='Wavelength')

            acc_ws = self._output_ws_name + '_acc'
            workspaces.append(acc_ws)
            CreateWorkspace(OutputWorkspace=acc_ws, DataX=dataX, DataY=dataA4,
                            NSpec=len(self._angles), UnitX='Wavelength')

        if self._interpolate:
            self._interpolate_corrections(workspaces)
        try:
            self. _copy_detector_table(workspaces)
        except RuntimeError:
            logger.warning('Cannot copy spectra mapping. Check input workspace instrument.')

        sample_log_workspaces = workspaces
        sample_logs = [('sample_shape', 'cylinder'),
                       ('sample_filename', self._sample_ws_name),
                       ('sample_inner', self._sample_inner_radius),
                       ('sample_outer', self._sample_outer_radius)]

        if self._use_can:
            sample_logs.append(('can_filename', self._can_ws_name))
            sample_logs.append(('can_outer', self._can_outer_radius))

        log_names = [item[0] for item in sample_logs]
        log_values = [item[1] for item in sample_logs]

        for ws_name in sample_log_workspaces:
            AddSampleLogMultiple(Workspace=ws_name, LogNames=log_names, LogValues=log_values)

        GroupWorkspaces(InputWorkspaces=','.join(workspaces), OutputWorkspace=self._output_ws_name)
        self.setPropertyValue('OutputWorkspace', self._output_ws_name)
Example #47
0
 def launch_custom_gui(self, filename):
     executioner = PythonCodeExecution()
     executioner.sig_exec_error.connect(lambda errobj: logger.warning(str(errobj)))
     executioner.execute(open(filename).read(), filename)
    def PyExec(self):
        self._setup()
        self._wave_range()

        setup_prog = Progress(self, start=0.0, end=0.2, nreports=2)
        # Set sample material form chemical formula
        setup_prog.report('Set sample material')
        self._sample_density = self._set_material(self._sample_ws_name,
                                                  self._set_sample_method,
                                                  self._sample_chemical_formula,
                                                  self._sample_coherent_cross_section,
                                                  self._sample_incoherent_cross_section,
                                                  self._sample_attenuation_cross_section,
                                                  self._sample_density_type,
                                                  self._sample_density,
                                                  self._sample_number_density_unit)

        # If using a can, set sample material using chemical formula
        if self._use_can:
            setup_prog.report('Set container sample material')
            self._can_density = self._set_material(self._can_ws_name,
                                                   self._set_can_method,
                                                   self._can_chemical_formula,
                                                   self._can_coherent_cross_section,
                                                   self._can_incoherent_cross_section,
                                                   self._can_attenuation_cross_section,
                                                   self._can_density_type,
                                                   self._can_density,
                                                   self._can_number_density_unit)

        # Holders for the corrected data
        data_ass = []
        data_assc = []
        data_acsc = []
        data_acc = []

        self._get_angles()
        num_angles = len(self._angles)
        workflow_prog = Progress(self, start=0.2, end=0.8, nreports=num_angles * 2)

        # Check sample input
        sam_material = mtd[self._sample_ws_name].sample().getMaterial()
        self._has_sample_in = \
            bool(self._sample_density and self._sample_thickness and (sam_material.totalScatterXSection() + sam_material.absorbXSection()))
        if not self._has_sample_in:
            logger.warning("The sample has not been given, or the information is incomplete. Continuing but no absorption for sample will "
                           "be computed.")

        # Check can input
        if self._use_can:
            can_material = mtd[self._can_ws_name].sample().getMaterial()
            if self._can_density and (can_material.totalScatterXSection() + can_material.absorbXSection()):
                self._has_can_front_in = bool(self._can_front_thickness)
                self._has_can_back_in = bool(self._can_back_thickness)
            else:
                logger.warning(
                    "A can workspace was given but the can information is incomplete. Continuing but no absorption for the can will "
                    "be computed.")

            if not self._has_can_front_in:
                logger.warning(
                    "A can workspace was given but the can front thickness was not given. Continuing but no absorption for can front"
                    " will be computed.")
            if not self._has_can_back_in:
                logger.warning(
                    "A can workspace was given but the can back thickness was not given. Continuing but no absorption for can back"
                    " will be computed.")

        for angle_idx in range(num_angles):
            workflow_prog.report('Running flat correction for angle %s' % angle_idx)
            angle = self._angles[angle_idx]
            (ass, assc, acsc, acc) = self._flat_abs(angle)

            logger.information('Angle %d: %f successful' % (angle_idx + 1, self._angles[angle_idx]))
            workflow_prog.report('Appending data for angle %s' % angle_idx)
            data_ass = np.append(data_ass, ass)
            data_assc = np.append(data_assc, assc)
            data_acsc = np.append(data_acsc, acsc)
            data_acc = np.append(data_acc, acc)

        log_prog = Progress(self, start=0.8, end=1.0, nreports=8)

        sample_logs = {'sample_shape': 'flatplate', 'sample_filename': self._sample_ws_name,
                       'sample_thickness': self._sample_thickness, 'sample_angle': self._sample_angle,
                       'emode': self._emode, 'efixed': self._efixed}
        dataX = self._wavelengths * num_angles

        # Create the output workspaces
        ass_ws = self._output_ws_name + '_ass'
        log_prog.report('Creating ass output Workspace')
        CreateWorkspace(OutputWorkspace=ass_ws,
                        DataX=dataX,
                        DataY=data_ass,
                        NSpec=num_angles,
                        UnitX='Wavelength',
                        VerticalAxisUnit='SpectraNumber',
                        ParentWorkspace=self._sample_ws_name,
                        EnableLogging=False)
        log_prog.report('Adding sample logs')
        self._add_sample_logs(ass_ws, sample_logs)

        workspaces = [ass_ws]

        if self._use_can:
            log_prog.report('Adding can sample logs')
            AddSampleLog(Workspace=ass_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name), EnableLogging=False)

            assc_ws = self._output_ws_name + '_assc'
            workspaces.append(assc_ws)
            log_prog.report('Creating assc output workspace')
            CreateWorkspace(OutputWorkspace=assc_ws,
                            DataX=dataX,
                            DataY=data_assc,
                            NSpec=num_angles,
                            UnitX='Wavelength',
                            VerticalAxisUnit='SpectraNumber',
                            ParentWorkspace=self._sample_ws_name,
                            EnableLogging=False)
            log_prog.report('Adding assc sample logs')
            self._add_sample_logs(assc_ws, sample_logs)
            AddSampleLog(Workspace=assc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name), EnableLogging=False)

            acsc_ws = self._output_ws_name + '_acsc'
            workspaces.append(acsc_ws)
            log_prog.report('Creating acsc outputworkspace')
            CreateWorkspace(OutputWorkspace=acsc_ws,
                            DataX=dataX,
                            DataY=data_acsc,
                            NSpec=num_angles,
                            UnitX='Wavelength',
                            VerticalAxisUnit='SpectraNumber',
                            ParentWorkspace=self._sample_ws_name,
                            EnableLogging=False)
            log_prog.report('Adding acsc sample logs')
            self._add_sample_logs(acsc_ws, sample_logs)
            AddSampleLog(Workspace=acsc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name), EnableLogging=False)

            acc_ws = self._output_ws_name + '_acc'
            workspaces.append(acc_ws)
            log_prog.report('Creating acc workspace')
            CreateWorkspace(OutputWorkspace=acc_ws,
                            DataX=dataX,
                            DataY=data_acc,
                            NSpec=num_angles,
                            UnitX='Wavelength',
                            VerticalAxisUnit='SpectraNumber',
                            ParentWorkspace=self._sample_ws_name,
                            EnableLogging=False)
            log_prog.report('Adding acc sample logs')
            self._add_sample_logs(acc_ws, sample_logs)
            AddSampleLog(Workspace=acc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name), EnableLogging=False)

        if self._interpolate:
            self._interpolate_corrections(workspaces)
        log_prog.report('Grouping Output Workspaces')
        GroupWorkspaces(InputWorkspaces=','.join(workspaces), OutputWorkspace=self._output_ws_name, EnableLogging=False)
        self.setPropertyValue('OutputWorkspace', self._output_ws_name)
Example #49
0
def export_masks(ws,fileName='',returnMasksOnly=False):
    """Exports masks applied to Mantid workspace
       (e.g. drawn using the instrument view) and write these masks
       into the old fashioned ASCII .msk file containing masked spectra numbers.

       The file is Libisis/Mantid old ISIS format compatible and can be read by Libisis
       or Mantid LoadMasks algorithm

       If optional parameter fileName is present, the masks are saved
       in the file with this name
       Otherwise, the file with the name equal to the workspace
       name and the extension .msk is used.

       If returnMasks is set to True, the function does not write to file but returns
       list of masks instead.
    """
   # get pointer to the workspace
    if isinstance(ws, str):
        pws = mtd[ws]
    else:
        pws = ws

    ws_name=pws.getName()
    nhist = pws.getNumberHistograms()

    no_detectors = 0
    masks = []
    for i in range(nhist):
        # set provisional spectra ID
        ms = i+1
        try:
            sp = pws.getSpectrum(i)
            # got real spectra ID, which would correspond real spectra num to spectra ID map
            ms = sp.getSpectrumNo()
#pylint: disable=W0703
        except Exception:
            logger.notice("Can not retrieve spectra No: " + str(i) + ". Have masked it")
            masks.append(ms)
            continue
        try:
            det = pws.getDetector(i)
#pylint: disable=W0703
        except Exception:
            no_detectors = no_detectors +1
            masks.append(ms)
            continue
        if det.isMasked():
            masks.append(ms)

    filename=''
    if len(fileName)==0 :
        filename = os.path.join(config.getString('defaultsave.directory'),ws_name+'.msk')
    else:
        filename = fileName

    nMasks = len(masks)
    if nMasks == 0:
        if returnMasksOnly:
            logger.warning("Workspace {0} have no masked spectra. File {1} have not been created".format(ws_name,filename))
        else:
            logger.notice("Workspace "+ws_name+" have no masked spectra")
        return masks

    logger.notice("Workspace {0} has {1} masked spectra, including {2} spectra without detectors".format(ws_name,nMasks,no_detectors))

    if not returnMasksOnly :
        writeISISmasks(filename,masks,8)
    return masks
Example #50
0
    def PyExec(self):
        self._setup()
        self._wave_range()

        # Set sample material form chemical formula
        SetSampleMaterial(self._sample_ws_name , ChemicalFormula=self._sample_chemical_formula,
                          SampleNumberDensity=self._sample_number_density)

        # If using a can, set sample material using chemical formula
        if self._use_can:
            SetSampleMaterial(InputWorkspace=self._can_ws_name, ChemicalFormula=self._can_chemical_formula,
                              SampleNumberDensity=self._can_number_density)

        # Holders for the corrected data
        data_ass = []
        data_assc = []
        data_acsc = []
        data_acc = []

        self._get_angles()
        num_angles = len(self._angles)

        for angle_idx in range(num_angles):
            angle = self._angles[angle_idx]
            (ass, assc, acsc, acc) = self._flat_abs(angle)

            logger.information('Angle %d: %f successful' % (angle_idx+1, self._angles[angle_idx]))

            data_ass = np.append(data_ass, ass)
            data_assc = np.append(data_assc, assc)
            data_acsc = np.append(data_acsc, acsc)
            data_acc = np.append(data_acc, acc)

        sample_logs = {'sample_shape': 'flatplate', 'sample_filename': self._sample_ws_name,
                       'sample_thickness': self._sample_thickness, 'sample_angle': self._sample_angle}
        dataX = self._waves * num_angles

        # Create the output workspaces
        ass_ws = self._output_ws_name + '_ass'
        CreateWorkspace(OutputWorkspace=ass_ws, DataX=dataX, DataY=data_ass,
                        NSpec=num_angles, UnitX='Wavelength',
                        VerticalAxisUnit='SpectraNumber')
        self._add_sample_logs(ass_ws, sample_logs)

        workspaces = [ass_ws]

        if self._use_can:
            AddSampleLog(Workspace=ass_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name))

            assc_ws = self._output_ws_name + '_assc'
            workspaces.append(assc_ws)
            CreateWorkspace(OutputWorkspace=assc_ws, DataX=dataX, DataY=data_assc,
                            NSpec=num_angles, UnitX='Wavelength',
                            VerticalAxisUnit='SpectraNumber')
            self._add_sample_logs(assc_ws, sample_logs)
            AddSampleLog(Workspace=assc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name))

            acsc_ws = self._output_ws_name + '_acsc'
            workspaces.append(acsc_ws)
            CreateWorkspace(OutputWorkspace=acsc_ws, DataX=dataX, DataY=data_acsc,
                            NSpec=num_angles, UnitX='Wavelength',
                            VerticalAxisUnit='SpectraNumber')
            self._add_sample_logs(acsc_ws, sample_logs)
            AddSampleLog(Workspace=acsc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name))

            acc_ws = self._output_ws_name + '_acc'
            workspaces.append(acc_ws)
            CreateWorkspace(OutputWorkspace=acc_ws, DataX=dataX, DataY=data_acc,
                            NSpec=num_angles, UnitX='Wavelength',
                            VerticalAxisUnit='SpectraNumber')
            self._add_sample_logs(acc_ws, sample_logs)
            AddSampleLog(Workspace=acc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name))

        if self._interpolate:
            self._interpolate_corrections(workspaces)

        try:
            self. _copy_detector_table(workspaces)
        except RuntimeError:
            logger.warning('Cannot copy spectra mapping. Check input workspace instrument.')

        GroupWorkspaces(InputWorkspaces=','.join(workspaces), OutputWorkspace=self._output_ws_name)
        self.setPropertyValue('OutputWorkspace', self._output_ws_name)
    def PyExec(self):

        from IndirectImport import is_supported_f2py_platform, import_f2py

        if is_supported_f2py_platform():
            cylabs = import_f2py("cylabs")
        else:
            raise RuntimeError('This algorithm is only available on Windows')

        workdir = config['defaultsave.directory']
        self._setup()
        self._wave_range()

        # Set sample material from chemical formula
        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
        sigs = [sam_material.totalScatterXSection()]
        # absorption x-section
        siga = [sam_material.absorbXSection()]
        density = [self._sample_number_density, self._can_number_density, self._can_number_density]
        half_width = 0.5*float(self._beam_width)
        beam = [self._beam_height, half_width, -half_width, half_width, -half_width, 0.0, self._beam_height, 0.0, self._beam_height]
        radii = [self._sample_inner_radius, self._sample_outer_radius, self._can_outer_radius, self._can_outer_radius]
        ncan = 0

        # If using a can, set sample material using chemical formula
        if self._use_can:
            ncan = 2
            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()

            # total scattering x-section for can
            sigs.append(can_material.totalScatterXSection())
            sigs.append(can_material.totalScatterXSection())
            # absorption x-section for can
            siga.append(can_material.absorbXSection())
            siga.append(can_material.absorbXSection())

        else:
            # total scattering x-section for can
            sigs.append(0.0)
            sigs.append(0.0)
            # absorption x-section for can
            siga.append(0.0)
            siga.append(0.0)

        # Holders for the corrected data
        data_ass = []
        data_assc = []
        data_acsc = []
        data_acc = []

        # initially set errors to zero
        wrk = workdir + self._can_ws_name
        self._get_angles()
        number_angles = len(self._angles)

        for angle_idx in range(number_angles):
            kill, ass, assc, acsc, acc = cylabs.cylabs(self._step_size, beam, ncan, radii,
                                                       density, sigs, siga, self._angles[angle_idx],
                                                       self._elastic, self._waves, angle_idx, wrk, 0)
            if kill == 0:
                logger.information('Angle %d: %f successful' % (angle_idx+1, self._angles[angle_idx]))

                data_ass = np.append(data_ass, ass)
                data_assc = np.append(data_assc, assc)
                data_acsc = np.append(data_acsc, acsc)
                data_acc = np.append(data_acc, acc)

            else:
                raise ValueError('Angle ' + str(angle_idx) + ' : ' + str(self._angles[angle_idx]) + ' *** failed : Error code ' + str(kill))

        sample_logs = {'sample_shape': 'cylinder', 'sample_filename': self._sample_ws_name,
                       'sample_inner_radius': self._sample_inner_radius, 'sample_outer_radius': self._sample_outer_radius}
        dataX = self._waves * number_angles

        # Create the output workspaces
        ass_ws = self._output_ws_name + '_ass'

        CreateWorkspace(OutputWorkspace=ass_ws, DataX=dataX, DataY=data_ass,
                        NSpec=number_angles, UnitX='Wavelength')
        self._add_sample_logs(ass_ws, sample_logs)
        workspaces = [ass_ws]

        if self._use_can:
            sample_logs['can_filename'] = self._can_ws_name
            sample_logs['can_outer_radius'] = self._can_outer_radius

            assc_ws = self._output_ws_name + '_assc'
            workspaces.append(assc_ws)
            CreateWorkspace(OutputWorkspace=assc_ws, DataX=dataX, DataY=data_assc,
                            NSpec=number_angles, UnitX='Wavelength')
            self._add_sample_logs(assc_ws, sample_logs)

            acsc_ws = self._output_ws_name + '_acsc'
            workspaces.append(acsc_ws)
            CreateWorkspace(OutputWorkspace=acsc_ws, DataX=dataX, DataY=data_acsc,
                            NSpec=number_angles, UnitX='Wavelength')
            self._add_sample_logs(acsc_ws, sample_logs)

            acc_ws = self._output_ws_name + '_acc'
            workspaces.append(acc_ws)
            CreateWorkspace(OutputWorkspace=acc_ws, DataX=dataX, DataY=data_acc,
                            NSpec=number_angles, UnitX='Wavelength')
            self._add_sample_logs(acc_ws, sample_logs)

        if self._interpolate:
            self._interpolate_corrections(workspaces)

        try:
            self. _copy_detector_table(workspaces)
        except RuntimeError:
            logger.warning('Cannot copy spectra mapping. Check input workspace instrument.')

        GroupWorkspaces(InputWorkspaces=','.join(workspaces), OutputWorkspace=self._output_ws_name)
        self.setPropertyValue('OutputWorkspace', self._output_ws_name)
Example #52
0
 def data_replace_cb(_, __):
     logger.warning("Updating data on this plot type is not yet supported")
Example #53
0
    def _transform(self):
        """
        Run TransformToIqt.
        """
        from IndirectCommon import CheckHistZero, CheckHistSame, CheckAnalysers
        trans_prog = Progress(self, start=0.3, end=0.8, nreports=15)
        try:
            CheckAnalysers(self._sample, self._resolution)
        except ValueError:
            # A genuine error the shows that the two runs are incompatible
            raise
        except:
            # Checking could not be performed due to incomplete or no instrument
            logger.warning('Could not check for matching analyser and reflection')

        # Process resolution data
        num_res_hist = CheckHistZero(self._resolution)[0]
        if num_res_hist > 1:
            CheckHistSame(self._sample, 'Sample', self._resolution, 'Resolution')

        rebin_param = str(self._e_min) + ',' + str(self._e_width) + ',' + str(self._e_max)
        trans_prog.report('Rebinning Workspace')
        Rebin(InputWorkspace=self._sample,
              OutputWorkspace='__sam_data',
              Params=rebin_param,
              FullBinsOnly=True)

        # Sample
        trans_prog.report('Rebinning sample')
        Rebin(InputWorkspace='__sam_data',
              OutputWorkspace='__sam_data',
              Params=rebin_param)
        trans_prog.report('Integrating Sample')
        Integration(InputWorkspace='__sam_data',
                    OutputWorkspace='__sam_int')
        trans_prog.report('Converting Sample to data points')
        ConvertToPointData(InputWorkspace='__sam_data',
                           OutputWorkspace='__sam_data')
        trans_prog.report('Extracting FFT spectrum for Sample')
        ExtractFFTSpectrum(InputWorkspace='__sam_data',
                           OutputWorkspace='__sam_fft',
                           FFTPart=2)
        trans_prog.report('Dividing Sample')
        Divide(LHSWorkspace='__sam_fft',
               RHSWorkspace='__sam_int',
               OutputWorkspace='__sam')

        # Resolution
        trans_prog.report('Rebinnig Resolution')
        Rebin(InputWorkspace=self._resolution,
              OutputWorkspace='__res_data',
              Params=rebin_param)
        trans_prog.report('Integrating Resolution')
        Integration(InputWorkspace='__res_data',
                    OutputWorkspace='__res_int')
        trans_prog.report('Converting Resolution to data points')
        ConvertToPointData(InputWorkspace='__res_data',
                           OutputWorkspace='__res_data')
        trans_prog.report('Extractig FFT Resolution spectrum')
        ExtractFFTSpectrum(InputWorkspace='__res_data',
                           OutputWorkspace='__res_fft',
                           FFTPart=2)
        trans_prog.report('Dividing Resolution')
        Divide(LHSWorkspace='__res_fft',
               RHSWorkspace='__res_int',
               OutputWorkspace='__res')

        trans_prog.report('Diving Workspaces')
        Divide(LHSWorkspace='__sam',
               RHSWorkspace='__res',
               OutputWorkspace=self._output_workspace)

        # Cleanup sample workspaces
        trans_prog.report('Deleting Sample temp')
        DeleteWorkspace('__sam_data')
        DeleteWorkspace('__sam_int')
        DeleteWorkspace('__sam_fft')
        DeleteWorkspace('__sam')

        # Crop nonsense values off workspace
        binning = int(math.ceil(mtd[self._output_workspace].blocksize() / 2.0))
        bin_v = mtd[self._output_workspace].dataX(0)[binning]
        trans_prog.report('Cropping output')
        CropWorkspace(InputWorkspace=self._output_workspace,
                      OutputWorkspace=self._output_workspace,
                      XMax=bin_v)

        # Set Y axis unit and label
        mtd[self._output_workspace].setYUnit('')
        mtd[self._output_workspace].setYUnitLabel('Intensity')

        trans_prog.report('Deleting Resolution temp')
        # Clean up resolution workspaces
        DeleteWorkspace('__res_data')
        DeleteWorkspace('__res_int')
        DeleteWorkspace('__res_fft')
        DeleteWorkspace('__res')