コード例 #1
0
ファイル: python_export.py プロジェクト: glue-viz/glue
def python_export_image_subset_layer(layer, *args):

    if not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = ["from glue.viewers.image.state import get_sliced_data_maker"]

    slices, agg_func, transpose = layer._viewer_state.numpy_slice_aggregation_transpose

    # TODO: implement aggregation, ignore for now

    script += "# Define a function that will get a fixed resolution buffer of the mask\n"

    options = {'data': code('layer_data'),
               'x_axis': layer._viewer_state.x_att.axis,
               'y_axis': layer._viewer_state.y_att.axis,
               'slices': slices}

    if transpose:
        options['transpose'] = True

    script += "array_maker = get_sliced_data_maker({0})\n\n".format(serialize_options(options))

    script += "\n\n"

    options = dict(origin='lower', interpolation='nearest', color=layer.state.color,
                   vmin=0, vmax=1, aspect=layer._viewer_state.aspect,
                   zorder=layer.state.zorder, alpha=layer.state.alpha)

    script += "imshow(ax, {0}, {1})\n".format(code('array_maker'), serialize_options(options))

    return imports, script.strip()
コード例 #2
0
ファイル: python_export.py プロジェクト: sunn-e/glue
def python_export_image_layer(layer, *args):

    if not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = ["from glue.viewers.image.state import get_sliced_data_maker"]

    slices, agg_func, transpose = layer._viewer_state.numpy_slice_aggregation_transpose

    # TODO: implement aggregation, ignore for now

    script += "# Define a function that will get a fixed resolution buffer\n"

    options = {
        'data': code('layer_data'),
        'x_axis': layer._viewer_state.x_att.axis,
        'y_axis': layer._viewer_state.y_att.axis,
        'slices': slices,
        'target_cid':
        code("layer_data.id['{0}']".format(layer.state.attribute))
    }

    if transpose:
        options['transpose'] = True

    script += "array_maker = get_sliced_data_maker({0})\n\n".format(
        serialize_options(options))

    script += "composite.allocate('{0}')\n".format(layer.uuid)

    if layer._viewer_state.color_mode == 'Colormaps':
        color = code('plt.cm.' + layer.state.cmap.name)
    else:
        color = layer.state.color

    options = dict(array=code('array_maker'),
                   clim=(layer.state.v_min, layer.state.v_max),
                   visible=layer.state.visible,
                   zorder=layer.state.zorder,
                   color=color,
                   contrast=layer.state.contrast,
                   bias=layer.state.bias,
                   alpha=layer.state.alpha,
                   stretch=layer.state.stretch)

    script += "composite.set('{0}', {1})\n\n".format(
        layer.uuid, serialize_options(options))

    return imports, script.strip()
コード例 #3
0
ファイル: python_export.py プロジェクト: shreyasbapat/glue
def python_export_image_subset_layer(layer, *args):

    if not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = []

    slices, agg_func, transpose = layer._viewer_state.numpy_slice_aggregation_transpose

    # TODO: implement aggregation, ignore for now

    script += "# Get main subset values\n"
    script += "mask = layer_data.to_mask(view={0})\n\n".format(tuple(slices))

    imports.append('from glue.utils import color2rgb')
    imports.append('import numpy as np')
    script += "# Convert to RGBA array\n"
    script += "r, g, b = color2rgb('{0}')\n".format(layer.state.color)
    script += "mask = np.dstack((r * mask, g * mask, b * mask, mask * .5))\n"
    script += "mask = (255 * mask).astype(np.uint8)\n"

    if transpose:
        script += ".transpose()"

    script += "\n\n"

    options = dict(origin='lower', interpolation='nearest',
                   vmin=0, vmax=1, aspect=layer._viewer_state.aspect,
                   zorder=layer.state.zorder, alpha=layer.state.alpha)

    script += "imshow(ax, mask, {0})\n".format(serialize_options(options))

    return imports, script.strip()
コード例 #4
0
def python_export_histogram_layer(layer, *args):

    if len(layer.mpl_artists) == 0 or not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = ["import numpy as np"]

    x = layer.layer[layer._viewer_state.x_att]
    x_min = nanmin(x)
    x_max = nanmax(x)

    hist_x_min = layer._viewer_state.hist_x_min
    hist_x_max = layer._viewer_state.hist_x_max

    script += "# Get main data values\n"
    script += "x = layer_data['{0}']\n\n".format(
        layer._viewer_state.x_att.label)

    script += "# Set up histogram bins\n"
    script += "hist_n_bin = {0}\n".format(layer._viewer_state.hist_n_bin)

    if abs((x_min - hist_x_min) / (hist_x_max - hist_x_min)) < 0.001:
        script += "hist_x_min = np.nanmin(x)\n"
    else:
        script += "hist_x_min = {0}\n".format(hist_x_min)

    if abs((x_max - hist_x_max) / (hist_x_max - hist_x_min)) < 0.001:
        script += "hist_x_max = np.nanmax(x)\n"
    else:
        script += "hist_x_max = {0}\n".format(hist_x_max)

    options = dict(alpha=layer.state.alpha,
                   color=layer.state.color,
                   zorder=layer.state.zorder,
                   edgecolor='none')

    if layer._viewer_state.x_log:
        script += "bins = np.logspace(np.log10(hist_x_min), np.log10(hist_x_max), hist_n_bin)\n"
        options['bins'] = code('bins')
    else:
        options['range'] = code('[hist_x_min, hist_x_max]')
        options['bins'] = code('hist_n_bin')

    if layer._viewer_state.normalize:
        if MATPLOTLIB_GE_30:
            options['density'] = True
        else:
            options['normed'] = True

    if layer._viewer_state.cumulative:
        options['cumulative'] = True

    script += "\nx = x[(x >= hist_x_min) & (x <= hist_x_max)]\n"

    script += "\nax.hist(x, {0})".format(serialize_options(options))

    return imports, script.strip()
