Revision: 7311
          http://matplotlib.svn.sourceforge.net/matplotlib/?rev=7311&view=rev
Author:   efiring
Date:     2009-07-31 02:48:18 +0000 (Fri, 31 Jul 2009)

Log Message:
-----------
Cache the color data to reduce startup time.
Also, cmap kwargs now accept colormap names as strings.

Modified Paths:
--------------
    trunk/matplotlib/CHANGELOG
    trunk/matplotlib/lib/matplotlib/_cm.py
    trunk/matplotlib/lib/matplotlib/axes.py
    trunk/matplotlib/lib/matplotlib/cm.py

Modified: trunk/matplotlib/CHANGELOG
===================================================================
--- trunk/matplotlib/CHANGELOG  2009-07-30 21:50:10 UTC (rev 7310)
+++ trunk/matplotlib/CHANGELOG  2009-07-31 02:48:18 UTC (rev 7311)
@@ -1,6 +1,7 @@
 2009-07-30 Add set_cmap and register_cmap, and improve get_cmap,
            to provide convenient handling of user-generated
-           colormaps. - EF
+           colormaps. Reorganized _cm and cm modules, and added
+           caching of the color data to reduce startup time. - EF
 
 2009-07-28 Quiver speed improved, thanks to tip by Ray Speth. -EF
 

Modified: trunk/matplotlib/lib/matplotlib/_cm.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/_cm.py      2009-07-30 21:50:10 UTC (rev 
7310)
+++ trunk/matplotlib/lib/matplotlib/_cm.py      2009-07-31 02:48:18 UTC (rev 
7311)
@@ -1,25 +1,15 @@
 """
-Color data and pre-defined cmap objects.
+Nothing here but dictionaries for generating LinearSegmentedColormaps,
+and a dictionary of these dictionaries.
 
-This is a helper for cm.py, originally part of that file.
-Separating the data (this file) from cm.py makes both easier
-to deal with.
-
-Objects visible in cm.py are the individual cmap objects ('autumn',
-etc.) and a dictionary, 'datad', including all of these objects.
 """
 
-import matplotlib as mpl
-import matplotlib.colors as colors
-LUTSIZE = mpl.rcParams['image.lut']
-
 _binary_data = {
     'red'  :  ((0., 1., 1.), (1., 0., 0.)),
     'green':  ((0., 1., 1.), (1., 0., 0.)),
     'blue' :  ((0., 1., 1.), (1., 0., 0.))
     }
 
-
 _bone_data = {'red':   ((0., 0., 0.),(1.0, 1.0, 1.0)),
               'green': ((0., 0., 0.),(1.0, 1.0, 1.0)),
               'blue':  ((0., 0., 0.),(1.0, 1.0, 1.0))}
@@ -379,44 +369,6 @@
                            (1.0, 0.80, 0.80)]}
 
 
-autumn = colors.LinearSegmentedColormap('autumn', _autumn_data, LUTSIZE)
-bone   = colors.LinearSegmentedColormap('bone  ', _bone_data, LUTSIZE)
-binary   = colors.LinearSegmentedColormap('binary  ', _binary_data, LUTSIZE)
-cool   = colors.LinearSegmentedColormap('cool',   _cool_data, LUTSIZE)
-copper = colors.LinearSegmentedColormap('copper', _copper_data, LUTSIZE)
-flag   = colors.LinearSegmentedColormap('flag',   _flag_data, LUTSIZE)
-gray   = colors.LinearSegmentedColormap('gray',   _gray_data, LUTSIZE)
-hot    = colors.LinearSegmentedColormap('hot',    _hot_data, LUTSIZE)
-hsv    = colors.LinearSegmentedColormap('hsv',    _hsv_data, LUTSIZE)
-jet    = colors.LinearSegmentedColormap('jet',    _jet_data, LUTSIZE)
-pink   = colors.LinearSegmentedColormap('pink',   _pink_data, LUTSIZE)
-prism  = colors.LinearSegmentedColormap('prism',  _prism_data, LUTSIZE)
-spring = colors.LinearSegmentedColormap('spring', _spring_data, LUTSIZE)
-summer = colors.LinearSegmentedColormap('summer', _summer_data, LUTSIZE)
-winter = colors.LinearSegmentedColormap('winter', _winter_data, LUTSIZE)
-spectral = colors.LinearSegmentedColormap('spectral', _spectral_data, LUTSIZE)
-
-
-
-datad = {
-    'autumn': _autumn_data,
-    'bone':   _bone_data,
-    'binary':   _binary_data,
-    'cool':   _cool_data,
-    'copper': _copper_data,
-    'flag':   _flag_data,
-    'gray' :  _gray_data,
-    'hot':    _hot_data,
-    'hsv':    _hsv_data,
-    'jet' :   _jet_data,
-    'pink':   _pink_data,
-    'prism':  _prism_data,
-    'spring': _spring_data,
-    'summer': _summer_data,
-    'winter': _winter_data,
-    'spectral': _spectral_data
-    }
-
 # 34 colormaps based on color specifications and designs
 # developed by Cynthia Brewer (http://colorbrewer.org).
 # The ColorBrewer palettes have been included under the terms
