示例#1
0
def setToolbarsVisible(visible):
    """Show/hide MantidPlot toolbars

    Args:
        visible: If True, make toolbars visible, if False - hidden
    """
    threadsafe_call(_qti.app.setToolbarsVisible, visible)
示例#2
0
def moveMouseToCentre(widget):
    """Moves the mouse over the widget
    """
    if qtest:
        QtCore.QCoreApplication.processEvents()
        threadsafe_call(QTest.mouseMove, widget)
        QtCore.QCoreApplication.processEvents()
示例#3
0
def closeAllSliceViewers():
    """
    Closes all currently open SliceViewer windows. This might be useful to
    clean up your desktop after opening many windows.
    """
    threadsafe_call(mantidqtpython.MantidQt.Factory.WidgetFactory.Instance().
                    closeAllSliceViewerWindows)
示例#4
0
def closeAllSliceViewers():
    """
    Closes all currently open SliceViewer windows. This might be useful to
    clean up your desktop after opening many windows.
    """
    import mantidqtpython
    threadsafe_call(mantidqtpython.MantidQt.Factory.WidgetFactory.Instance().closeAllSliceViewerWindows)
示例#5
0
def screenshot(widget, filename, description, png_exists=False):
    """ Take a screenshot of the widget for displaying in a html report.

    The MANTID_SCREENSHOT_REPORT environment variable must be set
    to the destination folder. Screenshot taking is skipped otherwise.

    :param widget: QWidget to grab.
    :param filename: Save to this file (no extension!).
    :param description: Short descriptive text of what the screenshot should look like.
    :param png_exists: if True, then the 'filename' already exists. Don't grab a screenshot, but add to the report.
    """
    dest = get_screenshot_dir()
    if dest is not None:
        report = os.path.join(dest, "index.html")

        if png_exists:
            pass
        else:
            # Find the widget if handled with a proxy
            if hasattr(widget, "_getHeldObject"):
                widget = widget._getHeldObject()

        if widget is not None:
            camera = Screenshot()
            threadsafe_call(camera.take_picture, widget,
                            os.path.join(dest, filename + ".png"))

        # Modify the section in the HTML page
        section_text = '<h2>%s</h2>' % filename
        now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        section_text += '%s (%s)<br />' % (description, now)
        section_text += '<img src="%s.png" alt="%s"></img>' % (filename,
                                                               description)

        _replace_report_text(report, filename, section_text)
示例#6
0
文件: __init__.py 项目: mducle/mantid
def screenshot(widget, filename, description, png_exists=False):
    """ Take a screenshot of the widget for displaying in a html report.

    The MANTID_SCREENSHOT_REPORT environment variable must be set
    to the destination folder. Screenshot taking is skipped otherwise.

    :param widget: QWidget to grab.
    :param filename: Save to this file (no extension!).
    :param description: Short descriptive text of what the screenshot should look like.
    :param png_exists: if True, then the 'filename' already exists. Don't grab a screenshot, but add to the report.
    """
    dest = get_screenshot_dir()
    if not dest is None:
        report = os.path.join(dest, "index.html")

        if png_exists:
            pass
        else:
            # Find the widget if handled with a proxy
            if hasattr(widget, "_getHeldObject"):
                widget = widget._getHeldObject()

        if widget is not None:
            camera = Screenshot()
            threadsafe_call(camera.take_picture, widget, os.path.join(dest, filename + ".png"))

        # Modify the section in the HTML page
        section_text = '<h2>%s</h2>' % filename
        now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
        section_text += '%s (%s)<br />' % (description, now)
        section_text += '<img src="%s.png" alt="%s"></img>' % (filename, description)

        _replace_report_text(report, filename, section_text)
示例#7
0
def moveMouseToCentre(widget):
    """Moves the mouse over the widget
    """
    if qtest:
        QtCore.QCoreApplication.processEvents()
        threadsafe_call(QTest.mouseMove, widget)
        QtCore.QCoreApplication.processEvents()
示例#8
0
文件: __init__.py 项目: mducle/mantid
def plotTableColumns(table, columns, type = -1):
    """
    This plots one or more columns from a table.

    Args:
        table: a qtiplot or mantid table (not a TableWorkspace)
        columns: a list or a tuple of columns names to plot or a string for a single column.
                To plot error bars add their column name(s).
        type: curve style for plot (-1: unspecified; 0: line, default; 1: scatter/dots)
    Returns:
        A handle to the created window. None in case of error.
    """
    # This function uses qtiplot's methods for plotting tables.
    # To be able to plot error bars all column names must be prefixed
    # with the table name.
    if isinstance(columns, tuple) or isinstance(columns, list):
        columns = ['%s_%s' % (table.name(), column) for column in columns]
        columns = tuple(columns)
    else:
        columns = '%s_%s' % (table.name(), columns)

    graph = proxies.Graph(threadsafe_call(_qti.app.plot, table._getHeldObject(), columns, type))
    threadsafe_call(graph.activeLayer().setTitle, table.windowLabel())

    if graph._getHeldObject() == None:
        raise RuntimeError("Cannot create graph, see log for details.")
    else:
        return graph