コード例 #5
0
ファイル: python_export.py プロジェクト: glue-viz/glue
def python_export_image_layer(layer, *args):

    if not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = ["from glue.viewers.image.state import get_sliced_data_maker"]

    slices, agg_func, transpose = layer._viewer_state.numpy_slice_aggregation_transpose

    # TODO: implement aggregation, ignore for now

    script += "# Define a function that will get a fixed resolution buffer\n"

    options = {'data': code('layer_data'),
               'x_axis': layer._viewer_state.x_att.axis,
               'y_axis': layer._viewer_state.y_att.axis,
               'slices': slices,
               'target_cid': code("layer_data.id['{0}']".format(layer.state.attribute))}

    if transpose:
        options['transpose'] = True

    script += "array_maker = get_sliced_data_maker({0})\n\n".format(serialize_options(options))

    script += "composite.allocate('{0}')\n".format(layer.uuid)

    if layer._viewer_state.color_mode == 'Colormaps':
        color = code('plt.cm.' + layer.state.cmap.name)
    else:
        color = layer.state.color

    options = dict(array=code('array_maker'),
                   clim=(layer.state.v_min, layer.state.v_max),
                   visible=layer.state.visible,
                   zorder=layer.state.zorder,
                   color=color,
                   contrast=layer.state.contrast,
                   bias=layer.state.bias,
                   alpha=layer.state.alpha,
                   stretch=layer.state.stretch)

    script += "composite.set('{0}', {1})\n\n".format(layer.uuid, serialize_options(options))

    return imports, script.strip()
コード例 #6
0
ファイル: python_export.py プロジェクト: sunn-e/glue
def python_export_image_subset_layer(layer, *args):

    if not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = ["from glue.viewers.image.state import get_sliced_data_maker"]

    slices, agg_func, transpose = layer._viewer_state.numpy_slice_aggregation_transpose

    # TODO: implement aggregation, ignore for now

    script += "# Define a function that will get a fixed resolution buffer of the mask\n"

    options = {
        'data': code('layer_data'),
        'x_axis': layer._viewer_state.x_att.axis,
        'y_axis': layer._viewer_state.y_att.axis,
        'slices': slices
    }

    if transpose:
        options['transpose'] = True

    script += "array_maker = get_sliced_data_maker({0})\n\n".format(
        serialize_options(options))

    script += "\n\n"

    options = dict(origin='lower',
                   interpolation='nearest',
                   color=layer.state.color,
                   vmin=0,
                   vmax=1,
                   aspect=layer._viewer_state.aspect,
                   zorder=layer.state.zorder,
                   alpha=layer.state.alpha)

    script += "imshow(ax, {0}, {1})\n".format(code('array_maker'),
                                              serialize_options(options))

    return imports, script.strip()
コード例 #7
0
ファイル: python_export.py プロジェクト: glue-viz/glue
def python_export_histogram_layer(layer, *args):

    if len(layer.mpl_artists) == 0 or not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = ["import numpy as np"]

    x = layer.layer[layer._viewer_state.x_att]
    x_min = nanmin(x)
    x_max = nanmax(x)

    hist_x_min = layer._viewer_state.hist_x_min
    hist_x_max = layer._viewer_state.hist_x_max

    script += "# Get main data values\n"
    script += "x = layer_data['{0}']\n\n".format(layer._viewer_state.x_att.label)

    script += "# Set up histogram bins\n"
    script += "hist_n_bin = {0}\n".format(layer._viewer_state.hist_n_bin)

    if abs((x_min - hist_x_min) / (hist_x_max - hist_x_min)) < 0.001:
        script += "hist_x_min = np.nanmin(x)\n"
    else:
        script += "hist_x_min = {0}\n".format(hist_x_min)

    if abs((x_max - hist_x_max) / (hist_x_max - hist_x_min)) < 0.001:
        script += "hist_x_max = np.nanmax(x)\n"
    else:
        script += "hist_x_max = {0}\n".format(hist_x_max)

    options = dict(alpha=layer.state.alpha,
                   color=layer.state.color,
                   zorder=layer.state.zorder,
                   edgecolor='none')

    if layer._viewer_state.x_log:
        script += "bins = np.logspace(np.log10(hist_x_min), np.log10(hist_x_max), hist_n_bin)\n"
        options['bins'] = code('bins')
    else:
        options['range'] = code('[hist_x_min, hist_x_max]')
        options['bins'] = code('hist_n_bin')

    if layer._viewer_state.normalize:
        options['normed'] = True

    if layer._viewer_state.cumulative:
        options['cumulative'] = True

    script += "\nx = x[(x >= hist_x_min) & (x <= hist_x_max)]\n"

    script += "\nax.hist(x, {0})".format(serialize_options(options))

    return imports, script.strip()
