root/ipython/branches/saw/sandbox/tconfig/mplconfig.py

Revision 2550, 16.8 kB (checked in by fperez, 3 years ago)

Small comment/formatting cleanups

Line 
1 """Traits-based declaration for Matplotlib configuration.
2 """
3
4 # Stdlib imports
5 import os, pytz, tempfile
6
7 # External imports
8 import enthought.traits.api as T
9
10 # Matplotlib-specific imports
11 from matplotlib import colors as mcolors
12 from matplotlib import cbook
13
14 is_string_like = cbook.is_string_like
15
16 # import/reload base modules for interactive testing/development
17 import tconfig; reload(tconfig)
18 from tconfig import TConfig
19
20 # Code begins
21
22 ##############################################################################
23 # Handlers and other support functions and data structures
24 ##############################################################################
25
26 def _is_writable_dir(p):
27     """
28     p is a string pointing to a putative writable dir -- return True p
29     is such a string, else False
30     """
31     try: p + ''  # test is string like
32     except TypeError: return False
33     try:
34         t = tempfile.TemporaryFile(dir=p)
35         t.write('1')
36         t.close()
37     except OSError: return False
38     else: return True
39
40 class IsWritableDir(T.TraitHandler):
41     """
42     """
43
44     def validate(self, object, name, value):
45         if _is_writable_dir(value):
46             return value
47         else:
48             raise OSError('%s is not a writable directory'%value)
49
50     def info(self):
51         return "a writable directory"
52
53 def get_home():
54     """Find user's home directory if possible.
55     Otherwise raise error.
56
57     :see:  http://mail.python.org/pipermail/python-list/2005-February/263921.html
58     """
59     path=''
60     try:
61         path=os.path.expanduser("~")
62     except:
63         pass
64     if not os.path.isdir(path):
65         for evar in ('HOME', 'USERPROFILE', 'TMP'):
66             try:
67                 path = os.environ[evar]
68                 if os.path.isdir(path):
69                     break
70             except: pass
71     if path:
72         return path
73     else:
74         raise RuntimeError('please define environment variable $HOME')
75
76 def get_configdir():
77     """
78     Return the string representing the configuration dir.
79
80     default is HOME/.matplotlib.  you can override this with the
81     MPLCONFIGDIR environment variable
82     """
83
84     configdir = os.environ.get('MPLCONFIGDIR')
85     if configdir is not None:
86         if not _is_writable_dir(configdir):
87             raise RuntimeError('Could not write to MPLCONFIGDIR="%s"'%configdir)
88         return configdir
89
90     h = get_home()
91     p = os.path.join(get_home(), '.matplotlib')
92
93     if os.path.exists(p):
94         if not _is_writable_dir(p):
95             raise RuntimeError("'%s' is not a writable dir; you must set %s/.matplotlib to be a writable dir.  You can also set environment variable MPLCONFIGDIR to any writable directory where you want matplotlib data stored "%h)
96     else:
97         if not _is_writable_dir(h):
98             raise RuntimeError("Failed to create %s/.matplotlib; consider setting MPLCONFIGDIR to a writable directory for matplotlib configuration data"%h)
99
100         os.mkdir(p)
101
102     return p
103
104 backends = {'tkagg': 'TkAgg',
105             'gtkagg': 'GTKAgg',
106             'gtkcairo': 'GTKCairo',
107             'qt4agg': 'Qt4Agg',
108             'qtagg': 'QtAgg',
109             'wxagg': 'WxAgg',
110             'agg': 'Agg',
111             'cairo': 'Cairo',
112             'ps': 'PS',
113             'pdf': 'PDF',
114             'svg': 'SVG',
115             'template': 'Templates' }
116
117 class BackendHandler(T.TraitHandler):
118     """
119     """
120
121     def validate(self, object, name, value):
122         try:
123             return backends[value.lower()]
124         except:
125             return self.error(object, name, value)
126
127     def info(self):
128         be = backends.keys()
129         be.sort
130         return "one of %s"% ', '.join('%s'%i for i in be)
131
132 class BoolHandler(T.TraitHandler):
133     """
134     """
135
136     bools = {'true': True,
137              'yes': True,
138              'y' : True,
139              'on': True,
140              1: True,
141              True: True,
142              'false': False,
143              'no': False,
144              'n': False,
145              'off': False,
146              0: False,
147              False: False}
148        
149     def validate(self, object, name, value):
150         try:
151             return self.bools[value]
152         except:
153             return self.error(object, name, value)
154
155     def info(self):
156         return "one of %s"% ', '.join('%s'%i for i in self.bools.keys())
157
158 class ColorHandler(T.TraitHandler):
159     """
160     This is a clever little traits mechanism -- users can specify the
161     color as any mpl color, and the traited object will keep the
162     original color, but will add a new attribute with a '_' postfix
163     which is the color rgba tuple.
164
165     Eg
166
167     class C(HasTraits):
168         fillcolor = traits.Trait('black', ColorHandler())
169
170     c = C()
171     c.fillcolor = 'red'
172     print c.fillcolor    # prints red
173     print c.fillcolor_   # print (1,0,0,1)
174     """
175     is_mapped = True
176
177     def post_setattr(self, object, name, value):
178         object.__dict__[ name + '_' ] = self.mapped_value( value )
179
180     def mapped_value(self, value ):
181         if value is None: return None
182         if is_string_like(value): value = value.lower()
183         return mcolors.colorConverter.to_rgba(value)
184        
185     def validate(self, object, name, value):
186         try:
187             self.mapped_value(value)
188         except ValueError:
189             return self.error(object, name, value)
190         else:           
191             return value
192
193     def info(self):
194         return """\
195 any valid matplotlib color, eg an abbreviation like 'r' for red, a full
196 name like 'orange', a hex color like '#efefef', a grayscale intensity
197 like '0.5', or an RGBA tuple (1,0,0,1)"""
198
199
200 colormaps = ['Accent', 'Accent_r', 'Blues', 'Blues_r', 'BrBG', 'BrBG_r', 'BuGn',
201              'BuGn_r', 'BuPu', 'BuPu_r', 'Dark2', 'Dark2_r', 'GnBu', 'GnBu_r',
202              'Greens', 'Greens_r', 'Greys', 'Greys_r', 'LUTSIZE', 'OrRd',
203              'OrRd_r', 'Oranges', 'Oranges_r', 'PRGn', 'PRGn_r', 'Paired',
204              'Paired_r', 'Pastel1', 'Pastel1_r', 'Pastel2', 'Pastel2_r', 'PiYG',
205              'PiYG_r', 'PuBu', 'PuBuGn', 'PuBuGn_r', 'PuBu_r', 'PuOr', 'PuOr_r',
206              'PuRd', 'PuRd_r', 'Purples', 'Purples_r', 'RdBu', 'RdBu_r', 'RdGy',
207              'RdGy_r', 'RdPu', 'RdPu_r', 'RdYlBu', 'RdYlBu_r', 'RdYlGn',
208              'RdYlGn_r', 'Reds', 'Reds_r', 'Set1', 'Set1_r', 'Set2', 'Set2_r',
209              'Set3', 'Set3_r', 'Spectral', 'Spectral_r', 'YlGn', 'YlGnBu',
210              'YlGnBu_r', 'YlGn_r', 'YlOrBr', 'YlOrBr_r', 'YlOrRd', 'YlOrRd_r',
211              'autumn', 'autumn_r', 'binary', 'binary_r', 'bone', 'bone_r',
212              'cbook', 'cmapdat_r', 'cmapname', 'cmapname_r', 'cmapnames',
213              'colors', 'cool', 'cool_r', 'copper', 'copper_r', 'datad', 'flag',
214              'flag_r', 'gist_earth', 'gist_earth_r', 'gist_gray', 'gist_gray_r',
215              'gist_heat', 'gist_heat_r', 'gist_ncar', 'gist_ncar_r',
216              'gist_rainbow', 'gist_rainbow_r', 'gist_stern', 'gist_stern_r',
217              'gist_yarg', 'gist_yarg_r', 'gray', 'gray_r', 'hot', 'hot_r',
218              'hsv', 'hsv_r', 'jet', 'jet_r', 'ma', 'mpl', 'pink', 'pink_r',
219              'prism', 'prism_r', 'revcmap', 'spectral', 'spectral_r', 'spring',
220              'spring_r', 'summer', 'summer_r', 'winter', 'winter_r']
221
222 ##############################################################################
223 # Main Config class follows
224 ##############################################################################
225 class MPLConfig(TConfig):
226     """
227     This is a sample matplotlib configuration file.  It should be placed
228     in HOME/.matplotlib/matplotlibrc (unix/linux like systems) and
229     C:\Documents and Settings\yourname\.matplotlib (win32 systems)
230
231     By default, the installer will overwrite the existing file in the install
232     path, so if you want to preserve yours, please move it to your HOME dir and
233     set the environment variable if necessary.
234
235     This file is best viewed in a editor which supports ini or conf mode syntax
236     highlighting.
237
238     Blank lines, or lines starting with a comment symbol, are ignored,
239     as are trailing comments.  Other lines must have the format
240
241       key = val   optional comment
242
243     val should be valid python syntax, just as you would use when setting
244     properties using rcParams. This should become more obvious by inspecting
245     the default values listed herein.
246
247     Colors: for the color values below, you can either use
248      - a matplotlib color string, such as r, k, or b
249      - an rgb tuple, such as (1.0, 0.5, 0.0)
250      - a hex string, such as #ff00ff or ff00ff
251      - a scalar grayscale intensity such as 0.75
252      - a legal html color name, eg red, blue, darkslategray
253
254     Interactivity: see http://matplotlib.sourceforge.net/interactive.html.
255     
256     ### CONFIGURATION BEGINS HERE ###
257     """
258
259     interactive = T.Trait(False, BoolHandler())
260     toolbar = T.Trait('toolbar2', None)
261     timezone = T.Trait('UTC', pytz.all_timezones)
262     datapath = T.Trait(get_configdir(), IsWritableDir())
263     numerix = T.Trait('numpy', 'numeric', 'numarray')
264     maskedarray = T.false
265    
266     class backend(TConfig):
267         """Valid backends are: 'GTKAgg', 'GTKCairo', 'QtAgg', 'Qt4Agg',
268         'TkAgg', 'Agg', 'Cairo', 'PS', 'PDF', 'SVG'"""
269         use = T.Trait('TkAgg', BackendHandler())
270        
271         class cairo(TConfig):
272             format = T.Trait('png', 'png', 'ps', 'pdf', 'svg')
273        
274         class tk(TConfig):
275             """
276             window_focus : Maintain shell focus for TkAgg
277             pythoninspect: tk sets PYTHONINSPECT
278             """
279
280             window_focus = T.false
281             pythoninspect = T.false
282        
283         class ps(TConfig):
284             papersize = T.Trait('auto', 'letter', 'legal', 'ledger',
285                                 'A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7',
286                                 'A8', 'A9', 'A10',
287                                 'B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7',
288                                 'B8', 'B9', 'B10')
289             useafm = T.false
290             fonttype = T.Trait(3, 42)
291            
292             class distiller(TConfig):
293                 use = T.Trait(None, 'ghostscript', 'xpdf')
294                 resolution = T.Float(6000)
295        
296         class pdf(TConfig):
297             compression = T.Range(0, 9, 6)
298             fonttype = T.Trait(3, 42)
299        
300         class svg(TConfig):
301             image_inline = T.true
302             image_noscale = T.false
303             embed_chars = T.false
304    
305     class lines(TConfig):
306         linewidth = T.Float(1.0)
307         linestyle = T.Trait('-','--','-.', ':', 'steps', '', ' ', None)
308         color = T.Trait('blue',ColorHandler())
309         solid_joinstyle = T.Trait('miter', 'round', 'bevel')
310         solid_capstyle = T.Trait('butt', 'round', 'projecting')
311         dash_joinstyle = T.Trait('miter', 'round', 'bevel')
312         dash_capstyle = T.Trait('butt', 'round', 'projecting')
313         marker = T.Trait(None, 'o', '.', ',', '^', 'v', '<', '>', 's', '+', 'x',
314                          'D','d', '1', '2', '3', '4', 'h', 'H', 'p', '|', '_')
315         markeredgewidth = T.Float(0.5)
316         markersize = T.Float(6)
317         antialiased = T.true
318
319     class patch(TConfig):
320         linewidth = T.Float(1.0)
321         facecolor = T.Trait('blue',ColorHandler())
322         edgecolor = T.Trait('black',ColorHandler())
323         antialiased = T.true
324
325     class font(TConfig):
326         family = T.Trait('sans-serif', 'serif', 'cursive', 'fantasy',
327                          'monospace')
328         style = T.Trait('normal', 'italic', 'oblique')
329         variant = T.Trait('normal', 'small-caps')
330         weight = T.Trait('normal', 'bold', 'bolder', 'lighter',
331                           100, 200, 300, 400, 500, 600, 700, 800, 900)
332         stretch = T.Trait('ultra-condensed', 'extra-condensed', 'condensed',
333                          'semi-condensed', 'normal', 'semi-expanded',
334                          'expanded', 'extra-expanded', 'ultra-expanded',
335                          'wider', 'narrower')
336         size = T.Float(12.0)
337         serif = T.ListStr(["Bitstream Vera Serif", "New Century Schoolbook",
338                  "Century Schoolbook L", "Utopia", "ITC Bookman", "Bookman",
339                  "Nimbus Roman No9 L", "Times New Roman", "Times", "Palatino",
340                  "Charter", "serif"])
341         sans_serif = T.ListStr(["Bitstream Vera Sans", "Lucida Grande", "Verdana",
342                       "Geneva", "Lucid", "Arial", "Helvetica", "Avant Garde",
343                       "sans-serif"])
344         cursive = T.ListStr(["Apple Chancery", "Textile", "Zapf Chancery", "Sand",
345                    "cursive"])
346         fantasy = T.ListStr(["Comic Sans MS", "Chicago", "Charcoal", "Impact", "Western",
347                    "fantasy"])
348         monospace = T.ListStr(["Bitstream Vera Sans Mono", "Andale Mono", "Nimbus Mono L",
349                      "Courier New", "Courier", "Fixed", "Terminal", "monospace"])
350
351     class text(TConfig):
352         color = T.Trait('black',ColorHandler())
353         usetex = T.false
354        
355         class latex(TConfig):
356             unicode = T.false
357             preamble = T.ListStr([])
358             dvipnghack = T.false
359
360     class axes(TConfig):
361         hold = T.Trait(True, BoolHandler())
362         facecolor = T.Trait('white',ColorHandler())
363         edgecolor = T.Trait('black',ColorHandler())
364         linewidth = T.Float(1.0)
365         grid = T.Trait(True, BoolHandler())
366         polargrid = T.Trait(True, BoolHandler())
367         titlesize = T.Trait('large', 'xx-small', 'x-small', 'small', 'medium',
368                             'large', 'x-large', 'xx-large', T.Float)
369         labelsize = T.Trait('medium', 'xx-small', 'x-small', 'small', 'medium',
370                             'large', 'x-large', 'xx-large', T.Float)
371         labelcolor = T.Trait('black',ColorHandler())
372         axisbelow = T.false
373        
374         class formatter(TConfig):
375             limits = T.List(T.Float, [-7, 7], minlen=2, maxlen=2)
376    
377     class xticks(TConfig):
378         color = T.Trait('black',ColorHandler())
379         labelsize = T.Trait('small', 'xx-small', 'x-small', 'small', 'medium',
380                             'large', 'x-large', 'xx-large', T.Float)
381         direction = T.Trait('in', 'out')
382        
383         class major(TConfig):
384             size = T.Float(4)
385             pad = T.Float(4)
386
387         class minor(TConfig):
388             size = T.Float(2)
389             pad = T.Float(4)
390
391     class yticks(TConfig):
392         color = T.Trait('black',ColorHandler())
393         labelsize = T.Trait('small', 'xx-small', 'x-small', 'small', 'medium',
394                             'large', 'x-large', 'xx-large', T.Float)
395         direction = T.Trait('in', 'out')
396        
397         class major(TConfig):
398             size = T.Float(4)
399             pad = T.Float(4)
400
401         class minor(TConfig):
402             size = T.Float(2)
403             pad = T.Float(4)
404
405     class grid(TConfig):
406         color = T.Trait('black',ColorHandler())
407         linestyle = T.Trait('-','--','-.', ':', 'steps', '', ' ')
408         linewidth = T.Float(0.5)
409
410     class legend(TConfig):
411         isaxes = T.true
412         numpoints = T.Int(3)
413         fontsize = T.Trait('medium', 'xx-small', 'x-small', 'small', 'medium',
414                            'large', 'x-large', 'xx-large', T.Float)
415         pad = T.Float(0.2)
416         markerscale = T.Float(1.0)
417         labelsep = T.Float(0.01)
418         handlelen = T.Float(0.05)
419         handletextsep = T.Float(0.02)
420         axespad = T.Float(0.02)
421         shadow = T.false
422
423     class figure(TConfig):
424         figsize = T.List(T.Float, [8,6], maxlen=2, minlen=2)
425         dpi = T.Float(80)
426         facecolor = T.Trait('0.75',ColorHandler())
427         edgecolor = T.Trait('white',ColorHandler())
428
429         class subplot(TConfig):
430             """The figure subplot parameters.  All dimensions are fraction
431             of the figure width or height"""
432             left = T.Float(0.125)
433             right = T.Float(0.9)
434             bottom = T.Float(0.1)
435             top = T.Float(0.9)
436             wspace = T.Float(0.2)
437             hspace = T.Float(0.2)
438
439     class image(TConfig):
440         aspect = T.Trait('equal', 'auto')
441         interpolation = T.Trait('bilinear', 'nearest', 'bicubic', 'spline16',
442                                 'spline36', 'hanning', 'hamming', 'hermite',
443                                 'kaiser', 'quadric', 'catrom', 'gaussian',
444                                 'bessel', 'mitchell', 'sinc', 'lanczos',
445                                 'blackman')
446         cmap = T.Trait('jet', *colormaps)
447         lut = T.Int(256)
448         origin = T.Trait('upper', 'lower')
449
450     class contour(TConfig):
451         negative_linestyle = T.Trait('dashed', 'solid')
452    
453     class savefig(TConfig):
454         dpi = T.Float(100)
455         facecolor = T.Trait('white',ColorHandler())
456         edgecolor = T.Trait('white',ColorHandler())
457    
458     class verbose(TConfig):
459         level = T.Trait('silent', 'helpful', 'debug', 'debug-annoying')
460         fileo = T.Trait('sys.stdout', T.File)
461
462 ##############################################################################
463 # Simple testing
464 ##############################################################################
465 if __name__ == "__main__":
466     mplrc = MPLConfig()
467     mplrc.backend.pdf.compression = 1.1
468     print mplrc
Note: See TracBrowser for help on using the browser.