示例#9
0
文件: __init__.py 项目: mducle/mantid
def stemPlot(source, index, power=None, startPoint=None, endPoint=None):
    """Generate a stem-and-leaf plot from an input table column or workspace spectrum

    Args:
        source: A reference to a workspace or a table.
        index: For a table, the column number or name. For a workspace, the workspace index.
        power: The stem unit as a power of 10. If not provided, a dialog will appear with a suggested value.
        startPoint: The first point (row or bin) to use (Default: the first one).
        endPoint: The last point (row or bin) to use (Default: the last one).

    Returns:
        A string representation of the stem plot
    """
    # Turn the optional arguments into the magic numbers that the C++ expects
    if power == None:
        power = 1001
    if startPoint == None:
        startPoint = 0
    if endPoint == None:
        endPoint = -1

    if isinstance(source, proxies.QtProxyObject):
        source = source._getHeldObject()
    elif hasattr(source, 'getName'):
        # If the source is a workspace, create a table from the specified index
        wsName = source.getName()
        source = threadsafe_call(_qti.app.mantidUI.workspaceToTable.wsName, wsName, [index], False, True)
        # The C++ stemPlot method takes the name of the column, so get that
        index = source.colName(2)
    # Get column name if necessary
    if isinstance(index, int):
        index = source.colName(index)
    # Call the C++ method
    return threadsafe_call(_qti.app.stemPlot, source, index, power, startPoint, endPoint)
示例#10
0
文件: __init__.py 项目: mducle/mantid
def setToolbarsVisible(visible):
    """Show/hide MantidPlot toolbars

    Args:
        visible: If True, make toolbars visible, if False - hidden
    """
    threadsafe_call(_qti.app.setToolbarsVisible, visible)
示例#11
0
def plotTableColumns(table, columns, type=-1):
    """
    This plots one or more columns from a table.

    Args:
        table: a qtiplot or mantid table (not a TableWorkspace)
        columns: a list or a tuple of columns names to plot or a string for a single column.
                To plot error bars add their column name(s).
        type: curve style for plot (-1: unspecified; 0: line, default; 1: scatter/dots)
    Returns:
        A handle to the created window. None in case of error.
    """
    # This function uses qtiplot's methods for plotting tables.
    # To be able to plot error bars all column names must be prefixed
    # with the table name.
    if isinstance(columns, tuple) or isinstance(columns, list):
        columns = ['%s_%s' % (table.name(), column) for column in columns]
        columns = tuple(columns)
    else:
        columns = '%s_%s' % (table.name(), columns)

    graph = proxies.Graph(
        threadsafe_call(_qti.app.plot, table._getHeldObject(), columns, type))
    threadsafe_call(graph.activeLayer().setTitle, table.windowLabel())

    if graph._getHeldObject() == None:
        raise RuntimeError("Cannot create graph, see log for details.")
    else:
        return graph
示例#12
0
def stemPlot(source, index, power=None, startPoint=None, endPoint=None):
    """Generate a stem-and-leaf plot from an input table column or workspace spectrum

    Args:
        source: A reference to a workspace or a table.
        index: For a table, the column number or name. For a workspace, the workspace index.
        power: The stem unit as a power of 10. If not provided, a dialog will appear with a suggested value.
        startPoint: The first point (row or bin) to use (Default: the first one).
        endPoint: The last point (row or bin) to use (Default: the last one).

    Returns:
        A string representation of the stem plot
    """
    # Turn the optional arguments into the magic numbers that the C++ expects
    if power == None:
        power = 1001
    if startPoint == None:
        startPoint = 0
    if endPoint == None:
        endPoint = -1

    if isinstance(source, proxies.QtProxyObject):
        source = source._getHeldObject()
    elif hasattr(source, 'getName'):
        # If the source is a workspace, create a table from the specified index
        wsName = source.getName()
        source = threadsafe_call(_qti.app.mantidUI.workspaceToTable.wsName, wsName, [index], False, True)
        # The C++ stemPlot method takes the name of the column, so get that
        index = source.colName(2)
    # Get column name if necessary
    if isinstance(index, int):
        index = source.colName(index)
    # Call the C++ method
    return threadsafe_call(_qti.app.stemPlot, source, index, power, startPoint, endPoint)
示例#13
0
def saveProjectAs(file_name, compress=False):
    """Save a mantid project

    This will serialise all associated workspaces and windows

    Args:
        file_name :: file path to save to
        compress :: whether to compress the project after saving
    """
    threadsafe_call(_qti.app.saveProjectAs, file_name, compress)
示例#14
0
文件: __init__.py 项目: mducle/mantid
def saveProjectAs(file_name, compress=False):
    """Save a mantid project

    This will serialise all associated workspaces and windows

    Args:
        file_name :: file path to save to
        compress :: whether to compress the project after saving
    """
    threadsafe_call(_qti.app.saveProjectAs, file_name, compress)
示例#15
0
def openProject(file_name, file_version=0):
    """Open a mantid project file.

    This will load all associated workspaces and plots.

    Args:
        file_name :: file path to a mantid project file
        file_version :: file version to use when loading (default 0).
    """
    working_dir = os.path.dirname(os.path.abspath(file_name))
    threadsafe_call(_qti.app.openProject, working_dir, file_name, file_version)
示例#16
0
def runPythonScript(code, asynchronous=False, quiet=False, redirect=True):
    """
        Redirects the runPythonScript method to the app object
        @param code :: A string of code to execute
        @param asynchronous :: If the true the code is executed in a separate thread
        @param quiet :: If true no messages reporting status are issued
        @param redirect :: If true then output is redirected to MantidPlot
    """
    if asynchronous and QtCore.QThread.currentThread() != QtGui.qApp.thread():
        asynchronous = False
    threadsafe_call(_qti.app.runPythonScript, code, asynchronous, quiet, redirect)
示例#17
0
文件: __init__.py 项目: mducle/mantid
def openProject(file_name, file_version=0):
    """Open a mantid project file.

    This will load all associated workspaces and plots.

    Args:
        file_name :: file path to a mantid project file
        file_version :: file version to use when loading (default 0).
    """
    working_dir = os.path.dirname(os.path.abspath(file_name))
    threadsafe_call(_qti.app.openProject, working_dir, file_name, file_version)
