mpl-typst 0.1.0__tar.gz

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,159 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # Ignore rendering products.
156
+ gallery/*.pdf
157
+ gallery/*.png
158
+ gallery/*.svg
159
+ gallery/*.typ
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Daniel Bershatsky
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.1
2
+ Name: mpl-typst
3
+ Version: 0.1.0
4
+ Summary: Typst backend for matplotlib (Python visualization library).
5
+ Author-email: Daniel Bershatsky <daniel.bershatsky@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/daskol/typst-mpl-backend
8
+ Project-URL: Repository, https://github.com/daskol/typst-mpl-backend.git
9
+ Classifier: Development Status :: 5 - Production/Stable
10
+ Classifier: Environment :: Other Environment
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: Intended Audience :: Information Technology
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Natural Language :: English
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python
20
+ Classifier: Programming Language :: Python :: 3
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Topic :: Scientific/Engineering
24
+ Classifier: Topic :: Scientific/Engineering :: Visualization
25
+ Classifier: Topic :: Text Processing
26
+ Classifier: Topic :: Text Processing :: Markup
27
+ Classifier: Topic :: Utilities
28
+ Classifier: Typing :: Typed
29
+ Requires-Python: <4,>=3.11
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ Requires-Dist: matplotlib
33
+ Provides-Extra: dev
34
+ Requires-Dist: flake8; extra == "dev"
35
+ Requires-Dist: isort; extra == "dev"
36
+ Requires-Dist: pytest>=7; extra == "dev"
37
+
38
+ # Typst Matplotlib Backend
39
+
40
+ *Typst backend for matplotlib (Python visualization library).*
41
+
42
+ ## Overview
43
+
44
+ At the moment, Typst supports main vector and raster image formats. Namely,
45
+ images in PNG, JPEG, GIF, or SVG format can be easily emplaced in a document
46
+ with Typst. However, it is **not possible** to keep metadata and annotations.
47
+ These are mandatory in order to allow a reader to select and interact with
48
+ vector content (e.g. text) on images. Although SVG can contain text metadata in
49
+ principle, Typst does not support this feature at the moment but still it is
50
+ able to render SVG as a vector content.
51
+
52
+ This package solves this problem for `matplotlib` users. Basically, this
53
+ project implements a custom render (or backend) for `matplotlib` which
54
+ generates `typ`-file containing Typst markup. Generated markup file can be
55
+ later included in the original markup so that the resulting PDF will have
56
+ interactable content. Matplotlib exploits exactly the same strategy in order to
57
+ generate PGF-files &mdash; a LaTeX markup itself &mdash; which can be included
58
+ into LaTeX markup directly.
59
+
60
+ ## Usage
61
+
62
+ In order to render image with `mpl_typst` one can import `mpl_typst.as_default`
63
+ module in order to use `mpl_typst` backend by default.
64
+
65
+ ```python
66
+ import mpl_typst.as_default
67
+ ```
68
+
69
+ Or one can configure it manually.
70
+
71
+ ```python
72
+ import matplotlib
73
+ import mpl_typst
74
+ mpl.use('module://mpl_typst')
75
+ ```
76
+
77
+ Also, it is possible to use rendering context as usual to override backend.
78
+
79
+ ```python
80
+ import matplotlib as mpl
81
+ import mpl_typst
82
+ with mpl.rc_context({'backend': 'module://mpl_typst'}): # or mpl_typst.BACKEND
83
+ ...
84
+ ```
85
+
86
+ Next, you can save your figure to `typ` as usual.
87
+
88
+ ```python
89
+ fig, ax = plt.subplots()
90
+ ...
91
+ fig.savefig('line-plot-simple.typ')
92
+ ```
93
+
94
+ As soon as you get a `typ`-file you can included it directly to `figure`
95
+ function and adjust figure time.
96
+
97
+ ```typst
98
+ #figure(
99
+ include "line-plot-simple.typ",
100
+ kind: image,
101
+ caption: [Simple line plot],
102
+ placement: top,
103
+ ) <line-plot-simple>
104
+ ```
@@ -0,0 +1,67 @@
1
+ # Typst Matplotlib Backend
2
+
3
+ *Typst backend for matplotlib (Python visualization library).*
4
+
5
+ ## Overview
6
+
7
+ At the moment, Typst supports main vector and raster image formats. Namely,
8
+ images in PNG, JPEG, GIF, or SVG format can be easily emplaced in a document
9
+ with Typst. However, it is **not possible** to keep metadata and annotations.
10
+ These are mandatory in order to allow a reader to select and interact with
11
+ vector content (e.g. text) on images. Although SVG can contain text metadata in
12
+ principle, Typst does not support this feature at the moment but still it is
13
+ able to render SVG as a vector content.
14
+
15
+ This package solves this problem for `matplotlib` users. Basically, this
16
+ project implements a custom render (or backend) for `matplotlib` which
17
+ generates `typ`-file containing Typst markup. Generated markup file can be
18
+ later included in the original markup so that the resulting PDF will have
19
+ interactable content. Matplotlib exploits exactly the same strategy in order to
20
+ generate PGF-files &mdash; a LaTeX markup itself &mdash; which can be included
21
+ into LaTeX markup directly.
22
+
23
+ ## Usage
24
+
25
+ In order to render image with `mpl_typst` one can import `mpl_typst.as_default`
26
+ module in order to use `mpl_typst` backend by default.
27
+
28
+ ```python
29
+ import mpl_typst.as_default
30
+ ```
31
+
32
+ Or one can configure it manually.
33
+
34
+ ```python
35
+ import matplotlib
36
+ import mpl_typst
37
+ mpl.use('module://mpl_typst')
38
+ ```
39
+
40
+ Also, it is possible to use rendering context as usual to override backend.
41
+
42
+ ```python
43
+ import matplotlib as mpl
44
+ import mpl_typst
45
+ with mpl.rc_context({'backend': 'module://mpl_typst'}): # or mpl_typst.BACKEND
46
+ ...
47
+ ```
48
+
49
+ Next, you can save your figure to `typ` as usual.
50
+
51
+ ```python
52
+ fig, ax = plt.subplots()
53
+ ...
54
+ fig.savefig('line-plot-simple.typ')
55
+ ```
56
+
57
+ As soon as you get a `typ`-file you can included it directly to `figure`
58
+ function and adjust figure time.
59
+
60
+ ```typst
61
+ #figure(
62
+ include "line-plot-simple.typ",
63
+ kind: image,
64
+ caption: [Simple line plot],
65
+ placement: top,
66
+ ) <line-plot-simple>
67
+ ```
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env python3
2
+
3
+ import matplotlib.pyplot as plt
4
+
5
+ from mpl_typst import rc_context
6
+
7
+ with rc_context():
8
+ fig, ax = plt.subplots(figsize=(3.25, 2.01), layout='constrained')
9
+ ax.plot([i ** 2 for i in range(10)], '-..', label=r'$x^2$')
10
+ ax.legend()
11
+ ax.set_xlabel(r'$x$')
12
+ ax.set_ylabel(r'$f(x)$')
13
+ fig.savefig('line-plot-simple.typ')
14
+ fig.savefig('line-plot-simple.pdf')
15
+ fig.savefig('line-plot-simple.png')
16
+ fig.savefig('line-plot-simple.svg')
@@ -0,0 +1,43 @@
1
+ /**
2
+ * main.typ
3
+ *
4
+ * This is an example paper which demonstrates how to use typ-files rendered
5
+ * with custom `matplotlib` backend based on Typst.
6
+ */
7
+
8
+ #set document(title: [#smallcaps[Typst] #smallcaps[Matplotlib] Backend Demo])
9
+ #set page(
10
+ paper: "a4",
11
+ margin: (left: 0.75in, right: 8.5in - (0.75in + 6.75in), top: 1.0in),
12
+ )
13
+
14
+ #set par(justify: true, leading: 0.58em)
15
+ #set text(font: "Times", size: 10pt)
16
+ #show: it => columns(2, gutter: 0.25in, it)
17
+
18
+ #lorem(50)
19
+
20
+ #lorem(50)
21
+
22
+ #lorem(50)
23
+
24
+ #lorem(50)
25
+
26
+ #lorem(50)
27
+
28
+ #lorem(50)
29
+
30
+ #lorem(50)
31
+
32
+ // NOTE The point is to include typ-file and adjust figure kind
33
+ // correspondently.
34
+ #figure(
35
+ include "line-plot-simple.typ",
36
+ kind: image,
37
+ caption: [Simple line plot],
38
+ placement: top,
39
+ ) <line-plot-simple>
40
+
41
+ #lorem(50)
42
+
43
+ #lorem(50)
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env python
2
+
3
+ import matplotlib as mpl
4
+ import matplotlib.pyplot as plt
5
+ import numpy as np
6
+ from mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable
7
+
8
+ from mpl_typst import rc_context
9
+
10
+ mpl.rcParams.update({
11
+ 'font.family': 'serif',
12
+ 'font.size': 8,
13
+ 'axes.labelsize': 8,
14
+ 'legend.fontsize': 6,
15
+ 'xtick.labelsize': 6,
16
+ 'ytick.labelsize': 6,
17
+ 'axes.titlesize': 8,
18
+ })
19
+
20
+ xticks = [512, 2048, 4096, 8192, 16384, 65536]
21
+ yticks = [8, 32, 64, 96, 128]
22
+ values = np.array([
23
+ 0.6, 0.0, 0.1, 0.1, -0.2, 0.7, -0.0, -0.0, 0.2, 0.1, -0.1, 1.7, 0.0, 0.1,
24
+ 0.1, 0.2, 0.1, 1.8, 0.0, 0.1, -0.0, 0.2, 0.5, 0.9, 0.0, 0.1, 0.2, 0.3, 0.8,
25
+ 2.1
26
+ ]).reshape(5, 6)
27
+
28
+ width, height = values.T.shape
29
+ xs, ys = np.mgrid[:width + 1, :height + 1]
30
+
31
+ with rc_context():
32
+ fig, ax = plt.subplots(figsize=(3.25, 2.01), layout='constrained')
33
+
34
+ img = ax.pcolor(xs, ys, values.T)
35
+
36
+ divider = make_axes_locatable(ax)
37
+ cax = divider.append_axes('right', size='8%', pad=0.1)
38
+ fig.colorbar(img, cax)
39
+
40
+ ax.set_xlabel('Number of tokens')
41
+ ax.set_xticks(np.arange(len(xticks)))
42
+ ax.set_xticklabels([f'{x:.1f}' if x < 1 else int(x) for x in xticks])
43
+
44
+ ax.set_ylabel('Rank r')
45
+ ax.set_yticks(np.arange(len(yticks)))
46
+ ax.set_yticklabels([str(x) for x in yticks])
47
+ ax.invert_yaxis()
48
+
49
+ fig.savefig('pcolor.pdf')
50
+ fig.savefig('pcolor.png')
51
+ fig.savefig('pcolor.svg')
52
+ fig.savefig('pcolor.typ')
@@ -0,0 +1,74 @@
1
+ """Package `mpl_typst` provides a :py:`matplotlib` backend for rendering
2
+ directly to Typst as well as rendering to PDF, PNG, SVG indirectly through
3
+ Typst renderer.
4
+
5
+ One can import `mpl_typst.as_default` module in order to use `mpl_typst`
6
+ backend by default.
7
+
8
+ .. code:: python
9
+
10
+ import mpl_typst.as_default
11
+
12
+ Or one can configure it manually.
13
+
14
+ .. code:: python
15
+
16
+ import matplotlib
17
+ import mpl_typst
18
+ mpl.use('module://mpl_typst')
19
+
20
+ Also, it is possible to use rendering context as usual to override backend.
21
+
22
+ .. code:: python
23
+
24
+ import matplotlib as mpl
25
+ import mpl_typst
26
+ with mpl.rc_context({'backend': 'module://mpl_typst'}):
27
+ ...
28
+ """
29
+
30
+ from contextlib import contextmanager
31
+ from os import PathLike
32
+ from pathlib import Path
33
+ from typing import Any, Generator
34
+
35
+ import matplotlib as mpl
36
+ from mpl_typst.backend import (FigureCanvas, FigureManager, TypstFigureCanvas,
37
+ TypstFigureManager, TypstRenderer,
38
+ TypstRenderingError)
39
+
40
+ __all__ = ('BACKEND', 'FigureCanvas', 'FigureManager', 'TypstFigureCanvas',
41
+ 'TypstFigureManager', 'TypstGraphicsContext', 'TypstRenderer',
42
+ 'TypstRenderingError', 'rc_context', 'use')
43
+
44
+ # Backend specification for use with `matplotlib.use`
45
+ BACKEND = 'module://mpl_typst'
46
+
47
+
48
+ @contextmanager
49
+ def rc_context(
50
+ rc: dict[str, Any] | None = None,
51
+ fname: PathLike | Path | str | None = None,
52
+ ) -> Generator[None, None, None]:
53
+ """A shortcut for using Typst as default backend in a context.
54
+
55
+ It forward all arguments to original :py:`matplotlib.rc_context` context
56
+ manager but it enforces use of `mpl_typst` backend in the beginning of
57
+ newly created context.
58
+
59
+ .. code:: python
60
+
61
+ import mpl_typst
62
+ with mpl_typst.rc_context():
63
+ ...
64
+ """
65
+ original_backend = mpl.rcParams['backend']
66
+ with mpl.rc_context(rc, fname):
67
+ mpl.use(BACKEND)
68
+ yield
69
+ mpl.use(original_backend)
70
+
71
+
72
+ def use(*, force: bool = True):
73
+ """Set Typst rendering backend as default on (see :py:`matplotlib.use`)."""
74
+ mpl.use(BACKEND)
@@ -0,0 +1,7 @@
1
+ """This module is aimed to use by end-users in order to configure `mpl_typst`
2
+ as default backend.
3
+ """
4
+
5
+ from mpl_typst import use
6
+
7
+ use() # Use this MPL backend as default.