コード例 #8
0
ファイル: python_export.py プロジェクト: dhomeier/glue
def python_export_profile_layer(layer, *args):

    if len(layer.mpl_artists) == 0 or not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = ["import numpy as np"]

    script += "# Calculate the profile of the data\n"
    script += "profile_axis = {0}\n".format(
        layer._viewer_state.x_att_pixel.axis)
    script += "collapsed_axes = tuple(i for i in range(layer_data.ndim) if i != profile_axis)\n"
    if isinstance(layer.state.layer, Subset):
        script += "base_data = layer_data.data\n"
        script += "cid = base_data.find_component_id('{0}')\n".format(
            layer.state.attribute.label)
        script += "profile_values = base_data.compute_statistic('{0}', cid, axis=collapsed_axes, subset_state=layer_data.subset_state)\n\n".format(
            layer._viewer_state.function)
    else:
        script += "cid = layer_data.find_component_id('{0}')\n".format(
            layer.state.attribute.label)
        script += "profile_values = layer_data.compute_statistic('{0}', cid, axis=collapsed_axes)\n\n".format(
            layer._viewer_state.function)

    script += "# Extract the values for the x-axis\n"
    script += "axis_view = [0] * layer_data.ndim\n"
    script += "axis_view[profile_axis] = slice(None)\n"
    script += "profile_x_values = layer_data['{0}', tuple(axis_view)]\n".format(
        layer._viewer_state.x_att)
    script += "keep = ~np.isnan(profile_values) & ~np.isnan(profile_x_values)\n\n"

    if layer._viewer_state.normalize:
        script += "# Normalize the profile data\n"
        script += "vmax = np.nanmax(profile_values)\n"
        script += "vmin = np.nanmin(profile_values)\n"
        script += "profile_values = (profile_values - vmin)/(vmax - vmin)\n\n"

    script += "# Plot the profile\n"
    plot_options = dict(color=layer.state.color,
                        linewidth=layer.state.linewidth,
                        alpha=layer.state.alpha,
                        zorder=layer.state.zorder,
                        drawstyle='steps-mid')

    script += "handle,  = ax.plot(profile_x_values[keep], profile_values[keep], '-', {0})\n".format(
        serialize_options(plot_options))
    script += "legend_handles.append(handle)\n"
    script += "legend_labels.append(layer_data.label)\n\n"

    return imports, script.strip()
コード例 #9
0
ファイル: python_export.py プロジェクト: sergiopasra/glue
def python_export_image_layer(layer, *args):

    if not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = []

    slices, agg_func, transpose = layer._viewer_state.numpy_slice_aggregation_transpose

    # TODO: implement aggregation, ignore for now

    script += "# Get main data values\n"
    script += "image = layer_data['{0}', {1}]".format(layer.state.attribute,
                                                      slices)

    if transpose:
        script += ".transpose()"

    script += "\n\n"

    script += "composite.allocate('{0}')\n".format(layer.uuid)

    if layer._viewer_state.color_mode == 'Colormaps':
        color = code('plt.cm.' + layer.state.cmap.name)
    else:
        color = layer.state.color

    options = dict(array=code('image'),
                   clim=(layer.state.v_min, layer.state.v_max),
                   visible=layer.state.visible,
                   zorder=layer.state.zorder,
                   color=color,
                   contrast=layer.state.contrast,
                   bias=layer.state.bias,
                   alpha=layer.state.alpha,
                   stretch=layer.state.stretch)

    script += "composite.set('{0}', {1})\n\n".format(
        layer.uuid, serialize_options(options))

    return imports, script.strip()
コード例 #10
0
ファイル: python_export.py プロジェクト: jzuhone/glue
def python_export_image_layer(layer, *args):

    if not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = []

    slices, agg_func, transpose = layer._viewer_state.numpy_slice_aggregation_transpose

    # TODO: implement aggregation, ignore for now

    script += "# Get main data values\n"
    script += "image = layer_data['{0}', {1}]".format(layer.state.attribute, tuple(slices))

    if transpose:
        script += ".transpose()"

    script += "\n\n"

    script += "composite.allocate('{0}')\n".format(layer.uuid)

    if layer._viewer_state.color_mode == 'Colormaps':
        color = code('plt.cm.' + layer.state.cmap.name)
    else:
        color = layer.state.color

    options = dict(array=code('image'),
                   clim=(layer.state.v_min, layer.state.v_max),
                   visible=layer.state.visible,
                   zorder=layer.state.zorder,
                   color=color,
                   contrast=layer.state.contrast,
                   bias=layer.state.bias,
                   alpha=layer.state.alpha,
                   stretch=layer.state.stretch)

    script += "composite.set('{0}', {1})\n\n".format(layer.uuid, serialize_options(options))

    return imports, script.strip()