示例#18
0
def runPythonScript(code, asynchronous=False, quiet=False, redirect=True):
    """
        Redirects the runPythonScript method to the app object
        @param code :: A string of code to execute
        @param asynchronous :: If the true the code is executed in a separate thread
        @param quiet :: If true no messages reporting status are issued
        @param redirect :: If true then output is redirected to MantidPlot
    """
    if asynchronous and QtCore.QThread.currentThread() != QtGui.qApp.thread():
        asynchronous = False
    threadsafe_call(_qti.app.runPythonScript, code, asynchronous, quiet,
                    redirect)
示例#19
0
def selectMultiPeak(source, showFitPropertyBrowser=True, xmin=None, xmax=None):
    """Switch on the multi-peak selecting tool for fitting with the Fit algorithm.

    Args:
        source: A reference to a MultiLayer with the data to fit.
        showFitPropertyBrowser: Whether to show the FitPropertyBrowser or not.
        xmin: An optionall minimum X value to select
        xmax: An optionall maximum X value to select
    """
    if xmin is not None and xmax is not None:
        threadsafe_call(_qti.app.selectMultiPeak, source._getHeldObject(), showFitPropertyBrowser, xmin, xmax)
    else:
        threadsafe_call(_qti.app.selectMultiPeak, source._getHeldObject(), showFitPropertyBrowser)
示例#20
0
文件: __init__.py 项目: mducle/mantid
def selectMultiPeak(source, showFitPropertyBrowser=True, xmin=None, xmax=None):
    """Switch on the multi-peak selecting tool for fitting with the Fit algorithm.

    Args:
        source: A reference to a MultiLayer with the data to fit.
        showFitPropertyBrowser: Whether to show the FitPropertyBrowser or not.
        xmin: An optionall minimum X value to select
        xmax: An optionall maximum X value to select
    """
    if xmin is not None and xmax is not None:
        threadsafe_call(_qti.app.selectMultiPeak, source._getHeldObject(), showFitPropertyBrowser, xmin, xmax)
    else:
        threadsafe_call(_qti.app.selectMultiPeak, source._getHeldObject(), showFitPropertyBrowser)
示例#21
0
def getSliceViewer(source, label=""):
    """Retrieves a handle to a previously-open SliceViewerWindow.
    This allows you to get a handle on, e.g., a SliceViewer that was open
    by the MultiSlice view in VATES Simple Interface.
    Will raise an exception if not found.

    Args:
        source :: name of the workspace that was open
        label :: additional label string that was used to identify the window.

    Returns:
        a handle to the SliceViewerWindow object that was created before.
    """
    import mantidqtpython
    workspace_names = getWorkspaceNames(source)
    if len(workspace_names) != 1:
        raise Exception("Please specify only one workspace.")
    else:
        svw = threadsafe_call(
            mantidqtpython.MantidQt.Factory.WidgetFactory.Instance().
            getSliceViewerWindow, workspace_names[0], label)
        if svw is not None:
            return proxies.SliceViewerWindowProxy(svw)
        else:
            return None
示例#22
0
文件: __init__.py 项目: mducle/mantid
def plot2D(source, style=DEFAULT_2D_STYLE, window=None):
    """Open a 2D plot of the given workspace(s)

    Produces a 2D histogram for each of the given workspaces

    Args:
        source: workspace or name of a workspace
        style: Indicates the type of plot required. Default=ColorMap
        window: window used for plotting. If None a new one will be created
    Returns:
        If a single workspace is specified then the handle is returned, otherwise a list
        of handles for each new window is returned
    """
    names = getWorkspaceNames(source)
    if len(names) == 0:
        raise ValueError("No workspace names given to plot")

    # Unwrap the window object, if any specified
    if window != None:
        window = window._getHeldObject()

    handles = []
    cfunc = _qti.app.mantidUI.drawSingleColorFillPlot
    for name in names:
        g = proxies.Graph(threadsafe_call(cfunc, name, style, window))
        if g:
            handles.append(g)
        else:
            raise RuntimeError("Cannot create graph from workspace '%s'" % name)

    if len(handles) == 1:
        return handles[0]
    else:
        return handles
示例#23
0
def copyFolder(source, destination):
    """Copy a folder (and its contents) into another.

    Returns:
        True on success.
    """
    return threadsafe_call(_qti.app.copyFolder, source._getHeldObject(), destination._getHeldObject())
示例#24
0
文件: __init__.py 项目: mducle/mantid
def copyFolder(source, destination):
    """Copy a folder (and its contents) into another.

    Returns:
        True on success.
    """
    return threadsafe_call(_qti.app.copyFolder, source._getHeldObject(), destination._getHeldObject())
