def __call__(self, val): if val is None: return val elif isinstance(val, six.string_types): return [ValidateInStrings.__call__(self, val), 1.0] elif np.asarray(val).ndim and isinstance(val[0], six.string_types): return [ValidateInStrings.__call__(self, val[0])] + list(val[1:]) # otherwise we assume an array else: return np.asarray(val, float)
def __call__(self, val): if val is None or self.instance_check(val): return val elif isinstance(val, int): return [self.default, val] elif isinstance(val, six.string_types): return [ValidateInStrings.__call__(self, val), None] elif isinstance(val[0], six.string_types): return [ValidateInStrings.__call__(self, val[0])] + list(val[1:]) # otherwise we assume an array else: return ValidateList(float)(val)
def __init__(self, *args, **kwargs): """ For parameter description see :class:`matplotlib.rcsetup.ValidateInStrings`. Other Parameters ---------------- inis: tuple Tuple of object types that may pass the check default: str The default string to use for an integer (Default: 'rounded')""" self.possible_instances = kwargs.pop('inis', None) self.default = kwargs.pop('default', 'rounded') ValidateInStrings.__init__(self, *args, **kwargs)
def __call__(self, val): # validate the ticks # if None, int or tuple (defining min- and max-range), pass if val is None or isinstance(val, int) or (isinstance(val, tuple) and len(val) <= 3): return val # strings must be in the given list elif isinstance(val, six.string_types): return [ValidateInStrings.__call__(self, val), None] elif len(val) and isinstance(val[0], six.string_types): return [ValidateInStrings.__call__(self, val[0])] + list(val[1:]) # otherwise we assume an array else: return ValidateList()(val)
def validate_sym_lims(val): validator = try_and_error( validate_none, ValidateInStrings('sym_links', ['min', 'max'], True)) val = safe_list(val) if len(val) != 2: val = val + val if not len(val) == 2: raise ValueError("Need two values for the symmetric limits, not %i" % (len(val))) return list(map(validator, val))
def validate_plot(val): validator = ValidateInStrings( '2d plot', ['mesh', 'contourf', 'contour', 'poly', 'tri', 'tricontourf', 'tricontour'], True) val = validator(val) depr_map = { "tri": "poly", "tricontourf": "contourf", "tricontour": "contour" } if val in depr_map: warn("plot=%r is depreceated for the plot formatoption and will be " "removed in psy-simple 1.4.0. Please use plot=%r instead." % ( val, depr_map[val]), DeprecationWarning) return depr_map[val] return val
def validate_text(value): """Validate a text formatoption Parameters ---------- value: see :attr:`psyplot.plotter.labelplotter.text` Raises ------ ValueError""" possible_transform = ['axes', 'fig', 'data'] validate_transform = ValidateInStrings('transform', possible_transform, True) tests = [ validate_float, validate_float, validate_str, validate_transform, dict ] if isinstance(value, six.string_types): xpos, ypos = rcParams['texts.default_position'] return [(xpos, ypos, value, 'axes', {'ha': 'right'})] elif isinstance(value, tuple): value = [value] try: value = list(value)[:] except TypeError: raise ValueError("Value must be string or list of tuples!") for i, val in enumerate(value): try: val = tuple(val) except TypeError: raise ValueError("Text must be an iterable of the form " "(x, y, s[, trans, params])!") if len(val) < 3: raise ValueError( "Text tuple must at least be like [x, y, s], with floats x, " "y and string s!") elif len(val) == 3 or isinstance(val[3], dict): val = list(val) val.insert(3, 'data') if len(val) == 4: val += [{}] val = tuple(val) if len(val) > 5: raise ValueError( "Text tuple must not be longer then length 5. It can be " "like (x, y, s[, trans, params])!") value[i] = (validate(x) for validate, x in zip(tests, val)) return value
def __init__(self, key, valid, validators, default, ignorecase=False): """ Parameters ---------- key: str The name of the formatoption (will be used for error handling) valid: list of str The valid keys for the dictionary validators: func The validation function for the values of the dictionary default: object The default value to use if a key from `valid` is given in the provided value ignorecase: bool Whether the case of the keys should be ignored """ self.key = key self.valid = valid self.key_validator = ValidateInStrings(key, valid, ignorecase) self.default = default self.validate = validators
import matplotlib.ticker as ticker import numpy as np import six import packaging.version # Local modules. # Globals and constants variables. __all__ = ['ColorBar'] # Setup of extra parameters in the matplotlic rc validate_orientation = ValidateInStrings('orientation', ['horizontal', 'vertical']) validate_ticklocation = ValidateInStrings( 'orientation', ['auto', 'left', 'right', 'bottom', 'top']) defaultParams.update({ 'colorbar.orientation': ['vertical', validate_orientation], 'colorbar.ticklocation': ['auto', validate_ticklocation], 'colorbar.length_fraction': [0.2, validate_float], 'colorbar.width_fraction': [0.02, validate_float], 'colorbar.location': ['upper right', validate_legend_loc], 'colorbar.pad': [0.2, validate_float], 'colorbar.border_pad': [0.1, validate_float], 'colorbar.sep': [5, validate_float], 'colorbar.frameon': [True, validate_bool], 'colorbar.color': ['k', validate_color], 'colorbar.box_color': ['w', validate_color],
(defaultParams, validate_float, validate_legend_loc, validate_bool, validate_color, ValidateInStrings) from matplotlib.offsetbox import \ AuxTransformBox, TextArea, VPacker, HPacker, AnchoredOffsetbox from matplotlib.patches import Rectangle # Local modules. from .dimension import \ (_Dimension, SILengthDimension, SILengthReciprocalDimension, ImperialLengthDimension) # Globals and constants variables. # Setup of extra parameters in the matplotlic rc validate_scale_loc = ValidateInStrings('scale_loc', ['bottom', 'top', 'right', 'left'], ignorecase=True) validate_label_loc = ValidateInStrings('label_loc', ['bottom', 'top', 'right', 'left'], ignorecase=True) defaultParams.update({ 'scalebar.length_fraction': [0.2, validate_float], 'scalebar.height_fraction': [0.01, validate_float], 'scalebar.location': ['upper right', validate_legend_loc], 'scalebar.pad': [0.2, validate_float], 'scalebar.border_pad': [0.1, validate_float], 'scalebar.sep': [5, validate_float], 'scalebar.frameon': [True, validate_bool], 'scalebar.color': ['k', validate_color], 'scalebar.box_color': ['w', validate_color],
else: value = list(value) for i, v in enumerate(value): if v is None: pass elif isinstance(v, six.string_types): value[i] = six.text_type(v) else: raise ValueError('Expected None or string, found %s' % (v, )) return value validate_ticklabels = try_and_error(validate_none, validate_str, validate_stringlist) validate_extend = ValidateInStrings('extend', ['neither', 'both', 'min', 'max']) class ValidateList(object): """Validate a list of the specified `dtype` """ def __init__(self, dtype=None, length=None, listtype=list): """ Parameters ---------- dtype: object A datatype (e.g. :class:`float`) that shall be used for the conversion length: int The expected length of the list listtype: type
# Local modules. from .dimension import ( _Dimension, SILengthDimension, SILengthReciprocalDimension, ImperialLengthDimension, PixelLengthDimension, AngleDimension, ) # Globals and constants variables. # Setup of extra parameters in the matplotlic rc _VALID_SCALE_LOCATIONS = ["bottom", "top", "right", "left"] _validate_scale_loc = ValidateInStrings("scale_loc", _VALID_SCALE_LOCATIONS, ignorecase=True) _VALID_LABEL_LOCATIONS = ["bottom", "top", "right", "left"] _validate_label_loc = ValidateInStrings("label_loc", _VALID_LABEL_LOCATIONS, ignorecase=True) _VALID_ROTATIONS = ["horizontal", "vertical"] _validate_rotation = ValidateInStrings("rotation", _VALID_ROTATIONS, ignorecase=True) def _validate_legend_loc(loc): rc = matplotlib.RcParams()
# Local modules. from matplotlib_scalebar.dimension import ( _Dimension, SILengthDimension, SILengthReciprocalDimension, ImperialLengthDimension, PixelLengthDimension, AngleDimension, ) # Globals and constants variables. # Setup of extra parameters in the matplotlic rc validate_scale_loc = ValidateInStrings("scale_loc", ["bottom", "top", "right", "left"], ignorecase=True) validate_label_loc = ValidateInStrings("label_loc", ["bottom", "top", "right", "left"], ignorecase=True) defaultParams.update({ "scalebar.length_fraction": [0.2, validate_float], "scalebar.height_fraction": [0.01, validate_float], "scalebar.location": ["upper right", validate_legend_loc], "scalebar.pad": [0.2, validate_float], "scalebar.border_pad": [0.1, validate_float], "scalebar.sep": [5, validate_float], "scalebar.frameon": [True, validate_bool], "scalebar.color": ["k", validate_color], "scalebar.box_color": ["w", validate_color],
else: value = list(value) for i, v in enumerate(value): if v is None: pass elif isinstance(v, six.string_types): value[i] = six.text_type(v) else: raise ValueError('Expected None or string, found %s' % (v, )) return value validate_ticklabels = try_and_error(validate_none, validate_str, validate_stringlist) validate_extend = ValidateInStrings('extend', ['neither', 'both', 'min', 'max']) class ValidateList(object): """Validate a list of the specified `dtype` """ def __init__(self, dtype=None, length=None, listtype=list): """ Parameters ---------- dtype: object A datatype (e.g. :class:`float`) that shall be used for the conversion length: int The expected length of the list