@@ -5859,48 +5811,26 @@
 0.0078431377187371254, 0.0078431377187371254), (1.0,
 0.0039215688593685627, 0.0039215688593685627)]}
 
-Accent = colors.LinearSegmentedColormap('Accent', _Accent_data, LUTSIZE)
-Blues = colors.LinearSegmentedColormap('Blues', _Blues_data, LUTSIZE)
-BrBG = colors.LinearSegmentedColormap('BrBG', _BrBG_data, LUTSIZE)
-BuGn = colors.LinearSegmentedColormap('BuGn', _BuGn_data, LUTSIZE)
-BuPu = colors.LinearSegmentedColormap('BuPu', _BuPu_data, LUTSIZE)
-Dark2 = colors.LinearSegmentedColormap('Dark2', _Dark2_data, LUTSIZE)
-GnBu = colors.LinearSegmentedColormap('GnBu', _GnBu_data, LUTSIZE)
-Greens = colors.LinearSegmentedColormap('Greens', _Greens_data, LUTSIZE)
-Greys = colors.LinearSegmentedColormap('Greys', _Greys_data, LUTSIZE)
-Oranges = colors.LinearSegmentedColormap('Oranges', _Oranges_data, LUTSIZE)
-OrRd = colors.LinearSegmentedColormap('OrRd', _OrRd_data, LUTSIZE)
-Paired = colors.LinearSegmentedColormap('Paired', _Paired_data, LUTSIZE)
-Pastel1 = colors.LinearSegmentedColormap('Pastel1', _Pastel1_data, LUTSIZE)
-Pastel2 = colors.LinearSegmentedColormap('Pastel2', _Pastel2_data, LUTSIZE)
-PiYG = colors.LinearSegmentedColormap('PiYG', _PiYG_data, LUTSIZE)
-PRGn = colors.LinearSegmentedColormap('PRGn', _PRGn_data, LUTSIZE)
-PuBu = colors.LinearSegmentedColormap('PuBu', _PuBu_data, LUTSIZE)
-PuBuGn = colors.LinearSegmentedColormap('PuBuGn', _PuBuGn_data, LUTSIZE)
-PuOr = colors.LinearSegmentedColormap('PuOr', _PuOr_data, LUTSIZE)
-PuRd = colors.LinearSegmentedColormap('PuRd', _PuRd_data, LUTSIZE)
-Purples = colors.LinearSegmentedColormap('Purples', _Purples_data, LUTSIZE)
-RdBu = colors.LinearSegmentedColormap('RdBu', _RdBu_data, LUTSIZE)
-RdGy = colors.LinearSegmentedColormap('RdGy', _RdGy_data, LUTSIZE)
-RdPu = colors.LinearSegmentedColormap('RdPu', _RdPu_data, LUTSIZE)
-RdYlBu = colors.LinearSegmentedColormap('RdYlBu', _RdYlBu_data, LUTSIZE)
-RdYlGn = colors.LinearSegmentedColormap('RdYlGn', _RdYlGn_data, LUTSIZE)
-Reds = colors.LinearSegmentedColormap('Reds', _Reds_data, LUTSIZE)
-Set1 = colors.LinearSegmentedColormap('Set1', _Set1_data, LUTSIZE)
-Set2 = colors.LinearSegmentedColormap('Set2', _Set2_data, LUTSIZE)
-Set3 = colors.LinearSegmentedColormap('Set3', _Set3_data, LUTSIZE)
-Spectral = colors.LinearSegmentedColormap('Spectral', _Spectral_data, LUTSIZE)
-YlGn = colors.LinearSegmentedColormap('YlGn', _YlGn_data, LUTSIZE)
-YlGnBu = colors.LinearSegmentedColormap('YlGnBu', _YlGnBu_data, LUTSIZE)
-YlOrBr = colors.LinearSegmentedColormap('YlOrBr', _YlOrBr_data, LUTSIZE)
-YlOrRd = colors.LinearSegmentedColormap('YlOrRd', _YlOrRd_data, LUTSIZE)
-gist_earth = colors.LinearSegmentedColormap('gist_earth', _gist_earth_data, 
LUTSIZE)
-gist_gray = colors.LinearSegmentedColormap('gist_gray', _gist_gray_data, 
LUTSIZE)
-gist_heat = colors.LinearSegmentedColormap('gist_heat', _gist_heat_data, 
LUTSIZE)
-gist_ncar = colors.LinearSegmentedColormap('gist_ncar', _gist_ncar_data, 
LUTSIZE)
-gist_rainbow = colors.LinearSegmentedColormap('gist_rainbow', 
_gist_rainbow_data, LUTSIZE)
-gist_stern = colors.LinearSegmentedColormap('gist_stern', _gist_stern_data, 
LUTSIZE)
-gist_yarg = colors.LinearSegmentedColormap('gist_yarg', _gist_yarg_data, 
LUTSIZE)
+datad = {
+    'autumn': _autumn_data,
+    'bone':   _bone_data,
+    'binary':   _binary_data,
+    'cool':   _cool_data,
+    'copper': _copper_data,
+    'flag':   _flag_data,
+    'gray' :  _gray_data,
+    'hot':    _hot_data,
+    'hsv':    _hsv_data,
+    'jet' :   _jet_data,
+    'pink':   _pink_data,
+    'prism':  _prism_data,
+    'spring': _spring_data,
+    'summer': _summer_data,
+    'winter': _winter_data,
+    'spectral': _spectral_data
+    }
+
+
 datad['Accent']=_Accent_data
 datad['Blues']=_Blues_data
 datad['BrBG']=_BrBG_data