示例#25
0
def plotSubplots(source,
                 indices,
                 distribution=mantidqtpython.MantidQt.DistributionDefault,
                 error_bars=False,
                 window=None):
    """Open a tiled plot.

    This plots one or more spectra, with X as the bin boundaries,
    and Y as the counts in each bin.

    If one workspace, each spectrum gets its own tile.
    Otherwise, each workspace gets its own tile.

    Args:
        source: list of workspace names
        indices: workspace index, or tuple or list of workspace indices to plot
        distribution: whether or not to plot as a distribution
        error_bars: bool, set to True to add error bars.
        window: window used for plotting. If None a new one will be created
    Returns:
        A handle to window if one was specified, otherwise a handle to the created one. None in case of error.
    """

    workspace_names = getWorkspaceNames(source)

    # Deal with workspace groups that may contain various types:
    # Only want to plot MatrixWorkspaces
    to_plot = []
    for name in workspace_names:
        if isinstance(mantid.api.mtd[name], mantid.api.MatrixWorkspace):
            to_plot.append(name)

    __checkPlotWorkspaces(to_plot)
    # check spectrum indices
    index_list = __getWorkspaceIndices(indices)
    if len(index_list) == 0:
        raise ValueError("No spectrum indices given")
    for idx in index_list:
        if idx < 0:
            raise ValueError("Wrong spectrum index (<0): %d" % idx)
    for name in to_plot:
        max_spec = workspace(name).getNumberHistograms() - 1
        for idx in index_list:
            if idx > max_spec:
                raise ValueError(
                    "Wrong spectrum index for workspace '%s': %d, which is bigger than the"
                    " number of spectra in this workspace - 1 (%d)" %
                    (name, idx, max_spec))

    # Unwrap the window object, if any specified
    if window is not None:
        window = window._getHeldObject()

    graph = proxies.Graph(
        threadsafe_call(_qti.app.mantidUI.plotSubplots, to_plot, index_list,
                        distribution, error_bars, window))
    if graph._getHeldObject() == None:
        raise RuntimeError("Cannot create graph, see log for details.")
    else:
        return graph
示例#26
0
def plot2D(source, style=DEFAULT_2D_STYLE, window=None):
    """Open a 2D plot of the given workspace(s)

    Produces a 2D histogram for each of the given workspaces

    Args:
        source: workspace or name of a workspace
        style: Indicates the type of plot required. Default=ColorMap
        window: window used for plotting. If None a new one will be created
    Returns:
        If a single workspace is specified then the handle is returned, otherwise a list
        of handles for each new window is returned
    """
    names = getWorkspaceNames(source)
    if len(names) == 0:
        raise ValueError("No workspace names given to plot")

    # Unwrap the window object, if any specified
    if window is not None:
        window = window._getHeldObject()

    handles = []
    cfunc = _qti.app.mantidUI.drawSingleColorFillPlot
    for name in names:
        g = proxies.Graph(threadsafe_call(cfunc, name, style, window))
        if g:
            handles.append(g)
        else:
            raise RuntimeError("Cannot create graph from workspace '%s'" %
                               name)

    if len(handles) == 1:
        return handles[0]
    else:
        return handles
示例#27
0
文件: __init__.py 项目: mducle/mantid
def screenshot_to_dir(widget, filename, screenshot_dir):
    """Take a screenshot_to_dir of a widget

    @param widget :: QWidget to take an image of
    @param filename :: Destination filename for that image
    @param screenshot_dir :: Directory to put the screenshots into.
    """
    # Find the widget if handled with a proxy
    if hasattr(widget, "_getHeldObject"):
        widget = widget._getHeldObject()

    if widget is not None:
        camera = Screenshot()
        imgpath = os.path.join(screenshot_dir, filename)
        threadsafe_call(camera.take_picture, widget, imgpath)
        return imgpath
    else:
        raise RuntimeError("Unable to retrieve widget. Has it been deleted?")
示例#28
0
def screenshot_to_dir(widget, filename, screenshot_dir):
    """Take a screenshot_to_dir of a widget

    @param widget :: QWidget to take an image of
    @param filename :: Destination filename for that image
    @param screenshot_dir :: Directory to put the screenshots into.
    """
    # Find the widget if handled with a proxy
    if hasattr(widget, "_getHeldObject"):
        widget = widget._getHeldObject()

    if widget is not None:
        camera = Screenshot()
        imgpath = os.path.join(screenshot_dir, filename)
        threadsafe_call(camera.take_picture, widget, imgpath)
        return imgpath
    else:
        raise RuntimeError("Unable to retrieve widget. Has it been deleted?")
示例#29
0
def plotBin(source,
            indices,
            error_bars=False,
            type=-1,
            window=None,
            clearWindow=False,
            waterfall=False):
    """Create a 1D Plot of bin count vs spectrum in a workspace.

    This puts the spectrum number as the X variable, and the
    count in the particular bin # (in 'indices') as the Y value.

    If indices is a tuple or list, then several curves are created, one
    for each bin index.

    Args:
        source: workspace or name of a workspace
        indices: bin number(s) to plot
        error_bars: bool, set to True to add error bars.
        type: Plot style
        window: window used for plotting. If None a new one will be created
        clearWindow: if is True, the window specified will be cleared before adding new curve
        waterfall: if True, plot as a waterfall if there is more than 1 curve
    Returns:
        A handle to window if one was specified, otherwise a handle to the created one. None in case of error.
    """
    workspace_names = getWorkspaceNames(source)
    __checkPlotWorkspaces(workspace_names)
    index_list = __getWorkspaceIndices(indices)
    if len(index_list) == 0:
        raise ValueError("No indices given")

    for idx in index_list:
        if idx < 0:
            raise ValueError("Wrong bin index (<0): %d" % idx)
    for name in workspace_names:
        max_bin = workspace(name).blocksize() - 1
        for idx in index_list:
            if idx > max_bin:
                raise ValueError(
                    "Wrong bin index for workspace '%s': %d, which is bigger than the"
                    " number of bins in this workspace - 1 (%d)" %
                    (name, idx, max_bin))

    # Unwrap the window object, if any specified
    if window is not None:
        window = window._getHeldObject()

    graph = proxies.Graph(
        threadsafe_call(_qti.app.mantidUI.plot1D, workspace_names, index_list,
                        False, mantidqtpython.MantidQt.DistributionDefault,
                        error_bars, type, window, clearWindow, waterfall))
    if graph._getHeldObject() == None:
        raise RuntimeError("Cannot create graph, see log for details.")
    else:
        return graph
