ambivalent 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ __version__ = 'v0.0.1'
ambivalent/__init__.py ADDED
@@ -0,0 +1,132 @@
1
+ """
2
+ src/ambivalent/__init__.py
3
+ """
4
+ # ruff: noqa: F401
5
+ from __future__ import (
6
+ absolute_import,
7
+ annotations,
8
+ division,
9
+ nested_scopes,
10
+ print_function,
11
+ )
12
+
13
+ import logging
14
+ import os
15
+ import shutil
16
+ import time
17
+ from pathlib import Path
18
+ from typing import Optional
19
+
20
+ import matplotlib as mpl
21
+ import matplotlib.pyplot as plt
22
+
23
+ from ambivalent.core import (
24
+ FONT_NAMES,
25
+ FONTS_DIR,
26
+ PROJECT_DIR,
27
+ STYLES,
28
+ STYLES_DIR,
29
+ download_googlefont,
30
+ update_matplotlib_fonts,
31
+ )
32
+ # from ambivalent.utils import (
33
+ # # add_attribution,
34
+ # # add_legend,
35
+ # # set_title_and_suptitle
36
+ # )
37
+
38
+ log = logging.getLogger(__name__)
39
+ log.setLevel(logging.DEBUG)
40
+
41
+ os.environ['PROJECT_DIR'] = os.path.abspath(PROJECT_DIR)
42
+
43
+ # __all__ = [
44
+ # 'FONTS_DIR',
45
+ # 'STYLES_DIR',
46
+ # 'PROJECT_DIR',
47
+ # 'download_googlefont',
48
+ # 'update_matplotlib_fonts',
49
+ # 'add_legend',
50
+ # # 'add_attribution',
51
+ # 'set_title_and_suptitle'
52
+ # ]
53
+
54
+
55
+ def reload_styles(
56
+ outdir: Optional[os.PathLike] = None,
57
+ verbose: Optional[bool] = False,
58
+ ):
59
+ outdir = (
60
+ Path(mpl.get_configdir()).joinpath('stylelib')
61
+ if outdir is None else Path(outdir)
62
+ )
63
+ outdir.mkdir(parents=True, exist_ok=True)
64
+ for src in STYLES.values():
65
+ dst = outdir.joinpath(Path(src).stem)
66
+ if verbose:
67
+ log.debug(f"Copying {src} to {dst}")
68
+ shutil.copy2(src, dst)
69
+
70
+ plt.style.reload_library()
71
+ ambivalent_stylesheets = plt.style.core.read_style_directory(STYLES_DIR)
72
+ plt.style.core.update_nested_dict(
73
+ plt.style.library,
74
+ ambivalent_stylesheets
75
+ )
76
+ plt.style.reload_library()
77
+ mpl_stylelib_dir = Path(mpl.get_configdir()).joinpath('stylelib')
78
+ mpl_stylelib_dir.mkdir(parents=True, exist_ok=True)
79
+ # # Update the list of available styles
80
+ plt.style.core.available[:] = sorted(plt.style.library.keys())
81
+ # mpl.pyplot.style.core.available[:] = sorted(
82
+ # mpl.pyplot.style.library.keys()
83
+ # )
84
+ plt.style.reload_library()
85
+
86
+
87
+ def check_if_font_already_present(font):
88
+ return FONTS_DIR.joinpath(font).exists()
89
+
90
+
91
+ def download_font_with_retry(
92
+ font: str,
93
+ retries: int = 3,
94
+ delay: int = 3,
95
+ verbose: Optional[bool] = False,
96
+ ) -> None:
97
+ for i in range(retries):
98
+ try:
99
+ if verbose:
100
+ log.debug(f"Now downloading: {font}")
101
+ download_googlefont(font=font)
102
+ return # return if the download was successful
103
+ except Exception as e:
104
+ if i < retries - 1: # i is zero indexed
105
+ if verbose:
106
+ log.debug(
107
+ f"Attempt {i+1} to download {font} failed with error:"
108
+ f"{str(e)}. Retrying in {delay} seconds."
109
+ )
110
+ time.sleep(delay)
111
+ else:
112
+ if verbose:
113
+ log.debug(
114
+ f"All attempts to download {font} failed."
115
+ "Please check your connection and the font name."
116
+ )
117
+ raise
118
+
119
+
120
+ def update_fonts(verbose: Optional[bool] = False):
121
+ for font in FONT_NAMES:
122
+ if FONTS_DIR.joinpath(f"{font}.zip").is_file():
123
+ if verbose:
124
+ log.debug(f"{font} already downloaded, continuing!")
125
+ continue
126
+ if not check_if_font_already_present(font):
127
+ download_font_with_retry(font)
128
+ update_matplotlib_fonts()
129
+
130
+
131
+ update_fonts()
132
+ reload_styles()
@@ -0,0 +1,112 @@
1
+ r"""°°°
2
+
3
+ # Build Example Plots
4
+
5
+ ![[Open in Colab](https://colab.research.google.com/github/MNoichl/ambivalent/blob/master/build_example_plots.ipynb)](https://colab.research.google.com/assets/colab-badge.svg)
6
+
7
+ °°°"""
8
+ # |%%--%%| <86R7V4Yv0S|3ZNGgtlKOP>
9
+ r"""°°°
10
+ # Building the example plots
11
+
12
+ First, we make the standard plot.
13
+ °°°"""
14
+ # |%%--%%| <3ZNGgtlKOP|NGT3Gnd9ZL>
15
+
16
+ # from google.colab import drive
17
+ # drive.mount('/content/gdrive/', force_remount=True)
18
+
19
+
20
+ # |%%--%%| <NGT3Gnd9ZL|Wd7ubZRq7l>
21
+
22
+ # %cd gdrive/MyDrive/ambivalent
23
+
24
+ # |%%--%%| <Wd7ubZRq7l|v99S6KbmRA>
25
+
26
+ # ruff: noqa: E402, F401
27
+
28
+ from typing import Optional
29
+ from ambivalent import reload_styles
30
+ import seaborn as sns
31
+ import ambivalent
32
+ from matplotlib import font_manager as fm, pyplot as plt
33
+
34
+ import os
35
+ import shutil
36
+ import matplotlib
37
+ from pathlib import Path
38
+ import pandas as pd
39
+
40
+ from ambivalent import PROJECT_DIR, STYLES_DIR
41
+ OUTPUT_DIR = PROJECT_DIR.joinpath('outputs')
42
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
43
+
44
+ penguins = sns.load_dataset("penguins")
45
+
46
+ #|%%--%%| <v99S6KbmRA|MCGiYS46iG>
47
+
48
+ # %load_ext autoreload
49
+ # %autoreload 2
50
+
51
+ #|%%--%%| <MCGiYS46iG|aZfsQfXq22>
52
+
53
+ def savefig(
54
+ fname: str,
55
+ outdir: Optional[os.PathLike] = None,
56
+ ):
57
+ outdir = OUTPUT_DIR if outdir is None else outdir
58
+ # fig = plt.gcf()
59
+ ext = {'png', 'svg'}
60
+ print(f"Saving {fname} to {outdir}")
61
+ for ext in ext:
62
+ edir = Path(outdir).joinpath(f"{ext}s")
63
+ edir.mkdir(exist_ok=True, parents=True)
64
+ outfile = Path(edir).joinpath(f"{fname}.{ext}")
65
+ plt.savefig(outfile, dpi=450, bbox_inches='tight')
66
+
67
+
68
+ #|%%--%%| <aZfsQfXq22|O1R7V0rhCm>
69
+
70
+ import os
71
+ import seaborn as sns
72
+ from ambivalent import STYLES, set_title_and_suptitle, add_attribution
73
+ import colormaps as cmaps
74
+
75
+ def make_plot(name: str):
76
+ fig, ax = plt.subplots()
77
+ cmap = sns.color_palette(list(cmaps.bold[2:5]._colors))
78
+ sns.scatterplot(
79
+ x="bill_length_mm",
80
+ y="flipper_length_mm",
81
+ data=penguins,
82
+ hue='species',
83
+ style='species',
84
+ palette=cmap,
85
+ alpha=0.75,
86
+ )
87
+ # ambivalent.add_legend()
88
+ plt.legend(bbox_to_anchor=(1.01, 0.5), loc='center left')
89
+ set_title_and_suptitle(
90
+ "Penguins",
91
+ "An Excellent Bird!"
92
+ )
93
+ savefig(f"penguins_{name}")
94
+
95
+ #|%%--%%| <O1R7V0rhCm|SmE8QMA9ZI>
96
+
97
+ plt.style.use('default')
98
+ make_plot('default')
99
+
100
+ #|%%--%%| <SmE8QMA9ZI|nFWJGWKGNm>
101
+
102
+ reload_styles()
103
+
104
+
105
+ #|%%--%%| <nFWJGWKGNm|jZ6yWZph0U>
106
+
107
+ with plt.style.context('default'):
108
+ make_plot('default')
109
+
110
+ for name, stylefile in STYLES.items():
111
+ with plt.style.context(Path(stylefile).as_posix()):
112
+ make_plot(name)
ambivalent/core.py ADDED
@@ -0,0 +1,223 @@
1
+ """
2
+ core.py
3
+ """
4
+ from __future__ import absolute_import, annotations, division, print_function
5
+
6
+ import requests
7
+ import zipfile
8
+ import os
9
+ import sys
10
+ from pathlib import Path
11
+ import io
12
+
13
+ import matplotlib as mpl
14
+
15
+ from typing import Optional, Sequence
16
+
17
+ import matplotlib.pyplot as plt
18
+ from matplotlib import font_manager as fm
19
+ from IPython.core.display import HTML
20
+
21
+ PYTHON_VERSION = [int(i) for i in sys.version.split(' ')[0].split('.')]
22
+ HERE = Path(os.path.abspath(__file__)).parent
23
+ PROJECT_DIR = HERE.parent.parent
24
+
25
+ FONTS_DIR = PROJECT_DIR.joinpath('fonts')
26
+ STYLES_DIR = HERE.joinpath('stylefiles')
27
+
28
+ FONTS_DIR.mkdir(parents=True, exist_ok=True)
29
+ STYLES_DIR.mkdir(parents=True, exist_ok=True)
30
+
31
+ STYLE_FILES = list(STYLES_DIR.rglob('*.mplstyle'))
32
+ STYLES = {f.stem: f.as_posix() for f in STYLE_FILES}
33
+
34
+ FONT_NAMES = (
35
+ # 'Fira Sans',
36
+ # 'Fira Sans Condensed',
37
+ 'IBM Plex Sans',
38
+ 'IBM Plex Sans Condensed',
39
+ 'IBM Plex Serif',
40
+ # 'Jost',
41
+ # 'Montserrat',
42
+ # 'Roboto',
43
+ # 'Roboto Condensed',
44
+ # 'Source Code Pro',
45
+ # 'Source Sans Pro',
46
+ # 'Space Grotesk',
47
+ # 'Space Mono',
48
+ # 'Titillium Web',
49
+ # 'Titillium WebRoboto Condensed',
50
+ # 'Shadows Into Light Two'
51
+ )
52
+
53
+ FONTS = {
54
+ f: FONTS_DIR.joinpath(f) for f in FONT_NAMES
55
+ }
56
+
57
+
58
+ def set_color_cycle(colors: list[str | Sequence[str | int]]) -> None:
59
+ plt.rcParams['axes.prop_cycle'] = plt.cycler(
60
+ 'color',
61
+ list(colors)
62
+ )
63
+
64
+
65
+ def _download_font(font: str) -> requests.Response:
66
+ return requests.get(
67
+ f'https://fonts.google.com/download?family={font}'
68
+ )
69
+
70
+
71
+ def save_font(font: str) -> None:
72
+ response = _download_font(font)
73
+ z = zipfile.ZipFile(io.BytesIO(response.content))
74
+ z.extractall(FONTS_DIR)
75
+ zip_fp = FONTS_DIR.joinpath(f'{font}.zip')
76
+ with open(zip_fp, 'wb') as f:
77
+ f.write(response.content)
78
+ print(f'Font saved to: {FONTS_DIR}/{font}')
79
+
80
+
81
+ def download_googlefont(
82
+ font='IBM Plex Sans',
83
+ add_to_cache=True
84
+ ):
85
+ """download a font from Google fonts
86
+
87
+ Args:
88
+ font (str, optional): The font to download.
89
+ Must be the name used by googlefonts. Defaults to 'IBM Plex Sans'.
90
+ """
91
+ try:
92
+ save_font(font)
93
+ except Exception:
94
+ print(f'Failed to download font: {font}, skipping!')
95
+ if add_to_cache:
96
+ update_matplotlib_fonts()
97
+
98
+
99
+ def make_html(fontname):
100
+ """
101
+ Make a HTML snippet to display a font in a notebook.
102
+ Utility used by show_installed_fonts().
103
+ """
104
+ return (
105
+ f"<p>{fontname}: <span style='font-family:{fontname};"
106
+ f"font-size: 24px;'>{fontname}</p>"
107
+ )
108
+
109
+
110
+ def show_installed_fonts():
111
+ """
112
+ Show all installed fonts in a columnized HTML table. Works in notebooks
113
+ only.
114
+ """
115
+ code = (
116
+ "\n".join(
117
+ [
118
+ make_html(font) for font in
119
+ sorted(set([f.name for f in fm.fontManager.ttflist]))
120
+ ]
121
+ )
122
+ )
123
+ HTML("<div style='column-count: 2;'>{}</div>".format(code))
124
+
125
+
126
+ def update_matplotlib_fonts():
127
+ """Update matplotlib's font cache.
128
+ Useful if you downloaded googlefonts to the fonts folder
129
+ (with download_googlefont) and want to use them in matplotlib.
130
+ """
131
+ for font_file in fm.findSystemFonts(fontpaths=str(FONTS_DIR)):
132
+ if ('.ttf' in font_file) or ('.otf' in font_file):
133
+ try:
134
+ fm.fontManager.addfont(
135
+ os.path.join(
136
+ FONTS_DIR,
137
+ font_file
138
+ )
139
+ )
140
+ except Exception:
141
+ print('This font could not be added: ', font_file)
142
+
143
+
144
+ def add_legend(*args, **kwargs):
145
+ fig: plt.Figure = plt.gcf() # type:ignore
146
+ ax: plt.Axes = plt.gca() # type:ignore
147
+ handles, _ = fig.axes[0].get_legend_handles_labels()
148
+ is_scatter = isinstance(handles[0], mpl.collections.PathCollection)
149
+ # is_scatter = (type(handles[0]) == mpl.collections.PathCollection)
150
+ # is_line_plot = (type(handles[0]) == mpl.lines.Line2D)
151
+ # kwargs |= {"bbox_to_anchor": (1.05, .5)}
152
+ if "bbox_to_anchor" not in kwargs:
153
+ kwargs["bbox_to_anchor"] = (1.05, .5)
154
+ if is_scatter:
155
+ if "handltextpad" not in kwargs:
156
+ kwargs["handletextpad"] = 0.
157
+ if 'scatterpoints' not in kwargs:
158
+ kwargs["scatterpoints"] = 1
159
+ if 'scatteryoffsets' not in kwargs:
160
+ kwargs["scatteryoffsets"] = [0]
161
+ legend = ax.legend(*args, **kwargs)
162
+ # legend.get_title().set_fontweight('bold')
163
+ if is_scatter:
164
+ [t.set_va('center_baseline') for t in legend.get_texts()]
165
+ return legend
166
+
167
+
168
+ def add_attribution(
169
+ attrib: str,
170
+ position: Optional[tuple[int, int]] = None,
171
+ ):
172
+ # fig = plt.gcf()
173
+ # bbox = {
174
+ # "facecolor":"orange",
175
+ # "alpha":0.5,
176
+ # "pad":5
177
+ # }
178
+ loc = (.9, -0.01) if position is None else position
179
+ plt.figtext(
180
+ loc[0],
181
+ loc[1],
182
+ attrib,
183
+ ha="right",
184
+ fontsize=14
185
+ )
186
+
187
+
188
+ def set_title_and_suptitle(
189
+ title_string,
190
+ sub_title_string: Optional[str] = None,
191
+ position_title: Optional[list] = None,
192
+ position_sub_title: Optional[list] = None,
193
+ ):
194
+ """
195
+ Set the title and subtitle of a plot.
196
+ The subtitle is set a bit lower than the title.
197
+ The adjust_y parameter can be used to
198
+ adjust the vertical position of the two titles.
199
+ Args:
200
+ title_string (str): The title string
201
+ sub_title_string (str): The subtitle string
202
+ position_title (list, optional): The position of the title.
203
+ Defaults to [.12, .97].
204
+ position_sub_title (list, optional): The position of the subtitle.
205
+ Defaults to [.12, .918].
206
+ """
207
+ position_title = [.12, .97] if position_title is None else position_title
208
+ position_sub_title = (
209
+ [.12, .918] if position_sub_title is None else position_sub_title
210
+ )
211
+ if sub_title_string is not None:
212
+ plt.figtext(
213
+ position_title[0],
214
+ position_title[1],
215
+ title_string,
216
+ )
217
+ else:
218
+ sub_title_string = title_string
219
+ plt.figtext(
220
+ position_sub_title[0],
221
+ position_sub_title[1],
222
+ sub_title_string,
223
+ )
@@ -0,0 +1,66 @@
1
+ font.family: sans-serif
2
+ font.size: 12.0
3
+
4
+ font.serif: IBM Plex Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
5
+ font.sans-serif: IBM Plex Sans, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
6
+ font.cursive: Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, Comic Neue, Comic Sans MS, cursive
7
+ font.fantasy: Chicago, Charcoal, Impact, Western, Humor Sans, xkcd, fantasy
8
+ font.monospace: IBM Plex Sans Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace
9
+ text.color: 838383
10
+
11
+ axes.facecolor: none # axes background color
12
+ axes.edgecolor: none # axes edge color
13
+ axes.grid: True # display grid or not
14
+ axes.titlecolor: 838383 # color of the axes title, auto falls back to
15
+ # text.color as default value
16
+ axes.labelcolor: 838383
17
+ # https://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes
18
+ axes.prop_cycle: cycler('color', ['2196F3', 'EF5350', '4CAF50', 'FFA726', 'AE81FF', 'ffeb3b', 'EC407A', '009688', '838383'])
19
+ xtick.color: none # color of the ticks
20
+ xtick.labelcolor: 838383 # color of the tick labels or inherit from xtick.color
21
+
22
+ ytick.color: none # color of the ticks
23
+ ytick.labelcolor: 838383 # color of the tick labels or inherit from ytick.color
24
+ lines.solid_capstyle: round
25
+ axes.linewidth: 0
26
+ xtick.major.size: 0
27
+ ytick.major.size: 0
28
+ xtick.minor.size: 0
29
+ ytick.minor.size: 0
30
+ axes.titlelocation: center
31
+ xaxis.labellocation: center
32
+ yaxis.labellocation: center
33
+
34
+ legend.frameon: False
35
+ legend.numpoints: 1
36
+ legend.scatterpoints: 1
37
+ legend.facecolor: none # inherit from axes.facecolor; or color spec
38
+ legend.edgecolor: none # background patch boundary color
39
+ legend.labelcolor: 838383
40
+
41
+
42
+ grid.color: 838383 # grid color
43
+ grid.linestyle: -- # solid
44
+ grid.linewidth: 0.4 # in points
45
+ grid.alpha: 0.25 # transparency, between 0.0 and 1.0
46
+
47
+ figure.figsize: 12.8, 9.6 # figure size in inches
48
+ figure.facecolor: none # figure face color
49
+
50
+ image.cmap: viridis # A colormap name (plasma, magma, etc.)
51
+ savefig.facecolor: none # figure face color when saving
52
+ savefig.format: svg # {png, ps, pdf, svg}
53
+ savefig.bbox: tight # {tight, standard}
54
+ savefig.transparent: True # whether figures are saved with a transparent
55
+
56
+ ## ***************************************************************************
57
+ ## * PATCHES *
58
+ ## ***************************************************************************
59
+ ## Patches are graphical objects that fill 2D space, like polygons or circles.
60
+ ## See https://matplotlib.org/stable/api/artist_api.html#module-matplotlib.patches
61
+ ## for more information on patch properties.
62
+ #patch.linewidth: 1.0 # edge width in points.
63
+ #patch.facecolor: C0
64
+ patch.edgecolor: none # if forced, or patch is not filled
65
+ #patch.force_edgecolor: False # True to always use edgecolor
66
+ patch.antialiased: True # render patches in antialiased (no jaggies)
@@ -0,0 +1 @@
1
+