@@ -5944,19 +5874,7 @@
 datad['gist_stern']=_gist_stern_data
 datad['gist_yarg']=_gist_yarg_data
 
-# reverse all the colormaps.
-# reversed colormaps have '_r' appended to the name.
 
-def revcmap(data):
-    data_r = {}
-    for key, val in data.iteritems():
-        valnew = [(1.-a, b, c) for a, b, c in reversed(val)]
-        data_r[key] = valnew
-    return data_r
 
-cmapnames = datad.keys()
-for cmapname in cmapnames:
-    cmapname_r = cmapname+'_r'
-    cmapdat_r = revcmap(datad[cmapname])
-    datad[cmapname_r] = cmapdat_r
-    locals()[cmapname_r] = colors.LinearSegmentedColormap(cmapname_r, 
cmapdat_r, LUTSIZE)
+
+

Modified: trunk/matplotlib/lib/matplotlib/axes.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/axes.py     2009-07-30 21:50:10 UTC (rev 
7310)
+++ trunk/matplotlib/lib/matplotlib/axes.py     2009-07-31 02:48:18 UTC (rev 
7311)
@@ -3911,12 +3911,12 @@
         *bbox_to_anchor* keyword argument. bbox_to_anchor can be an instance
         of BboxBase(or its derivatives) or a tuple of 2 or 4 floats.
         For example,