示例#30
0
def changeFolder(folder, force=False):
    """Changes the current folder.

    Args:
        folder: A reference to the folder to change to.
        force: Whether to do stuff even if the new folder is already the active one (default: no).

    Returns:
        True on success.
    """
    return threadsafe_call(_qti.app.changeFolder, folder._getHeldObject(), force)
示例#31
0
文件: __init__.py 项目: mducle/mantid
def changeFolder(folder, force=False):
    """Changes the current folder.

    Args:
        folder: A reference to the folder to change to.
        force: Whether to do stuff even if the new folder is already the active one (default: no).

    Returns:
        True on success.
    """
    return threadsafe_call(_qti.app.changeFolder, folder._getHeldObject(), force)
示例#32
0
def plotSpectrum(source,
                 indices,
                 distribution=mantidqtpython.MantidQt.DistributionDefault,
                 error_bars=False,
                 type=-1,
                 window=None,
                 clearWindow=False,
                 waterfall=False):
    """Open a 1D Plot of a spectrum in a workspace.

    This plots one or more spectra, with X as the bin boundaries,
    and Y as the counts in each bin.

    Args:
        source: workspace or name of a workspace
        indices: workspace index, or tuple or list of workspace indices to plot
        error_bars: bool, set to True to add error bars.
        type: curve style for plot (-1: unspecified; 0: line, default; 1: scatter/dots)
        window: window used for plotting. If None a new one will be created
        clearWindow: if is True, the window specified will be cleared before adding new curve
        waterfall: if True, plot as a waterfall if there is more than 1 curve
    Returns:
        A handle to window if one was specified, otherwise a handle to the created one. None in case of error.
    """
    workspace_names = getWorkspaceNames(source)
    __checkPlotWorkspaces(workspace_names)
    # check spectrum indices
    index_list = __getWorkspaceIndices(indices)
    if len(index_list) == 0:
        raise ValueError("No spectrum indices given")
    for idx in index_list:
        if idx < 0:
            raise ValueError("Wrong spectrum index (<0): %d" % idx)
    for name in workspace_names:
        max_spec = workspace(name).getNumberHistograms() - 1
        for idx in index_list:
            if idx > max_spec:
                raise ValueError(
                    "Wrong spectrum index for workspace '%s': %d, which is bigger than the"
                    " number of spectra in this workspace - 1 (%d)" %
                    (name, idx, max_spec))

    # Unwrap the window object, if any specified
    if window is not None:
        window = window._getHeldObject()

    graph = proxies.Graph(
        threadsafe_call(_qti.app.mantidUI.plot1D, workspace_names, index_list,
                        True, distribution, error_bars, type, window,
                        clearWindow, waterfall))
    if graph._getHeldObject() == None:
        raise RuntimeError("Cannot create graph, see log for details.")
    else:
        return graph
示例#33
0
def plotSubplots(source, indices, distribution = mantidqtpython.MantidQt.DistributionDefault, error_bars=False, window=None):
    """Open a tiled plot.

    This plots one or more spectra, with X as the bin boundaries,
    and Y as the counts in each bin.
    
    If one workspace, each spectrum gets its own tile.
    Otherwise, each workspace gets its own tile.

    Args:
        source: list of workspace names
        indices: workspace index, or tuple or list of workspace indices to plot
        distribution: whether or not to plot as a distribution
        error_bars: bool, set to True to add error bars.
        window: window used for plotting. If None a new one will be created
    Returns:
        A handle to window if one was specified, otherwise a handle to the created one. None in case of error.
    """

    workspace_names = getWorkspaceNames(source)
   
    # Deal with workspace groups that may contain various types:
    # Only want to plot MatrixWorkspaces
    to_plot = []
    for name in workspace_names:
        if isinstance(mantid.api.mtd[name], mantid.api.MatrixWorkspace):
            to_plot.append(name)
            
    __checkPlotWorkspaces(to_plot)
    # check spectrum indices
    index_list = __getWorkspaceIndices(indices)
    if len(index_list) == 0:
        raise ValueError("No spectrum indices given")
    for idx in index_list:
        if idx < 0:
            raise ValueError("Wrong spectrum index (<0): %d" % idx)
    for name in to_plot:
        max_spec = workspace(name).getNumberHistograms() - 1
        for idx in index_list:
            if idx > max_spec:
                raise ValueError("Wrong spectrum index for workspace '%s': %d, which is bigger than the"
                                 " number of spectra in this workspace - 1 (%d)" % (name, idx, max_spec))
    
    # Unwrap the window object, if any specified
    if window != None:
        window = window._getHeldObject()
    
    graph = proxies.Graph(threadsafe_call(_qti.app.mantidUI.plotSubplots,
                                          to_plot, index_list, distribution, error_bars, window))
    if graph._getHeldObject() == None:
        raise RuntimeError("Cannot create graph, see log for details.")
    else:
        return graph
