-
Notifications
You must be signed in to change notification settings - Fork 95
Expand file tree
/
Copy pathconfig.py
More file actions
1779 lines (1612 loc) · 69.6 KB
/
Copy pathconfig.py
File metadata and controls
1779 lines (1612 loc) · 69.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Tools for setting up proplot and configuring global settings.
See the :ref:`configuration guide <ug_config>` for details.
"""
# NOTE: The matplotlib analogue to this file is actually __init__.py
# but it makes more sense to have all the setup actions in a separate file
# so the namespace of the top-level module is unpolluted.
# NOTE: Why also load colormaps and cycles in this file and not colors.py?
# Because I think it makes sense to have all the code that "runs" (i.e. not
# just definitions) in the same place, and I was having issues with circular
# dependencies and where import order of __init__.py was affecting behavior.
import logging
import os
import re
import sys
from collections import namedtuple
from collections.abc import MutableMapping
from numbers import Real
import cycler
import matplotlib as mpl
import matplotlib.colors as mcolors
import matplotlib.font_manager as mfonts
import matplotlib.mathtext # noqa: F401
import matplotlib.style.core as mstyle
import numpy as np
from matplotlib import RcParams
from .internals import ic # noqa: F401
from .internals import (
_not_none,
_pop_kwargs,
_pop_props,
_translate_grid,
_version_mpl,
docstring,
rcsetup,
warnings,
)
try:
from IPython import get_ipython
except ImportError:
def get_ipython():
return
# Suppress warnings emitted by mathtext.py (_mathtext.py in recent versions)
# when when substituting dummy unavailable glyph due to fallback disabled.
logging.getLogger('matplotlib.mathtext').setLevel(logging.ERROR)
__all__ = [
'Configurator',
'rc',
'rc_proplot',
'rc_matplotlib',
'use_style',
'config_inline_backend',
'register_cmaps',
'register_cycles',
'register_colors',
'register_fonts',
'RcConfigurator', # deprecated
'inline_backend_fmt', # deprecated
]
# Constants
COLORS_KEEP = (
'red',
'green',
'blue',
'cyan',
'yellow',
'magenta',
'white',
'black'
)
# Configurator docstrings
_rc_docstring = """
local : bool, default: True
Whether to load settings from the `~Configurator.local_files` file.
user : bool, default: True
Whether to load settings from the `~Configurator.user_file` file.
default : bool, default: True
Whether to reload built-in default proplot settings.
"""
docstring._snippet_manager['rc.params'] = _rc_docstring
# Registration docstrings
_shared_docstring = """
*args : path-spec or `~proplot.colors.{type}Colormap`, optional
The {objects} to register. These can be file paths containing
RGB data or `~proplot.colors.{type}Colormap` instances. By default,
if positional arguments are passed, then `user` is set to ``False``.
Valid file extensions are listed in the below table. Note that {objects}
are registered according to their filenames -- for example, ``name.xyz``
will be registered as ``'name'``.
""" # noqa: E501
_cmap_exts_docstring = """
=================== ==========================================
Extension Description
=================== ==========================================
``.json`` JSON database of the channel segment data.
``.hex`` Comma-delimited list of HEX strings.
``.rgb``, ``.txt`` 3-4 column table of channel values.
=================== ==========================================
"""
_cycle_exts_docstring = """
================== ==========================================
Extension Description
================== ==========================================
``.hex`` Comma-delimited list of HEX strings.
``.rgb``, ``.txt`` 3-4 column table of channel values.
================== ==========================================
"""
_color_docstring = """
*args : path-like or dict, optional
The colors to register. These can be file paths containing RGB data or
dictionary mappings of names to RGB values. By default, if positional
arguments are passed, then `user` is set to ``False``. Files must have
the extension ``.txt`` and should contain one line per color in the
format ``name : hex``. Whitespace is ignored.
"""
_font_docstring = """
*args : path-like, optional
The font files to add. By default, if positional arguments are passed, then
`user` is set to ``False``. Files must have the extensions ``.ttf`` or ``.otf``.
See `this link \
<https://gree2.github.io/python/2015/04/27/python-change-matplotlib-font-on-mac>`__
for a guide on converting other font files to ``.ttf`` and ``.otf``.
"""
_register_docstring = """
user : bool, optional
Whether to reload {objects} from `~Configurator.user_folder`. Default is
``False`` if positional arguments were passed and ``True`` otherwise.
local : bool, optional
Whether to reload {objects} from `~Configurator.local_folders`. Default is
``False`` if positional arguments were passed and ``True`` otherwise.
default : bool, default: False
Whether to reload the default {objects} packaged with proplot.
Default is always ``False``.
"""
docstring._snippet_manager['rc.cmap_params'] = _register_docstring.format(objects='colormaps') # noqa: E501
docstring._snippet_manager['rc.cycle_params'] = _register_docstring.format(objects='color cycles') # noqa: E501
docstring._snippet_manager['rc.color_params'] = _register_docstring.format(objects='colors') # noqa: E501
docstring._snippet_manager['rc.font_params'] = _register_docstring.format(objects='fonts') # noqa: E501
docstring._snippet_manager['rc.cmap_args'] = _shared_docstring.format(objects='colormaps', type='Continuous') # noqa: E501
docstring._snippet_manager['rc.cycle_args'] = _shared_docstring.format(objects='color cycles', type='Discrete') # noqa: E501
docstring._snippet_manager['rc.color_args'] = _color_docstring
docstring._snippet_manager['rc.font_args'] = _font_docstring
docstring._snippet_manager['rc.cmap_exts'] = _cmap_exts_docstring
docstring._snippet_manager['rc.cycle_exts'] = _cycle_exts_docstring
def _init_user_file():
"""
Initialize .proplotrc file.
"""
file = Configurator.user_file()
if not os.path.exists(file):
Configurator._save_yaml(file, comment=True)
def _init_user_folders():
"""
Initialize .proplot folder.
"""
for subfolder in ('', 'cmaps', 'cycles', 'colors', 'fonts'):
folder = Configurator.user_folder(subfolder)
if not os.path.isdir(folder):
os.mkdir(folder)
def _get_data_folders(folder, user=True, local=True, default=True, reverse=False):
"""
Return data folder paths in reverse order of precedence.
"""
# When loading colormaps, cycles, and colors, files in the latter
# directories overwrite files in the former directories. When loading
# fonts, the resulting paths need to be *reversed*.
paths = []
if default:
paths.append(os.path.join(os.path.dirname(__file__), folder))
if user:
paths.append(Configurator.user_folder(folder))
if local:
paths.extend(Configurator.local_folders(folder))
if reverse:
paths = paths[::-1]
return paths
def _iter_data_objects(folder, *args, **kwargs):
"""
Iterate over input objects and files in the data folders that should be
registered. Also yield an index indicating whether these are user files.
"""
i = 0 # default files
for i, path in enumerate(_get_data_folders(folder, **kwargs)):
for dirname, dirnames, filenames in os.walk(path):
for filename in filenames:
if filename[0] == '.': # UNIX-style hidden files
continue
path = os.path.join(dirname, filename)
yield i, path
i += 1 # user files
for path in args:
path = os.path.expanduser(path)
if os.path.isfile(path):
yield i, path
else:
raise FileNotFoundError(f'Invalid file path {path!r}.')
def _filter_style_dict(rcdict, warn=True):
"""
Filter out blacklisted style parameters.
"""
# NOTE: This implements bugfix: https://github.com/matplotlib/matplotlib/pull/17252
# This fix is *critical* for proplot because we always run style.use()
# when the configurator is made. Without fix backend is reset every time
# you import proplot in jupyter notebooks. So apply retroactively.
rcdict_filtered = {}
for key in rcdict:
if key in mstyle.STYLE_BLACKLIST:
if warn:
warnings._warn_proplot(
f'Dictionary includes a parameter, {key!r}, that is not related '
'to style. Ignoring.'
)
else:
rcdict_filtered[key] = rcdict[key]
return rcdict_filtered
def _get_default_style_dict():
"""
Get the default rc parameters dictionary with deprecated parameters filtered.
"""
# NOTE: Use RcParams update to filter and translate deprecated settings
# before actually applying them to rcParams down pipeline. This way we can
# suppress warnings for deprecated default params but still issue warnings
# when user-supplied stylesheets have deprecated params.
# WARNING: Some deprecated rc params remain in dictionary as None so we
# filter them out. Beware if hidden attribute changes.
# WARNING: The examples.directory deprecation was handled specially inside
# RcParams in early versions. Manually pop it out here.
rcdict = _filter_style_dict(mpl.rcParamsDefault, warn=False)
with warnings.catch_warnings():
warnings.simplefilter('ignore', mpl.MatplotlibDeprecationWarning)
rcdict = dict(RcParams(rcdict))
for attr in ('_deprecated_set', '_deprecated_remain_as_none'):
deprecated = getattr(mpl, attr, ())
for key in deprecated: # _deprecated_set is in matplotlib < 3.4
rcdict.pop(key, None)
rcdict.pop('examples.directory', None) # special case for matplotlib < 3.2
return rcdict
def _get_style_dict(style, filter=True):
"""
Return a dictionary of settings belonging to the requested style(s). If `filter`
is ``True``, invalid style parameters like `backend` are filtered out.
"""
# NOTE: This is adapted from matplotlib source for the following changes:
# 1. Add an 'original' pseudo style. Like rcParamsOrig except we also reload
# from the user matplotlibrc file.
# 2. When the style is changed we reset to the default state ignoring matplotlibrc.
# By contrast matplotlib applies styles on top of current state (including
# matplotlibrc changes and runtime rcParams changes) but the word 'style'
# implies a rigid static format. This makes more sense.
# 3. Add a separate function that returns lists of style dictionaries so that
# we can modify the active style in a context block. Proplot context is more
# conservative than matplotlib's rc_context because it gets called a lot
# (e.g. every time you make an axes and every format() call). Instead of
# copying the entire rcParams dict we just track the keys that were changed.
style_aliases = {
'538': 'fivethirtyeight',
'mpl20': 'default',
'mpl15': 'classic',
'original': mpl.matplotlib_fname(),
}
# Always apply the default style *first* so styles are rigid
kw_matplotlib = _get_default_style_dict()
if style == 'default' or style is mpl.rcParamsDefault:
return kw_matplotlib
# Apply limited deviations from the matplotlib style that we want to propagate to
# other styles. Want users selecting stylesheets to have few surprises, so
# currently just enforce the new aesthetically pleasing fonts.
kw_matplotlib['font.family'] = 'sans-serif'
for fmly in ('serif', 'sans-serif', 'monospace', 'cursive', 'fantasy'):
kw_matplotlib['font.' + fmly] = rcsetup._rc_matplotlib_default['font.' + fmly]
# Apply user input style(s) one by one
if isinstance(style, str) or isinstance(style, dict):
styles = [style]
else:
styles = style
for style in styles:
if isinstance(style, dict):
kw = style
elif isinstance(style, str):
style = style_aliases.get(style, style)
if style in mstyle.library:
kw = mstyle.library[style]
else:
try:
kw = mpl.rc_params_from_file(style, use_default_template=False)
except IOError:
raise IOError(
f'Style {style!r} not found in the style library and input '
'is not a valid URL or file path. Available styles are: '
+ ', '.join(map(repr, mstyle.available))
+ '.'
)
else:
raise ValueError(f'Invalid style {style!r}. Must be string or dictionary.')
if filter:
kw = _filter_style_dict(kw, warn=True)
kw_matplotlib.update(kw)
return kw_matplotlib
def _infer_proplot_dict(kw_params):
"""
Infer values for proplot's "added" parameters from stylesheet parameters.
"""
kw_proplot = {}
mpl_to_proplot = {
'xtick.labelsize': (
'tick.labelsize', 'grid.labelsize',
),
'ytick.labelsize': (
'tick.labelsize', 'grid.labelsize',
),
'axes.titlesize': (
'abc.size', 'suptitle.size', 'title.size',
'leftlabel.size', 'rightlabel.size',
'toplabel.size', 'bottomlabel.size',
),
'text.color': (
'abc.color', 'suptitle.color', 'title.color',
'tick.labelcolor', 'grid.labelcolor',
'leftlabel.color', 'rightlabel.color',
'toplabel.color', 'bottomlabel.color',
),
}
for key, params in mpl_to_proplot.items():
if key in kw_params:
value = kw_params[key]
for param in params:
kw_proplot[param] = value
return kw_proplot
def config_inline_backend(fmt=None):
"""
Set up the ipython `inline backend display format \
<https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-matplotlib>`__
and ensure that inline figures always look the same as saved figures.
This runs the following ipython magic commands:
.. code-block:: ipython
%config InlineBackend.figure_formats = rc['inlineformat']
%config InlineBackend.rc = {} # never override rc settings
%config InlineBackend.close_figures = True # cells start with no active figures
%config InlineBackend.print_figure_kwargs = {'bbox_inches': None}
When the inline backend is inactive or unavailable, this has no effect.
This function is called when you modify the :rcraw:`inlineformat` property.
Parameters
----------
fmt : str or sequence, default: :rc:`inlineformat`
The inline backend file format or a list thereof. Valid formats
include ``'jpg'``, ``'png'``, ``'svg'``, ``'pdf'``, and ``'retina'``.
See also
--------
Configurator
"""
# Note if inline backend is unavailable this will fail silently
ipython = get_ipython()
if ipython is None:
return
fmt = _not_none(fmt, rc_proplot['inlineformat'])
if isinstance(fmt, str):
fmt = [fmt]
elif np.iterable(fmt):
fmt = list(fmt)
else:
raise ValueError(f'Invalid inline backend format {fmt!r}. Must be string.')
ipython.magic('config InlineBackend.figure_formats = ' + repr(fmt))
ipython.magic('config InlineBackend.rc = {}')
ipython.magic('config InlineBackend.close_figures = True')
ipython.magic("config InlineBackend.print_figure_kwargs = {'bbox_inches': None}")
def use_style(style):
"""
Apply the `matplotlib style(s) \
<https://matplotlib.org/stable/tutorials/introductory/customizing.html>`__
with `matplotlib.style.use`. This function is
called when you modify the :rcraw:`style` property.
Parameters
----------
style : str or sequence or dict-like
The matplotlib style name(s) or stylesheet filename(s), or dictionary(s)
of settings. Use ``'default'`` to apply matplotlib default settings and
``'original'`` to include settings from your user ``matplotlibrc`` file.
See also
--------
Configurator
matplotlib.style.use
"""
# NOTE: This function is not really necessary but makes proplot's
# stylesheet-supporting features obvious. Plus changing the style does
# so much *more* than changing rc params or quick settings, so it is
# nice to have dedicated function instead of just another rc_param name.
kw_matplotlib = _get_style_dict(style)
rc_matplotlib.update(kw_matplotlib)
rc_proplot.update(_infer_proplot_dict(kw_matplotlib))
@docstring._snippet_manager
def register_cmaps(*args, user=None, local=None, default=False):
"""
Register named colormaps. This is called on import.
Parameters
----------
%(rc.cmap_args)s
%(rc.cmap_exts)s
%(rc.cmap_params)s
See also
--------
register_cycles
register_colors
register_fonts
proplot.demos.show_cmaps
"""
# Register input colormaps
from . import colors as pcolors
user = _not_none(user, not bool(args)) # skip user folder if input args passed
local = _not_none(local, not bool(args))
paths = []
for arg in args:
if isinstance(arg, mcolors.Colormap):
pcolors._cmap_database[arg.name] = arg
else:
paths.append(arg)
# Register data files
for i, path in _iter_data_objects(
'cmaps', *paths, user=user, local=local, default=default
):
cmap = pcolors.ContinuousColormap.from_file(path, warn_on_failure=True)
if not cmap:
continue
if i == 0 and cmap.name.lower() in pcolors.CMAPS_CYCLIC:
cmap.set_cyclic(True)
pcolors._cmap_database[cmap.name] = cmap
@docstring._snippet_manager
def register_cycles(*args, user=None, local=None, default=False):
"""
Register named color cycles. This is called on import.
Parameters
----------
%(rc.cycle_args)s
%(rc.cycle_exts)s
%(rc.cycle_params)s
See also
--------
register_cmaps
register_colors
register_fonts
proplot.demos.show_cycles
"""
# Register input color cycles
from . import colors as pcolors
user = _not_none(user, not bool(args)) # skip user folder if input args passed
local = _not_none(local, not bool(args))
paths = []
for arg in args:
if isinstance(arg, mcolors.Colormap):
pcolors._cmap_database[arg.name] = arg
else:
paths.append(arg)
# Register data files
for _, path in _iter_data_objects(
'cycles', *paths, user=user, local=local, default=default
):
cmap = pcolors.DiscreteColormap.from_file(path, warn_on_failure=True)
if not cmap:
continue
pcolors._cmap_database[cmap.name] = cmap
@docstring._snippet_manager
def register_colors(
*args, user=None, local=None, default=False, space=None, margin=None, **kwargs
):
"""
Register named colors. This is called on import.
Parameters
----------
%(rc.color_args)s
%(rc.color_params)s
space : {'hcl', 'hsl', 'hpl'}, optional
The colorspace used to pick "perceptually distinct" colors from
the `XKCD color survey <https://xkcd.com/color/rgb/>`__.
If passed then `default` is set to ``True``.
margin : float, default: 0.1
The margin used to pick "perceptually distinct" colors from the
`XKCD color survey <https://xkcd.com/color/rgb/>`__. The normalized hue,
saturation, and luminance of each color must differ from the channel
values of the prededing colors by `margin` in order to be registered.
Must fall between ``0`` and ``1`` (``0`` will register all colors).
If passed then `default` is set to ``True``.
**kwargs
Additional color name specifications passed as keyword arguments rather
than positional argument dictionaries.
See also
--------
register_cmaps
register_cycles
register_fonts
proplot.demos.show_colors
"""
from . import colors as pcolors
default = default or space is not None or margin is not None
margin = _not_none(margin, 0.1)
space = _not_none(space, 'hcl')
# Remove previously registered colors
# NOTE: Try not to touch matplotlib colors for compatibility
srcs = {'xkcd': pcolors.COLORS_XKCD, 'opencolor': pcolors.COLORS_OPEN}
if default: # possibly slow but not these dicts are empty on startup
for src in srcs.values():
for key in src:
if key not in COLORS_KEEP:
pcolors._color_database.pop(key, None) # this also clears cache
src.clear()
# Register input colors
user = _not_none(user, not bool(args) and not bool(kwargs)) # skip if args passed
local = _not_none(local, not bool(args) and not bool(kwargs))
paths = []
for arg in args:
if isinstance(arg, dict):
kwargs.update(arg)
else:
paths.append(arg)
for key, color in kwargs.items():
if mcolors.is_color_like(color):
pcolors._color_database[key] = mcolors.to_rgba(color)
else:
raise ValueError(f'Invalid color {key}={color!r}.')
# Load colors from file and get their HCL values
# NOTE: Colors that come *later* overwrite colors that come earlier.
for i, path in _iter_data_objects(
'colors', *paths, user=user, local=local, default=default
):
loaded = pcolors._load_colors(path, warn_on_failure=True)
if i == 0:
cat, _ = os.path.splitext(os.path.basename(path))
if cat not in srcs:
raise RuntimeError(f'Unknown proplot color database {path!r}.')
src = srcs[cat]
if cat == 'xkcd':
for key in COLORS_KEEP:
loaded[key] = pcolors._color_database[key] # keep the same
loaded = pcolors._standardize_colors(loaded, space, margin)
src.clear()
src.update(loaded) # needed for demos.show_colors()
pcolors._color_database.update(loaded)
@docstring._snippet_manager
def register_fonts(*args, user=True, local=True, default=False):
"""
Register font families. This is called on import.
Parameters
----------
%(rc.font_args)s
%(rc.font_params)s
See also
--------
register_cmaps
register_cycles
register_colors
proplot.demos.show_fonts
"""
# Find proplot fonts
# WARNING: Must search data files in reverse because font manager will
# not overwrite existing fonts with user-input fonts.
# WARNING: If you include a font file with an unrecognized style,
# matplotlib may use that font instead of the 'normal' one! Valid styles:
# 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman',
# 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'
# https://matplotlib.org/api/font_manager_api.html
# For macOS the only fonts with 'Thin' in one of the .ttf file names
# are Helvetica Neue and .SF NS Display Condensed. Never try to use these!
paths_proplot = _get_data_folders(
'fonts', user=user, local=local, default=default, reverse=True
)
fnames_proplot = set(mfonts.findSystemFonts(paths_proplot))
for path in args:
path = os.path.expanduser(path)
if os.path.isfile(path):
fnames_proplot.add(path)
else:
raise FileNotFoundError(f'Invalid font file path {path!r}.')
# Detect user-input ttc fonts and issue warning
fnames_proplot_ttc = {
file for file in fnames_proplot if os.path.splitext(file)[1] == '.ttc'
}
if fnames_proplot_ttc:
warnings._warn_proplot(
'Ignoring the following .ttc fonts because they cannot be '
'saved into PDF or EPS files (see matplotlib issue #3135): '
+ ', '.join(map(repr, sorted(fnames_proplot_ttc)))
+ '. Please consider expanding them into separate .ttf files.'
)
# Rebuild font cache only if necessary! Can be >50% of total import time!
fnames_all = {font.fname for font in mfonts.fontManager.ttflist}
fnames_proplot -= fnames_proplot_ttc
if not fnames_all >= fnames_proplot:
warnings._warn_proplot(
'Rebuilding font cache. This usually happens '
'after installing or updating proplot.'
)
if hasattr(mfonts.fontManager, 'addfont'):
# Newer API lets us add font files manually and deprecates TTFPATH. However
# to cache fonts added this way, we must call json_dump explicitly.
# NOTE: Previously, cache filename was specified as _fmcache variable, but
# recently became inaccessible. Must reproduce mpl code instead.
# NOTE: Older mpl versions used fontList.json as the cache, but these
# versions also did not have 'addfont', so makes no difference.
for fname in fnames_proplot:
mfonts.fontManager.addfont(fname)
cache = os.path.join(
mpl.get_cachedir(),
f'fontlist-v{mfonts.FontManager.__version__}.json'
)
mfonts.json_dump(mfonts.fontManager, cache)
else:
# Older API requires us to modify TTFPATH
# NOTE: Previously we tried to modify TTFPATH before importing
# font manager with hope that it would load proplot fonts on
# initialization. But 99% of the time font manager just imports
# the FontManager from cache, so we would have to rebuild anyway.
paths = ':'.join(paths_proplot)
if 'TTFPATH' not in os.environ:
os.environ['TTFPATH'] = paths
elif paths not in os.environ['TTFPATH']:
os.environ['TTFPATH'] += ':' + paths
mfonts._rebuild()
# Remove ttc files and 'Thin' fonts *after* rebuild
# NOTE: 'Thin' filter is ugly kludge but without this matplotlib picks up on
# Roboto thin ttf files installed on the RTD server when compiling docs.
mfonts.fontManager.ttflist = [
font
for font in mfonts.fontManager.ttflist
if os.path.splitext(font.fname)[1] != '.ttc' and (
_version_mpl >= '3.3'
or 'Thin' not in os.path.basename(font.fname)
)
]
class Configurator(MutableMapping, dict):
"""
A dictionary-like class for managing `matplotlib settings
<https://matplotlib.org/stable/tutorials/introductory/customizing.html>`__
stored in `rc_matplotlib` and :ref:`proplot settings <ug_rcproplot>`
stored in `rc_proplot`. This class is instantiated as the `rc` object
on import. See the :ref:`user guide <ug_config>` for details.
"""
def __repr__(self):
cls = type('rc', (dict,), {}) # temporary class with short name
src = cls({key: val for key, val in rc_proplot.items() if '.' not in key})
return type(rc_matplotlib).__repr__(src).strip()[:-1] + ',\n ...\n })'
def __str__(self):
cls = type('rc', (dict,), {}) # temporary class with short name
src = cls({key: val for key, val in rc_proplot.items() if '.' not in key})
return type(rc_matplotlib).__str__(src) + '\n...'
def __iter__(self):
yield from rc_proplot # sorted proplot settings, ignoring deprecations
yield from rc_matplotlib # sorted matplotlib settings, ignoring deprecations
def __len__(self):
return len(tuple(iter(self)))
def __delitem__(self, key): # noqa: U100
raise RuntimeError('rc settings cannot be deleted.')
def __delattr__(self, attr): # noqa: U100
raise RuntimeError('rc settings cannot be deleted.')
@docstring._snippet_manager
def __init__(self, local=True, user=True, default=True, **kwargs):
"""
Parameters
----------
%(rc.params)s
"""
self._context = []
self._init(local=local, user=user, default=default, **kwargs)
def __getitem__(self, key):
"""
Return an `rc_matplotlib` or `rc_proplot` setting using dictionary notation
(e.g., ``value = pplt.rc[name]``).
"""
key, _ = self._validate_key(key) # might issue proplot removed/renamed error
try:
return rc_proplot[key]
except KeyError:
pass
return rc_matplotlib[key] # might issue matplotlib removed/renamed error
def __setitem__(self, key, value):
"""
Modify an `rc_matplotlib` or `rc_proplot` setting using dictionary notation
(e.g., ``pplt.rc[name] = value``).
"""
kw_proplot, kw_matplotlib = self._get_item_dicts(key, value)
rc_proplot.update(kw_proplot)
rc_matplotlib.update(kw_matplotlib)
def __getattr__(self, attr):
"""
Return an `rc_matplotlib` or `rc_proplot` setting using "dot" notation
(e.g., ``value = pplt.rc.name``).
"""
if attr[:1] == '_':
return super().__getattribute__(attr) # raise built-in error
else:
return self.__getitem__(attr)
def __setattr__(self, attr, value):
"""
Modify an `rc_matplotlib` or `rc_proplot` setting using "dot" notation
(e.g., ``pplt.rc.name = value``).
"""
if attr[:1] == '_':
super().__setattr__(attr, value)
else:
self.__setitem__(attr, value)
def __enter__(self):
"""
Apply settings from the most recent context block.
"""
if not self._context:
raise RuntimeError(
'rc object must be initialized for context block using rc.context().'
)
context = self._context[-1]
kwargs = context.kwargs
rc_new = context.rc_new # used for context-based _get_item_context
rc_old = context.rc_old # used to re-apply settings without copying whole dict
for key, value in kwargs.items():
try: # TODO: consider moving setting validation to .context()
kw_proplot, kw_matplotlib = self._get_item_dicts(key, value)
except ValueError as error:
self.__exit__()
raise error
for rc_dict, kw_new in zip(
(rc_proplot, rc_matplotlib),
(kw_proplot, kw_matplotlib),
):
for key, value in kw_new.items():
rc_old[key] = rc_dict[key]
rc_new[key] = rc_dict[key] = value
def __exit__(self, *args): # noqa: U100
"""
Restore settings from the most recent context block.
"""
if not self._context:
raise RuntimeError(
'rc object must be initialized for context block using rc.context().'
)
context = self._context[-1]
for key, value in context.rc_old.items():
kw_proplot, kw_matplotlib = self._get_item_dicts(key, value)
rc_proplot.update(kw_proplot)
rc_matplotlib.update(kw_matplotlib)
del self._context[-1]
def _init(self, *, local, user, default, skip_cycle=False):
"""
Initialize the configurator.
"""
# Always remove context objects
self._context.clear()
# Update from default settings
# NOTE: see _remove_blacklisted_style_params bugfix
if default:
rc_matplotlib.update(_get_style_dict('original', filter=False))
rc_matplotlib.update(rcsetup._rc_matplotlib_default)
rc_proplot.update(rcsetup._rc_proplot_default)
for key, value in rc_proplot.items():
kw_proplot, kw_matplotlib = self._get_item_dicts(
key, value, skip_cycle=skip_cycle
)
rc_matplotlib.update(kw_matplotlib)
rc_proplot.update(kw_proplot)
# Update from user home
user_path = None
if user:
user_path = self.user_file()
if os.path.isfile(user_path):
self.load(user_path)
# Update from local paths
if local:
local_paths = self.local_files()
for path in local_paths:
if path == user_path: # local files always have precedence
continue
self.load(path)
@staticmethod
def _validate_key(key, value=None):
"""
Validate setting names and handle `rc_proplot` deprecations.
"""
# NOTE: Not necessary to check matplotlib key here because... not sure why.
# Think deprecated matplotlib keys are not involved in any synced settings.
# Also note _check_key includes special handling for some renamed keys.
if not isinstance(key, str):
raise KeyError(f'Invalid key {key!r}. Must be string.')
key = key.lower()
if '.' not in key:
key = rcsetup._rc_nodots.get(key, key)
key, value = rc_proplot._check_key(key, value) # may issue deprecation warning
return key, value
@staticmethod
def _validate_value(key, value):
"""
Validate setting values and convert numpy ndarray to list if possible.
"""
# NOTE: Ideally would implicitly validate on subsequent assignment to rc
# dictionaries, but must explicitly do it here, so _get_item_dicts can
# work with e.g. 'tick.lenratio', so _get_item_dicts does not have to include
# deprecated name handling in its if statements, and so _load_file can
# catch errors and emit warnings with line number indications as files
# are being read rather than after the end of the file reading.
if isinstance(value, np.ndarray):
value = value.item() if value.size == 1 else value.tolist()
validate_matplotlib = getattr(rc_matplotlib, 'validate', None)
validate_proplot = rc_proplot._validate
if validate_matplotlib is not None and key in validate_matplotlib:
value = validate_matplotlib[key](value)
elif key in validate_proplot:
value = validate_proplot[key](value)
return value
def _get_item_context(self, key, mode=None):
"""
As with `~Configurator.__getitem__` but the search is limited based
on the context mode and ``None`` is returned if the key is not found.
"""
key, _ = self._validate_key(key)
if mode is None:
mode = self._context_mode
cache = tuple(context.rc_new for context in self._context)
if mode == 0:
rcdicts = (*cache, rc_proplot, rc_matplotlib)
elif mode == 1:
rcdicts = (*cache, rc_proplot) # added settings only!
elif mode == 2:
rcdicts = (*cache,)
else:
raise ValueError(f'Invalid caching mode {mode!r}.')
for rcdict in rcdicts:
if not rcdict:
continue
try:
return rcdict[key]
except KeyError:
continue
if mode == 0: # otherwise return None
raise KeyError(f'Invalid rc setting {key!r}.')
def _get_item_dicts(self, key, value, skip_cycle=False):
"""
Return dictionaries for updating the `rc_proplot` and `rc_matplotlib`
properties associated with this key. Used when setting items, entering
context blocks, or loading files.
"""
# Get validated key, value, and child keys
key, value = self._validate_key(key, value)
value = self._validate_value(key, value)
keys = (key,) + rcsetup._rc_children.get(key, ()) # settings to change
contains = lambda *args: any(arg in keys for arg in args) # noqa: E731
# Fill dictionaries of matplotlib and proplot settings
# NOTE: Raise key error right away so it can be caught by _load_file().
# Also ignore deprecation warnings so we only get them *once* on assignment
kw_proplot = {} # custom properties
kw_matplotlib = {} # builtin properties
with warnings.catch_warnings():
warnings.simplefilter('ignore', mpl.MatplotlibDeprecationWarning)
warnings.simplefilter('ignore', warnings.ProplotWarning)
for key in keys:
if key in rc_matplotlib:
kw_matplotlib[key] = value
elif key in rc_proplot:
kw_proplot[key] = value
else:
raise KeyError(f'Invalid rc setting {key!r}.')
# Special key: configure inline backend
if contains('inlineformat'):
config_inline_backend(value)
# Special key: apply stylesheet
elif contains('style'):
if value is not None:
ikw_matplotlib = _get_style_dict(value)
kw_matplotlib.update(ikw_matplotlib)
kw_proplot.update(_infer_proplot_dict(ikw_matplotlib))
# Cycler
# NOTE: Have to skip this step during initial proplot import
elif contains('cycle') and not skip_cycle:
from .colors import _get_cmap_subtype
cmap = _get_cmap_subtype(value, 'discrete')
kw_matplotlib['axes.prop_cycle'] = cycler.cycler('color', cmap.colors)
kw_matplotlib['patch.facecolor'] = 'C0'
# Turning bounding box on should turn border off and vice versa
elif contains('abc.bbox', 'title.bbox', 'abc.border', 'title.border'):
if value:
name, this = key.split('.')
other = 'border' if this == 'bbox' else 'bbox'
kw_proplot[name + '.' + other] = False
# Fontsize
# NOTE: Re-application of e.g. size='small' uses the updated 'font.size'
elif contains('font.size'):
kw_proplot.update(
{
key: value for key, value in rc_proplot.items()
if key in rcsetup.FONT_KEYS and value in mfonts.font_scalings
}
)
kw_matplotlib.update(
{
key: value for key, value in rc_matplotlib.items()
if key in rcsetup.FONT_KEYS and value in mfonts.font_scalings
}
)
# Tick length/major-minor tick length ratio
elif contains('tick.len', 'tick.lenratio'):
if contains('tick.len'):
ticklen = value
ratio = rc_proplot['tick.lenratio']
else:
ticklen = rc_proplot['tick.len']
ratio = value
kw_matplotlib['xtick.minor.size'] = ticklen * ratio
kw_matplotlib['ytick.minor.size'] = ticklen * ratio