FunctionNorm.py
Go to the documentation of this file.
1 from __future__ import (absolute_import, division, print_function,
2  unicode_literals)
3 
4 import numpy as np
5 from numpy import ma
6 import matplotlib.cbook as cbook
7 from matplotlib.colors import Normalize
8 
9 def ArcsinhNorm(scale=1.,*args,**kwargs):
10  fn = lambda d: np.arcsinh(d*scale)
11  invfn = lambda d: np.sinh(d)/scale
12  return FunctionNorm(fn,invfn,*args,**kwargs)
13 
14 class FunctionNorm(Normalize):
15  """
16  Normalize a given value to the ``[0, 1]`` interval with a power-law
17  scaling. This will clip any negative data points to 0.
18  """
19  def __init__(self, fn, invfn, vmin=None, vmax=None, clip=False):
20  Normalize.__init__(self, vmin, vmax, clip)
21  self.fn = fn
22  self.invfn = invfn
23 
24  def __call__(self, value, clip=None):
25  if clip is None:
26  clip = self.clip
27 
28  result, is_scalar = self.process_value(value)
29 
30  self.autoscale_None(result)
31  vmin, vmax = self.vmin, self.vmax
32  if vmin > vmax:
33  raise ValueError("minvalue must be less than or equal to maxvalue")
34  elif vmin == vmax:
35  result.fill(0)
36  else:
37  if clip:
38  mask = ma.getmask(result)
39  result = ma.array(np.clip(result.filled(vmax), vmin, vmax),
40  mask=mask)
41  resdat = result.data
42  resdat = self.fn(resdat)
43  resdat -= self._lower
44  resdat /= (self._upper - self._lower)
45 
46  result = np.ma.array(resdat, mask=result.mask, copy=False)
47  if is_scalar:
48  result = result[0]
49  return result
50 
52  """
53  Calculates vmin and vmax in the transformed system.
54  """
55  vmin, vmax = self.vmin, self.vmax
56  arr = np.array([vmax, vmin]).astype(np.float)
57  self._upper, self._lower = self.fn(arr)
58 
59  def inverse(self, value):
60  if not self.scaled():
61  raise ValueError("Not invertible until scaled")
62 
63  vmin, vmax = self.vmin, self.vmax
64  if cbook.iterable(value):
65  val = ma.asarray(value)
66  val = val * (self._upper - self._lower) + self._lower
67  return self.invfn(val)
68  else:
69  value = value * (self._upper - self._lower) + self._lower
70  return self.invfn(value)
71 
72  def autoscale(self, A):
73  """
74  Set *vmin*, *vmax* to min, max of *A*.
75  """
76  self.vmin = ma.min(A)
77  self.vmax = ma.max(A)
79 
80  def autoscale_None(self, A):
81  ' autoscale only None-valued vmin or vmax'
82  if self.vmin is None and np.size(A) > 0:
83  self.vmin = ma.min(A)
84 
85  if self.vmax is None and np.size(A) > 0:
86  self.vmax = ma.max(A)
88 
def __call__(self, value, clip=None)
Definition: FunctionNorm.py:24
def __init__(self, fn, invfn, vmin=None, vmax=None, clip=False)
Definition: FunctionNorm.py:19
def ArcsinhNorm(scale=1., args, kwargs)
Definition: FunctionNorm.py:9
def autoscale_None(self, A)
Definition: FunctionNorm.py:80
def inverse(self, value)
Definition: FunctionNorm.py:59