示例#34
0
def plotMD(source,
           plot_axis=-2,
           normalization=DEFAULT_MD_NORMALIZATION,
           error_bars=False,
           window=None,
           clearWindow=False):
    """Open a 1D plot of a MDWorkspace.

    Args:
        source: Workspace(s) to plot
        plot_axis: Index of the plot axis (defaults to auto-select)
        normalization: Type of normalization required (defaults to volume, options available:
        MDNormalization.NoNormalization, MDNormalization.NumEventsNormalization, and
        MDNormalization.VolumeNormalization).
        error_bars: Flag for error bar plotting.
        window: window used for plotting. If None a new one will be created
        clearWindow: if is True, the window specified will be cleared before adding new curve
    Returns:
        A handle to the matrix containing the image data.
    """
    workspace_names = getWorkspaceNames(source)
    __checkPlotMDWorkspaces(workspace_names)

    for name in workspace_names:
        non_integrated_dims = mantid.api.mtd[name].getNonIntegratedDimensions()
        if not len(non_integrated_dims) == 1:
            raise ValueError(
                "'%s' must have a single non-integrated dimension in order to be rendered via plotMD"
                % name)

    # check axis index
    for name in workspace_names:
        ws = workspace(name)
        if hasattr(ws, "axes"):
            max_axis = workspace(name).axes()
            # see choice in MantidQwtIMDWorkspaceData::setPlotAxisChoice, -2: auto, -1: distance
            if plot_axis < -2 or plot_axis > max_axis:
                raise ValueError(
                    "Incorrect axis index given for workspace '%s': %d, should be < %d"
                    % (name, plot_axis, max_axis))

    # Unwrap the window object, if any specified
    if window is not None:
        window = window._getHeldObject()

    graph = proxies.Graph(
        threadsafe_call(_qti.app.mantidUI.plotMDList, workspace_names,
                        plot_axis, normalization, error_bars, window,
                        clearWindow))

    return graph
示例#35
0
文件: __init__.py 项目: mducle/mantid
def plotBin(source, indices, error_bars=False, type=-1, window=None, clearWindow=False,
            waterfall=False):
    """Create a 1D Plot of bin count vs spectrum in a workspace.

    This puts the spectrum number as the X variable, and the
    count in the particular bin # (in 'indices') as the Y value.

    If indices is a tuple or list, then several curves are created, one
    for each bin index.

    Args:
        source: workspace or name of a workspace
        indices: bin number(s) to plot
        error_bars: bool, set to True to add error bars.
        type: Plot style
        window: window used for plotting. If None a new one will be created
        clearWindow: if is True, the window specified will be cleared before adding new curve
        waterfall: if True, plot as a waterfall if there is more than 1 curve
    Returns:
        A handle to window if one was specified, otherwise a handle to the created one. None in case of error.
    """
    workspace_names = getWorkspaceNames(source)
    __checkPlotWorkspaces(workspace_names)
    index_list = __getWorkspaceIndices(indices)
    if len(index_list) == 0:
        raise ValueError("No indices given")

    for idx in index_list:
        if idx < 0:
            raise ValueError("Wrong bin index (<0): %d" % idx)
    for name in workspace_names:
        max_bin = workspace(name).blocksize() - 1
        for idx in index_list:
            if idx > max_bin:
                raise ValueError("Wrong bin index for workspace '%s': %d, which is bigger than the"
                                 " number of bins in this workspace - 1 (%d)" % (name, idx, max_bin))

    # Unwrap the window object, if any specified
    if window != None:
        window = window._getHeldObject()

    graph = proxies.Graph(threadsafe_call(_qti.app.mantidUI.plot1D,
                                          workspace_names, index_list, False, mantidqtpython.MantidQt.DistributionDefault, error_bars,
                                          type, window, clearWindow, waterfall))
    if graph._getHeldObject() == None:
        raise RuntimeError("Cannot create graph, see log for details.")
    else:
        return graph
示例#36
0
文件: __init__.py 项目: mducle/mantid
def plotSpectrum(source, indices, distribution = mantidqtpython.MantidQt.DistributionDefault, error_bars=False, type=-1, window=None,
                 clearWindow=False, waterfall=False):
    """Open a 1D Plot of a spectrum in a workspace.

    This plots one or more spectra, with X as the bin boundaries,
    and Y as the counts in each bin.

    Args:
        source: workspace or name of a workspace
        indices: workspace index, or tuple or list of workspace indices to plot
        error_bars: bool, set to True to add error bars.
        type: curve style for plot (-1: unspecified; 0: line, default; 1: scatter/dots)
        window: window used for plotting. If None a new one will be created
        clearWindow: if is True, the window specified will be cleared before adding new curve
        waterfall: if True, plot as a waterfall if there is more than 1 curve
    Returns:
        A handle to window if one was specified, otherwise a handle to the created one. None in case of error.
    """
    workspace_names = getWorkspaceNames(source)
    __checkPlotWorkspaces(workspace_names)
    # check spectrum indices
    index_list = __getWorkspaceIndices(indices)
    if len(index_list) == 0:
        raise ValueError("No spectrum indices given")
    for idx in index_list:
        if idx < 0:
            raise ValueError("Wrong spectrum index (<0): %d" % idx)
    for name in workspace_names:
        max_spec = workspace(name).getNumberHistograms() - 1
        for idx in index_list:
            if idx > max_spec:
                raise ValueError("Wrong spectrum index for workspace '%s': %d, which is bigger than the"
                                 " number of spectra in this workspace - 1 (%d)" % (name, idx, max_spec))

    # Unwrap the window object, if any specified
    if window != None:
        window = window._getHeldObject()

    graph = proxies.Graph(threadsafe_call(_qti.app.mantidUI.plot1D,
                                          workspace_names, index_list, True, distribution, error_bars,
                                          type, window, clearWindow, waterfall))
    if graph._getHeldObject() == None:
        raise RuntimeError("Cannot create graph, see log for details.")
    else:
        return graph
