def perform_version_check( configfile=(_os.path.join(_os.path.expanduser("~"), ".graphlab", "config")), _version_url=__GLCREATE_CURRENT_VERSION_URL__, _feature_url=__GLCREATE_CURRENT_VERSION_FEATURES_URL__, _outputstream=_sys.stderr): """ Checks if currently running version of GraphLab Create is less than the version available from graphlab.com. Prints a message if the graphlab.com servers are reachable, and the current version is out of date. Does nothing otherwise. If the configfile contains a key "skip_version_check" in the Product section with non-zero value, this function does nothing. Also returns True if a message is printed, and returns False otherwise. """ skip_version_check = False try: if (_os.path.isfile(configfile)): config = _ConfigParser.ConfigParser() config.read(configfile) section = 'Product' key = 'skip_version_check' skip_version_check = config.getboolean(section, key) __LOGGER__.debug("skip_version_check=%s" % str(skip_version_check)) except: # eat all errors pass # skip version check set. Quit if not skip_version_check: try: latest_version = get_newest_version(timeout=1, _url=_version_url).strip() if _parse_version(latest_version) > _parse_version( _version_info.version): try: _feature_url += '/' + get_major_version( _version_info.version) latest_features = get_newest_features( timeout=1, _url=_feature_url).strip() except: latest_features = '' msg = ("A newer version of GraphLab Create (v%s) is available! " "Your current version is v%s.\n" "%s" # this is the string of new features list "You can use pip to upgrade the graphlab-create package. " "For more information see https://dato.com/products/create/upgrade.") % \ (latest_version, _version_info.version, latest_features) _outputstream.write(msg) return True except: # eat all errors pass return False
def __init__(self, plot, parent=None): super(BackendMatplotlib, self).__init__(plot, parent) # matplotlib is handling keep aspect ratio at draw time # When keep aspect ratio is on, and one changes the limits and # ask them *before* next draw has been performed he will get the # limits without applying keep aspect ratio. # This attribute is used to ensure consistent values returned # when getting the limits at the expense of a replot self._dirtyLimits = True self._axesDisplayed = True self._matplotlibVersion = _parse_version(matplotlib.__version__) self.fig = Figure() self.fig.set_facecolor("w") self.ax = self.fig.add_axes([.15, .15, .75, .75], label="left") self.ax2 = self.ax.twinx() self.ax2.set_label("right") # Make sure background of Axes is displayed self.ax2.patch.set_visible(True) # Set axis zorder=0.5 so grid is displayed at 0.5 self.ax.set_axisbelow(True) # disable the use of offsets try: self.ax.get_yaxis().get_major_formatter().set_useOffset(False) self.ax.get_xaxis().get_major_formatter().set_useOffset(False) self.ax2.get_yaxis().get_major_formatter().set_useOffset(False) self.ax2.get_xaxis().get_major_formatter().set_useOffset(False) except: _logger.warning('Cannot disabled axes offsets in %s ' % matplotlib.__version__) # critical for picking!!!! self.ax2.set_zorder(0) self.ax2.set_autoscaley_on(True) self.ax.set_zorder(1) # this works but the figure color is left if self._matplotlibVersion < _parse_version('2'): self.ax.set_axis_bgcolor('none') else: self.ax.set_facecolor('none') self.fig.sca(self.ax) self._background = None self._colormaps = {} self._graphCursor = tuple() self._enableAxis('right', False) self._isXAxisTimeSeries = False
def __init__(self, plot, parent=None): super(BackendMatplotlib, self).__init__(plot, parent) # matplotlib is handling keep aspect ratio at draw time # When keep aspect ratio is on, and one changes the limits and # ask them *before* next draw has been performed he will get the # limits without applying keep aspect ratio. # This attribute is used to ensure consistent values returned # when getting the limits at the expense of a replot self._dirtyLimits = True self._axesDisplayed = True self._matplotlibVersion = _parse_version(matplotlib.__version__) self.fig = Figure() self.fig.set_facecolor("w") self.ax = self.fig.add_axes([.15, .15, .75, .75], label="left") self.ax2 = self.ax.twinx() self.ax2.set_label("right") # Make sure background of Axes is displayed self.ax2.patch.set_visible(True) # disable the use of offsets try: self.ax.get_yaxis().get_major_formatter().set_useOffset(False) self.ax.get_xaxis().get_major_formatter().set_useOffset(False) self.ax2.get_yaxis().get_major_formatter().set_useOffset(False) self.ax2.get_xaxis().get_major_formatter().set_useOffset(False) except: _logger.warning('Cannot disabled axes offsets in %s ' % matplotlib.__version__) # critical for picking!!!! self.ax2.set_zorder(0) self.ax2.set_autoscaley_on(True) self.ax.set_zorder(1) # this works but the figure color is left if self._matplotlibVersion < _parse_version('2'): self.ax.set_axis_bgcolor('none') else: self.ax.set_facecolor('none') self.fig.sca(self.ax) self._overlays = set() self._background = None self._colormaps = {} self._graphCursor = tuple() self._enableAxis('right', False) self._isXAxisTimeSeries = False
def perform_version_check(configfile=(_os.path.join(_os.path.expanduser("~"), ".graphlab", "config")), _version_url=__GLCREATE_CURRENT_VERSION_URL__, _feature_url=__GLCREATE_CURRENT_VERSION_FEATURES_URL__, _outputstream=_sys.stderr): """ Checks if currently running version of GraphLab Create is less than the version available from graphlab.com. Prints a message if the graphlab.com servers are reachable, and the current version is out of date. Does nothing otherwise. If the configfile contains a key "skip_version_check" in the Product section with non-zero value, this function does nothing. Also returns True if a message is printed, and returns False otherwise. """ skip_version_check = False try: if (_os.path.isfile(configfile)): config = _ConfigParser.ConfigParser() config.read(configfile) section = 'Product' key = 'skip_version_check' skip_version_check = config.getboolean(section, key) __LOGGER__.debug("skip_version_check=%s" % str(skip_version_check)) except: # eat all errors pass # skip version check set. Quit if not skip_version_check: try: latest_version = get_newest_version(timeout=1, _url=_version_url).strip() if _parse_version(latest_version) > _parse_version(_version_info.version).replace(".gpu",""): try: _feature_url += '/' + get_major_version(_version_info.version) latest_features = get_newest_features(timeout=1, _url=_feature_url).strip() except: latest_features = '' msg = ("A newer version of GraphLab Create (v%s) is available! " "Your current version is v%s.\n" "%s" # this is the string of new features list "You can use pip to upgrade the graphlab-create package. " "For more information see https://dato.com/products/create/upgrade.") % \ (latest_version, _version_info.version, latest_features) _outputstream.write(msg) return True except: # eat all errors pass return False
def test_get_conda_info(self): conda_info = _annotation.get_conda_info() conda_info_keys = sorted(list(conda_info.keys())) self.assertTrue('status' in conda_info_keys) if 'Failed' not in conda_info['status']: import conda if _parse_version(conda.__version__) >= _parse_version('4.2.0'): self.assertListEqual(self.ref_conda_420_info_keys, conda_info_keys) else: self.assertListEqual(self.ref_conda_410_info_keys, conda_info_keys) self.assertTrue(conda_info['status'] == 'Succeeded')
def parse_version(v): """ In old versions of Python (for instance on Ubuntu 14.04), pkg_resources.parse_version returns a tuple and not a version object. """ parsed = _parse_version(v) return VersionCompat(parsed)
def draw(self): """Overload draw It performs a full redraw (including overlays) of the plot. It also resets background and emit limits changed signal. This is directly called by matplotlib for widget resize. """ # Hide axes borders to defer rendering if self.ax.axison: for spine in self.ax.spines.values(): spine.set_visible(False) # Starting with mpl 2.1.0, toggling autoscale raises a ValueError # in some situations. See #1081, #1136, #1163, if self._matplotlibVersion >= _parse_version("2.0.0"): try: FigureCanvasQTAgg.draw(self) except ValueError as err: _logger.debug( "ValueError caught while calling FigureCanvasQTAgg.draw: " "'%s'", err) else: FigureCanvasQTAgg.draw(self) self.__drawItems(overlay=False) if self._hasOverlays(): # Save background self._background = self.copy_from_bbox(self.fig.bbox) else: self._background = None # Reset background # Check if limits changed due to a resize of the widget if self._limitsBeforeResize is not None: xLimits, yLimits, yRightLimits = self._limitsBeforeResize self._limitsBeforeResize = None if (xLimits != self.ax.get_xbound() or yLimits != self.ax.get_ybound()): self._updateMarkers() if xLimits != self.ax.get_xbound(): self._plot.getXAxis()._emitLimitsChanged() if yLimits != self.ax.get_ybound(): self._plot.getYAxis(axis='left')._emitLimitsChanged() if yRightLimits != self.ax2.get_ybound(): self._plot.getYAxis(axis='right')._emitLimitsChanged() self._drawOverlays() # Draw axes borders at last if self.ax.axison: for spine in self.ax.spines.values(): spine.set_visible(True) self.ax.draw_artist(spine)
def setXAxisLogarithmic(self, flag): # Workaround for matplotlib 2.1.0 when one tries to set an axis # to log scale with both limits <= 0 # In this case a draw with positive limits is needed first if flag and self._matplotlibVersion >= _parse_version('2.1.0'): xlim = self.ax.get_xlim() if xlim[0] <= 0 and xlim[1] <= 0: self.ax.set_xlim(1, 10) self.draw() self.ax2.set_xscale('log' if flag else 'linear') self.ax.set_xscale('log' if flag else 'linear')
def replot(self): BackendMatplotlib.replot(self) dirtyFlag = self._plot._getDirtyPlot() if dirtyFlag == 'overlay': # Only redraw overlays using fast rendering path if self._background is None: self._background = self.copy_from_bbox(self.fig.bbox) self.restore_region(self._background) self._drawOverlays() self.blit(self.fig.bbox) elif dirtyFlag: # Need full redraw self.draw() # Workaround issue of rendering overlays with some matplotlib versions if (_parse_version('1.5') <= self._matplotlibVersion < _parse_version('2.1') and not hasattr(self, '_firstReplot')): self._firstReplot = False if self._overlays or self._graphCursor: qt.QTimer.singleShot(0, self.draw) # Request async draw
def replot(self): BackendMatplotlib.replot(self) dirtyFlag = self._plot._getDirtyPlot() if dirtyFlag == 'overlay': # Only redraw overlays using fast rendering path if self._background is None: self._background = self.copy_from_bbox(self.fig.bbox) self.restore_region(self._background) self._drawOverlays() self.blit(self.fig.bbox) elif dirtyFlag: # Need full redraw self.draw() # Workaround issue of rendering overlays with some matplotlib versions if (_parse_version('1.5') <= self._matplotlibVersion < _parse_version('2.1') and not hasattr(self, '_firstReplot')): self._firstReplot = False if self._hasOverlays(): qt.QTimer.singleShot(0, self.draw) # Request async draw
def _synchronizeBackgroundColors(self): backgroundColor = self._plot.getBackgroundColor().getRgbF() dataBackgroundColor = self._plot.getDataBackgroundColor() if dataBackgroundColor.isValid(): dataBackgroundColor = dataBackgroundColor.getRgbF() else: dataBackgroundColor = backgroundColor if self.ax2.axison: self.fig.patch.set_facecolor(backgroundColor) if self._matplotlibVersion < _parse_version('2'): self.ax2.set_axis_bgcolor(dataBackgroundColor) else: self.ax2.set_facecolor(dataBackgroundColor) else: self.fig.patch.set_facecolor(dataBackgroundColor)
def _synchronizeBackgroundColors(self): backgroundColor = self._plot.getBackgroundColor().getRgbF() dataBackgroundColor = self._plot.getDataBackgroundColor() if dataBackgroundColor.isValid(): dataBackgroundColor = dataBackgroundColor.getRgbF() else: dataBackgroundColor = backgroundColor if self.ax.axison: self.fig.patch.set_facecolor(backgroundColor) if self._matplotlibVersion < _parse_version('2'): self.ax.set_axis_bgcolor(dataBackgroundColor) else: self.ax.set_facecolor(dataBackgroundColor) else: self.fig.patch.set_facecolor(dataBackgroundColor)
def setYAxisLogarithmic(self, flag): # Workaround for matplotlib 2.0 issue with negative bounds # before switching to log scale if flag and self._matplotlibVersion >= _parse_version('2.0.0'): redraw = False for axis, dataRangeIndex in ((self.ax, 1), (self.ax2, 2)): ylim = axis.get_ylim() if ylim[0] <= 0 or ylim[1] <= 0: dataRange = self._plot.getDataRange()[dataRangeIndex] if dataRange is None: dataRange = 1, 100 # Fallback axis.set_ylim(*dataRange) redraw = True if redraw: self.draw() self.ax2.set_yscale('log' if flag else 'linear') self.ax.set_yscale('log' if flag else 'linear')
def draw(self): """Overload draw It performs a full redraw (including overlays) of the plot. It also resets background and emit limits changed signal. This is directly called by matplotlib for widget resize. """ # Starting with mpl 2.1.0, toggling autoscale raises a ValueError # in some situations. See #1081, #1136, #1163, if self._matplotlibVersion >= _parse_version("2.0.0"): try: FigureCanvasQTAgg.draw(self) except ValueError as err: _logger.debug( "ValueError caught while calling FigureCanvasQTAgg.draw: " "'%s'", err) else: FigureCanvasQTAgg.draw(self) if self._overlays or self._graphCursor: # Save background self._background = self.copy_from_bbox(self.fig.bbox) else: self._background = None # Reset background # Check if limits changed due to a resize of the widget if self._limitsBeforeResize is not None: xLimits, yLimits, yRightLimits = self._limitsBeforeResize self._limitsBeforeResize = None if (xLimits != self.ax.get_xbound() or yLimits != self.ax.get_ybound()): self._updateMarkers() if xLimits != self.ax.get_xbound(): self._plot.getXAxis()._emitLimitsChanged() if yLimits != self.ax.get_ybound(): self._plot.getYAxis(axis='left')._emitLimitsChanged() if yRightLimits != self.ax2.get_ybound(): self._plot.getYAxis(axis='right')._emitLimitsChanged() self._drawOverlays()
def parse_arch_version(v: str) -> Tuple[int, Version]: if ':' in v: epoch = int(v.split(':', 1)[0]) else: epoch = 0 return epoch, _parse_version(v)
from __future__ import print_function as _ from pkg_resources import parse_version as _parse_version from ._notification_manager import notification_manager import os as _os import sys as _sys import json as _json import dash as _dash _ddk_needs_polyfills = _parse_version( _dash.__version__) < _parse_version('1.6.1') _resource_modifier = '.polyfill' if _ddk_needs_polyfills else '' # noinspection PyUnresolvedReferences from ._imports_ import * from ._imports_ import __all__ from ._CopyText import _CopyText from . import shortcuts from . import datasets from ._init_py_ddk_template import _setup_template _setup_template() if not hasattr(_dash, 'development'): print( 'Dash was not successfully imported. ' 'Make sure you don\'t have a file ' 'named \n"dash.py" in your current directory.', file=_sys.stderr)
def parse_arch_version(v): if ':' in v: epoch = int(v.split(':', 1)[0]) else: epoch = 0 return epoch, _parse_version(v)
import time until the library is actually used.""" def __init__(self, error): self._error = error def __getattr__(self, name): raise self._error _PYMONGOCRYPT_LIB = os.environ.get('PYMONGOCRYPT_LIB') try: if _PYMONGOCRYPT_LIB: lib = ffi.dlopen(_PYMONGOCRYPT_LIB) else: try: lib = ffi.dlopen(_path) except OSError as exc: # Fallback to libmongocrypt installed on the system. lib = ffi.dlopen('mongocrypt') except OSError as exc: # dlopen raises OSError when the library cannot be found. # Delay the error until the library is actually used. lib = _Library(exc) else: # Check the libmongocrypt version when the library is found. _limongocrypt_version = _parse_version(libmongocrypt_version()) if _limongocrypt_version < _parse_version(_MIN_LIBMONGOCRYPT_VERSION): exc = RuntimeError( "Expected libmongocrypt version %s or greater, found %s" % (_MIN_LIBMONGOCRYPT_VERSION, libmongocrypt_version())) lib = _Library(exc)
def addImage(self, data, legend, origin, scale, z, selectable, draggable, colormap, alpha): # Non-uniform image # http://wiki.scipy.org/Cookbook/Histograms # Non-linear axes # http://stackoverflow.com/questions/11488800/non-linear-axes-for-imshow-in-matplotlib for parameter in (data, legend, origin, scale, z, selectable, draggable): assert parameter is not None origin = float(origin[0]), float(origin[1]) scale = float(scale[0]), float(scale[1]) height, width = data.shape[0:2] picker = (selectable or draggable) # Debian 7 specific support # No transparent colormap with matplotlib < 1.2.0 # Add support for transparent colormap for uint8 data with # colormap with 256 colors, linear norm, [0, 255] range if self._matplotlibVersion < _parse_version('1.2.0'): if (len(data.shape) == 2 and colormap.getName() is None and colormap.getColormapLUT() is not None): colors = colormap.getColormapLUT() if (colors.shape[-1] == 4 and not numpy.all(numpy.equal(colors[3], 255))): # This is a transparent colormap if (colors.shape == (256, 4) and colormap.getNormalization() == 'linear' and not colormap.isAutoscale() and colormap.getVMin() == 0 and colormap.getVMax() == 255 and data.dtype == numpy.uint8): # Supported case, convert data to RGBA data = colors[data.reshape(-1)].reshape( data.shape + (4,)) else: _logger.warning( 'matplotlib %s does not support transparent ' 'colormap.', matplotlib.__version__) if ((height * width) > 5.0e5 and origin == (0., 0.) and scale == (1., 1.)): imageClass = ModestImage else: imageClass = AxesImage # All image are shown as RGBA image image = imageClass(self.ax, label="__IMAGE__" + legend, interpolation='nearest', picker=picker, zorder=z, origin='lower') if alpha < 1: image.set_alpha(alpha) # Set image extent xmin = origin[0] xmax = xmin + scale[0] * width if scale[0] < 0.: xmin, xmax = xmax, xmin ymin = origin[1] ymax = ymin + scale[1] * height if scale[1] < 0.: ymin, ymax = ymax, ymin image.set_extent((xmin, xmax, ymin, ymax)) # Set image data if scale[0] < 0. or scale[1] < 0.: # For negative scale, step by -1 xstep = 1 if scale[0] >= 0. else -1 ystep = 1 if scale[1] >= 0. else -1 data = data[::ystep, ::xstep] if self._matplotlibVersion < _parse_version('2.1'): # matplotlib 1.4.2 do not support float128 dtype = data.dtype if dtype.kind == "f" and dtype.itemsize >= 16: _logger.warning("Your matplotlib version do not support " "float128. Data converted to float64.") data = data.astype(numpy.float64) if data.ndim == 2: # Data image, convert to RGBA image data = colormap.applyToData(data) image.set_data(data) self.ax.add_artist(image) return image
from itertools import cycle import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from pkg_resources import parse_version as _parse_version from magni.cs.phase_transition import config as _conf from magni.utils.plotting import linestyles as _linestyles from magni.utils.validation import decorate_validation as _decorate_validation from magni.utils.validation import validate_generic as _generic from magni.utils.validation import validate_levels as _levels from magni.utils.validation import validate_numeric as _numeric if _parse_version(mpl.__version__) >= _parse_version('1.5.0'): _mpl_prop_era = True else: _mpl_prop_era = False def plot_phase_transitions(curves, plot_l1=True, output_path=None, legend_loc='upper left', errorevery=None, reference_curves=None): r""" Plot of a set of phase transition boundary curves. The set of phase transition boundary curves are plotted an saved under the
def get_conda_info(): """ Return a dictionary contianing information from Conda. `Conda <http://conda.pydata.org/>`_ is the package manager for the Anaconda scientific Python distribution. This function will return various information about the Anaconda installation on the system by querying the Conda package database. .. warning:: THIS IS HIGHLY EXPERIMENTAL AND MAY BREAK WITHOUT FURTHER NOTICE. .. note:: This only works with the conda root environment. Returns ------- conda_info : dict Various information from conda (see notes below for further details). Notes ----- If the Python intepreter is unable to locate and import the conda package, an empty dicionary is returned. The returned dictionary contains the same infomation that is returned by "conda info" in addition to an overview of the linked modules in the Anaconda installation as well as information about the "conda env" if it is available. Specifically, the returned dictionary has the following keys: * platform * conda_version * root_prefix * default_prefix * envs_dirs * package_cache * channels * config_file * linked_modules * env_export For conda < 4.2.0, it also includes the key: * is_foreign_system For conda >= 4.2.0, it also includes the keys: * python_version * conda_is_private * offline_mode Additionally, the returned dictionary has a key named *status*, which can have either of the following values: * 'Succeeded' (Everything seems to be OK) * 'Failed' (Something went wrong - a few details are incluede in the key) If "conda-env" is installed on the system, the `env_export` essentially holds the infomation from "conda env export -n root" as a dictionary. The information provided by this key partially overlaps with the infomation in the `linked_modules` and `modules_info` keys. """ try: import conda import conda.config import conda.install except ImportError: return {'status': 'Failed: Conda not importable'} # Conda info + linked modules if _parse_version(conda.__version__) >= _parse_version('4.2.0'): try: import conda.models.channel import conda.base.context except ImportError: return {'status': 'Failed: Conda context not importable'} conda_channel_urls = conda.models.channel.prioritize_channels( conda.base.context.context.channels) else: # Ugly hack to silence the # "Using Anaconda Cloud api site https://api.anaconda.org" # message being sent to stderr by the binstar/anaconda client. with _silence_stderr(): conda_channel_urls = conda.config.get_channel_urls() conda_info = { 'platform': conda.config.subdir, 'conda_version': conda.__version__, 'root_prefix': conda.config.root_dir, 'default_prefix': conda.config.default_prefix, 'envs_dirs': json.dumps(conda.config.envs_dirs), 'package_cache': json.dumps(conda.config.pkgs_dirs), 'channels': json.dumps(conda_channel_urls), 'config_file': json.dumps(conda.config.rc_path) } # Ugly hack to silence the # "Using Anaconda Cloud api site https://api.anaconda.org" # message being sent to stderr by the binstar/anaconda client. with _silence_stderr(): linked_modules = sorted(conda.install.linked(conda.config.root_dir)) if _parse_version(conda.__version__) >= _parse_version('4.2.0'): conda_info['python_version'] = '.'.join(map(str, sys.version_info)) conda_info['conda_is_private'] = json.dumps( conda.base.context.context.conda_private) conda_info['offline_mode'] = json.dumps( conda.base.context.context.offline) else: conda_info['is_foreign_system'] = json.dumps(bool( conda.config.foreign)) modules_info = { module: conda.install.is_linked(conda_info['root_prefix'], module) for module in linked_modules } conda_info['modules_info'] = json.dumps(modules_info) conda_info['linked_modules'] = json.dumps(linked_modules) conda_info['status'] = 'Succeeded' # Conda env export try: import conda_env.env conda_info['env_export'] = json.dumps( conda_env.env.from_environment('root', conda.config.root_dir).to_dict()) except ImportError: conda_info['env_export'] = 'Failed: conda-env not available' return conda_info
def parse_arch_version(v): if ':' in v: epoch = int(v.split(':', 1)[0]) else: epoch = 0 return (epoch,) + _parse_version(v)
def addImage(self, data, legend, origin, scale, z, selectable, draggable, colormap, alpha): # Non-uniform image # http://wiki.scipy.org/Cookbook/Histograms # Non-linear axes # http://stackoverflow.com/questions/11488800/non-linear-axes-for-imshow-in-matplotlib for parameter in (data, legend, origin, scale, z, selectable, draggable): assert parameter is not None origin = float(origin[0]), float(origin[1]) scale = float(scale[0]), float(scale[1]) height, width = data.shape[0:2] picker = (selectable or draggable) # Debian 7 specific support # No transparent colormap with matplotlib < 1.2.0 # Add support for transparent colormap for uint8 data with # colormap with 256 colors, linear norm, [0, 255] range if self._matplotlibVersion < _parse_version('1.2.0'): if (len(data.shape) == 2 and colormap.getName() is None and colormap.getColormapLUT() is not None): colors = colormap.getColormapLUT() if (colors.shape[-1] == 4 and not numpy.all(numpy.equal(colors[3], 255))): # This is a transparent colormap if (colors.shape == (256, 4) and colormap.getNormalization() == 'linear' and not colormap.isAutoscale() and colormap.getVMin() == 0 and colormap.getVMax() == 255 and data.dtype == numpy.uint8): # Supported case, convert data to RGBA data = colors[data.reshape(-1)].reshape(data.shape + (4, )) else: _logger.warning( 'matplotlib %s does not support transparent ' 'colormap.', matplotlib.__version__) if ((height * width) > 5.0e5 and origin == (0., 0.) and scale == (1., 1.)): imageClass = ModestImage else: imageClass = AxesImage # All image are shown as RGBA image image = imageClass(self.ax, label="__IMAGE__" + legend, interpolation='nearest', picker=picker, zorder=z, origin='lower') if alpha < 1: image.set_alpha(alpha) # Set image extent xmin = origin[0] xmax = xmin + scale[0] * width if scale[0] < 0.: xmin, xmax = xmax, xmin ymin = origin[1] ymax = ymin + scale[1] * height if scale[1] < 0.: ymin, ymax = ymax, ymin image.set_extent((xmin, xmax, ymin, ymax)) # Set image data if scale[0] < 0. or scale[1] < 0.: # For negative scale, step by -1 xstep = 1 if scale[0] >= 0. else -1 ystep = 1 if scale[1] >= 0. else -1 data = data[::ystep, ::xstep] if self._matplotlibVersion < _parse_version('2.1'): # matplotlib 1.4.2 do not support float128 dtype = data.dtype if dtype.kind == "f" and dtype.itemsize >= 16: _logger.warning("Your matplotlib version do not support " "float128. Data converted to float64.") data = data.astype(numpy.float64) if data.ndim == 2: # Data image, convert to RGBA image data = colormap.applyToData(data) image.set_data(data) self.ax.add_artist(image) return image
def get_DCT(shape, overcomplete_shape=None): """ Get the DCT fast operation dictionary for the given image shape. Parameters ---------- shape : list or tuple The shape of the image for which the dictionary is the DCT dictionary. overcomplete_shape : list or tuple, optional The shape of the (overcomplete) frequency domain for the DCT dictionary. The entries must be greater than or equal to the corresponding entries in `shape`. Returns ------- matrix : magni.utils.matrices.Matrix The specified DCT dictionary. See Also -------- magni.utils.matrices.Matrix : The matrix emulator class. Examples -------- Create a dummy image: >>> import numpy as np, magni >>> img = np.random.randn(64, 64) >>> vec = magni.imaging.mat2vec(img) Perform DCT in the ordinary way: >>> dct_normal = magni.imaging.dictionaries._fastops.dct2(vec, img.shape) Perform DCT using the present function: >>> from magni.imaging.dictionaries import get_DCT >>> matrix = get_DCT(img.shape) >>> dct_matrix = matrix.T.dot(vec) Check that the two ways produce the same result: >>> np.allclose(dct_matrix, dct_normal) True Compute the overcomplete transform (and back again) and check that the resulting image is identical to the original. Notice how this example first ensures that the necessary version of SciPy is available: >>> from pkg_resources import parse_version >>> from scipy import __version__ as _scipy_version >>> if parse_version(_scipy_version) >= parse_version('0.16.0'): ... matrix = get_DCT(img.shape, img.shape) ... dct_matrix = matrix.T.dot(vec) ... vec_roundtrip = matrix.dot(dct_matrix) ... np.allclose(vec, vec_roundtrip) ... else: ... True True """ @_decorate_validation def validate_input(): _levels('shape', (_generic(None, 'explicit collection', len_=2), _numeric(None, 'integer', range_='[1;inf)'))) if overcomplete_shape is not None: _generic('overcomplete_shape', 'explicit collection', len_=2), _numeric(('overcomplete_shape', 0), 'integer', range_='[{};inf)'.format(shape[0])) _numeric(('overcomplete_shape', 1), 'integer', range_='[{};inf)'.format(shape[1])) validate_input() entries = shape[0] * shape[1] if overcomplete_shape is None: args = (shape, ) shape = (entries, entries) else: if _parse_version(_scipy_version) < _parse_version('0.16.0'): raise NotImplementedError( 'Over-complete DCT requires SciPy >= 0.16.0') args = (shape, overcomplete_shape) shape = (entries, overcomplete_shape[0] * overcomplete_shape[1]) return _Matrix(_fastops.idct2, _fastops.dct2, args, shape)
""" from __future__ import division import unittest import numpy as np from pkg_resources import parse_version as _parse_version from scipy import __version__ as _scipy_version from magni.imaging.dictionaries import get_DCT from magni.imaging.dictionaries import get_DFT from magni.imaging import mat2vec from magni.imaging import vec2mat _scipy_pre_016 = _parse_version(_scipy_version) < _parse_version('0.16.0') class TransformsMixin(object): """ Test of overcomplete transforms on a square matrix. """ @unittest.skipIf(_scipy_pre_016, "Not supported for SciPy <= 0.16.0") def test_wrong_size_dct(self): # Check that the function does not allow specifying an # _under_-complete transform with self.assertRaises(ValueError): matrix = get_DCT( self.array_shape, (self.array_shape[0] - 1, self.array_shape[1] - 1))