コード例 #11
0
ファイル: python_export.py プロジェクト: sunn-e/glue
def python_export_scatter_layer(layer, *args):

    if len(layer.mpl_artists) == 0 or not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = []

    script += "# Get main data values\n"
    script += "x = layer_data['{0}']\n".format(layer._viewer_state.x_att.label)
    script += "y = layer_data['{0}']\n\n".format(
        layer._viewer_state.y_att.label)

    if layer.state.cmap_mode == 'Linear':

        script += "# Set up colors\n"
        script += "colors = layer_data['{0}']\n".format(
            layer.state.cmap_att.label)
        script += "cmap_vmin = {0}\n".format(layer.state.cmap_vmin)
        script += "cmap_vmax = {0}\n".format(layer.state.cmap_vmax)
        script += "colors = plt.cm.{0}((colors - cmap_vmin) / (cmap_vmax - cmap_vmin))\n\n".format(
            layer.state.cmap.name)

    if layer.state.size_mode == 'Linear':

        imports = ['import numpy as np']

        script += "# Set up size values\n"
        script += "sizes = layer_data['{0}']\n".format(
            layer.state.size_att.label)
        script += "size_vmin = {0}\n".format(layer.state.size_vmin)
        script += "size_vmax = {0}\n".format(layer.state.size_vmax)
        script += "sizes = 30 * (np.clip((sizes - size_vmin) / (size_vmax - size_vmin), 0, 1) * 0.95 + 0.05) * {0}\n\n".format(
            layer.state.size_scaling)

    if layer.state.markers_visible:
        if layer.state.density_map:

            imports += ["from mpl_scatter_density import ScatterDensityArtist"]
            imports += [
                "from glue.viewers.scatter.layer_artist import DensityMapLimits, STRETCHES"
            ]
            imports += ["from astropy.visualization import ImageNormalize"]

            script += "density_limits = DensityMapLimits()\n"
            script += "density_limits.contrast = {0}\n\n".format(
                layer.state.density_contrast)

            options = dict(alpha=layer.state.alpha,
                           zorder=layer.state.zorder,
                           dpi=layer._viewer_state.dpi)

            if layer.state.cmap_mode == 'Fixed':
                options['color'] = layer.state.color
                options['vmin'] = code('density_limits.min')
                options['vmax'] = code('density_limits.max')
                options['norm'] = code(
                    "ImageNormalize(stretch=STRETCHES['{0}']())".format(
                        layer.state.stretch))
            else:
                options['c'] = code("layer_data['{0}']".format(
                    layer.state.cmap_att.label))
                options['cmap'] = code("plt.cm.{0}".format(
                    layer.state.cmap.name))
                options['vmin'] = layer.state.cmap_vmin
                options['vmax'] = layer.state.cmap_vmax

            script += "density = ScatterDensityArtist(ax, x, y, {0})\n".format(
                serialize_options(options))
            script += "ax.add_artist(density)\n\n"

        else:
            if layer.state.cmap_mode == 'Fixed' and layer.state.size_mode == 'Fixed':
                options = dict(color=layer.state.color,
                               markersize=layer.state.size *
                               layer.state.size_scaling,
                               alpha=layer.state.alpha,
                               zorder=layer.state.zorder)
                if layer.state.fill:
                    options['mec'] = 'none'
                else:
                    options['mfc'] = 'none'
                script += "ax.plot(x, y, 'o', {0})\n\n".format(
                    serialize_options(options))
            else:
                options = dict(alpha=layer.state.alpha,
                               zorder=layer.state.zorder)

                if layer.state.cmap_mode == 'Fixed':
                    options['facecolor'] = layer.state.color
                else:
                    options['c'] = code('colors')

                if layer.state.size_mode == 'Fixed':
                    options['s'] = code('{0} ** 2'.format(
                        layer.state.size * layer.state.size_scaling))
                else:
                    options['s'] = code('sizes ** 2')

                if layer.state.fill:
                    options['edgecolor'] = 'none'
                else:
                    script += "s = "

                script += "ax.scatter(x, y, {0})\n".format(
                    serialize_options(options))

                if not layer.state.fill:
                    script += "s.set_edgecolors(s.get_facecolors())\n"
                    script += "s.set_facecolors('none')\n"

                script += "\n"

    if layer.state.vector_visible:

        if layer.state.vx_att is not None and layer.state.vy_att is not None:

            imports += ['import numpy as np']

            script += "# Get vector data\n"
            if layer.state.vector_mode == 'Polar':
                script += "angle = layer_data['{0}']\n".format(
                    layer.state.vx_att.label)
                script += "length = layer_data['{0}']\n".format(
                    layer.state.vy_att.label)
                script += "vx = length * np.cos(np.radians(angle))\n"
                script += "vy = length * np.sin(np.radians(angle))\n"
            else:
                script += "vx = layer_data['{0}']\n".format(
                    layer.state.vx_att.label)
                script += "vy = layer_data['{0}']\n".format(
                    layer.state.vy_att.label)

        if layer.state.vector_arrowhead:
            hw = 3
            hl = 5
        else:
            hw = 1
            hl = 0

        script += 'vmax = np.nanmax(np.hypot(vx, vy))\n\n'

        scale = code('{0} * vmax'.format(10 / layer.state.vector_scaling))

        options = dict(units='width',
                       pivot=layer.state.vector_origin,
                       headwidth=hw,
                       headlength=hl,
                       scale_units='width',
                       scale=scale,
                       angles='xy',
                       alpha=layer.state.alpha,
                       zorder=layer.state.zorder)

        if layer.state.cmap_mode == 'Fixed':
            options['color'] = layer.state.color
        else:
            options['color'] = code('colors')

        script += "ax.quiver(x, y, vx, vy, {0})\n\n".format(
            serialize_options(options))

    if layer.state.xerr_visible or layer.state.yerr_visible:

        if layer.state.xerr_visible and layer.state.xerr_att is not None:
            xerr = code("layer_data['{0}']".format(layer.state.xerr_att.label))
        else:
            xerr = code("None")

        if layer.state.yerr_visible and layer.state.yerr_att is not None:
            yerr = code("layer_data['{0}']".format(layer.state.yerr_att.label))
        else:
            yerr = code("None")

        options = dict(fmt='none',
                       xerr=xerr,
                       yerr=yerr,
                       alpha=layer.state.alpha,
                       zorder=layer.state.zorder)

        if layer.state.cmap_mode == 'Fixed':
            options['ecolor'] = layer.state.color
        else:
            options['ecolor'] = code('colors')

        script += "ax.errorbar(x, y, {0})\n\n".format(
            serialize_options(options))

    if layer.state.line_visible:

        options = dict(color=layer.state.color,
                       linewidth=layer.state.linewidth,
                       linestyle=layer.state.linestyle,
                       alpha=layer.state.alpha,
                       zorder=layer.state.zorder)
        if layer.state.cmap_mode == 'Fixed':
            script += "ax.plot(x, y, '-', {0})\n\n".format(
                serialize_options(options))
        else:
            options['c'] = code('colors')
            imports.append(
                "from glue.viewers.scatter.layer_artist import plot_colored_line"
            )
            script += "plot_colored_line(ax, x, y, {0})\n\n".format(
                serialize_options(options))

    return imports, script.strip()