示例#37
0
文件: __init__.py 项目: mducle/mantid
def plotMD(source, plot_axis=-2, normalization=DEFAULT_MD_NORMALIZATION, error_bars=False, window=None,
           clearWindow=False):
    """Open a 1D plot of a MDWorkspace.

    Args:
        source: Workspace(s) to plot
        plot_axis: Index of the plot axis (defaults to auto-select)
        normalization: Type of normalization required (defaults to volume, options available:
        MDNormalization.NoNormalization, MDNormalization.NumEventsNormalization, and
        MDNormalization.VolumeNormalization).
        error_bars: Flag for error bar plotting.
        window: window used for plotting. If None a new one will be created
        clearWindow: if is True, the window specified will be cleared before adding new curve
    Returns:
        A handle to the matrix containing the image data.
    """
    workspace_names = getWorkspaceNames(source)
    __checkPlotMDWorkspaces(workspace_names)

    for name in workspace_names:
        non_integrated_dims = mantid.api.mtd[name].getNonIntegratedDimensions()
        if not len(non_integrated_dims) == 1:
            raise ValueError(
                "'%s' must have a single non-integrated dimension in order to be rendered via plotMD" % name)

    # check axis index
    for name in workspace_names:
        ws = workspace(name)
        if hasattr(ws, "axes"):
            max_axis = workspace(name).axes()
            # see choice in MantidQwtIMDWorkspaceData::setPlotAxisChoice, -2: auto, -1: distance
            if plot_axis < -2 or plot_axis > max_axis:
                raise ValueError(
                    "Incorrect axis index given for workspace '%s': %d, should be < %d" % (name, plot_axis, max_axis))

    # Unwrap the window object, if any specified
    if window != None:
        window = window._getHeldObject()

    graph = proxies.Graph(threadsafe_call(_qti.app.mantidUI.plotMDList, workspace_names, plot_axis, normalization,
                                          error_bars, window, clearWindow))

    return graph
示例#38
0
def getSliceViewer(source, label=""):
    """Retrieves a handle to a previously-open SliceViewerWindow.
    This allows you to get a handle on, e.g., a SliceViewer that was open
    by the MultiSlice view in VATES Simple Interface.
    Will raise an exception if not found.

    Args:
        source :: name of the workspace that was open
        label :: additional label string that was used to identify the window.

    Returns:
        a handle to the SliceViewerWindow object that was created before.
    """
    import mantidqtpython
    workspace_names = getWorkspaceNames(source)
    if len(workspace_names) != 1:
        raise Exception("Please specify only one workspace.")
    else:
        svw = threadsafe_call(mantidqtpython.MantidQt.Factory.WidgetFactory.Instance().getSliceViewerWindow, workspace_names[0], label)
        if svw is not None:
            return proxies.SliceViewerWindowProxy(svw)
        else:
            return None
示例#39
0
文件: __init__.py 项目: mducle/mantid
def setPreferences(layer):
    threadsafe_call(_qti.app.setPreferences, layer._getHeldObject())
示例#40
0
文件: __init__.py 项目: mducle/mantid
def setWindowName(window, name):
    """Set the given window to have the given name"""
    threadsafe_call(_qti.app.setWindowName, window._getHeldObject(), name)
示例#41
0
文件: __init__.py 项目: mducle/mantid
def saveAsTemplate(window, filename):
    """Save the characteristics of the given window to file"""
    threadsafe_call(_qti.app.saveAsTemplate, window._getHeldObject(), filename)
示例#42
0
def newProject():
    """Start a new mantid project

    This will clear all existing unsaved projects
    """
    threadsafe_call(_qti.app.newProject)
示例#43
0
def __doSliceViewer(wsname,
                    label="",
                    xydim=None,
                    slicepoint=None,
                    colormin=None,
                    colormax=None,
                    colorscalelog=False,
                    limits=None,
                    normalization=1):
    """Open a single SliceViewerWindow for the workspace, and shows it

    Args:
        wsname :: name of the workspace
    See plotSlice() for full list of keyword parameters.

    Returns:
        A handle to the created SliceViewerWindow widget
    """
    import mantidqtpython
    from PyQt4 import QtCore

    svw = threadsafe_call(
        mantidqtpython.MantidQt.Factory.WidgetFactory.Instance().
        createSliceViewerWindow, wsname, label)
    threadsafe_call(svw.show)

    # -- Connect to main window's shut down signal ---
    QtCore.QObject.connect(_qti.app, QtCore.SIGNAL("shutting_down()"), svw,
                           QtCore.SLOT("close()"))

    sv = threadsafe_call(svw.getSlicer)
    # --- X/Y Dimensions ---
    if (xydim is not None):
        if len(xydim) != 2:
            raise Exception(
                "You need to specify two values in the 'xydim' parameter")
        else:
            threadsafe_call(sv.setXYDim, xydim[0], xydim[1])

    # --- Slice point ---
    if slicepoint is not None:
        for d in range(len(slicepoint)):
            try:
                val = float(slicepoint[d])
            except ValueError:
                raise ValueError(
                    "Could not convert item %d of slicepoint parameter to float (got '%s'"
                    % (d, slicepoint[d]))
            sv.setSlicePoint(d, val)

    # Set the normalization before the color scale
    threadsafe_call(sv.setNormalization, normalization)

    # --- Color scale ---
    if (colormin is not None) and (colormax is not None):
        threadsafe_call(sv.setColorScale, colormin, colormax, colorscalelog)
    else:
        if colormin is not None:
            threadsafe_call(sv.setColorScaleMin, colormin)
        if colormax is not None:
            threadsafe_call(sv.setColorScaleMax, colormax)
    try:
        threadsafe_call(sv.setColorScaleLog, colorscalelog)
    except:
        print("Log color scale not possible.")

    # --- XY limits ---
    if limits is not None:
        threadsafe_call(sv.setXYLimits, limits[0], limits[1], limits[2],
                        limits[3])

    return svw
示例#44
0
文件: __init__.py 项目: mducle/mantid
def deleteFolder(folder):
    """Delete the referenced folder"""
    return threadsafe_call(_qti.app.deleteFolder, folder._getHeldObject())