-        
+
           loc = 'upper right', bbox_to_anchor = (0.5, 0.5)
 
         will place the legend so that the upper right corner of the legend at
         the center of the axes.
-        
+
         The legend location can be specified in other coordinate, by using the
         *bbox_transform* keyword.
 
@@ -3946,7 +3946,7 @@
 
           *fancybox*: [ None | False | True ]
             if True, draw a frame with a round fancybox.  If None, use rc
-            
+
           *shadow*: [ None | False | True ]
             If *True*, draw a shadow behind legend. If *None*, use rc settings.
 
@@ -5172,9 +5172,9 @@
         arguments will be used only if *c* is an array of floats.
 
           *cmap*: [ None | Colormap ]
-            A :class:`matplotlib.colors.Colormap` instance. If *None*,
-            defaults to rc ``image.cmap``. *cmap* is only used if *c*
-            is an array of floats.
+            A :class:`matplotlib.colors.Colormap` instance or registered
+            name. If *None*, defaults to rc ``image.cmap``. *cmap* is
+            only used if *c* is an array of floats.
 
           *norm*: [ None | Normalize ]
             A :class:`matplotlib.colors.Normalize` instance is used to
@@ -5370,7 +5370,6 @@
 
         if colors is None:
             if norm is not None: assert(isinstance(norm, mcolors.Normalize))
-            if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
             collection.set_array(np.asarray(c))
             collection.set_cmap(cmap)
             collection.set_norm(norm)
@@ -5712,7 +5711,6 @@
             accum = bins.searchsorted(accum)
 
         if norm is not None: assert(isinstance(norm, mcolors.Normalize))
-        if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
         collection.set_array(accum)
         collection.set_cmap(cmap)
         collection.set_norm(norm)
@@ -6245,7 +6243,6 @@
         if not self._hold: self.cla()
 
         if norm is not None: assert(isinstance(norm, mcolors.Normalize))
