From 5d3663e35f0dad4d077c43a5ce9dbf686a8429ec Mon Sep 17 00:00:00 2001 From: Aaron Ayres Date: Thu, 15 Apr 2021 07:49:01 -0700 Subject: [PATCH 1/5] delete entire chaco.shell subpackage --- chaco/shell/__init__.py | 1 - chaco/shell/chaco_shell_error.py | 8 - chaco/shell/commands.py | 846 -------------------- chaco/shell/plot_maker.py | 446 ----------- chaco/shell/plot_window.py | 257 ------ chaco/shell/preferences.py | 44 - chaco/shell/scaly_plot.py | 151 ---- chaco/shell/session.py | 160 ---- chaco/shell/tests/__init__.py | 0 chaco/shell/tests/test_make_data_sources.py | 28 - chaco/shell/tests/test_tutorial_example.py | 21 - 11 files changed, 1962 deletions(-) delete mode 100644 chaco/shell/__init__.py delete mode 100644 chaco/shell/chaco_shell_error.py delete mode 100644 chaco/shell/commands.py delete mode 100644 chaco/shell/plot_maker.py delete mode 100644 chaco/shell/plot_window.py delete mode 100644 chaco/shell/preferences.py delete mode 100644 chaco/shell/scaly_plot.py delete mode 100644 chaco/shell/session.py delete mode 100644 chaco/shell/tests/__init__.py delete mode 100644 chaco/shell/tests/test_make_data_sources.py delete mode 100644 chaco/shell/tests/test_tutorial_example.py diff --git a/chaco/shell/__init__.py b/chaco/shell/__init__.py deleted file mode 100644 index 3d6090306..000000000 --- a/chaco/shell/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from .commands import * diff --git a/chaco/shell/chaco_shell_error.py b/chaco/shell/chaco_shell_error.py deleted file mode 100644 index 1387866ea..000000000 --- a/chaco/shell/chaco_shell_error.py +++ /dev/null @@ -1,8 +0,0 @@ -""" Defines the ChacoShellError class. -""" - - -class ChacoShellError(RuntimeError): - """Error raised by the Chaco shell.""" - - pass diff --git a/chaco/shell/commands.py b/chaco/shell/commands.py deleted file mode 100644 index d11bb72df..000000000 --- a/chaco/shell/commands.py +++ /dev/null @@ -1,846 +0,0 @@ -""" Defines commands for the Chaco shell. -""" - - -try: - from wx import GetApp -except ImportError: - GetApp = lambda: None - -from chaco.plot import Plot -from chaco.tools.pan_tool import PanTool -from chaco.tools.zoom_tool import ZoomTool - -# Note: these are imported to be exposed in the namespace. -from chaco.scales.scales import FixedScale, Pow10Scale, LogScale -from chaco.scales.time_scale import CalendarScaleSystem -from chaco.default_colormaps import * - -from . import plot_maker -from .session import PlotSession - -session = PlotSession() - - -# ------------------------------------------------------------------------ -# General help commands -# ------------------------------------------------------------------------ - - -def chaco_commands(): - """ - Prints the current list of all shell commands. Information - on each command is available in that command's docstring (__doc__). - - Window/Plot Management - ---------------------- - figure - creates a new figure window - activate - activates an existing window or plot - close - closes a window - curplot - returns a reference to the active window's Plot object - show - starts the GUI and displays windows (should only be used in scripts) - - Plotting - -------- - plot - plots some data - imread - creates an array from an image file on disk - imshow - creates an image plot from a file on disk - pcolor - plots some scalar data as a pseudocolor image - contour - creates a contour line plot of some scalar data - contourf - creates a contour poly plot of some scalar data - loglog - plots an x-y line or scatter plot on log-log scale - semilogx - plots an x-y line or scatter plot with a log x-scale - semilogy - plots an x-y line or scatter plot with a log y-scale - hold - turns "hold" on or off - show - shows plot on screen; used when running from script - - - Axes, Annotations, Legends - -------------------------- - xaxis - toggles the horizontal axis, sets the interval - yaxis - toggles the vertical axis, sets the interval - xgrid - toggles the grid running along the X axis - ygrid - toggles the grid running along the Y axis - xtitle - sets the title of a horizontal axis - ytitle - sets the title of a vertical axis - xscale - sets the tick scale system of the X axis - yscale - sets the tick scale system of the Y axis - title - sets the title of the plot - - - Tools - ----- - colormap - sets the current colormap - - IO - -- - save - saves the current plot to a file (png, bmp, jpg, pdf) - """ - print(chaco_commands.__doc__) - - # The following are not implemented yet - """ - tool -- toggles certain tools on or off - load -- loads a saved plot from file into the active plot area - scatter -- plots some data as a scatterplot (unordered X/Y data) - line -- plots some data as an ordered set of of X,Y points - label -- adds a label at a data point - legend -- creates a legend and adds it to the plot - - Layout - ------ - names -- temporarily overlays plot areas with their names - hidenames -- force remove the name overlays from show_names - happend -- create a new plot area horizontally after the active plot - vappend -- create a new plot area vertically after the active plot - hsplit -- splits the current plot into two horizontal subplots - vsplit -- splits the current plot into two vertical subplots - save_layout -- saves the current layout of plots and plots areas - load_layout -- loads a saved layout of plot areas and applies it to the - current set of plots - - Sessions - -------- - save_session -- saves the current "workspace", defined as the set of - active windows and plots - load_session -- restores a previously-saved session - save_prefs -- saves the current session's preferences, either in a - separate file or as the chaco.shell defaults - load_prefs -- loads a previously-saved set of preferences - """ - - -# ------------------------------------------------------------------------ -# Window management commands -# ------------------------------------------------------------------------ - - -def figure(name=None, title=None): - """Creates a new figure window and returns its index. - - Parameters - ---------- - name : string - The name to use for this window. If this parameter is provided, then - this name can be used instead of the window's integer index in other - window-related functions. - title : string - The title of the plot window. If this is blank but *name* is provided, - then that is used. If neither *name* nor *title* is provided, then the - method uses the value of default_window_name in the Preferences. - """ - win = session.new_window(name, title) - activate(win) - return win - - -def activate(ident=None): - """Activates and raises a figure window. - - Parameters - ---------- - ident : integer or string - Index or name of the window. If neither is specified, - then the function raises the currently active window. - """ - if ident is not None: - win = session.get_window(ident) - else: - win = session.active_window - - if win is not None: - session.active_window = win - win.raise_window() - - -def show(): - """Shows all the figure windows that have been created thus far, and - creates a GUI main loop. This function is useful in scripts to show plots - and keep their windows open, and has no effect when used from the - interpreter prompt. - """ - - from traits.etsconfig.api import ETSConfig - from pyface.util import guisupport - - is_event_loop_running = getattr( - guisupport, "is_event_loop_running_" + ETSConfig.toolkit - ) - start_event_loop = getattr( - guisupport, "start_event_loop_" + ETSConfig.toolkit - ) - - if not is_event_loop_running(): - frame = session.active_window - frame.raise_window() - start_event_loop() - - -def close(ident=None): - """Closes a figure window - - Parameters - ---------- - ident : integer or string - Index or name of the window to close, or "all". If nothing - is specified, then the function closes the active window. - """ - win_list = [] - if ident is None: - win_list.append(session.active_window) - elif ident == "all": - win_list = session.windows - else: - win_list.append(session.get_window(ident)) - - for win in win_list: - win.close() - - -def colormap(map): - """Sets the active colormap. - - Parameters - ---------- - map : a string, or a callable - The color map to use; if it is a string, it is the name of a default - colormap; if it is a callable, it must return an AbstractColorMap. - """ - if isinstance(map, str): - session.colormap = color_map_name_dict[map] - else: - session.colormap = map - - -def hold(state=None): - """Turns "hold" on or off, or toggles the current state if none - is given. - - Parameters - ---------- - state : Boolean - The desired hold state. - """ - if state is None: - session.hold = not session.hold - else: - session.hold = state - - -def curplot(): - if session.active_window: - return session.active_window.container - else: - return None - - -# ------------------------------------------------------------------------ -# Plotting functions -# ------------------------------------------------------------------------ - - -def _do_plot_boilerplate(kwargs, image=False): - """Used by various plotting functions. Checks/handles hold state, - returns a Plot object for the plotting function to use. - """ - - if "hold" in kwargs: - hold(kwargs["hold"]) - del kwargs["hold"] - - # Check for an active window; if none, open one. - if len(session.windows) == 0: - if image: - win = session.new_window(is_image=True) - activate(win) - else: - figure() - - cont = session.active_window.container - - if not cont: - cont = Plot(session.data) - session.active_window.container = cont - - existing_tools = [type(t) for t in (cont.tools + cont.overlays)] - if not PanTool in existing_tools: - cont.tools.append(PanTool(cont)) - if not ZoomTool in existing_tools: - cont.overlays.append( - ZoomTool( - cont, tool_mode="box", always_on=True, drag_button="right" - ) - ) - - if not session.hold: - cont.delplot(*list(cont.plots.keys())) - - return cont - - -def plot(*data, **kwargs): - """Plots data in a Matlab-compatible way. Data is assumed to be - X vs Y. Any additional *kwargs* passed in are broadcast to all plots. - - Example:: - - x = arange(-pi, pi, pi/100.) - plot(x, sin(x), "b-") - - To use previous data, specify names instead of actual data arrays. - """ - - cont = _do_plot_boilerplate(kwargs) - - plots = plot_maker.do_plot(session.data, cont, *data, **kwargs) - - cont.request_redraw() - - -def semilogx(*data, **kwargs): - """Plots data on a semilog scale in a Matlab-compatible way. Data is - assumed to be X vs Y. Any additional *kwargs* passed in are broadcast - to all plots. - - Example:: - - x = linspace(0.01, 10.0 100) - semilogx(x, sqrt(x), "b-") - - To use previous data, specify names instead of actual data arrays. - - Adding a semilog plot to an active plot with a currently different scale - rescales the plot. - """ - kwargs["index_scale"] = "log" - plot(*data, **kwargs) - - -def semilogy(*data, **kwargs): - """Plots data on a semilog scale in a Matlab-compatible way. Data is - assumed to be X vs Y. Any additional *kwargs* passed in are broadcast - to all plots. - - Example:: - - x = linspace(0, 10.0, 100) - semilogy(x, exp(x), "b-") - - To use previous data, specify names instead of actual data arrays. - - Adding a semilog plot to an active plot with a currently different scale - rescales the plot. - """ - kwargs["value_scale"] = "log" - plot(*data, **kwargs) - - -def loglog(*data, **kwargs): - """Plots data on a log-log scale in a Matlab-compatible way. Data is - assumed to be X vs Y. Any additional *kwargs* passed in are broadcast - to all plots. - - Example:: - - x = linspace(0.001, 10.0, 100) - loglog(x, x**2, "b-") - - To use previous data, specify names instead of actual data arrays. - - Adding a log-log plot to an active plot with a currently different scale - rescales the plot. - """ - kwargs["index_scale"] = "log" - kwargs["value_scale"] = "log" - plot(*data, **kwargs) - - -def imread(*data, **kwargs): - """ Returns image file as an array. """ - - return plot_maker.do_imread(*data, **kwargs) - - -def imshow(*data, **kwargs): - """Creates an image plot from a file on disk. Takes either - filename or image data. Any additional *kwargs* passed in are broadcast - to all plots. - - Example 1:: - - imshow("example.jpg") - - Example 2:: - - image = ImageData.fromfile("example.jpg") - imshow(image) - - To use previous data, specify names instead of filename or data arrays. - - """ - - cont = _do_plot_boilerplate(kwargs, image=True) - - if "colormap" not in kwargs: - kwargs["colormap"] = session.colormap - plots = plot_maker.do_imshow(session.data, cont, *data, **kwargs) - cont.request_redraw() - - -def pcolor(*data, **kwargs): - """Colormaps scalar data in a roughly Matlab-compatible way. Data are - assumed to be a scalar image. Any additional *kwargs* passed in are - broadcast to all plots. - - Example:: - - xs = linspace(0,10,100) - ys = linspace(0,20,200) - x,y=meshgrid(xs,ys) - z = sin(x)*y - pcolor(x, y, z) - - To use previous data, specify names instead of actual data arrays. - """ - - cont = _do_plot_boilerplate(kwargs) - - plots = plot_maker.do_pcolor( - session.data, session.colormap, cont, *data, **kwargs - ) - cont.request_redraw() - - -def contour(*data, **kwargs): - """Contour line plots of scalar data in a roughly Matlab-compatible way. - Data are assumed to be a scalar image. Any additional *kwargs* passed in - are broadcast to all plots. - - Example:: - - xs = linspace(0,10,100) - ys = linspace(0,20,200) - x,y=meshgrid(xs,ys) - z = sin(x)*y - contour(z) - - To use previous data, specify names instead of actual data arrays. - """ - - cont = _do_plot_boilerplate(kwargs) - - plots = plot_maker.do_contour( - session.data, session.colormap, cont, "line", *data, **kwargs - ) - cont.request_redraw() - - -def contourf(*data, **kwargs): - """Contour polygon plots of scalar data in a roughly Matlab-compatible way. - Data are assumed to be a scalar image. Any additional *kwargs* passed in - are broadcast to all plots. - - Example:: - - xs = linspace(0,10,100) - ys = linspace(0,20,200) - x,y=meshgrid(xs,ys) - z = sin(x)*y - contourf(z) - - To use previous data, specify names instead of actual data arrays. - """ - - cont = _do_plot_boilerplate(kwargs) - - plots = plot_maker.do_contour( - session.data, session.colormap, cont, "poly", *data, **kwargs - ) - cont.request_redraw() - - -def plotv(*args, **kwargs): - """Creates a plot of a particular type, or using a "best guess" - approach based on the data, using chaco semantics. - - The number and shape of data arrays determine how the data is - interpreted, and how many plots are created. - - Single-dimensional arrays (shape = (N,)) - ---------------------------------------- - 1. Single array: the data is treated as the value array, and an index - array is generated automatically using arange(len(value)) - 2. Multiple arrays: the first array is treated as the index array, and - each subsequent array is used as the value for a new plot. All of - the plots share a common index (first array). - - Multi-dimensional arrays (shape = (N,2) or (2,N)) - ------------------------------------------------- - 1. Single array (NxM or MxN, N > M): interpreted as M-1 plots of - N data points each, just like in the multiple 1D array case above. - 2. Multiple arrays: each array is treated as a separate set of inter- - related plots, with its own index and value data sources - - Keyword Arguments - ----------------- - type - comma-separated combination of "line", "scatter", "polar" - sort - "ascending", "descending", or "none", indicating the sorting order - of the array that will be used as the index - color - the color of the plot line and/or marker - bgcolor - the background color of the plot - grid - boolean specifying whether or not to draw a grid on the plot - axis - boolean specifying whether or not to draw an axis on the plot - orientation - "h" for index on the X axis, "v" for index on the Y axis - - Scatter plot keywords - --------------------- - marker - the type of marker to use (square, diamond, circle, cross, - crossed circle, triangle, inverted triangle, plus, dot, pixel - marker_size - the size (in pixels) of the marker - outline_color - the color of the marker outline - - Line plot keywords - ------------------ - width - the thickness of the line - dash - the dash style to use (solid, dot dash, dash, dot, long dash) - """ - - cont = _do_plot_boilerplate(kwargs) - plots = plot_maker.do_plotv(session, *args, **kwargs) - cont.add(*plots) - cont.request_redraw() - - -# ----------------------------------------------------------------------------- -# Annotations -# ----------------------------------------------------------------------------- - - -def xtitle(text): - """ Sets the horizontal axis label to *text*. """ - p = curplot() - if p: - p.x_axis.title = text - p.request_redraw() - - -def ytitle(text): - """ Sets the vertical axis label to *text*. """ - p = curplot() - if p: - p.y_axis.title = text - p.request_redraw() - - -def title(text): - """ Sets the plot title to *text*. """ - p = curplot() - if p: - p.title = text - p.request_redraw() - - -_axis_params = """Parameters - ---------- - title : str - The text of the title - title_font : KivaFont('modern 12') - The font in which to render the title - title_color : color ('color_name' or (red, green, blue, [alpha]) tuple) - The color in which to render the title - tick_weight : float - The thickness (in pixels) of each tick - tick_color : color ('color_name' or (red, green, blue, [alpha]) tuple) - The color of the ticks - tick_label_font : KivaFont('modern 10') - The font in which to render the tick labels - tick_label_color : color ('color_name' or (red, green, blue, [alpha]) tuple) - The color of the tick labels - tick_label_formatter : callable - A callable that is passed the numerical value of each tick label and - which should return a string. - tick_in : int - The number of pixels by which the ticks go "into" the plot area - tick_out : int - The number of pixels by which the ticks extend into the label area - tick_visible : bool - Are ticks visible at all? - tick_interval : 'auto' or float - What is the dataspace interval between ticks? - orientation : Enum("top", "bottom", "left", "right") - The location of the axis relative to the plot. This determines where - the axis title is located relative to the axis line. - axis_line_visible : bool - Is the axis line visible? - axis_line_color : color ('color_name' or (red, green, blue, [alpha]) tuple) - The color of the axis line - axis_line_weight : float - The line thickness (in pixels) of the axis line - axis_line_style : LineStyle('solid') - The dash style of the axis line""" - - -def xaxis(**kwds): - """ Configures the x-axis. - - Usage - ----- - * ``xaxis()``: toggles the horizontal axis on or off. - * ``xaxis(**kwds)``: set parameters of the horizontal axis. - - %s - """ % _axis_params - p = curplot() - if p: - if kwds: - p.x_axis.trait_set(**kwds) - else: - p.x_axis.visible ^= True - p.request_redraw() - - -xaxis.__doc__ = ( - """ Configures the x-axis. - - Usage - ----- - * ``xaxis()``: toggles the horizontal axis on or off. - * ``xaxis(**kwds)``: set parameters of the horizontal axis. - - %s - """ - % _axis_params -) - - -def yaxis(**kwds): - """ Configures the y-axis. - - Usage - ----- - * ``yaxis()``: toggles the vertical axis on or off. - * ``yaxis(**kwds)``: set parameters of the vertical axis. - - %s - """ % _axis_params - p = curplot() - if p: - if kwds: - p.y_axis.trait_set(**kwds) - else: - p.y_axis.visible ^= True - p.request_redraw() - - -yaxis.__doc__ = ( - """ Configures the y-axis. - - Usage - ----- - * ``yaxis()``: toggles the vertical axis on or off. - * ``yaxis(**kwds)``: set parameters of the vertical axis. - - %s - """ - % _axis_params -) - - -def xgrid(): - """ Toggles the grid perpendicular to the X axis. """ - p = curplot() - if p: - p.x_grid.visible ^= True - p.request_redraw() - - -def ygrid(): - """ Toggles the grid perpendicular to the Y axis. """ - p = curplot() - if p: - p.y_grid.visible ^= True - p.request_redraw() - - -def _set_scale(axis, system): - p = curplot() - if p: - if axis == "x": - log_linear_trait = "index_scale" - ticks = p.x_ticks - else: - log_linear_trait = "value_scale" - ticks = p.y_ticks - if system == "time": - system = CalendarScaleSystem() - if isinstance(system, str): - setattr(p, log_linear_trait, system) - else: - if system is None: - system = dict(linear=p.linear_scale, log=p.log_scale).get( - p.get(log_linear_trait), p.linear_scale - ) - ticks.scale = system - p.request_redraw() - - -def xscale(system=None): - """Change the scale system for the X-axis ticks. - - Usage - ----- - * ``xscale()``: revert the scale system to the default. - * ``xscale('time')``: use the calendar scale system for time series. - * ``xscale('log')``: use a generic log-scale. - * ``xscale('linear')``: use a generic linear-scale. - * ``xscale(some_scale_system)``: use an arbitrary ScaleSystem object. - """ - _set_scale("x", system) - - -def yscale(system=None): - """Change the scale system for the Y-axis ticks. - - Usage - ----- - * ``yscale()``: revert the scale system to the default. - * ``yscale('time')``: use the calendar scale system for time series. - * ``yscale('log')``: use a generic log-scale. - * ``yscale('linear')``: use a generic linear-scale. - * ``yscale(some_scale_system)``: use an arbitrary ScaleSystem object. - """ - _set_scale("y", system) - - -def legend(setting=None): - """Sets or toggles the presence of the legend - - Usage - ----- - * ``legend()``: toggles the legend; if it is currently visible, it is hideen, and if it is currently hidden, then it is displayed - * ``legend(True)``: shows the legend - * ``legend(False)``: hides the legend - """ - p = curplot() - if p: - if setting is None: - setting = not p.legend.visible - p.legend.visible = setting - p.request_redraw() - - -# ----------------------------------------------------------------------------- -# Tools -# ----------------------------------------------------------------------------- - - -def tool(): - """ Toggles tools on and off. """ - p = curplot() - if p: - pass - - -# ----------------------------------------------------------------------------- -# Saving and IO -# ----------------------------------------------------------------------------- - - -def save( - filename="chacoplot.png", - dpi=72, - pagesize="letter", - dest_box=None, - units="inch", -): - """Saves the active plot to an file. Currently supported file types - are: bmp, png, jpg. - """ - p = curplot() - if not p: - print("Doing nothing because there is no active plot.") - return - - import os.path - - ext = os.path.splitext(filename)[-1] - if ext == ".pdf": - print("Warning: the PDF backend is still a little buggy.") - from chaco.pdf_graphics_context import PdfPlotGraphicsContext - - # Set some default PDF options if none are provided - if dest_box is None: - dest_box = (0.5, 0.5, -0.5, -0.5) - gc = PdfPlotGraphicsContext( - filename=filename, - pagesize=pagesize, - dest_box=dest_box, - dest_box_units=units, - ) - - # temporarily turn off the backbuffer for offscreen rendering - use_backbuffer = p.use_backbuffer - p.use_backbuffer = False - gc.render_component(p) - p.use_backbuffer = use_backbuffer - - gc.save() - del gc - print("Saved to", filename) - - elif ext in [".bmp", ".png", ".jpg"]: - from chaco.plot_graphics_context import PlotGraphicsContext - - gc = PlotGraphicsContext(tuple(p.outer_bounds), dpi=dpi) - - # temporarily turn off the backbuffer for offscreen rendering - use_backbuffer = p.use_backbuffer - p.use_backbuffer = False - gc.render_component(p) - p.use_backbuffer = use_backbuffer - - gc.save(filename) - del gc - print("Saved to", filename) - else: - print("Format not yet supported:", ext) - print("Currently supported formats are: bmp, png, jpg.") diff --git a/chaco/shell/plot_maker.py b/chaco/shell/plot_maker.py deleted file mode 100644 index 4d4f9488d..000000000 --- a/chaco/shell/plot_maker.py +++ /dev/null @@ -1,446 +0,0 @@ -""" -Contains the logic behind creating and configuring new plots -from a set of user-supplied arguments. -""" - -# Standard library imports -import io -import re - -# Major library imports -from numpy import all, array, arange, asarray, reshape, shape, transpose - -# Chaco imports -from chaco.plot_factory import create_line_plot, create_scatter_plot -from chaco.array_data_source import ArrayDataSource -from chaco.image_data import ImageData - -from chaco.tools.highlight_tool import HighlightTool - - -# Local relative imports -from .chaco_shell_error import ChacoShellError - - -# Normally I don't define an __all__, but this lets us distinguish -# the top level plot-producing functions from the various helper -# functions. -__all__ = [ - "do_plot", - "do_imshow", - "do_pcolor", - "do_contour", - "do_plotv", - "SizeMismatch", -] - - -# ----------------------------------------------------------------------------- -# Exceptions -# ----------------------------------------------------------------------------- - - -class SizeMismatch(ChacoShellError): - pass - - -# ----------------------------------------------------------------------------- -# Utility functions -# ----------------------------------------------------------------------------- - - -def is1D(a): - s = shape(a) - return (len(s) == 1) or (s[0] == 1) or (s[1] == 1) - - -def is2D(a): - return len(shape(a)) == 2 - - -def row(a): - return reshape(asarray(a), [1, -1]) - - -def col(a): - return reshape(asarray(a), [-1, 1]) - - -# ----------------------------------------------------------------------------- -# Plot commands for chaco-style plotv() -# ----------------------------------------------------------------------------- - - -def do_plotv(session, *args, **kw): - """Creates a list of plots from the data in ``*args`` and options in - ``**kw``, according to the docstring on commands.plot(). - """ - - sort = kw.get("sort", "none") - sources_list = make_data_sources(session, sort, *args) - - plot_type = kw.get("type", "line") - if plot_type == "scatter": - plots = [create_scatter_plot(sources) for sources in sources_list] - elif plot_type == "line": - plots = [create_line_plot(sources) for sources in sources_list] - else: - raise ChacoShellError("Unknown plot type '%s'." % plot_type) - - for plot in plots: - plot.orientation = kw.get("orientation", "h") - - return plots - - -def make_data_sources(session, index_sort="none", *args): - """Given a list of arguments, returns a list of (index, value) datasources - to create plots from. - """ - # Make sure everything is a numpy array - data = [] - for arg in args: - if isinstance(arg, list) or isinstance(arg, tuple): - data.append(array(arg)) - else: - data.append(arg) - - if len(data) == 0: - raise ChacoShellError("Insufficient data for plot.") - - # 1D array(s) - if len(data[0].shape) == 1: - if len(data) == 1: - # Only a single array was provided - index_ds = ArrayDataSource( - arange(len(data[0])), sort_order="ascending" - ) - value_ds = ArrayDataSource(data[0], sort_order="none") - return [(index_ds, value_ds)] - - else: - # multiple arrays were provided - index_ds = ArrayDataSource(data[0], sort_order=index_sort) - return [ - (index_ds, ArrayDataSource(v, sort_order="none")) - for v in data[1:] - ] - - # 2D arrays - elif len(data[0].shape) == 2: - sources = [] - # Loop over all the 2D arrays - for ary in data: - if ary.shape[0] > ary.shape[1]: - index_ary = ary[:, 0] - value_arrays = ary[:, 1:] - else: - index_ary = ary[0] - value_arrays = transpose(ary[1:]) - index_ds = ArrayDataSource(index_ary, sort_order=index_sort) - sources.extend( - [ - (index_ds, ArrayDataSource(v, sort_order="none")) - for v in value_arrays - ] - ) - return sources - - # Not a two-dimensional array, error. - else: - raise ChacoShellError( - "Unable to create plot data sources from array of shape " - + str(data[1].shape) - + "." - ) - - -# ----------------------------------------------------------------------------- -# Plot commands for matlab-compatible plot() function -# ----------------------------------------------------------------------------- - -# Regular expressions for parsing the format string - -color_re = re.compile("[ymcrgbwk]") -color_trans = { - "y": "yellow", - "m": "magenta", - "c": "cyan", - "r": "red", - "g": "green", - "b": "blue", - "w": "white", - "k": "black", -} - -# This one isn't quite right: - -marker_re = re.compile("[ox+s^v]|(?:[^-])[.]") -marker_trans = { - ".": "dot", - "o": "circle", - "x": "cross", - "+": "plus", - "s": "square", - "^": "triangle", - "v": "inverted_triangle", -} - -line_re = re.compile("--|-\.|[-:]") -line_trans = {"-": "solid", ":": "dot", "-.": "dot dash", "--": "dash"} - - -def _process_format(format): - """ - Converts a format string into a (color, line, marker, marker_color) tuple. - """ - if format == "": - return ("black", "solid", None, None) - color, line, marker, marker_color = "black", None, None, None - m = color_re.findall(format) - if len(m) > 0: - color = marker_color = color_trans[m[0]] - if len(m) > 1: - marker_color = color_trans[m[1]] - m = marker_re.findall(format) - # The -1 takes care of 'r.', etc: - if len(m) > 0: - marker = marker_trans[m[0][-1]] - m = line_re.findall(format) - if len(m): - line = line_trans[m[0]] - return (color, line, marker, marker_color) - - -def _process_group(group, plot_data=None): - """Returns a (x_1D, y_1D, format_str) tuple from an input tuple - of 1 to 3 elements: (x,y,format_str). - - A PlotData object can be optionally provided to disambiguate the cases - when exactly two strings are passed in. The two strings could be the - names of the x and y datasources, or they could be the name of the y - datasource and a format string. By checking the second string against - the plot_data's list of datasources, the method can determine what it is meant - to be. - """ - # Interpret and split the 'group' tuple into x, y, and plotinfo - plotinfo = "" - if len(group) == 1: - y = group[0] - y_data = plot_data.get_data(y) - x = plot_data.set_data("", arange(len(y_data)), generate_name=True) - elif len(group) == 2: - # There are two possibilities here; a single y was provided along - # with a format string, or an x and y were provided. If PlotData - # was provided, use that to disambiguate; otherwise, assume that the - # second string is a format string. - if isinstance(group[1], str): - if plot_data and group[1] in plot_data.list_data(): - x = group[0] - y = group[1] - else: - plotinfo = group[1] - y = group[0] - y_data = plot_data.get_data(y) - x = plot_data.set_data( - "", arange(len(y_data)), generate_name=True - ) - else: - x, y = group - elif len(group) == 3: - x, y, plotinfo = group - else: - raise ChacoShellError( - "Found too many elements in group while constructing plot." - ) - return x, y, plotinfo - - -def _check_sort_order(data): - diffs = data[1:] - data[:-1] - if all(diffs >= 0): - return "ascending" - elif all(diffs <= 0): - return "descending" - else: - return "none" - - -def do_plot(plotdata, active_plot, *data_and_formats, **kwtraits): - """Takes a list of data (arrays or names) and format string arguments - and creates new plots on the active_plot. Returns a list of plot names - on the active plot. - """ - # The list of data and formats is broken up by format strings, - # so we break it up by arguments that are strings. - cur_group = [] - groups = [] - valid_names = plotdata.list_data() - for arg in data_and_formats: - if not isinstance(arg, str): - # an array was passed in - cur_group.append(plotdata.set_data("", arg, generate_name=True)) - elif arg in valid_names: - # the name of an existing plotdata item was passed in - cur_group.append(arg) - else: - # String that is not in plotdata is interpreted as a format - # string, thereby terminating this group - cur_group.append(arg) - groups.append(cur_group) - cur_group = [] - - if len(cur_group) > 0: - groups.append(cur_group) - - # Process the list of groups and create a list of plots; - # broadcast the keyword traits to all of them. - plots = [] - - for group in groups: - x, y, format_str = _process_group(group, plot_data=plotdata) - linecolor, line, marker, markercolor = _process_format(format_str) - plot_type = [] - format = kwtraits.copy() - if line is not None: - plot_type.append("line") - format["line_style"] = line - format["color"] = linecolor - if marker is not None: - plot_type.append("scatter") - format["marker"] = marker - format["color"] = markercolor - - x_sort_order = _check_sort_order(plotdata.get_data(x)) - plots.extend( - active_plot.plot((x, y), type=",".join(plot_type), **format) - ) - - # Set the sort order - x_ds = active_plot.datasources[x] - if isinstance(x_ds, ArrayDataSource): - x_ds.sort_order = x_sort_order - - # Check to see if the active_plot has a highlighter tool already; if not, - # then add it. - for tool in active_plot.tools: - if isinstance(tool, HighlightTool): - break - else: - active_plot.tools.append(HighlightTool(active_plot)) - - return plots - - -def do_imread(*data, **kwargs): - """ Returns image file as array. """ - - # Check to see if the data given is either a file path or a file object - if isinstance(data[0], str) or isinstance(data[0], io.IOBase): - return ImageData.fromfile(data[0]) - else: - raise ValueError("do_imread takes a string filename") - - -def do_imshow(plotdata, active_plot, *data, **kwargs): - """Creates an image plot on the active plot, given either - a filename or data. - """ - - if len(data) != 1: - raise ValueError("do_imshow takes one data source") - - x = None - y = None - try: - z = _get_or_create_plot_data(data[0], plotdata) - except ValueError: - # z is the name of the file - # create plot data - image = do_imread(data[0], *data, **kwargs) - z = plotdata.set_data("", image, generate_name=True) - - plot_list = [active_plot.img_plot(z, xbounds=x, ybounds=y, **kwargs)] - - return plot_list - - -def do_pcolor(plotdata, colormap, active_plot, *data, **kwargs): - """Creates a pseudocolor image plot on the active plot, given a 2-D - scalar data and a colormap. - """ - - # if we get just one data source, it is assumed to be the scalar field - if len(data) == 1: - x = None - y = None - z = _get_or_create_plot_data(data[0], plotdata) - - # three data sources means we got x-y grid data of some sort, too - elif len(data) == 3: - x = _get_or_create_plot_data(data[0], plotdata) - y = _get_or_create_plot_data(data[1], plotdata) - z = _get_or_create_plot_data(data[2], plotdata) - else: - raise ValueError("do_pcolor takes one or three data sources") - - plot_list = [ - active_plot.img_plot( - z, xbounds=x, ybounds=y, colormap=colormap, **kwargs - ) - ] - return plot_list - - -def do_contour(plotdata, colormap, active_plot, type, *data, **kwargs): - """Creates a contour plot on the active plot, given a 2-D - scalar data and a colormap. - """ - - # if we get just one data source, it is assumed to be the scalar field - if len(data) == 1: - x = None - y = None - z = _get_or_create_plot_data(data[0], plotdata) - - # three data sources means we got x-y grid data of some sort, too - elif len(data) == 3: - x = _get_or_create_plot_data(data[0], plotdata) - y = _get_or_create_plot_data(data[1], plotdata) - z = _get_or_create_plot_data(data[2], plotdata) - - else: - raise ValueError("do_contour takes one or three data sources") - - # we have to do slightly different calls here because of the different - # handling of colormaps - if type is "poly": - plot_list = [ - active_plot.contour_plot( - z, type, xbounds=x, ybounds=y, poly_cmap=colormap, **kwargs - ) - ] - else: - plot_list = [ - active_plot.contour_plot( - z, type, xbounds=x, ybounds=y, colors=colormap, **kwargs - ) - ] - - return plot_list - - -def _get_or_create_plot_data(data, plotdata): - """Create a new name for `data` if necessary, or check it is a valid name.""" - valid_names = plotdata.list_data() - - if not isinstance(data, str): - name = plotdata.set_data("", data, generate_name=True) - else: - if data not in valid_names: - msg = "{} is not an existing name for plot data" - raise ValueError(msg.format(data)) - - name = data - - return name diff --git a/chaco/shell/plot_window.py b/chaco/shell/plot_window.py deleted file mode 100644 index feeabb781..000000000 --- a/chaco/shell/plot_window.py +++ /dev/null @@ -1,257 +0,0 @@ -""" Defines the PlotWindow class. -""" - -from enable.api import Window -from chaco.shell.scaly_plot import ScalyPlot - -from traits.etsconfig.api import ETSConfig - -if ETSConfig.toolkit == "wx": - - import wx - - class PlotWindow(wx.Frame): - """A window for holding top-level plot containers. - - Contains many utility methods for controlling the appearance of the - window, which mostly pass through to underlying WX calls. - """ - - def __init__( - self, - is_image=False, - bgcolor="white", - image_default_origin="top left", - *args, - **kw - ): - - kw.setdefault("size", (600, 600)) - wx.Frame.__init__(self, None, *args, **kw) - - # Some defaults which should be overridden by preferences. - self.bgcolor = bgcolor - self.image_default_origin = image_default_origin - - # Create an empty top-level container - if is_image: - top_container = self._create_top_img_container() - else: - top_container = self._create_top_container() - - # The PlotSession of which we are a part. We need to know this in order - # to notify it of our being closed, etc. - self.session = None - - # Create the Enable Window object, and store a reference to it. - # (This will be handy later.) The Window requires a WX parent object - # as its first argument, so we just pass 'self'. - self.plot_window = Window(self, component=top_container) - - # We'll create a default sizer to put our plot_window in. - sizer = wx.BoxSizer(wx.HORIZONTAL) - - # Since Window is an Enable object, we need to get its corresponding - # WX control. This is stored in its ".control" attribute. - sizer.Add(self.plot_window.control, 1, wx.EXPAND) - - # Hook up event handlers for destroy, etc. - wx.EVT_WINDOW_DESTROY(self, self._on_window_close) - - # More WX boilerplate. - self.SetSizer(sizer) - self.SetAutoLayout(True) - self.Show(True) - - # This is a Python property because this is not a HasTraits subclass. - @property - def container(self): - return self.plot_window.component - - @container.setter - def container(self, container): - self.plot_window.component = container - - def iconize(self, iconize): - """Iconizes the window if *iconize* is True.""" - self.Iconize(iconize) - - def maximize(self, maximize): - """If *maximize* is True, maximizes the window size; restores if False.""" - self.Maximize(maximize) - - def set_size(self, width, height): - self.SetSize((width, height)) - - def set_title(self, title): - self.SetTitle(title) - - def raise_window(self): - """Raises this window to the top of the window hierarchy.""" - self.Raise() - - def close(self): - self.Close() - - # ------------------------------------------------------------------------ - # Private methods - # ------------------------------------------------------------------------ - - def _create_top_container(self): - plot = ScalyPlot( - padding=50, - fill_padding=True, - bgcolor=self.bgcolor, - use_backbuffer=True, - ) - return plot - - def _create_top_img_container(self): - plot = ScalyPlot( - padding=50, - fill_padding=True, - bgcolor=self.bgcolor, - use_backbuffer=True, - default_origin=self.image_default_origin, - ) - return plot - - def _on_window_close(self, event): - if self.session: - try: - ndx = self.session.windows.index(self) - self.session.del_window(ndx) - except ValueError: - pass - - -elif ETSConfig.toolkit == "qt4": - - from pyface.qt import QtCore, QtGui - - class PlotWindow(QtGui.QFrame): - """A window for holding top-level plot containers. - - Contains many utility methods for controlling the appearance of the - window, which mostly pass through to underlying Qt calls. - """ - - def __init__( - self, - is_image=False, - bgcolor="white", - image_default_origin="top left", - *args, - **kw - ): - - size = kw.pop("size", None) - if isinstance(size, tuple): - size = QtCore.QSize(*size) - - super(PlotWindow, self).__init__(None, *args, **kw) - - if size is not None: - self.resize(size) - - # Some defaults which should be overridden by preferences. - self.bgcolor = bgcolor - self.image_default_origin = image_default_origin - - # Create an empty top-level container - if is_image: - top_container = self._create_top_img_container() - else: - top_container = self._create_top_container() - - # The PlotSession of which we are a part. We need to know this in order - # to notify it of our being closed, etc. - self.session = None - - # Create the Enable Window object, and store a reference to it. - # (This will be handy later.) The Window requires a parent object - # as its first argument, so we just pass 'self'. - self.plot_window = Window(self, component=top_container) - - layout = QtGui.QVBoxLayout() - layout.setContentsMargins(0, 0, 0, 0) - layout.addWidget(self.plot_window.control) - self.setLayout(layout) - - size = kw.get("size", QtCore.QSize(600, 600)) - self.set_size(size.width(), size.height()) - - self.show() - - # This is a Python property because this is not a HasTraits subclass. - @property - def container(self): - return self.plot_window.component - - @container.setter - def container(self, container): - self.plot_window.component = container - - def iconize(self, iconize): - """Iconizes the window if *iconize* is True.""" - if iconize: - self.showMinimized() - else: - self.showNormal() - - def maximize(self, maximize): - """If *maximize* is True, maximizes the window size; restores if False.""" - if maximize: - self.showMaximized() - else: - self.showNormal() - - def set_size(self, width, height): - self.resize(width, height) - - def set_title(self, title): - self.setWindowTitle(title) - - def raise_window(self): - """Raises this window to the top of the window hierarchy.""" - self.raise_() - - # ------------------------------------------------------------------------ - # Private methods - # ------------------------------------------------------------------------ - - def _create_top_container(self): - plot = ScalyPlot( - padding=50, - fill_padding=True, - bgcolor=self.bgcolor, - use_backbuffer=True, - ) - return plot - - def _create_top_img_container(self): - plot = ScalyPlot( - padding=50, - fill_padding=True, - bgcolor=self.bgcolor, - use_backbuffer=True, - default_origin=self.image_default_origin, - ) - return plot - - def closeEvent(self, event): - if self.session: - try: - ndx = self.session.windows.index(self) - self.session.del_window(ndx) - except ValueError: - pass - - -else: - - class PlotWindow(object): - def __init__(self, *args, **kwargs): - raise NotImplementedError( - "PlotWindow not implemented for `null` toolkit" - ) diff --git a/chaco/shell/preferences.py b/chaco/shell/preferences.py deleted file mode 100644 index 16cf46d69..000000000 --- a/chaco/shell/preferences.py +++ /dev/null @@ -1,44 +0,0 @@ -""" Defines the Preferences class for the Chaco shell. -""" - -from enable.api import white_color_trait -from traits.api import Enum, HasTraits, Int, Str - - -class Preferences(HasTraits): - """Contains all the preferences that configure the Chaco shell session.""" - - #: Width of the plot window, in pixels. - window_width = Int(600) - - #: Height of the plot window, in pixels. - window_height = Int(600) - - #: The type of plot to display. - plot_type = Enum("line", "scatter") - - #: Default name to use for the plot window. - default_window_name = Str("Chaco Plot") - - #: The default background color. - bgcolor = white_color_trait - - #: The default location of the origin for new image plots - image_default_origin = Enum( - "top left", "bottom left", "bottom right", "top right" - ) - - @classmethod - def from_file(cls, filename): - """Creates a new preferences object from a file on disk.""" - prefs = cls() - prefs.load(filename) - return prefs - - def load(self, filename): - """Loads a preferences file; existing settings are overwritten.""" - pass - - def save(self, filename): - """Saves the preferences to *filename*.""" - pass diff --git a/chaco/shell/scaly_plot.py b/chaco/shell/scaly_plot.py deleted file mode 100644 index 7192af204..000000000 --- a/chaco/shell/scaly_plot.py +++ /dev/null @@ -1,151 +0,0 @@ -""" A Plot which uses ScaleSystems for its ticks. -""" - -from traits.api import Any - -from chaco.axis import PlotAxis -from chaco.data_range_2d import DataRange2D -from chaco.grid import PlotGrid -from chaco.linear_mapper import LinearMapper -from chaco.log_mapper import LogMapper -from chaco.plot import Plot -from chaco.scales.scales import DefaultScale, LogScale, ScaleSystem -from chaco.scales_tick_generator import ScalesTickGenerator - - -def add_default_axes(plot, orientation="normal", vtitle="", htitle=""): - """ - Creates left and bottom axes for a plot. Assumes that the index is - horizontal and value is vertical by default; set orientation to - something other than "normal" if they are flipped. - """ - if orientation in ("normal", "h"): - v_mapper = plot.value_mapper - h_mapper = plot.index_mapper - else: - v_mapper = plot.index_mapper - h_mapper = plot.value_mapper - - yticks = ScalesTickGenerator() - left = PlotAxis( - orientation="left", - title=vtitle, - mapper=v_mapper, - component=plot, - tick_generator=yticks, - ) - - xticks = ScalesTickGenerator() - bottom = PlotAxis( - orientation="bottom", - title=htitle, - mapper=h_mapper, - component=plot, - tick_generator=xticks, - ) - - plot.underlays.append(left) - plot.underlays.append(bottom) - return left, bottom - - -class ScalyPlot(Plot): - x_axis = Any() - y_axis = Any() - x_ticks = Any() - y_ticks = Any() - linear_scale_factory = Any() - log_scale_factory = Any() - - def _linear_scale_default(self): - return self._make_scale("linear") - - def _log_scale_default(self): - return self._make_scale("log") - - def _make_scale(self, scale_type="linear"): - """ Returns a new linear or log scale """ - if scale_type == "linear": - if self.linear_scale_factory is not None: - return self.linear_scale_factory() - else: - return ScaleSystem(DefaultScale()) - else: - if self.log_scale_factory is not None: - return self.log_scale_factory() - else: - return ScaleSystem(LogScale()) - - def _init_components(self): - # Since this is called after the HasTraits constructor, we have to make - # sure that we don't blow away any components that the caller may have - # already set. - - if self.range2d is None: - self.range2d = DataRange2D() - - if self.index_mapper is None: - if self.index_scale == "linear": - imap = LinearMapper(range=self.range2d.x_range) - else: - imap = LogMapper(range=self.range2d.x_range) - self.index_mapper = imap - - if self.value_mapper is None: - if self.value_scale == "linear": - vmap = LinearMapper(range=self.range2d.y_range) - else: - vmap = LogMapper(range=self.range2d.y_range) - self.value_mapper = vmap - - if self.x_ticks is None: - self.x_ticks = ScalesTickGenerator( - scale=self._make_scale(self.index_scale) - ) - if self.y_ticks is None: - self.y_ticks = ScalesTickGenerator( - scale=self._make_scale(self.value_scale) - ) - - if self.x_grid is None: - self.x_grid = PlotGrid( - mapper=self.x_mapper, - orientation="vertical", - line_color="lightgray", - line_style="dot", - component=self, - tick_generator=self.x_ticks, - ) - if self.y_grid is None: - self.y_grid = PlotGrid( - mapper=self.y_mapper, - orientation="horizontal", - line_color="lightgray", - line_style="dot", - component=self, - tick_generator=self.y_ticks, - ) - if self.x_axis is None: - self.x_axis = PlotAxis( - mapper=self.x_mapper, - orientation="bottom", - component=self, - tick_generator=self.x_ticks, - ) - if self.y_axis is None: - self.y_axis = PlotAxis( - mapper=self.y_mapper, - orientation="left", - component=self, - tick_generator=self.y_ticks, - ) - - def _index_scale_changed(self, old, new): - Plot._index_scale_changed(self, old, new) - # Now adjust the ScaleSystems. - self.x_ticks.scale = self._make_scale(self.index_scale) - - def _value_scale_changed(self, old, new): - Plot._value_scale_changed(self, old, new) - # Now adjust the ScaleSystems. - self.y_ticks.scale = self._make_scale(self.value_scale) diff --git a/chaco/shell/session.py b/chaco/shell/session.py deleted file mode 100644 index e1e7b8538..000000000 --- a/chaco/shell/session.py +++ /dev/null @@ -1,160 +0,0 @@ -""" Defines the PlotSession class. -""" - - -# Enthoght library imports -from chaco.array_plot_data import ArrayPlotData -from chaco.default_colormaps import * -from traits.api import ( - Any, - Bool, - Dict, - HasTraits, - Instance, - Int, - List, - Property, - Trait, - Str, -) - - -# Local, relative imports -from .plot_window import PlotWindow -from .preferences import Preferences - - -class PlotSession(HasTraits): - """ - Encapsulates all of the session-level globals, including preferences, - windows, etc. - """ - - #: The preferences object in effect for this session. - prefs = Instance(Preferences, args=()) - - #: The list of currently active windows. - windows = List(PlotWindow) - - #: A dict mapping names to windows. - window_map = Dict(Str, PlotWindow) - - #: The current hold state. - hold = Bool(False) - - #: The session holds a single ArrayPlotData instance to which it adds unnamed - #: arrays that are provided to various plotting commands. - data = Instance(ArrayPlotData, args=()) - - # ------------------------------------------------------------------------ - # "active" pointers - # ------------------------------------------------------------------------ - - #: The index of the active window. - active_window_index = Trait(None, None, Int) - - #: The active window. - active_window = Property - - #: The active colormap. - colormap = Trait(jet, Any) - - def new_window(self, name=None, title=None, is_image=False): - """Creates a new window and returns the index into the **windows** list - for the new window. - """ - new_win = PlotWindow( - is_image=is_image, - size=(self.prefs.window_width, self.prefs.window_height), - bgcolor=self.prefs.bgcolor, - image_default_origin=self.prefs.image_default_origin, - ) - new_win.data = self.data - new_win.container.data = self.data - new_win.session = self - - if title is not None: - new_win.set_title(title) - elif name != None: - new_win.set_title(name) - else: - new_win.set_title(self.prefs.default_window_name) - - self.windows.append(new_win) - if name != None: - self.window_map[name] = new_win - return len(self.windows) - 1 - - def get_window(self, ident): - """ Retrieves a window either by index or by name """ - if isinstance(ident, str): - return self.window_map.get(ident, None) - elif type(ident) == int and ident < len(self.windows): - return self.windows[ident] - else: - return None - - def del_window(self, ident): - """Deletes the specified window. - - Parameters - ---------- - ident : string or number - The name of the window in **window_map**, or the index of the - window in **windows**. - """ - if isinstance(ident, str): - if ident in self.window_map: - win = self.window_map[ident] - del self.window_map[ident] - else: - return - elif type(ident) == int: - if ident >= len(self.windows): - print("No such window %d." % ident) - - win = self.windows.pop(ident) - if len(self.windows) == 0: - self.active_window = None - elif self.active_window_index >= ident: - self.active_window_index -= 1 - - if win in self.window_map.values(): - # we have to go through the whole dict and remove all keys - # that correspond to the deleted window - for k, v in list(self.window_map.items()): - if v == win: - del self.window_map[k] - else: - return - - def _get_active_window(self): - if self.active_window_index is not None: - return self.windows[self.active_window_index] - else: - return None - - def _set_active_window(self, win): - if win in self.windows: - self.active_window_index = self.windows.index(win) - elif win is None: - self.active_window_index = None - else: - raise RuntimeError("That window is not part of this session.") - - def _colormap_changed(self): - plots = [] - for w in self.windows: - container = w.container - for vals in container.plots.values(): - plots.extend(vals) - for p in plots: - if hasattr(p, "color_mapper"): - p.color_mapper = self.colormap(p.color_mapper.range) - p.invalidate_draw() - p.request_redraw() - elif hasattr(p, "colors"): - if isinstance(p.colors, str) or isinstance( - p.colors, AbstractColormap - ): - p.colors = color_map_dict[self.colormap] diff --git a/chaco/shell/tests/__init__.py b/chaco/shell/tests/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/chaco/shell/tests/test_make_data_sources.py b/chaco/shell/tests/test_make_data_sources.py deleted file mode 100644 index c02224d53..000000000 --- a/chaco/shell/tests/test_make_data_sources.py +++ /dev/null @@ -1,28 +0,0 @@ -import unittest - -import numpy as np -from numpy.testing.utils import assert_almost_equal -from chaco.shell.plot_maker import make_data_sources - - -class MakeDataSourcesTestCase(unittest.TestCase): - def test_1D_single(self): - session = None - ary = np.array([3.0, 2.1, 1.3, 1.8, 5.7]) - sources = make_data_sources(session, "none", ary) - assert_almost_equal(sources[0][0].get_data(), np.arange(len(ary))) - assert_almost_equal(sources[0][1].get_data(), ary) - - def test_1d_multiple(self): - session = None - index = np.arange(-np.pi, np.pi, np.pi / 30.0) - s = np.sin(index) - c = np.cos(index) - t = np.tan(index) - sources = make_data_sources(session, "ascending", index, s, c, t) - assert_almost_equal(sources[0][0].get_data(), index) - self.assertTrue(sources[0][0] == sources[1][0]) - self.assertTrue(sources[0][0] == sources[2][0]) - assert_almost_equal(sources[0][1].get_data(), s) - assert_almost_equal(sources[1][1].get_data(), c) - assert_almost_equal(sources[2][1].get_data(), t) diff --git a/chaco/shell/tests/test_tutorial_example.py b/chaco/shell/tests/test_tutorial_example.py deleted file mode 100644 index b50507f7e..000000000 --- a/chaco/shell/tests/test_tutorial_example.py +++ /dev/null @@ -1,21 +0,0 @@ -""" Test script-oriented example from interactive plotting tutorial - -source: docs/source/user_manual/chaco_tutorial.rst - -""" -import unittest - -from numpy import linspace, pi, sin - -from traits.etsconfig.api import ETSConfig -from chaco.shell import plot, title, ytitle - - -@unittest.skipIf(ETSConfig.toolkit == "null", "Skip on 'null' toolkit") -class InteractiveTestCase(unittest.TestCase): - def test_script(self): - x = linspace(-2 * pi, 2 * pi, 100) - y = sin(x) - plot(x, y, "r-") - title("First plot") - ytitle("sin(x)") From cde866065724e88ec62b4f115aabdcfc9fdcf7be Mon Sep 17 00:00:00 2001 From: Aaron Ayres Date: Thu, 15 Apr 2021 07:52:18 -0700 Subject: [PATCH 2/5] delete all the examples from examples/demo/shell --- examples/demo/shell/__init__.py | 0 examples/demo/shell/add_tool.py | 50 --------------------------------- examples/demo/shell/contour.py | 27 ------------------ examples/demo/shell/contourf.py | 28 ------------------ examples/demo/shell/dates.py | 44 ----------------------------- examples/demo/shell/imshow.py | 32 --------------------- examples/demo/shell/lines.py | 30 -------------------- examples/demo/shell/loglog.py | 27 ------------------ examples/demo/shell/pcolor.py | 35 ----------------------- examples/demo/shell/scatter.py | 26 ----------------- examples/demo/shell/semilog.py | 25 ----------------- 11 files changed, 324 deletions(-) delete mode 100644 examples/demo/shell/__init__.py delete mode 100644 examples/demo/shell/add_tool.py delete mode 100644 examples/demo/shell/contour.py delete mode 100644 examples/demo/shell/contourf.py delete mode 100644 examples/demo/shell/dates.py delete mode 100644 examples/demo/shell/imshow.py delete mode 100644 examples/demo/shell/lines.py delete mode 100644 examples/demo/shell/loglog.py delete mode 100644 examples/demo/shell/pcolor.py delete mode 100644 examples/demo/shell/scatter.py delete mode 100644 examples/demo/shell/semilog.py diff --git a/examples/demo/shell/__init__.py b/examples/demo/shell/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/examples/demo/shell/add_tool.py b/examples/demo/shell/add_tool.py deleted file mode 100644 index ca67c661e..000000000 --- a/examples/demo/shell/add_tool.py +++ /dev/null @@ -1,50 +0,0 @@ -""" -This example demonstrates customizing a plot object with a plot tool -using the chaco.shell subpackage. - -The functions in the chaco.shell package allow us to quickly generate plots -with some basic interactivity without using the object-oriented core of Chaco. -""" - -# Major library imports -from numpy import linspace, meshgrid, sin - -# Enthought library imports -from chaco.shell import show, title, pcolor, colormap, curplot -from chaco.default_colormaps import viridis - -# Crate some scalar data -xs = linspace(0, 10, 200) -ys = linspace(0, 20, 400) -x, y = meshgrid(xs, ys) -z = sin(x) * y - -# Create a pseudo-color-map -pcolor(x, y, z, name="sin_x_times_y") - -# Change the color mapping -colormap(viridis) - -# Add some titles -title("pseudo colormap image plot") - - -# From the current plot object, grab the first plot -img_plot = curplot().plots["sin_x_times_y"][0] - -# Add a custom tool - in this case, an ImageInspector -from chaco.tools.api import ImageInspectorTool, ImageInspectorOverlay - -tool = ImageInspectorTool(img_plot) -img_plot.tools.append(tool) -overlay = ImageInspectorOverlay( - img_plot, image_inspector=tool, bgcolor="white", border_visible=True -) -img_plot.overlays.append(overlay) - - -# If running this from the command line and outside of a wxPython -# application or process, the show() command is necessary to keep -# the plot from disappearing instantly. If a wxPython mainloop -# is already running, then this command is not necessary. -show() diff --git a/examples/demo/shell/contour.py b/examples/demo/shell/contour.py deleted file mode 100644 index 9a8ba062d..000000000 --- a/examples/demo/shell/contour.py +++ /dev/null @@ -1,27 +0,0 @@ -""" -This example demonstrates creating a contour plot using the chaco -shell subpackage. -""" - -# Major library imports -from numpy import linspace, meshgrid, sin -from scipy.special import jn - -# Enthought library imports -from chaco.shell import show, title, contour - - -# Crate some scalar data -xs = linspace(-10, 10, 200) -ys = linspace(-10, 10, 400) -x, y = meshgrid(xs, ys) -z = sin(x) * x * jn(0, y) - -# Create a contour line plot -contour(x, y, z, bgcolor="black") - -# Add some titles -title("contour line plot") - -# This command is only necessary if running from command line -show() diff --git a/examples/demo/shell/contourf.py b/examples/demo/shell/contourf.py deleted file mode 100644 index 5d0ba0d85..000000000 --- a/examples/demo/shell/contourf.py +++ /dev/null @@ -1,28 +0,0 @@ -""" -This example demonstrates creating a filled contour plot using the chaco -shell subpackage. -""" - -# Major library Imports -from numpy import linspace, meshgrid, tanh - -# Enthought Library Imports -from chaco.shell import contourf, colormap, title, show -from chaco.default_colormaps import viridis - - -# Crate some scalar data -xs = linspace(-10, 10, 200) -ys = linspace(-10, 10, 400) -x, y = meshgrid(xs, ys) -z = x * tanh(y) - -# Create a filled contour plot -contourf(x, y, z) -colormap(viridis) - -# Add some titles -title("filled contour plot") - -# This command is only necessary if running from command line -show() diff --git a/examples/demo/shell/dates.py b/examples/demo/shell/dates.py deleted file mode 100644 index 7af48830a..000000000 --- a/examples/demo/shell/dates.py +++ /dev/null @@ -1,44 +0,0 @@ -""" -This example demonstrates using dates as labels for the axis ticks using -the chaco shell subpackage. - -Try zooming in and out using the mouse wheel and see the resolution of -the dates gradually changing from days to years. -""" - -# Major library imports -from numpy import linspace, pi, sin - -# Enthought library imports -from chaco.shell import show, plot, title, curplot -from chaco.scales.api import CalendarScaleSystem - -# Create some data -numpoints = 100 -x = linspace(-2 * pi, 2 * pi, numpoints) -y1 = sin(x) - -# Create the dates -import time - -now = time.time() -dt = 24 * 3600 # data points are spaced by 1 day -dates = linspace(now, now + numpoints * dt, numpoints) - -# Create some line plots -plot(dates, y1, "b-", bgcolor="white") - -# Add some titles -title("Plotting Dates") - -current_plot = curplot() -# Set the plot's horizontal axis to be a time scale -current_plot.x_axis.tick_generator.scale = CalendarScaleSystem() -zoom_tool = current_plot.overlays[2] -pan_tool = current_plot.tools[0] -zoom_tool.x_min_zoom_factor = float(1e-3) -pan_tool.restrict_to_data = True - - -# This command is only necessary if running from command line -show() diff --git a/examples/demo/shell/imshow.py b/examples/demo/shell/imshow.py deleted file mode 100644 index 30a7856f6..000000000 --- a/examples/demo/shell/imshow.py +++ /dev/null @@ -1,32 +0,0 @@ -# Standard library imports -import os.path -import sys - -# Enthought library imports -from traits.util.resource import find_resource -from chaco.shell import imread, imshow, title, show - -# Get the image file using the find_resource module -image_path = os.path.join("examples", "basic", "capitol.jpg") -alt_path = os.path.join("..", "basic", "capitol.jpg") -image_file = find_resource("Chaco", image_path, alt_path=alt_path) - -# Check to see if the image was found -if image_file is None: - print('The image "capitol.jpg" could not be found.') - sys.exit() - -# Create the image -image = imread(image_file) - -# Create the plot -imshow(image, origin="top left") - -# Alternatively, you can call imshow using the path to the image file -# imshow(alt_path) - -# Add a title -title("Simple Image Plot") - -# This command is only necessary if running from command line -show() diff --git a/examples/demo/shell/lines.py b/examples/demo/shell/lines.py deleted file mode 100644 index c231c4ffe..000000000 --- a/examples/demo/shell/lines.py +++ /dev/null @@ -1,30 +0,0 @@ -""" -This example displays some line plots in different colors and styles using -the chaco.shell subpackage. - -The functions in the chaco.shell package allow us to quickly generate plots -with some basic interactivity without using the object-oriented core of Chaco. -""" - -from numpy import linspace, pi, sin, cos -from chaco.shell import plot, hold, title, show - -# Create some data -x = linspace(-2 * pi, 2 * pi, 100) -y1 = sin(x) -y2 = cos(x) - -# Create some line plots using the plot() command and using -# Matlab-style format specifiers -plot(x, y1, "b-", bgcolor="white") -hold() -plot(x, y2, "g-.", marker_size=2) - -# Set the plot title -title("simple line plots") - -# If running this from the command line and outside of a wxPython -# application or process, the show() command is necessary to keep -# the plot from disappearing instantly. If a wxPython mainloop -# is already running, then this command is not necessary. -show() diff --git a/examples/demo/shell/loglog.py b/examples/demo/shell/loglog.py deleted file mode 100644 index 41ea2c064..000000000 --- a/examples/demo/shell/loglog.py +++ /dev/null @@ -1,27 +0,0 @@ -""" -This example shows how to createa log-log plot using the chaco -`shell` subpackage. -""" - -# Major library imports -from numpy import linspace, exp - -# Enthought library imports -from chaco.shell import show, title, loglog, hold - - -# Create some data -x = linspace(1, 15, 200) - -# Create some line plots -loglog(x, x ** 2, "b-.", name="y=x**2", bgcolor="white") -hold(True) -loglog(x, x ** 4 + 3 * x + 2, "r-", name="y=x**4+3x+2", bgcolor="white") -loglog(x, exp(x), "g-", name="y=exp(x)", bgcolor="white") -loglog(x, x, "m--", name="y=x", bgcolor="white") - -# Add some titles -title("simple loglog plots") - -# This command is only necessary if running from command line -show() diff --git a/examples/demo/shell/pcolor.py b/examples/demo/shell/pcolor.py deleted file mode 100644 index 39280e4a8..000000000 --- a/examples/demo/shell/pcolor.py +++ /dev/null @@ -1,35 +0,0 @@ -""" -This example displays a pseudo-color map using the chaco.shell subpackage. - -The functions in the chaco.shell package allow us to quickly generate plots -with some basic interactivity without using the object-oriented core of Chaco. -""" - -# Major library imports -from numpy import linspace, meshgrid, sin - -# Enthought library imports -from chaco.shell import show, title, pcolor, colormap -from chaco.default_colormaps import viridis - - -# Crate some scalar data -xs = linspace(0, 10, 200) -ys = linspace(0, 20, 400) -x, y = meshgrid(xs, ys) -z = sin(x) * y - -# Create a pseudo-color-map -pcolor(x, y, z) - -# change the color mapping -colormap(viridis) - -# Add some titles -title("pseudo colormap image plot") - -# If running this from the command line and outside of a wxPython -# application or process, the show() command is necessary to keep -# the plot from disappearing instantly. If a wxPython mainloop -# is already running, then this command is not necessary. -show() diff --git a/examples/demo/shell/scatter.py b/examples/demo/shell/scatter.py deleted file mode 100644 index ea2d623cd..000000000 --- a/examples/demo/shell/scatter.py +++ /dev/null @@ -1,26 +0,0 @@ -""" -This example shows how to create a scatter plot using the `shell` package. -""" - -# Major library imports -from numpy import linspace, random, pi - -# Enthought library imports -from chaco.shell import plot, hold, title, show - - -# Create some data -x = linspace(-2 * pi, 2 * pi, 100) -y1 = random.random(100) -y2 = random.random(100) - -# Create some scatter plots -plot(x, y1, "b.") -hold(True) -plot(x, y2, "g+", marker_size=2) - -# Add some titles -title("simple scatter plots") - -# This command is only necessary if running from command line -show() diff --git a/examples/demo/shell/semilog.py b/examples/demo/shell/semilog.py deleted file mode 100644 index 9bd016727..000000000 --- a/examples/demo/shell/semilog.py +++ /dev/null @@ -1,25 +0,0 @@ -""" -This example shows how to create a semi-log plot using the `shell` package. -""" - -# Major library imports -from numpy import linspace, exp - -# Enthought library imports -from chaco.shell import semilogy, hold, title, show - - -# Create some data -x = linspace(1, 10, 200) - -# Create some line plots -semilogy(x, exp(x), "b-", name="y=exp(x)", bgcolor="white") -hold(True) -semilogy(x, x ** x, "r--", name="y=x**x") -semilogy(x, x, "g-", name="y=x") - -# Add some titles -title("simple semilog plots") - -# This command is only necessary if running from command line -show() From 1f60c9002a915e7d23c4bc58c05e8e4c19a2876b Mon Sep 17 00:00:00 2001 From: Aaron Ayres Date: Thu, 15 Apr 2021 09:08:30 -0700 Subject: [PATCH 3/5] remove chaco.plugin which provides an envisage plugin fo using chaco.shell --- chaco/plugin/__init__.py | 0 chaco/plugin/chaco_plugin.py | 54 ------------ chaco/plugin/plot_editor.py | 137 ------------------------------ chaco/plugin/workbench_session.py | 56 ------------ 4 files changed, 247 deletions(-) delete mode 100644 chaco/plugin/__init__.py delete mode 100644 chaco/plugin/chaco_plugin.py delete mode 100644 chaco/plugin/plot_editor.py delete mode 100644 chaco/plugin/workbench_session.py diff --git a/chaco/plugin/__init__.py b/chaco/plugin/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/chaco/plugin/chaco_plugin.py b/chaco/plugin/chaco_plugin.py deleted file mode 100644 index 3af765b04..000000000 --- a/chaco/plugin/chaco_plugin.py +++ /dev/null @@ -1,54 +0,0 @@ -""" Envisage 3 plugin for Chaco functionality. -""" - -from envisage.api import Plugin -from traits.api import List - - -ID = "chaco" -ICHACO_SESSION = ID + ".plugin.session_service.SessionService" - - -class ChacoPlugin(Plugin): - """Envisage 3 plugin for Chaco functionality.""" - - id = ID - name = "Chaco plugin" - - #### Contributions to extension points made by this plugin ################# - - # Extension point Ids. - COMMANDS = "envisage.plugins.python_shell.commands" - - contributed_commands = List(contributes_to=COMMANDS) - - def _contributed_commands_default(self): - commands = [ - "from chaco.shell.commands import *", - ] - return commands - - #### Plugin interface ###################################################### - - def start(self): - """Monkeypatch the Chaco shell subsystem.""" - from chaco import shell - from chaco.shell import commands - from chaco.plugin.workbench_session import WorkbenchSession - - commands.session = shell.session = WorkbenchSession( - application=self.application - ) - - def show(): - """Shows all the figure windows that have been created thus far, and - creates a GUI main loop. This function is useful in scripts to show plots and - keep their windows open, and has no effect when used from the interpreter - prompt. - - Inside Envisage, just raise the current window. - """ - win = commands.session.active_window - win.raise_window() - - commands.show = show diff --git a/chaco/plugin/plot_editor.py b/chaco/plugin/plot_editor.py deleted file mode 100644 index e57b6be79..000000000 --- a/chaco/plugin/plot_editor.py +++ /dev/null @@ -1,137 +0,0 @@ -from chaco.shell.scaly_plot import ScalyPlot -from enable.api import ComponentEditor -from pyface.workbench.api import TraitsUIEditor -from traits.api import Any, Enum, HasTraits, Property, Str -from traitsui.api import Item, View - - -class PlotUI(HasTraits): - """Simple TraitsUI proxy for a Chaco plot.""" - - # The plot. - component = Any() - - traits_view = View( - Item("component", editor=ComponentEditor(), show_label=False), - resizable=True, - ) - - -class PlotEditor(TraitsUIEditor): - """A Workbench Editor showing a Chaco plot for the shell interface.""" - - bgcolor = Str("white") - image_default_origin = Enum( - "bottom left", "top left", "bottom right", "top right" - ) - - # The plot. - component = Property(Any) - container = Property(Any) - - # The PlotData. - data = Any() - - # The PlotSession of which we are a part. We need to know this in order - # to notify it of our being closed, etc. - session = Any() - - def __init__( - self, - is_image=False, - bgcolor="white", - image_default_origin="top left", - *args, - **kw - ): - - super(TraitsUIEditor, self).__init__(**kw) - - # Some defaults which should be overridden by preferences. - self.bgcolor = bgcolor - self.image_default_origin = image_default_origin - - # Create an empty top-level container - if is_image: - top_container = self._create_top_img_container() - else: - top_container = self._create_top_container() - - self.obj = PlotUI(component=top_container) - - #### PlotWindow interface ################################################## - - def get_container(self): - return self.obj.component - - def set_container(self, container): - self.obj.component = container - - def iconize(self, iconize): - """Iconizes the window if *iconize* is True. - - Do nothing in this implementation. - """ - - def maximize(self, maximize): - """If *maximize* is True, maximizes the window size; restores if False. - - Do nothing in this implementation. - """ - - def set_size(self, width, height): - pass - - def set_title(self, title): - self.name = title - - def raise_window(self): - self.window.activate_editor(self) - - #### Editor interface ###################################################### - - def destroy_control(self): - """Destroy the toolkit-specific control that represents the part.""" - self._on_window_close() - super(TraitsUIEditor, self).destroy_control() - - #### Private interface ##################################################### - - def _get_container(self): - return self.obj.component - - def _set_container(self, value): - self.obj.component = value - - def _get_component(self): - return self.obj.component - - def _set_component(self, value): - self.obj.component = value - - def _create_top_container(self): - plot = ScalyPlot( - padding=50, - fill_padding=True, - bgcolor=self.bgcolor, - use_backbuffer=True, - ) - return plot - - def _create_top_img_container(self): - plot = ScalyPlot( - padding=50, - fill_padding=True, - bgcolor=self.bgcolor, - use_backbuffer=True, - default_origin=self.image_default_origin, - ) - return plot - - def _on_window_close(self): - if self.session: - try: - ndx = self.session.windows.index(self) - self.session.del_window(ndx) - except ValueError: - pass diff --git a/chaco/plugin/workbench_session.py b/chaco/plugin/workbench_session.py deleted file mode 100644 index 70a9311cb..000000000 --- a/chaco/plugin/workbench_session.py +++ /dev/null @@ -1,56 +0,0 @@ -""" A Chaco Shell PlotSession which raises Workbench Editors instead of -free-standing windows. -""" - -from traits.api import Any, Dict, List, Str -from chaco.shell.session import PlotSession - -from .plot_editor import PlotEditor - - -class WorkbenchSession(PlotSession): - """A Chaco Shell PlotSession which raises Workbench Editors instead of - free-standing windows. - """ - - # The Envisage Application we are in. - application = Any() - - # The list of currently active windows. - windows = List() - - # A dict mapping names to windows. - window_map = Dict(Str, Any) - - def new_window(self, name=None, title=None, is_image=False): - """Creates a new window and returns the index into the **windows** list - for the new window. - """ - workbench = self.application.get_service( - "envisage.ui.workbench.workbench.Workbench" - ) - new_win = PlotEditor( - is_image=is_image, - size=(self.prefs.window_width, self.prefs.window_height), - bgcolor=self.prefs.bgcolor, - image_default_origin=self.prefs.image_default_origin, - window=workbench.active_window, - ) - new_win.data = self.data - new_win.container.data = self.data - new_win.session = self - - if title is not None: - new_win.set_title(title) - elif name != None: - new_win.set_title(name) - else: - new_win.set_title(self.prefs.default_window_name) - - self.windows.append(new_win) - if name != None: - self.window_map[name] = new_win - - workbench.edit(new_win.obj, kind=lambda *args, **kwds: new_win) - - return len(self.windows) - 1 From c6f53875f06ac23ff679ec4e3ef55aa112ef6675 Mon Sep 17 00:00:00 2001 From: Aaron Ayres Date: Thu, 15 Apr 2021 09:09:05 -0700 Subject: [PATCH 4/5] remove shell related items from tox.ini --- tox.ini | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tox.ini b/tox.ini index e1e750983..52a33812c 100644 --- a/tox.ini +++ b/tox.ini @@ -112,11 +112,6 @@ exclude = chaco/layers/api.py chaco/layers/status_layer.py chaco/layers/svg_range_selection_overlay.py - chaco/shell/plot_window.py - chaco/shell/session.py - chaco/shell/__init__.py - chaco/shell/plot_maker.py - chaco/shell/commands.py chaco/overlays/simple_inspector_overlay.py chaco/overlays/databox.py chaco/overlays/api.py From 675f6b6fe882b04174d76f55bc3f6a53e1322f33 Mon Sep 17 00:00:00 2001 From: Aaron Ayres Date: Thu, 15 Apr 2021 09:09:57 -0700 Subject: [PATCH 5/5] remove shell examples and plugin files from tox.ini as well --- tox.ini | 5 ----- 1 file changed, 5 deletions(-) diff --git a/tox.ini b/tox.ini index 52a33812c..60a919001 100644 --- a/tox.ini +++ b/tox.ini @@ -124,9 +124,6 @@ exclude = chaco/tests/test_speedups.py chaco/tests/test_base_utils.py chaco/tests/test_serializable.py - chaco/plugin/workbench_session.py - chaco/plugin/plot_editor.py - chaco/plugin/chaco_plugin.py chaco/scales/time_scale.py chaco/scales/formatters.py chaco/scales/scales.py @@ -170,8 +167,6 @@ exclude = examples/demo/zoomed_plot/zoom_plot.py examples/demo/financial/correlations.py examples/demo/financial/stock_prices.py - examples/demo/shell/add_tool.py - examples/demo/shell/dates.py examples/demo/basic/image_inspector.py examples/demo/basic/draw_layers.py examples/demo/basic/traits_editor.py