示例#45
0
文件: __init__.py 项目: mducle/mantid
def disableTools():
    """Disable all the tools from all the graphs within MantidPlot."""
    threadsafe_call(_qti.app.disableTools)
示例#46
0
def convertToWaterfall(graph):
    """Convert a graph (containing a number of plotted spectra) to a waterfall plot"""
    threadsafe_call(_qti.app.mantidUI.convertToWaterfall,
                    graph._getHeldObject())
示例#47
0
文件: __init__.py 项目: mducle/mantid
def newProject():
    """Start a new mantid project

    This will clear all existing unsaved projects
    """
    threadsafe_call(_qti.app.newProject)
示例#48
0
def disableTools():
    """Disable all the tools from all the graphs within MantidPlot."""
    threadsafe_call(_qti.app.disableTools)
示例#49
0
def setWindowName(window, name):
    """Set the given window to have the given name"""
    threadsafe_call(_qti.app.setWindowName, window._getHeldObject(), name)
示例#50
0
def setPreferences(layer):
    threadsafe_call(_qti.app.setPreferences, layer._getHeldObject())
示例#51
0
文件: __init__.py 项目: mducle/mantid
def convertToWaterfall(graph):
    """Convert a graph (containing a number of plotted spectra) to a waterfall plot"""
    threadsafe_call(_qti.app.mantidUI.convertToWaterfall, graph._getHeldObject())
示例#52
0
文件: __init__.py 项目: mducle/mantid
def createScriptInputDialog(alg_name, preset_values, optional_msg, enabled, disabled):
    """Raises a property input dialog for an algorithm"""
    return threadsafe_call(_qti.app.mantidUI.createScriptInputDialog, alg_name, preset_values, optional_msg, enabled,
                           disabled)
示例#53
0
文件: __init__.py 项目: mducle/mantid
    return mantid.AnalysisDataService.Instance()


# -------------------------- Wrapped MantidPlot functions -----------------

def runPythonScript(code, async=False, quiet=False, redirect=True):
    """
        Redirects the runPythonScript method to the app object
        @param code :: A string of code to execute
        @param async :: If the true the code is executed in a separate thread
        @param quiet :: If true no messages reporting status are issued
        @param redirect :: If true then output is redirected to MantidPlot
    """
    if async and QtCore.QThread.currentThread() != QtGui.qApp.thread():
        async = False
    threadsafe_call(_qti.app.runPythonScript, code, async, quiet, redirect)


# Overload for consistency with qtiplot table(..) & matrix(..) commands
def workspace(name):
    """Get a handle on a workspace.

    Args:
        name: The name of the workspace in the Analysis Data Service.
    """
    return _get_analysis_data_service()[name]


def table(name):
    """Get a handle on a table.
示例#54
0
def saveAsTemplate(window, filename):
    """Save the characteristics of the given window to file"""
    threadsafe_call(_qti.app.saveAsTemplate, window._getHeldObject(), filename)
示例#55
0
def deleteFolder(folder):
    """Delete the referenced folder"""
    return threadsafe_call(_qti.app.deleteFolder, folder._getHeldObject())
示例#56
0
文件: __init__.py 项目: mducle/mantid
def __doSliceViewer(wsname, label="", xydim=None, slicepoint=None,
                    colormin=None, colormax=None, colorscalelog=False,
                    limits=None, normalization=1):
    """Open a single SliceViewerWindow for the workspace, and shows it

    Args:
        wsname :: name of the workspace
    See plotSlice() for full list of keyword parameters.

    Returns:
        A handle to the created SliceViewerWindow widget
    """
    import mantidqtpython
    from PyQt4 import QtCore

    svw = threadsafe_call(mantidqtpython.MantidQt.Factory.WidgetFactory.Instance().createSliceViewerWindow, wsname,
                          label)
    threadsafe_call(svw.show)

    # -- Connect to main window's shut down signal ---
    QtCore.QObject.connect(_qti.app, QtCore.SIGNAL("shutting_down()"),
                           svw, QtCore.SLOT("close()"))

    sv = threadsafe_call(svw.getSlicer)
    # --- X/Y Dimensions ---
    if (not xydim is None):
        if len(xydim) != 2:
            raise Exception("You need to specify two values in the 'xydim' parameter")
        else:
            threadsafe_call(sv.setXYDim, xydim[0], xydim[1])

    # --- Slice point ---
    if not slicepoint is None:
        for d in xrange(len(slicepoint)):
            try:
                val = float(slicepoint[d])
            except ValueError:
                raise ValueError(
                    "Could not convert item %d of slicepoint parameter to float (got '%s'" % (d, slicepoint[d]))
            sv.setSlicePoint(d, val)

    # Set the normalization before the color scale
    threadsafe_call(sv.setNormalization, normalization)

    # --- Color scale ---
    if (not colormin is None) and (not colormax is None):
        threadsafe_call(sv.setColorScale, colormin, colormax, colorscalelog)
    else:
        if (not colormin is None): threadsafe_call(sv.setColorScaleMin, colormin)
        if (not colormax is None): threadsafe_call(sv.setColorScaleMax, colormax)
    try:
        threadsafe_call(sv.setColorScaleLog, colorscalelog)
    except:
        print("Log color scale not possible.")

    # --- XY limits ---
    if not limits is None:
        threadsafe_call(sv.setXYLimits, limits[0], limits[1], limits[2], limits[3])

    return svw
示例#57
0
def createScriptInputDialog(alg_name, preset_values, optional_msg, enabled,
                            disabled):
    """Raises a property input dialog for an algorithm"""
    return threadsafe_call(_qti.app.mantidUI.createScriptInputDialog, alg_name,
                           preset_values, optional_msg, enabled, disabled)