-        if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
         if aspect is None: aspect = rcParams['image.aspect']
         self.set_aspect(aspect)
         im = mimage.AxesImage(self, cmap, norm, interpolation, origin, extent,
@@ -6490,7 +6487,6 @@
         collection.set_alpha(alpha)
         collection.set_array(C)
         if norm is not None: assert(isinstance(norm, mcolors.Normalize))
-        if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
         collection.set_cmap(cmap)
         collection.set_norm(norm)
         if vmin is not None or vmax is not None:
@@ -6612,7 +6608,6 @@
         collection.set_alpha(alpha)
         collection.set_array(C)
         if norm is not None: assert(isinstance(norm, mcolors.Normalize))
-        if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
         collection.set_cmap(cmap)
         collection.set_norm(norm)
         if vmin is not None or vmax is not None:
@@ -6719,7 +6714,6 @@
         vmin = kwargs.pop('vmin', None)
         vmax = kwargs.pop('vmax', None)
         if norm is not None: assert(isinstance(norm, mcolors.Normalize))
-        if cmap is not None: assert(isinstance(cmap, mcolors.Colormap))
 
         C = args[-1]
         nr, nc = C.shape

Modified: trunk/matplotlib/lib/matplotlib/cm.py
===================================================================
--- trunk/matplotlib/lib/matplotlib/cm.py       2009-07-30 21:50:10 UTC (rev 
7310)
+++ trunk/matplotlib/lib/matplotlib/cm.py       2009-07-31 02:48:18 UTC (rev 
7311)
@@ -1,25 +1,68 @@
 """
 This module contains the instantiations of color mapping classes
 """
+import os
 
+try:
+    import cPickle as pickle
+except ImportError:
+    import pickle
+
 import numpy as np
 from numpy import ma
 import matplotlib as mpl
 import matplotlib.colors as colors
 import matplotlib.cbook as cbook
-from matplotlib._cm import *
 
-# Dictionary for user-registered colormaps:
+LUTSIZE = mpl.rcParams['image.lut']
+
+_cmcache = os.path.join(mpl.get_configdir(), 'colormaps.cache')
+
+loaded = False
+try:
+    c = open(_cmcache)
+    datad = pickle.load(c)
+    c.close()
+    mpl.verbose.report("Using colormaps from %s" % _cmcache)
+    loaded = True
+except:
+    mpl.verbose.report("Could not load colormaps from %s" % _cmcache)
+
+if not loaded:
+    from matplotlib._cm import datad
+
+    try:
+        c = open(_cmcache, 'w')
+        pickle.dump(datad, c, 2)
+        c.close()
+        mpl.verbose.report("New colormap cache in %s" % _cmcache)
+    except:
+        mpl.verbose.report("Failed to generate colormap cache")
+
 cmap_d = dict()
 
-# Using this second dictionary allows us to handle any
-# Colormap instance; the built-in datad is only for
-# LinearSegmentedColormaps.  The advantage of keeping
-# datad is that it delays the generation of the Colormap
-# instance until it is actually needed. Generating the
-# instance is fast enough, and typically done few enough
-# times, that there is no need to cache the result.
+# reverse all the colormaps.
+# reversed colormaps have '_r' appended to the name.
 
+def revcmap(data):
+    data_r = {}
+    for key, val in data.iteritems():
+        valnew = [(1.0-a, b, c) for a, b, c in reversed(val)]
+        data_r[key] = valnew
+    return data_r
+
+_cmapnames = datad.keys()  # need this list because datad is changed in loop
+for cmapname in _cmapnames:
+    cmapname_r = cmapname+'_r'
+    cmapdat_r = revcmap(datad[cmapname])
+    datad[cmapname_r] = cmapdat_r
+    cmap_d[cmapname] = colors.LinearSegmentedColormap(
+                            cmapname, datad[cmapname], LUTSIZE)
+    cmap_d[cmapname_r] = colors.LinearSegmentedColormap(
+                            cmapname_r, cmapdat_r, LUTSIZE)
+
+locals().update(cmap_d)
+
 def register_cmap(name=None, cmap=None, data=None, lut=None):
     """
     Add a colormap to the set recognized by :func:`get_cmap`.
@@ -67,6 +110,11 @@
 
     If *name* is a :class:`colors.Colormap` instance, it will be
     returned.
+
+    If *lut* is not None it must be an integer giving the number of
+    entries desired in the lookup table, and *name* must be a
+    standard mpl colormap name with a corresponding data dictionary
+    in *datad*.
     """
     if name is None:
         name = mpl.rcParams['image.cmap']
@@ -75,15 +123,13 @@
         return name
 
     if name in cmap_d:
-        return cmap_d[name]
+        if lut is None:
+            return cmap_d[name]
+        elif name in datad:
+            return colors.LinearSegmentedColormap(name,  datad[name], lut)
+        else:
+            raise ValueError("Colormap %s is not recognized" % name)
 
-    if name not in datad:
-        raise ValueError("%s is not a known colormap name" % name)
-
-    if lut is None:
-        lut = mpl.rcParams['image.lut']
-    return colors.LinearSegmentedColormap(name,  datad[name], lut)
-
 class ScalarMappable:
     """
     This is a mixin class to support scalar -> RGBA mapping.  Handles
@@ -105,7 +151,7 @@
 
         self._A = None
         self.norm = norm
-        self.cmap = cmap
+        self.cmap = get_cmap(cmap)
         self.colorbar = None
         self.update_dict = {'array':False}
 


This was sent by the SourceForge.net collaborative development platform, the 
world's largest Open Source development site.

------------------------------------------------------------------------------
Let Crystal Reports handle the reporting - Free Crystal Reports 2008 30-Day 
trial. Simplify your report design, integration and deployment - and focus on 
what you do best, core application coding. Discover what's new with 
Crystal Reports now.  http://p.sf.net/sfu/bobj-july
_______________________________________________
Matplotlib-checkins mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/matplotlib-checkins

Reply via email to