def _load_ws(self, file_paths, ws_names): not_loaded = [] not_opened = [] multi = len(ws_names) > 1 allChecked = False for i, ws_name in enumerate(ws_names): if not self._confirm_workspace_overwrite(ws_name): not_loaded.append(ws_name) else: try: if file_paths[i].endswith('.txt'): load_from_ascii(file_paths[i], ws_name) allChecked = True else: load(filename=file_paths[i], output_workspace=ws_name) except ValueError as e: self._view.error_loading_workspace(e) except RuntimeError: not_opened.append(ws_name) else: if not allChecked: allChecked = self.check_efixed(ws_name, multi) else: get_workspace_handle(ws_name).e_fixed = self._EfCache if self._main_presenter is not None: self._main_presenter.show_workspace_manager_tab() self._main_presenter.update_displayed_workspaces() self._main_presenter.show_tab_for_workspace(get_workspace_handle(ws_name)) self._report_load_errors(ws_names, not_opened, not_loaded)
def _load_ws(self, file_paths, ws_names): not_loaded = [] not_opened = [] multi = len(ws_names) > 1 allChecked = False for i, ws_name in enumerate(ws_names): if not self._confirm_workspace_overwrite(ws_name): not_loaded.append(ws_name) else: try: if file_paths[i].endswith('.txt'): load_from_ascii(file_paths[i], ws_name) else: load(filename=file_paths[i], output_workspace=ws_name) except ValueError as e: self._view.error_loading_workspace(e) except RuntimeError: not_opened.append(ws_name) else: if not allChecked: allChecked = self.check_efixed(ws_name, multi) else: get_workspace_handle(ws_name).e_fixed = self._EfCache if self._main_presenter is not None: self._main_presenter.show_workspace_manager_tab() self._main_presenter.update_displayed_workspaces() self._main_presenter.show_tab_for_workspace( get_workspace_handle(ws_name)) self._report_load_errors(ws_names, not_opened, not_loaded)
def _get_slice_mdhisto(workspace, ws_name): from mslice.models.slice.slice_functions import compute_slice try: return get_workspace_handle('__' + ws_name) except KeyError: x_axis = get_axis_from_dimension(workspace, ws_name, 0) y_axis = get_axis_from_dimension(workspace, ws_name, 1) compute_slice(ws_name, x_axis, y_axis, False) return get_workspace_handle('__' + ws_name)
def _get_slice_mdhisto(workspace, ws_name): from mslice.models.slice.slice_functions import compute_slice try: return get_workspace_handle('__' + ws_name) except KeyError: x_axis = get_axis_from_dimension(workspace, ws_name, 0) y_axis = get_axis_from_dimension(workspace, ws_name, 1) compute_slice(ws_name, x_axis, y_axis, False) return get_workspace_handle('__' + ws_name)
def subtract(workspaces, background_ws, ssf): bg_ws = get_workspace_handle(str(background_ws)).raw_ws scaled_bg_ws = Scale(OutputWorkspace='scaled_bg_ws', store=False, InputWorkspace=bg_ws, Factor=ssf) try: for ws_name in workspaces: ws = get_workspace_handle(ws_name) result = Minus(OutputWorkspace=ws_name + '_subtracted', LHSWorkspace=ws.raw_ws, RHSWorkspace=scaled_bg_ws.raw_ws) propagate_properties(ws, result) except ValueError as e: raise ValueError(e)
def subtract(workspaces, background_ws, ssf): bg_ws = get_workspace_handle(str(background_ws)).raw_ws scaled_bg_ws = Scale(OutputWorkspace='scaled_bg_ws', store=False, InputWorkspace=bg_ws, Factor=ssf) try: for ws_name in workspaces: ws = get_workspace_handle(ws_name) result = Minus(OutputWorkspace=ws_name + '_subtracted', LHSWorkspace=ws.raw_ws, RHSWorkspace=scaled_bg_ws.raw_ws) propagate_properties(ws, result) except ValueError as e: raise ValueError(e)
def preprocess_lines(ws_name, plot_handler, ax): from mslice.plotting.plot_window.cut_plot import CutPlot script_lines = [] if isinstance(plot_handler, CutPlot): cache_list = get_cut_plotter_presenter()._cut_cache_dict[ax] ws_list = {} # use a dict to ensure unique workspaces for workspace_name in [cut.workspace_raw_name for cut in cache_list]: ws_list[get_workspace_handle(workspace_name).raw_ws] = workspace_name for ws, workspace_name in list(ws_list.items()): script_lines += generate_script_lines(ws, workspace_name) else: ws = get_workspace_handle(ws_name).raw_ws script_lines += generate_script_lines(ws, ws_name) return script_lines
def Load(Filename, OutputWorkspace=None): """ Load a workspace from a file. :param Filename: full path to input file (string) :return: """ from mslice.app.presenters import get_dataloader_presenter if not isinstance(Filename, string_types): raise RuntimeError('path given to load must be a string') merge = False if not ospath.exists(Filename): if all([ospath.exists(f) for f in Filename.split('+')]): merge = True else: raise RuntimeError('could not find the path %s' % Filename) get_dataloader_presenter().load_workspace([Filename], merge) name = ospath.splitext(ospath.basename(Filename))[0] if OutputWorkspace is not None: old_name = ospath.splitext(ospath.basename(Filename))[0] if merge: old_name = old_name + '_merged' name = rename_workspace(workspace=old_name, new_name=OutputWorkspace).name return get_workspace_handle(name)
def PlotCut(InputWorkspace, IntensityStart=0, IntensityEnd=0, PlotOver=False): """ Create mslice standard matplotlib plot of a cut workspace. :param InputWorkspace: Workspace to cut. The parameter can be either a python handle to the workspace OR the workspace name as a string. :param IntensityStart: Lower bound of the y axis :param IntensityEnd: Upper bound of the y axis :param PlotOver: if true the cut will be plotted on an existing figure. :return: """ _check_workspace_name(InputWorkspace) workspace = get_workspace_handle(InputWorkspace) if not isinstance(workspace, HistogramWorkspace): raise RuntimeError("Incorrect workspace type.") if IntensityStart == 0 and IntensityEnd == 0: intensity_range = None else: intensity_range = (IntensityStart, IntensityEnd) from mslice.app.presenters import cli_cut_plotter_presenter cli_cut_plotter_presenter.plot_cut_from_workspace(workspace, intensity_range=intensity_range, plot_over=PlotOver) return GlobalFigureManager._active_figure
def Cut(InputWorkspace, CutAxis=None, IntegrationAxis=None, NormToOne=False): """ Cuts workspace. :param InputWorkspace: Workspace to cut. The parameter can be either a python handle to the workspace OR the workspace name as a string. :param CutAxis: The x axis of the cut. If not specified will default to |Q| (or Degrees). :param IntegrationAxis: The integration axis of the cut. If not specified will default to DeltaE. Axis Format:- Either a string in format '<name>, <start>, <end>, <step_size>' e.g. 'DeltaE,0,100,5' (step_size may be omitted for the integration axis) or just the name e.g. 'DeltaE'. In that case, the start and end will default to the full range of the data. Optionally you can also specify the energy unit at the end e.g. '<name>, <start>, <end>, <step>, cm-1', or '<name>, <start>, <end>, meV' Recognised energy units are 'meV' (default) and 'cm-1' :param NormToOne: if True the cut will be normalized to one. :return: """ from mslice.app.presenters import get_cut_plotter_presenter _check_workspace_name(InputWorkspace) workspace = get_workspace_handle(InputWorkspace) _check_workspace_type(workspace, PixelWorkspace) cut_axis = _process_axis(CutAxis, 0, workspace) integration_axis = _process_axis(IntegrationAxis, 1 if workspace.is_PSD else 2, workspace, string_function=_string_to_integration_axis) cut = compute_cut(workspace, cut_axis, integration_axis, NormToOne, store=True) get_cut_plotter_presenter().update_main_window() return cut
def Slice(InputWorkspace, Axis1=None, Axis2=None, NormToOne=False): """ Slices workspace. :param InputWorkspace: The workspace to slice. The parameter can be either a python handle to the workspace OR the workspace name as a string. :param Axis1: The x axis of the slice. If not specified will default to |Q| (or Degrees). :param Axis2: The y axis of the slice. If not specified will default to DeltaE Axis Format:- Either a string in format '<name>, <start>, <end>, <step_size>' e.g. 'DeltaE,0,100,5' or just the name e.g. 'DeltaE'. In that case, the start and end will default to the range in the data. Optionally you can also specify the energy unit at the end e.g. '<name>, <start>, <end>, <step>, cm-1'. Recognised energy units are 'meV' (default) and 'cm-1' :param NormToOne: if True the slice will be normalized to one. :return: """ from mslice.app.presenters import get_slice_plotter_presenter _check_workspace_name(InputWorkspace) workspace = get_workspace_handle(InputWorkspace) _check_workspace_type(workspace, PixelWorkspace) x_axis = _process_axis(Axis1, 0, workspace) y_axis = _process_axis(Axis2, 1 if workspace.is_PSD else 2, workspace) return get_slice_plotter_presenter().create_slice(workspace, x_axis, y_axis, None, None, NormToOne, DEFAULT_CMAP)
def plot_interactive_cut(self, workspace, cut_axis, integration_axis, store): workspace = get_workspace_handle(workspace) cut = Cut(cut_axis, integration_axis, None, None) self._cut_cache[workspace.name] = cut self._plot_cut(workspace, cut, False, store, update_main=False) draw_interactive_cut(workspace)
def compute_recoil_line(ws_name, axis, relative_mass=1): efixed = get_workspace_handle(ws_name).e_fixed x_axis = np.arange(axis.start, axis.end, axis.step) if is_momentum(axis.units): momentum_transfer = x_axis line = np.square(momentum_transfer * 1.e10 * constants.hbar) / (2 * relative_mass * constants.neutron_mass) /\ (constants.elementary_charge / 1000) elif is_twotheta(axis.units): tth = x_axis * np.pi / 180. if 'Direct' in get_workspace_handle(ws_name).e_mode: line = efixed * (2 - 2 * np.cos(tth)) / (relative_mass + 1 - np.cos(tth)) else: line = efixed * (2 - 2 * np.cos(tth)) / (relative_mass - 1 + np.cos(tth)) else: raise RuntimeError("units of axis not recognised") return x_axis, line
def is_sliceable(workspace): ws = get_workspace_handle(workspace) if isinstance(ws, PixelWorkspace): return True else: validator = WorkspaceUnitValidator('DeltaE') return isinstance(ws, Workspace) and validator.isValid(ws.raw_ws) == ''
def is_sliceable(workspace): ws = get_workspace_handle(workspace) if isinstance(ws, PixelWorkspace): return True else: validator = WorkspaceUnitValidator('DeltaE') return isinstance(ws, Workspace) and validator.isValid(ws.raw_ws) == ''
def Slice(InputWorkspace, Axis1=None, Axis2=None, NormToOne=False): """ Slices workspace. :param InputWorkspace: The workspace to slice. The parameter can be either a python handle to the workspace OR the workspace name as a string. :param Axis1: The x axis of the slice. If not specified will default to |Q| (or Degrees). :param Axis2: The y axis of the slice. If not specified will default to DeltaE Axis Format:- Either a string in format '<name>, <start>, <end>, <step_size>' e.g. 'DeltaE,0,100,5' or just the name e.g. 'DeltaE'. In that case, the start and end will default to the range in the data. :param NormToOne: if true the slice will be normalized to one. :return: """ _check_workspace_name(InputWorkspace) workspace = get_workspace_handle(InputWorkspace) _check_workspace_type(workspace, PixelWorkspace) x_axis = _process_axis(Axis1, 0, workspace) y_axis = _process_axis(Axis2, 1 if workspace.is_PSD else 2, workspace) return get_slice_plotter_presenter().create_slice(workspace, x_axis, y_axis, None, None, NormToOne, DEFAULT_CMAP)
def test_rename_workspace(self): rename_workspace('test_ws_md', 'newname') self.assertTrue('newname' in get_visible_workspace_names()) self.assertFalse('test_ws_md' in get_visible_workspace_names()) new_ws = get_workspace_handle('newname') self.assertFalse(new_ws.ef_defined) self.assertEqual(new_ws.limits['DeltaE'], [0, 2, 1])
def test_add_workspace(self): original_data = self.test_ws_2d.raw_ws.dataY(0) add_workspace_runs(['test_ws_2d', 'test_ws_2d']) result = get_workspace_handle('test_ws_2d_sum') np.testing.assert_array_almost_equal(result.raw_ws.dataY(0), [2.0] * 20) np.testing.assert_array_almost_equal(original_data, [1] * 20)
def _name_or_wrapper_to_workspace(input_ws): if isinstance(input_ws, MsliceWorkspace): return input_ws.raw_ws elif isinstance(input_ws, str): return get_workspace_handle(input_ws).raw_ws else: return input_ws
def test_rename_workspace(self): rename_workspace('test_ws_md', 'newname') self.assertTrue('newname' in get_visible_workspace_names()) self.assertFalse('test_ws_md' in get_visible_workspace_names()) new_ws = get_workspace_handle('newname') self.assertFalse(new_ws.ef_defined) self.assertEqual(new_ws.limits['DeltaE'], [0, 2, 1])
def Cut(InputWorkspace, CutAxis=None, IntegrationAxis=None, NormToOne=False): """ Cuts workspace. :param InputWorkspace: Workspace to cut. The parameter can be either a python handle to the workspace OR the workspace name as a string. :param CutAxis: The x axis of the cut. If not specified will default to |Q| (or Degrees). :param IntegrationAxis: The integration axis of the cut. If not specified will default to DeltaE. Axis Format:- Either a string in format '<name>, <start>, <end>, <step_size>' e.g. 'DeltaE,0,100,5' (step_size may be omitted for the integration axis) or just the name e.g. 'DeltaE'. In that case, the start and end will default to the full range of the data. :param NormToOne: if true the cut will be normalized to one. :return: """ _check_workspace_name(InputWorkspace) workspace = get_workspace_handle(InputWorkspace) _check_workspace_type(workspace, PixelWorkspace) cut_axis = _process_axis(CutAxis, 0, workspace) integration_axis = _process_axis( IntegrationAxis, 1 if workspace.is_PSD else 2, workspace, string_function=_string_to_integration_axis) cut = compute_cut(workspace, cut_axis, integration_axis, NormToOne, store=True) get_cut_plotter_presenter().update_main_window() return cut
def _get_current_axis_parameters_if_chosen(self, workspace, available_axes): if self._previous_cut is not None: previous_cut_workspace = get_workspace_handle(self._previous_cut) prev_cut_par, _ = previous_cut_workspace.get_saved_cut_parameters(self._previous_axis) if available_axes == prev_cut_par['axes'] and not workspace.is_axis_saved(self._previous_axis): return prev_cut_par return False
def _name_or_wrapper_to_workspace(input_ws): if isinstance(input_ws, MsliceWorkspace): return input_ws.raw_ws elif isinstance(input_ws, str): return get_workspace_handle(input_ws).raw_ws else: return input_ws
def calculate_projection(self, input_workspace, axis1, axis2, units): """Calculate the projection workspace AND return a python handle to it""" workspace = get_workspace_handle(input_workspace) if not workspace.is_PSD: raise RuntimeError('Cannot calculate projections for non-PSD workspaces') # can have Q-E or 2theta-E or their transpose. if axis1 != DELTA_E_LABEL and axis2 != DELTA_E_LABEL: raise NotImplementedError("Must have a '%s' axis" % DELTA_E_LABEL) if (axis1 == MOD_Q_LABEL or axis2 == MOD_Q_LABEL): projection_type='QE' output_workspace_name = workspace.name + ('_QE' if axis1 == MOD_Q_LABEL else '_EQ') elif (axis1 == THETA_LABEL or axis2 == THETA_LABEL): projection_type='Theta' output_workspace_name = workspace.name + ('_ThE' if axis1 == THETA_LABEL else '_ETh') else: raise NotImplementedError(" Axis '%s' not recognised. Must be '|Q|' or '2Theta'." % (axis1 if axis1 != DELTA_E_LABEL else axis2)) if units == WAVENUMBER_LABEL: output_workspace_name += '_cm' new_ws = mantid_algorithms.MakeProjection(OutputWorkspace=output_workspace_name, InputWorkspace=workspace, Axis1=axis1, Axis2=axis2, Units=units, EMode=workspace.e_mode, Limits=workspace.limits['MomentumTransfer'], ProjectionType=projection_type) propagate_properties(workspace, new_ws) return new_ws
def errorbar(axes, workspace, *args, **kwargs): """ Same as the cli PlotCut but returns the relevant axes object. """ from mslice.app.presenters import get_cut_plotter_presenter cur_fig = plt.gcf() cur_canvas = cur_fig.canvas _check_workspace_name(workspace) workspace = get_workspace_handle(workspace) if not isinstance(workspace, HistogramWorkspace): raise RuntimeError("Incorrect workspace type.") presenter = get_cut_plotter_presenter() plot_over = kwargs.pop('plot_over', True) intensity_range = kwargs.pop('intensity_range', (None, None)) label = kwargs.pop('label', None) label = workspace.name if label is None else label en_conversion_allowed = kwargs.pop('en_conversion', True) cut_axis, int_axis = tuple(workspace.axes) # Checks that current cut has consistent units with previous if plot_over: cached_cuts = presenter.get_cache(axes) if cached_cuts: if (cut_axis.units != cached_cuts[0].cut_axis.units): raise RuntimeError('Cut axes not consistent with current plot. ' 'Expected {}, got {}'.format(cached_cuts[0].cut_axis.units, cut_axis.units)) # Checks whether we should do an energy unit conversion if 'DeltaE' in cut_axis.units and cut_axis.e_unit != cached_cuts[0].cut_axis.e_unit: if en_conversion_allowed: _rescale_energy_cut_plot(presenter, cached_cuts, cut_axis.e_unit) else: raise RuntimeError('Wrong energy unit for cut. ' 'Expected {}, got {}'.format(cached_cuts[0].cut_axis.e_unit, cut_axis.e_unit)) plotfunctions.errorbar(axes, workspace.raw_ws, label=label, *args, **kwargs) axes.set_ylim(*intensity_range) if intensity_range is not None else axes.autoscale() intensity_min, intensity_max = axes.get_ylim() if cur_canvas.manager.window.action_toggle_legends.isChecked(): leg = axes.legend(fontsize='medium') leg.draggable() axes.set_xlabel(get_display_name(cut_axis), picker=CUT_PICKER_TOL_PTS) axes.set_ylabel(CUT_INTENSITY_LABEL, picker=CUT_PICKER_TOL_PTS) if not plot_over: cur_canvas.set_window_title(workspace.name) cur_canvas.manager.update_grid() if not cur_canvas.manager.has_plot_handler(): cur_canvas.manager.add_cut_plot(presenter, workspace.name) cur_fig.canvas.draw() axes.pchanged() # This call is to let the waterfall callback know to update cut = Cut(cut_axis, int_axis, intensity_min, intensity_max, workspace.norm_to_one, width='') cut.workspace_name = workspace.parent presenter.save_cache(axes, cut, plot_over) return axes.lines
def _crystal_structure(ws_name, element, cif_file): if cif_file: ws = get_workspace_handle(ws_name).raw_ws LoadCIF(Workspace=ws, InputFile=cif_file) return ws.sample().getCrystalStructure() else: return CrystalStructure(crystal_structure[element][0], crystal_structure[element][1], crystal_structure[element][2])
def update_integration_axis(self): workspace = get_workspace_handle(self._main_presenter.get_selected_workspaces()[0]) axes = get_available_axes(workspace) if self._cut_view.get_cut_axis() == 'DeltaE': axes.remove('DeltaE') self._cut_view.populate_integration_axis_options(axes) else: self._cut_view.populate_integration_axis_options(['DeltaE'])
def test_subtract_workspace(self): subtract(['test_ws_2d'], 'test_ws_2d', 0.95) result = get_workspace_handle('test_ws_2d_subtracted') np.testing.assert_array_almost_equal(result.raw_ws.dataY(0), [0.05] * 20) np.testing.assert_array_almost_equal(self.test_ws_2d.raw_ws.dataY(0), [1] * 20) self.assertFalse('scaled_bg_ws' in get_visible_workspace_names())
def pcolormesh(axes, workspace, *args, **kwargs): """ Same as the CLI PlotSlice but returns the relevant axes object. """ from mslice.app.presenters import get_slice_plotter_presenter, cli_slice_plotter_presenter _check_workspace_name(workspace) workspace = get_workspace_handle(workspace) _check_workspace_type(workspace, HistogramWorkspace) # slice cache needed from main slice plotter presenter if is_gui() and GlobalFigureManager.get_active_figure().plot_handler is not None: cli_slice_plotter_presenter._slice_cache = app.MAIN_WINDOW.slice_plotter_presenter._slice_cache else: # Needed so the figure manager knows about the slice plot handler create_slice_figure(workspace.name[2:], get_slice_plotter_presenter()) slice_cache = get_slice_plotter_presenter().get_slice_cache(workspace) intensity = kwargs.pop('intensity', None) temperature = kwargs.pop('temperature', None) if temperature is not None: get_slice_plotter_presenter().set_sample_temperature(workspace.name[2:], temperature) if intensity is not None and intensity != 's(q,e)': workspace = getattr(slice_cache, _intensity_to_workspace[intensity]) plot_window = GlobalFigureManager.get_active_figure().window plot_handler = GlobalFigureManager.get_active_figure().plot_handler intensity_action = getattr(plot_window, _intensity_to_action[intensity]) plot_handler.set_intensity(intensity_action) intensity_action.setChecked(True) # Set intensity properties for generated script to use if not is_gui(): for key, value in _function_to_intensity.items(): if value == intensity: intensity_method = key break plot_handler.intensity = True plot_handler.intensity_method = intensity_method plot_handler.temp = temperature plot_handler.temp_dependent = True if temperature is not None else False plot_handler._slice_plotter_presenter._slice_cache[plot_handler.ws_name].colourmap = kwargs.get('cmap') if not workspace.is_PSD and not slice_cache.rotated: workspace = Transpose(OutputWorkspace=workspace.name, InputWorkspace=workspace, store=False) plotfunctions.pcolormesh(axes, workspace.raw_ws, *args, **kwargs) axes.set_title(workspace.name[2:], picker=SLICE_PICKER_TOL_PTS) x_axis = slice_cache.energy_axis if slice_cache.rotated else slice_cache.momentum_axis y_axis = slice_cache.momentum_axis if slice_cache.rotated else slice_cache.energy_axis axes.get_xaxis().set_units(x_axis.units) axes.get_yaxis().set_units(y_axis.units) # labels axes.set_xlabel(get_display_name(x_axis), picker=SLICE_PICKER_TOL_PTS) axes.set_ylabel(get_display_name(y_axis), picker=SLICE_PICKER_TOL_PTS) axes.set_xlim(x_axis.start, x_axis.end) axes.set_ylim(y_axis.start, y_axis.end) return axes.collections[0] # Quadmesh object
def compute_recoil_line(ws_name, axis, relative_mass=1): efixed = get_workspace_handle(ws_name).e_fixed x_axis = np.arange(axis.start, axis.end, axis.step) if axis.units == 'MomentumTransfer' or axis.units == '|Q|': momentum_transfer = x_axis line = np.square(momentum_transfer * 1.e10 * constants.hbar) / (2 * relative_mass * constants.neutron_mass) /\ (constants.elementary_charge / 1000) elif axis.units == 'Degrees': tth = x_axis * np.pi / 180. if 'Direct' in get_workspace_handle(ws_name).e_mode: line = efixed * (2 - 2 * np.cos(tth)) / (relative_mass + 1 - np.cos(tth)) else: line = efixed * (2 - 2 * np.cos(tth)) / (relative_mass - 1 + np.cos(tth)) else: raise RuntimeError("units of axis not recognised") return x_axis, line
def _crystal_structure(ws_name, element, cif_file): if cif_file: ws = get_workspace_handle(ws_name).raw_ws LoadCIF(InputWorkspace=ws, InputFile=cif_file) return ws.sample().getCrystalStructure() else: return CrystalStructure(crystal_structure[element][0], crystal_structure[element][1], crystal_structure[element][2])
def validate_workspace(self, ws): workspace = get_workspace_handle(ws) try: axes = [workspace.raw_ws.getAxis(0), workspace.raw_ws.getAxis(1)] if not all([ax.isSpectra() or ax.getUnit().unitID() == 'DeltaE' for ax in axes]): raise AttributeError except (AttributeError, IndexError): raise TypeError('Input workspace for projection calculation must be a reduced ' 'data workspace with a spectra and energy transfer axis.')
def save_nexus(workspace, path, is_slice): if isinstance(workspace, HistogramWorkspace): if is_slice: workspace = get_workspace_handle(workspace.name[2:]) save_alg = SaveMD else: save_alg = SaveNexus with WrapWorkspaceAttribute(workspace): save_alg(InputWorkspace=workspace, Filename=path)
def compute_slice(selected_workspace, x_axis, y_axis, norm_to_one): workspace = get_workspace_handle(selected_workspace) slice = mantid_algorithms.Slice(OutputWorkspace='__' + workspace.name, InputWorkspace=workspace, XAxis=x_axis.to_dict(), YAxis=y_axis.to_dict(), PSD=workspace.is_PSD, EMode=workspace.e_mode, NormToOne=norm_to_one) propagate_properties(workspace, slice) if norm_to_one: slice = _norm_to_one(slice) return slice
def save_nexus(workspace, path, is_slice): if isinstance(workspace, HistogramWorkspace): if is_slice: SaveMD(InputWorkspace=get_workspace_handle(workspace.name[2:]), Filename=path) else: SaveMD(InputWorkspace=workspace, Filename=path) else: SaveNexus(InputWorkspace=workspace, Filename=path)
def run_cut(self, workspace, cut, plot_over=False, save_only=False): workspace = get_workspace_handle(workspace) self._cut_cache[workspace.name] = cut if cut.width is not None: self._plot_with_width(workspace, cut, plot_over) elif save_only: self.save_cut_to_workspace(workspace, cut) else: self._plot_cut(workspace, cut, plot_over)
def update_integration_axis(self): workspace = get_workspace_handle( self._main_presenter.get_selected_workspaces()[0]) axes = get_available_axes(workspace) if self._cut_view.get_cut_axis() == 'DeltaE': axes.remove('DeltaE') self._cut_view.populate_integration_axis_options(axes) else: self._cut_view.populate_integration_axis_options(['DeltaE'])
def workspace_selection_changed(self): if self._previous_cut is not None and self._previous_axis is not None: if not self._cut_view.is_fields_cleared(): previous_cut_workspace = get_workspace_handle(self._previous_cut) previous_cut_workspace.set_saved_cut_parameters(self._previous_axis, self._cut_view.get_input_fields()) else: self._previous_cut = None self._previous_axis = None workspace_selection = self._main_presenter.get_selected_workspaces() if len(workspace_selection) == 0 or not all([is_cuttable(ws) for ws in workspace_selection]): self._cut_view.clear_input_fields() self._cut_view.disable() self._previous_cut = None self._previous_axis = None else: non_psd = all([not get_workspace_handle(ws).is_PSD for ws in workspace_selection]) self._cut_view.enable_integration_axis(non_psd) self._populate_fields_using_workspace(workspace_selection[0])
def check_efixed(self, ws_name, multi=False): """checks if a newly loaded workspace has efixed set""" ws = get_workspace_handle(ws_name) if ws.e_mode == 'Indirect' and not ws.ef_defined: Ef, allChecked = self._view.get_workspace_efixed( ws_name, multi, self._EfCache) self._EfCache = Ef ws.e_fixed = Ef return allChecked
def run_cut(self, workspace, cut, plot_over=False, save_only=False): workspace = get_workspace_handle(workspace) cut.workspace_name = workspace.name if cut.width is not None: self._plot_with_width(workspace, cut, plot_over) elif save_only: self.save_cut_to_workspace(workspace, cut) else: self._plot_cut(workspace, cut, plot_over)
def export_workspace_to_ads(workspace): """ Exports an MSlice workspace to ADS. If the workspace is MDHisto, convert it to Matrix :param workspace: name of MSlice workspace to export to ADS """ workspace = get_workspace_handle(workspace) if isinstance(workspace, HistogramWorkspace): with wrap_in_ads([workspace]): workspace = workspace.convert_to_matrix() add_to_ads(workspace)
def export_workspace_to_ads(workspace): """ Exports an MSlice workspace to ADS. If the workspace is MDHisto, convert it to Matrix :param workspace: name of MSlice workspace to export to ADS """ workspace = get_workspace_handle(workspace) if isinstance(workspace, HistogramWorkspace): with wrap_in_ads([workspace]): workspace = workspace.convert_to_matrix() add_to_ads(workspace)
def _save_single_ws(workspace, save_name, save_method, path, extension, slice_nonpsd): slice = False save_as = save_name if save_name is not None else str(workspace) + extension full_path = os.path.join(str(path), save_as) workspace = get_workspace_handle(workspace) non_psd_slice = slice_nonpsd and isinstance(workspace, MatrixWorkspace) and not workspace.is_PSD if is_pixel_workspace(workspace) or non_psd_slice: slice = True workspace = _get_slice_mdhisto(workspace, get_workspace_name(workspace)) save_method(workspace, full_path, slice)
def get_cut_parameters(self, pos1, pos2): start = pos1[not self.horizontal] end = pos2[not self.horizontal] units = self._canvas.figure.gca().get_xaxis().units if self.horizontal else \ self._canvas.figure.gca().get_yaxis().units step = get_limits(get_workspace_handle(self._ws_title), units)[2] * self._en_from_meV ax = Axis(units, start, end, step, self._en_unit) integration_start = pos1[self.horizontal] integration_end = pos2[self.horizontal] return ax, integration_start, integration_end
def get_cut_parameters(self, pos1, pos2): start = pos1[not self.horizontal] end = pos2[not self.horizontal] units = self._canvas.figure.gca().get_xaxis().units if self.horizontal else \ self._canvas.figure.gca().get_yaxis().units step = get_limits(get_workspace_handle(self._ws_title), units)[2] ax = Axis(units, start, end, step) integration_start = pos1[self.horizontal] integration_end = pos2[self.horizontal] return ax, integration_start, integration_end
def check_efixed(self, ws_name, multi=False): """checks if a newly loaded workspace has efixed set""" ws = get_workspace_handle(ws_name) if ws.e_mode == 'Indirect' and not ws.ef_defined: Ef, allChecked = self._view.get_workspace_efixed(ws_name, multi, self._EfCache) self._EfCache = Ef ws.e_fixed = Ef ws.raw_ws.run().addProperty('Efix', Ef, True) get_limits(ws_name, 'DeltaE') # This is call needed to process the limits. return allChecked
def _save_single_ws(workspace, save_name, save_method, path, extension, slice_nonpsd): slice = False save_as = save_name if save_name is not None else str(workspace) + extension full_path = os.path.join(str(path), save_as) workspace = get_workspace_handle(workspace) non_psd_slice = slice_nonpsd and isinstance(workspace, Workspace) and not workspace.is_PSD if is_pixel_workspace(workspace) or non_psd_slice: slice = True workspace = _get_slice_mdhisto(workspace, get_workspace_name(workspace)) save_method(workspace, full_path, slice)
def _get_current_axis_parameters_if_chosen(self, workspace, available_axes): if self._previous_cut is not None: previous_cut_workspace = get_workspace_handle(self._previous_cut) prev_cut_par, _ = previous_cut_workspace.get_saved_cut_parameters( self._previous_axis) if available_axes == prev_cut_par[ 'axes'] and not workspace.is_axis_saved( self._previous_axis): return prev_cut_par return False
def get_available_axes(workspace): workspace = get_workspace_handle(workspace) if not workspace.is_PSD: return ['|Q|', '2Theta', 'DeltaE'] dim_names = [] for i in range(workspace.raw_ws.getNumDims()): dim_names.append(workspace.raw_ws.getDimension(i).getName()) if 'Degrees' in dim_names: dim_names.remove('Degrees') dim_names.append('2Theta') return dim_names
def get_available_axes(workspace): workspace = get_workspace_handle(workspace) if not workspace.is_PSD: return ['|Q|', '2Theta', 'DeltaE'] dim_names = [] for i in range(workspace.raw_ws.getNumDims()): dim_names.append(workspace.raw_ws.getDimension(i).getName()) if 'Degrees' in dim_names: dim_names.remove('Degrees') dim_names.append('2Theta') return dim_names
def bragg(self, workspace, element=None, cif=None): from mslice.app.presenters import get_slice_plotter_presenter _check_workspace_name(workspace) workspace = get_workspace_handle(workspace) _check_workspace_type(workspace, HistogramWorkspace) key = _get_overplot_key(element, rmm=None) get_slice_plotter_presenter().add_overplot_line(workspace.name, key, recoil=False, cif=cif) _update_overplot_checklist(key) _update_legend()
def compute_powder_line(ws_name, axis, element, cif_file=False): efixed = get_workspace_handle(ws_name).e_fixed if is_momentum(axis.units): x0 = _compute_powder_line_momentum(ws_name, axis, element, cif_file) elif is_twotheta(axis.units): x0 = _compute_powder_line_degrees(ws_name, axis, element, efixed, cif_file) else: raise RuntimeError("units of axis not recognised") x = sum([[xv, xv, np.nan] for xv in x0], []) y = sum([[efixed / 20, -efixed / 20, np.nan] for xv in x0], []) return x, y
def workspace_selection_changed(self): if self._workspace_manager_view.current_tab() == TAB_2D: psd = all([ get_workspace_handle(ws).is_PSD for ws in self._workspace_manager_view.get_workspace_selected() ]) if psd and not self._psd: self._workspace_manager_view.tab_changed.emit(TAB_2D) self._psd = True elif not psd and self._psd: self._workspace_manager_view.tab_changed.emit(TAB_NONPSD) self._psd = False
def workspace_selection_changed(self): if self._workspace_manager_view.current_tab() == TAB_2D: psd = all([get_workspace_handle(ws).is_PSD for ws in self._workspace_manager_view.get_workspace_selected()]) if psd and not self._psd: self._workspace_manager_view.tab_changed.emit(TAB_2D) self._psd = True elif not psd and self._psd: self._workspace_manager_view.tab_changed.emit(TAB_NONPSD) self._psd = False else: # Default is PSD mode, if changed to a non-2D-workspace the GUI resets to the PSD ("Powder") tab self._psd = True
def plot_cut_from_workspace(self, workspace, intensity_range=None, plot_over=False): workspace = get_workspace_handle(workspace) lines = plot_cut_impl(workspace, self, workspace.raw_ws.getDimension(0).getUnits(), intensity_range=intensity_range, plot_over=plot_over) return lines
def add_workspace(self, workspace): item = QListWidgetItem(workspace) self.onscreen_workspaces.append(workspace) workspace = get_workspace_handle(workspace) if isinstance(workspace, PixelWorkspace): self.listWorkspacesEvent.addItem(item) elif isinstance(workspace, HistogramWorkspace): self.listWorkspacesHisto.addItem(item) elif isinstance(workspace, Workspace): self.listWorkspaces2D.addItem(item) else: raise TypeError("Loaded file is not a valid workspace")
def workspace_selection_changed(self): workspace_selection = self._get_main_presenter( ).get_selected_workspaces() if len(workspace_selection) != 1 or not is_sliceable( workspace_selection[0]): self._slice_view.clear_input_fields() self._slice_view.disable() else: non_psd = all([ not get_workspace_handle(ws).is_PSD for ws in workspace_selection ]) workspace_selection = workspace_selection[0] self._slice_view.enable() self._slice_view.enable_units_choice(non_psd) axis = get_available_axes( get_workspace_handle(workspace_selection)) self._slice_view.populate_slice_x_options(axis) self._slice_view.populate_slice_y_options(axis[::-1]) self.populate_slice_params()
def compute_powder_line(ws_name, axis, element, cif_file=False): efixed = get_workspace_handle(ws_name).e_fixed if axis.units == 'MomentumTransfer' or axis.units == '|Q|': x0 = _compute_powder_line_momentum(ws_name, axis, element, cif_file) elif axis.units == 'Degrees': x0 = _compute_powder_line_degrees(ws_name, axis, element, efixed, cif_file) else: raise RuntimeError("units of axis not recognised") x = sum([[xv, xv, np.nan] for xv in x0], []) y = sum([[efixed / 20, -efixed / 20, np.nan] for xv in x0], []) return x, y
def ask_sample_temperature_field(self, ws_name): text = 'Sample Temperature not found. Select the sample temperature field or enter a value in Kelvin:' ws = get_workspace_handle(ws_name) try: keys = ws.raw_ws.run().keys() except AttributeError: keys = ws.raw_ws.getExperimentInfo(0).run().keys() temp_field, confirm = QtWidgets.QInputDialog.getItem(self.plot_window, 'Sample Temperature', text, keys) if not confirm: raise RuntimeError("sample_temperature_dialog cancelled") else: return str(temp_field), temp_field in keys
def workspace_selection_changed(self): workspace_selection = self._get_main_presenter().get_selected_workspaces() if len(workspace_selection) != 1 or not is_sliceable(workspace_selection[0]): self._slice_view.clear_input_fields() self._slice_view.disable() else: workspace_selection = workspace_selection[0] self._slice_view.enable() axis = get_available_axes(get_workspace_handle(workspace_selection)) self._slice_view.populate_slice_x_options(axis) self._slice_view.populate_slice_y_options(axis[::-1]) self.populate_slice_params()