コード例 #12
0
ファイル: python_export.py プロジェクト: dhomeier/glue
def python_export_scatter_layer(layer, *args):

    if len(layer.mpl_artists) == 0 or not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = ["import numpy as np"]

    polar = layer._viewer_state.using_polar
    degrees = polar and getattr(layer._viewer_state, 'using_degrees', False)
    if polar:
        theta_formatter = 'ThetaDegreeFormatter' if degrees else 'ThetaRadianFormatter'
        imports += [
            "from glue.core.util import polar_tick_alignment, PolarRadiusFormatter, {0}"
            .format(theta_formatter),
            "from matplotlib.projections.polar import ThetaFormatter, ThetaLocator",
            "from matplotlib.ticker import AutoLocator"
        ]

    script += "layer_handles = []  # for legend"

    script += "# Get main data values\n"
    x_transform_open = "np.radians(" if degrees else ""
    x_transform_close = ")" if degrees else ""
    script += "x = {0}layer_data['{1}']{2}\n".format(
        x_transform_open, layer._viewer_state.x_att.label, x_transform_close)
    script += "y = layer_data['{0}']\n".format(layer._viewer_state.y_att.label)
    script += "keep = ~np.isnan(x) & ~np.isnan(y)\n\n"
    if polar:
        script += 'ax.xaxis.set_major_locator(ThetaLocator(AutoLocator()))\n'
        script += 'ax.xaxis.set_major_formatter({0}("{1}"))\n'.format(
            theta_formatter, layer._viewer_state.x_axislabel)
        script += "for lbl, loc in zip(ax.xaxis.get_majorticklabels(), ax.xaxis.get_majorticklocs()):\n"
        script += "\tlbl.set_horizontalalignment(polar_tick_alignment(loc, {0}))\n\n".format(
            not degrees)

        script += 'ax.yaxis.set_major_locator(AutoLocator())\n'
        script += 'ax.yaxis.set_major_formatter(PolarRadiusFormatter("{0}"))\n'.format(
            layer._viewer_state.y_axislabel)
        script += 'for lbl in ax.yaxis.get_majorticklabels():\n'
        script += '\tlbl.set_fontstyle(\'italic\')\n\n'

    if layer.state.cmap_mode == 'Linear':

        script += "# Set up colors\n"
        script += "colors = layer_data['{0}']\n".format(
            layer.state.cmap_att.label)
        script += "cmap_vmin = {0}\n".format(layer.state.cmap_vmin)
        script += "cmap_vmax = {0}\n".format(layer.state.cmap_vmax)
        script += "keep &= ~np.isnan(colors)\n"
        script += "colors = plt.cm.{0}((colors - cmap_vmin) / (cmap_vmax - cmap_vmin))\n\n".format(
            layer.state.cmap.name)

    if layer.state.size_mode == 'Linear':

        script += "# Set up size values\n"
        script += "sizes = layer_data['{0}']\n".format(
            layer.state.size_att.label)
        script += "size_vmin = {0}\n".format(layer.state.size_vmin)
        script += "size_vmax = {0}\n".format(layer.state.size_vmax)
        script += "keep &= ~np.isnan(sizes)\n"
        script += "sizes = 30 * (np.clip((sizes - size_vmin) / (size_vmax - size_vmin), 0, 1) * 0.95 + 0.05) * {0}\n\n".format(
            layer.state.size_scaling)

    if layer.state.markers_visible:
        if layer.state.density_map:

            imports += ["from mpl_scatter_density import ScatterDensityArtist"]
            imports += [
                "from glue.viewers.scatter.layer_artist import DensityMapLimits, STRETCHES"
            ]
            imports += ["from astropy.visualization import ImageNormalize"]

            script += "density_limits = DensityMapLimits()\n"
            script += "density_limits.contrast = {0}\n\n".format(
                layer.state.density_contrast)

            options = dict(alpha=layer.state.alpha,
                           zorder=layer.state.zorder,
                           dpi=layer._viewer_state.dpi)

            if layer.state.cmap_mode == 'Fixed':
                options['color'] = layer.state.color
                options['vmin'] = code('density_limits.min')
                options['vmax'] = code('density_limits.max')
                options['norm'] = code(
                    "ImageNormalize(stretch=STRETCHES['{0}']())".format(
                        layer.state.stretch))
            else:
                options['c'] = code("layer_data['{0}']".format(
                    layer.state.cmap_att.label))
                options['cmap'] = code("plt.cm.{0}".format(
                    layer.state.cmap.name))
                options['vmin'] = layer.state.cmap_vmin
                options['vmax'] = layer.state.cmap_vmax

            script += "density = ScatterDensityArtist(ax, x, y, {0})\n".format(
                serialize_options(options))
            script += "ax.add_artist(density)\n\n"

            # legend
            imports += ["from matplotlib.lines import Line2D"]

            options = dict(ms=layer.state.size,
                           alpha=layer.state.alpha,
                           color=layer.state.color)
            script += "layer_handles.append(\n"
            script += "    Line2D([0, ], [0, ],\n"
            script += "           marker='.', linestyle='none',\n"
            script += "           {0}))\n".format(serialize_options(options))

        else:
            if layer._use_plot_artist():
                options = dict(color=layer.state.color,
                               markersize=layer.state.size *
                               layer.state.size_scaling,
                               alpha=layer.state.alpha,
                               zorder=layer.state.zorder,
                               label=layer.layer.label)
                if layer.state.fill:
                    options['mec'] = 'none'
                else:
                    options['mfc'] = 'none'
                script += "plot_artists = ax.plot(x[keep], y[keep], 'o', {0})\n".format(
                    serialize_options(options))
                script += "layer_handles.extend(plot_artists)\n\n"
            else:
                options = dict(alpha=layer.state.alpha,
                               zorder=layer.state.zorder)

                if layer.state.cmap_mode == 'Fixed':
                    options['facecolor'] = layer.state.color
                else:
                    options['c'] = code('colors[keep]')

                if layer.state.size_mode == 'Fixed':
                    options['s'] = code('{0} ** 2'.format(
                        layer.state.size * layer.state.size_scaling))
                else:
                    options['s'] = code('sizes[keep] ** 2')

                if layer.state.fill:
                    options['edgecolor'] = 'none'

                script += "scatter_artist = ax.scatter(x[keep], y[keep], {0})\n".format(
                    serialize_options(options))

                if not layer.state.fill:
                    script += "scatter_artist.set_edgecolors(scatter_artist.get_facecolors())\n"
                    script += "scatter_artist.set_facecolors('none')\n"

                script += "layer_handles.append(scatter_artist)\n\n"

    if layer.state.vector_visible:

        if layer.state.vx_att is not None and layer.state.vy_att is not None:

            imports += ['import numpy as np']

            script += "# Get vector data\n"
            if layer.state.vector_mode == 'Polar':
                script += "angle = layer_data['{0}'][keep]\n".format(
                    layer.state.vx_att.label)
                script += "length = layer_data['{0}'][keep]\n".format(
                    layer.state.vy_att.label)
                script += "vx = length * np.cos(np.radians(angle))\n"
                script += "vy = length * np.sin(np.radians(angle))\n"
            else:
                script += "vx = layer_data['{0}'][keep]\n".format(
                    layer.state.vx_att.label)
                script += "vy = layer_data['{0}'][keep]\n".format(
                    layer.state.vy_att.label)

        if layer.state.vector_arrowhead:
            hw = 3
            hl = 5
        else:
            hw = 1
            hl = 0

        script += 'vmax = np.nanmax(np.hypot(vx, vy))\n\n'

        scale = code('{0} * vmax'.format(10 / layer.state.vector_scaling))

        options = dict(units='width',
                       pivot=layer.state.vector_origin,
                       headwidth=hw,
                       headlength=hl,
                       scale_units='width',
                       scale=scale,
                       angles='xy',
                       alpha=layer.state.alpha,
                       zorder=layer.state.zorder)

        if layer.state.cmap_mode == 'Fixed':
            options['color'] = layer.state.color
        else:
            options['color'] = code('colors[keep]')

        script += "vector_artist = ax.quiver(x[keep], y[keep], vx, vy, {0})\n".format(
            serialize_options(options))
        script += "layer_handles.append(vector_artist)\n\n"

    if layer.state.xerr_visible or layer.state.yerr_visible:

        if layer.state.xerr_visible and layer.state.xerr_att is not None:
            xerr = code("xerr[keep]")
        else:
            xerr = code("None")

        if layer.state.yerr_visible and layer.state.yerr_att is not None:
            yerr = code("yerr[keep]")
        else:
            yerr = code("None")

        options = dict(fmt='none',
                       xerr=xerr,
                       yerr=yerr,
                       alpha=layer.state.alpha,
                       zorder=layer.state.zorder)

        if layer.state.cmap_mode == 'Fixed':
            options['ecolor'] = layer.state.color
        else:
            options['ecolor'] = code('colors[keep]')

        script += "xerr = layer_data['{0}']\n".format(
            layer.state.xerr_att.label)
        script += "yerr = layer_data['{0}']\n".format(
            layer.state.yerr_att.label)
        script += "keep &= ~np.isnan(xerr) & ~np.isnan(yerr)\n"
        script += "error_artist = ax.errorbar(x[keep], y[keep], {0})\n".format(
            serialize_options(options))
        script += "layer_handles.append(error_artist)\n\n"

    if layer.state.line_visible:

        options = dict(color=layer.state.color,
                       linewidth=layer.state.linewidth,
                       linestyle=layer.state.linestyle,
                       alpha=layer.state.alpha,
                       zorder=layer.state.zorder)
        if layer.state.cmap_mode == 'Fixed':
            script += "ax.plot(x[keep], y[keep], '-', {0})\n\n".format(
                serialize_options(options))
        else:
            options['c'] = code('colors')
            imports.append(
                "from glue.viewers.scatter.layer_artist import plot_colored_line"
            )
            script += "line_collection = plot_colored_line(ax, x, y, {0})\n".format(
                serialize_options(options))
            script += "layer_handles.append(line_collection)\n\n"

    script += "legend_handles.append(tuple(layer_handles))\n"
    script += "legend_labels.append(layer_data.label)\n\n"
    return imports, script.strip()
コード例 #13
0
ファイル: python_export.py プロジェクト: glue-viz/glue
def python_export_scatter_layer(layer, *args):

    if len(layer.mpl_artists) == 0 or not layer.enabled or not layer.visible:
        return [], None

    script = ""
    imports = []

    script += "# Get main data values\n"
    script += "x = layer_data['{0}']\n".format(layer._viewer_state.x_att.label)
    script += "y = layer_data['{0}']\n\n".format(layer._viewer_state.y_att.label)

    if layer.state.cmap_mode == 'Linear':

        script += "# Set up colors\n"
        script += "colors = layer_data['{0}']\n".format(layer.state.cmap_att.label)
        script += "cmap_vmin = {0}\n".format(layer.state.cmap_vmin)
        script += "cmap_vmax = {0}\n".format(layer.state.cmap_vmax)
        script += "colors = plt.cm.{0}((colors - cmap_vmin) / (cmap_vmax - cmap_vmin))\n\n".format(layer.state.cmap.name)

    if layer.state.size_mode == 'Linear':

        imports = ['import numpy as np']

        script += "# Set up size values\n"
        script += "sizes = layer_data['{0}']\n".format(layer.state.size_att.label)
        script += "size_vmin = {0}\n".format(layer.state.size_vmin)
        script += "size_vmax = {0}\n".format(layer.state.size_vmax)
        script += "sizes = 30 * (np.clip((sizes - size_vmin) / (size_vmax - size_vmin), 0, 1) * 0.95 + 0.05) * {0}\n\n".format(layer.state.size_scaling)

    if layer.state.markers_visible:
        if layer.state.density_map:

            imports += ["from mpl_scatter_density import ScatterDensityArtist"]
            imports += ["from glue.viewers.scatter.layer_artist import DensityMapLimits, STRETCHES"]
            imports += ["from astropy.visualization import ImageNormalize"]

            script += "density_limits = DensityMapLimits()\n"
            script += "density_limits.contrast = {0}\n\n".format(layer.state.density_contrast)

            options = dict(alpha=layer.state.alpha,
                           zorder=layer.state.zorder,
                           dpi=layer._viewer_state.dpi)

            if layer.state.cmap_mode == 'Fixed':
                options['color'] = layer.state.color
                options['vmin'] = code('density_limits.min')
                options['vmax'] = code('density_limits.max')
                options['norm'] = code("ImageNormalize(stretch=STRETCHES['{0}']())".format(layer.state.stretch))
            else:
                options['c'] = code("layer_data['{0}']".format(layer.state.cmap_att.label))
                options['cmap'] = code("plt.cm.{0}".format(layer.state.cmap.name))
                options['vmin'] = layer.state.cmap_vmin
                options['vmax'] = layer.state.cmap_vmax

            script += "density = ScatterDensityArtist(ax, x, y, {0})\n".format(serialize_options(options))
            script += "ax.add_artist(density)\n\n"

        else:
            if layer.state.cmap_mode == 'Fixed' and layer.state.size_mode == 'Fixed':
                options = dict(color=layer.state.color,
                               markersize=layer.state.size * layer.state.size_scaling,
                               alpha=layer.state.alpha,
                               zorder=layer.state.zorder)
                if layer.state.fill:
                    options['mec'] = 'none'
                else:
                    options['mfc'] = 'none'
                script += "ax.plot(x, y, 'o', {0})\n\n".format(serialize_options(options))
            else:
                options = dict(alpha=layer.state.alpha,
                               zorder=layer.state.zorder)

                if layer.state.cmap_mode == 'Fixed':
                    options['facecolor'] = layer.state.color
                else:
                    options['c'] = code('colors')

                if layer.state.size_mode == 'Fixed':
                    options['s'] = code('{0} ** 2'.format(layer.state.size * layer.state.size_scaling))
                else:
                    options['s'] = code('sizes ** 2')

                if layer.state.fill:
                    options['edgecolor'] = 'none'
                else:
                    script += "s = "

                script += "ax.scatter(x, y, {0})\n".format(serialize_options(options))

                if not layer.state.fill:
                    script += "s.set_edgecolors(s.get_facecolors())\n"
                    script += "s.set_facecolors('none')\n"

                script += "\n"

    if layer.state.vector_visible:

        if layer.state.vx_att is not None and layer.state.vy_att is not None:

            imports += ['import numpy as np']

            script += "# Get vector data\n"
            if layer.state.vector_mode == 'Polar':
                script += "angle = layer_data['{0}']\n".format(layer.state.vx_att.label)
                script += "length = layer_data['{0}']\n".format(layer.state.vy_att.label)
                script += "vx = length * np.cos(np.radians(angle))\n"
                script += "vy = length * np.sin(np.radians(angle))\n"
            else:
                script += "vx = layer_data['{0}']\n".format(layer.state.vx_att.label)
                script += "vy = layer_data['{0}']\n".format(layer.state.vy_att.label)

        if layer.state.vector_arrowhead:
            hw = 3
            hl = 5
        else:
            hw = 1
            hl = 0

        script += 'vmax = np.nanmax(np.hypot(vx, vy))\n\n'

        scale = code('{0} * vmax'.format(10 / layer.state.vector_scaling))

        options = dict(units='width',
                       pivot=layer.state.vector_origin,
                       headwidth=hw, headlength=hl,
                       scale_units='width',
                       scale=scale,
                       angles='xy',
                       alpha=layer.state.alpha,
                       zorder=layer.state.zorder)

        if layer.state.cmap_mode == 'Fixed':
            options['color'] = layer.state.color
        else:
            options['color'] = code('colors')

        script += "ax.quiver(x, y, vx, vy, {0})\n\n".format(serialize_options(options))

    if layer.state.xerr_visible or layer.state.yerr_visible:

        if layer.state.xerr_visible and layer.state.xerr_att is not None:
            xerr = code("layer_data['{0}']".format(layer.state.xerr_att.label))
        else:
            xerr = code("None")

        if layer.state.yerr_visible and layer.state.yerr_att is not None:
            yerr = code("layer_data['{0}']".format(layer.state.yerr_att.label))
        else:
            yerr = code("None")

        options = dict(fmt='none', xerr=xerr, yerr=yerr,
                       alpha=layer.state.alpha, zorder=layer.state.zorder)

        if layer.state.cmap_mode == 'Fixed':
            options['ecolor'] = layer.state.color
        else:
            options['ecolor'] = code('colors')

        script += "ax.errorbar(x, y, {0})\n\n".format(serialize_options(options))

    if layer.state.line_visible:

        options = dict(color=layer.state.color,
                       linewidth=layer.state.linewidth,
                       linestyle=layer.state.linestyle,
                       alpha=layer.state.alpha,
                       zorder=layer.state.zorder)
        if layer.state.cmap_mode == 'Fixed':
            script += "ax.plot(x, y, '-', {0})\n\n".format(serialize_options(options))
        else:
            options['c'] = code('colors')
            imports.append("from glue.viewers.scatter.layer_artist import plot_colored_line")
            script += "plot_colored_line(ax, x, y, {0})\n\n".format(serialize_options(options))

    return imports, script.strip()