mpl-depth-style 0.6.1__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.
Files changed (54) hide show
  1. mpl_depth_style-0.6.1/MANIFEST.in +9 -0
  2. mpl_depth_style-0.6.1/PKG-INFO +77 -0
  3. mpl_depth_style-0.6.1/README.md +61 -0
  4. mpl_depth_style-0.6.1/README.zh-CN.md +63 -0
  5. mpl_depth_style-0.6.1/benchmarks/benchmark.py +85 -0
  6. mpl_depth_style-0.6.1/benchmarks/my_mpl_style.py +276 -0
  7. mpl_depth_style-0.6.1/benchmarks/results/my_mpl_style/README.md +61 -0
  8. mpl_depth_style-0.6.1/benchmarks/results/my_mpl_style/isosurface_comparison.png +0 -0
  9. mpl_depth_style-0.6.1/benchmarks/results/my_mpl_style/isosurface_geometry.json +119 -0
  10. mpl_depth_style-0.6.1/benchmarks/results/my_mpl_style/trisurf_comparison.png +0 -0
  11. mpl_depth_style-0.6.1/benchmarks/results/my_mpl_style/trisurf_timings.json +497 -0
  12. mpl_depth_style-0.6.1/data/LICENSE-my-mpl-style.txt +21 -0
  13. mpl_depth_style-0.6.1/data/README.md +14 -0
  14. mpl_depth_style-0.6.1/data/cheese.npz +0 -0
  15. mpl_depth_style-0.6.1/data/peanut.npz +0 -0
  16. mpl_depth_style-0.6.1/docs/api.md +491 -0
  17. mpl_depth_style-0.6.1/docs/examples.md +70 -0
  18. mpl_depth_style-0.6.1/docs/gallery/intersecting_scalar_slices.png +0 -0
  19. mpl_depth_style-0.6.1/docs/gallery/random_field_isosurface.png +0 -0
  20. mpl_depth_style-0.6.1/docs/gallery/reference/ax3D_setting.png +0 -0
  21. mpl_depth_style-0.6.1/docs/gallery/reference/plot.png +0 -0
  22. mpl_depth_style-0.6.1/docs/gallery/reference/plot_rc.png +0 -0
  23. mpl_depth_style-0.6.1/docs/gallery/reference/plot_surface.png +0 -0
  24. mpl_depth_style-0.6.1/docs/gallery/reference/plot_trisurf.png +0 -0
  25. mpl_depth_style-0.6.1/docs/gallery/reference/scatter.png +0 -0
  26. mpl_depth_style-0.6.1/docs/plot_catalog.md +18 -0
  27. mpl_depth_style-0.6.1/docs/scene.md +223 -0
  28. mpl_depth_style-0.6.1/examples/intersecting_scalar_slices.py +61 -0
  29. mpl_depth_style-0.6.1/examples/random_field_isosurface.py +51 -0
  30. mpl_depth_style-0.6.1/examples/reference/ax3D_setting.py +68 -0
  31. mpl_depth_style-0.6.1/examples/reference/plot.py +59 -0
  32. mpl_depth_style-0.6.1/examples/reference/plot_rc.py +77 -0
  33. mpl_depth_style-0.6.1/examples/reference/plot_surface.py +58 -0
  34. mpl_depth_style-0.6.1/examples/reference/plot_trisurf.py +67 -0
  35. mpl_depth_style-0.6.1/examples/reference/scatter.py +59 -0
  36. mpl_depth_style-0.6.1/examples/render_reference.py +230 -0
  37. mpl_depth_style-0.6.1/mpl_depth_style/__init__.py +10 -0
  38. mpl_depth_style-0.6.1/mpl_depth_style/_axes.py +521 -0
  39. mpl_depth_style-0.6.1/mpl_depth_style/_axes_style.py +229 -0
  40. mpl_depth_style-0.6.1/mpl_depth_style/_geometry.py +191 -0
  41. mpl_depth_style-0.6.1/mpl_depth_style/charts.py +108 -0
  42. mpl_depth_style-0.6.1/mpl_depth_style/scene.py +314 -0
  43. mpl_depth_style-0.6.1/mpl_depth_style/surfaces.py +50 -0
  44. mpl_depth_style-0.6.1/mpl_depth_style/volumes.py +44 -0
  45. mpl_depth_style-0.6.1/mpl_depth_style.egg-info/PKG-INFO +77 -0
  46. mpl_depth_style-0.6.1/mpl_depth_style.egg-info/SOURCES.txt +52 -0
  47. mpl_depth_style-0.6.1/mpl_depth_style.egg-info/dependency_links.txt +1 -0
  48. mpl_depth_style-0.6.1/mpl_depth_style.egg-info/requires.txt +7 -0
  49. mpl_depth_style-0.6.1/mpl_depth_style.egg-info/top_level.txt +1 -0
  50. mpl_depth_style-0.6.1/pyproject.toml +22 -0
  51. mpl_depth_style-0.6.1/setup.cfg +4 -0
  52. mpl_depth_style-0.6.1/tests/test_charts.py +48 -0
  53. mpl_depth_style-0.6.1/tests/test_integration.py +467 -0
  54. mpl_depth_style-0.6.1/tests/test_plotting_api.py +145 -0
@@ -0,0 +1,9 @@
1
+ include examples/*.py
2
+ include examples/reference/*.py
3
+ include data/*.npz data/README.md data/LICENSE-my-mpl-style.txt
4
+ include tests/test_*.py
5
+ include docs/*.md
6
+ include README.zh-CN.md
7
+ recursive-include docs/gallery *.png
8
+ include benchmarks/*.py
9
+ recursive-include benchmarks/results *.md *.png *.json
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: mpl-depth-style
3
+ Version: 0.6.1
4
+ Summary: Scientific 3D plotting with VTK and native Matplotlib axes
5
+ Project-URL: Repository, https://github.com/guessable/mpl-depth-style
6
+ Project-URL: Documentation, https://github.com/guessable/mpl-depth-style/blob/main/docs/plot_catalog.md
7
+ Project-URL: Issues, https://github.com/guessable/mpl-depth-style/issues
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: numpy>=1.25
11
+ Requires-Dist: matplotlib<3.12,>=3.11
12
+ Requires-Dist: vtk<10,>=9.4
13
+ Requires-Dist: my-mpl-style>=0.3.3
14
+ Provides-Extra: test
15
+ Requires-Dist: pytest>=8; extra == "test"
16
+
17
+ # mpl-depth-style
18
+
19
+ [简体中文](https://github.com/guessable/mpl-depth-style/blob/main/README.zh-CN.md)
20
+
21
+ `mpl-depth-style` adds a VTK-backed `vtk3d` projection to Matplotlib. Draw NumPy data as gridded surfaces, triangle meshes, isosurfaces, lines, and scatter plots. Use Matplotlib for axes, camera controls, colorbars, layout, and figure export.
22
+
23
+ ## Installation
24
+
25
+ From the root of a source checkout, run `python -m pip install .`.
26
+
27
+ To install a published release from PyPI, run `python -m pip install mpl-depth-style`.
28
+
29
+ Requires Python 3.11+, NumPy 1.25+, Matplotlib 3.11.x, VTK 9.4–9.x, and a working OpenGL context. For headless rendering, see the [export guide](https://github.com/guessable/mpl-depth-style/blob/main/docs/examples.md#export-and-cleanup).
30
+
31
+ ## Quickstart
32
+
33
+ Import `mpl_depth_style` to register the `vtk3d` projection. Call `mpl_depth_style.plot_rc()` before creating a figure to set typography, 2D styling, and a seven-color series cycle. See the [style preview](docs/scene.md#plot_rc).
34
+
35
+ ```python
36
+ import matplotlib.pyplot as plt
37
+ import numpy as np
38
+ import mpl_depth_style
39
+
40
+ mpl_depth_style.plot_rc()
41
+ t = np.linspace(-2, 2, 201)
42
+ x, y = np.meshgrid(t, t)
43
+ z = np.exp(x * np.sin(y))
44
+
45
+ fig = plt.figure(figsize=(9, 4), layout="constrained")
46
+ ax = fig.add_subplot(121, projection="vtk3d")
47
+ surface = ax.plot_surface(x, y, z, cmap=plt.get_cmap())
48
+ mpl_depth_style.ax3D_setting(ax)
49
+ ax.set(xlabel="x", ylabel="y", zlabel="u")
50
+ fig.colorbar(surface, ax=ax, shrink=.7)
51
+
52
+ profile = fig.add_subplot(122)
53
+ profile.plot(t, np.exp(t))
54
+ profile.set(xlabel="x", ylabel="u", title=r"$y=\pi/2$")
55
+
56
+ fig.savefig("surface.png", dpi=180)
57
+ plt.show()
58
+ ```
59
+
60
+ Use `ax.view_init()` to change the view and `surface.set_heights()` or `surface.set_values()` to update data. Multiple plots on the same axes share the VTK depth buffer.
61
+
62
+ `ax3D_setting` applies equal data scaling, an orthographic view, and projected ticks with regular-weight labels. Omitted limits and tick locations use the current axes settings. Pass `grid=False` to hide the 3D grid on that subplot.
63
+
64
+ ## Examples
65
+
66
+ | Intersecting scalar slices | Random-field zero isosurface |
67
+ | --- | --- |
68
+ | ![Three intersecting scalar slices with a shared colorbar](docs/gallery/intersecting_scalar_slices.png) | ![Green zero isosurface of a seeded random field](docs/gallery/random_field_isosurface.png) |
69
+ | [Documentation](docs/api.md#plot_surface) · [Source code](examples/intersecting_scalar_slices.py) | [Documentation](docs/api.md#plot_isosurface) · [Source code](examples/random_field_isosurface.py) |
70
+
71
+ ## Documentation
72
+
73
+ - [Gallery](https://github.com/guessable/mpl-depth-style/blob/main/docs/plot_catalog.md) · Browse figures with their API references and runnable Python sources.
74
+ - [Examples and export](https://github.com/guessable/mpl-depth-style/blob/main/docs/examples.md) · Run a complete script or save a figure.
75
+ - [Example datasets](https://github.com/guessable/mpl-depth-style/blob/main/data/README.md) · Load triangle meshes from NumPy archives.
76
+ - API reference · [Plotting](https://github.com/guessable/mpl-depth-style/blob/main/docs/api.md) and [Styles and plot handles](https://github.com/guessable/mpl-depth-style/blob/main/docs/scene.md).
77
+ - [Benchmarks](https://github.com/guessable/mpl-depth-style/blob/main/docs/examples.md#tests-and-benchmarks) · Measure plot construction and compare rendering with mplot3d.
@@ -0,0 +1,61 @@
1
+ # mpl-depth-style
2
+
3
+ [简体中文](https://github.com/guessable/mpl-depth-style/blob/main/README.zh-CN.md)
4
+
5
+ `mpl-depth-style` adds a VTK-backed `vtk3d` projection to Matplotlib. Draw NumPy data as gridded surfaces, triangle meshes, isosurfaces, lines, and scatter plots. Use Matplotlib for axes, camera controls, colorbars, layout, and figure export.
6
+
7
+ ## Installation
8
+
9
+ From the root of a source checkout, run `python -m pip install .`.
10
+
11
+ To install a published release from PyPI, run `python -m pip install mpl-depth-style`.
12
+
13
+ Requires Python 3.11+, NumPy 1.25+, Matplotlib 3.11.x, VTK 9.4–9.x, and a working OpenGL context. For headless rendering, see the [export guide](https://github.com/guessable/mpl-depth-style/blob/main/docs/examples.md#export-and-cleanup).
14
+
15
+ ## Quickstart
16
+
17
+ Import `mpl_depth_style` to register the `vtk3d` projection. Call `mpl_depth_style.plot_rc()` before creating a figure to set typography, 2D styling, and a seven-color series cycle. See the [style preview](docs/scene.md#plot_rc).
18
+
19
+ ```python
20
+ import matplotlib.pyplot as plt
21
+ import numpy as np
22
+ import mpl_depth_style
23
+
24
+ mpl_depth_style.plot_rc()
25
+ t = np.linspace(-2, 2, 201)
26
+ x, y = np.meshgrid(t, t)
27
+ z = np.exp(x * np.sin(y))
28
+
29
+ fig = plt.figure(figsize=(9, 4), layout="constrained")
30
+ ax = fig.add_subplot(121, projection="vtk3d")
31
+ surface = ax.plot_surface(x, y, z, cmap=plt.get_cmap())
32
+ mpl_depth_style.ax3D_setting(ax)
33
+ ax.set(xlabel="x", ylabel="y", zlabel="u")
34
+ fig.colorbar(surface, ax=ax, shrink=.7)
35
+
36
+ profile = fig.add_subplot(122)
37
+ profile.plot(t, np.exp(t))
38
+ profile.set(xlabel="x", ylabel="u", title=r"$y=\pi/2$")
39
+
40
+ fig.savefig("surface.png", dpi=180)
41
+ plt.show()
42
+ ```
43
+
44
+ Use `ax.view_init()` to change the view and `surface.set_heights()` or `surface.set_values()` to update data. Multiple plots on the same axes share the VTK depth buffer.
45
+
46
+ `ax3D_setting` applies equal data scaling, an orthographic view, and projected ticks with regular-weight labels. Omitted limits and tick locations use the current axes settings. Pass `grid=False` to hide the 3D grid on that subplot.
47
+
48
+ ## Examples
49
+
50
+ | Intersecting scalar slices | Random-field zero isosurface |
51
+ | --- | --- |
52
+ | ![Three intersecting scalar slices with a shared colorbar](docs/gallery/intersecting_scalar_slices.png) | ![Green zero isosurface of a seeded random field](docs/gallery/random_field_isosurface.png) |
53
+ | [Documentation](docs/api.md#plot_surface) · [Source code](examples/intersecting_scalar_slices.py) | [Documentation](docs/api.md#plot_isosurface) · [Source code](examples/random_field_isosurface.py) |
54
+
55
+ ## Documentation
56
+
57
+ - [Gallery](https://github.com/guessable/mpl-depth-style/blob/main/docs/plot_catalog.md) · Browse figures with their API references and runnable Python sources.
58
+ - [Examples and export](https://github.com/guessable/mpl-depth-style/blob/main/docs/examples.md) · Run a complete script or save a figure.
59
+ - [Example datasets](https://github.com/guessable/mpl-depth-style/blob/main/data/README.md) · Load triangle meshes from NumPy archives.
60
+ - API reference · [Plotting](https://github.com/guessable/mpl-depth-style/blob/main/docs/api.md) and [Styles and plot handles](https://github.com/guessable/mpl-depth-style/blob/main/docs/scene.md).
61
+ - [Benchmarks](https://github.com/guessable/mpl-depth-style/blob/main/docs/examples.md#tests-and-benchmarks) · Measure plot construction and compare rendering with mplot3d.
@@ -0,0 +1,63 @@
1
+ # mpl-depth-style
2
+
3
+ [English](README.md)
4
+
5
+ `mpl-depth-style` 为 Matplotlib 添加由 VTK 渲染的 `vtk3d` 投影。可将 NumPy 数据绘制为网格曲面、三角网格、等值面、线和散点。坐标轴、视角、色条、布局和导出沿用 Matplotlib。
6
+
7
+ ## 安装
8
+
9
+ 从源码安装时,在仓库根目录运行 `python -m pip install .`。
10
+
11
+ 从 PyPI 安装已发布版本时,运行 `python -m pip install mpl-depth-style`。
12
+
13
+ 运行需要 Python 3.11+、NumPy 1.25+、Matplotlib 3.11.x、VTK 9.4–9.x 和可用的 OpenGL 上下文。无显示环境的配置见[导出指南](docs/examples.md#export-and-cleanup)。
14
+
15
+ ## 快速开始
16
+
17
+ 导入 `mpl_depth_style` 注册 `vtk3d` 投影。创建图形前调用 `mpl_depth_style.plot_rc()`,设置字体、二维图样式和七色循环。参见[样式示例](docs/scene.md#plot_rc)。
18
+
19
+ ```python
20
+ import matplotlib.pyplot as plt
21
+ import numpy as np
22
+ import mpl_depth_style
23
+
24
+ mpl_depth_style.plot_rc()
25
+ t = np.linspace(-2, 2, 201)
26
+ x, y = np.meshgrid(t, t)
27
+ z = np.exp(x * np.sin(y))
28
+
29
+ fig = plt.figure(figsize=(9, 4), layout="constrained")
30
+ ax = fig.add_subplot(121, projection="vtk3d")
31
+ surface = ax.plot_surface(x, y, z, cmap=plt.get_cmap())
32
+ mpl_depth_style.ax3D_setting(ax)
33
+ ax.set(xlabel="x", ylabel="y", zlabel="u")
34
+ fig.colorbar(surface, ax=ax, shrink=.7)
35
+
36
+ profile = fig.add_subplot(122)
37
+ profile.plot(t, np.exp(t))
38
+ profile.set(xlabel="x", ylabel="u", title=r"$y=\pi/2$")
39
+
40
+ fig.savefig("surface.png", dpi=180)
41
+ plt.show()
42
+ ```
43
+
44
+ 用 `ax.view_init()` 调整视角,用 `surface.set_heights()` 或 `surface.set_values()` 更新数据。同一个坐标轴上的多个 VTK 图元共用深度缓冲区。
45
+
46
+ `ax3D_setting` 为三维子图设置等比例、正交视角和常规字重刻度。省略范围或刻度位置时使用坐标轴的当前设置。传入 `grid=False` 可以关闭该子图的网格。
47
+
48
+ ## 绘图示例
49
+
50
+ | 三张相交的标量切片 | 随机场的零等值面 |
51
+ | --- | --- |
52
+ | ![三张共用色条的相交标量切片](docs/gallery/intersecting_scalar_slices.png) | ![固定种子生成的绿色零等值面](docs/gallery/random_field_isosurface.png) |
53
+ | [文档](docs/api.md#plot_surface) · [源代码](examples/intersecting_scalar_slices.py) | [文档](docs/api.md#plot_isosurface) · [源代码](examples/random_field_isosurface.py) |
54
+
55
+ ## 文档
56
+
57
+ 详细文档采用英文。
58
+
59
+ - [图集](docs/plot_catalog.md) · 每张图都附有 API 文档和可运行的 Python 源代码链接。
60
+ - [示例与导出](docs/examples.md) · 运行完整脚本或保存图形。
61
+ - [示例数据](data/README.md) · 查看三角网格和 NumPy 文件格式。
62
+ - API 参考 · [绘图](docs/api.md)和[样式和图元句柄](docs/scene.md)。
63
+ - [性能测试](docs/examples.md#tests-and-benchmarks) · 查看建图耗时和与 mplot3d 的渲染对比。
@@ -0,0 +1,85 @@
1
+ """Measure construction time for the five vtk3d plotting methods."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+ import platform
6
+ from statistics import median
7
+ from time import perf_counter
8
+
9
+ import matplotlib
10
+ matplotlib.use("Agg")
11
+ import matplotlib.pyplot as plt
12
+ import numpy as np
13
+ import vtk
14
+
15
+ import mpl_depth_style
16
+
17
+
18
+ def workloads(ax, data_dir):
19
+ t = np.linspace(-2, 2, 600)
20
+ x, y = np.meshgrid(t, t, sparse=True)
21
+ heights = np.sin(x) * np.cos(y)
22
+
23
+ with np.load(data_dir / "cheese.npz", allow_pickle=False) as data:
24
+ a, b, c = data["vertices"].T
25
+ faces = data["elements"]
26
+ colors = a * np.sin(c) + b * np.sin(a ** 2)
27
+
28
+ coords = np.linspace(-1, 1, 128)
29
+ X, Y, Z = np.meshgrid(coords, coords, coords, sparse=True)
30
+ volume = X ** 2 + Y ** 2 + Z ** 2
31
+ volume_colors = X + Y + Z
32
+
33
+ u = np.linspace(0, 8 * np.pi, 250_000)
34
+ line = (np.cos(u), np.sin(u), u)
35
+ points = np.random.default_rng(42).uniform(-1, 1, size=(3, 250_000))
36
+ return {
37
+ "plot_surface": lambda: ax.plot_surface(t, t, heights, cmap="viridis", lighting="gouraud"),
38
+ "plot_trisurf": lambda: ax.plot_trisurf(a, b, c, triangles=faces, values=colors, cmap="viridis"),
39
+ "plot_isosurface": lambda: ax.plot_isosurface(
40
+ volume, level=.5, coordinates=(coords,) * 3, color_values=volume_colors, cmap="viridis"
41
+ ),
42
+ "plot": lambda: ax.plot(*line),
43
+ "scatter": lambda: ax.scatter(*points, s=20, c="tab:blue"),
44
+ }
45
+
46
+
47
+ def measure(draw, repeats):
48
+ samples = []
49
+ for index in range(repeats + 3):
50
+ start = perf_counter()
51
+ handles = draw()
52
+ elapsed = (perf_counter() - start) * 1000
53
+ for handle in handles if isinstance(handles, list) else [handles]:
54
+ handle.remove()
55
+ if index >= 3:
56
+ samples.append(elapsed)
57
+ return {"median_ms": median(samples), "samples_ms": samples}
58
+
59
+
60
+ def main():
61
+ cli = argparse.ArgumentParser(description=__doc__)
62
+ cli.add_argument("--repeats", type=int, default=25)
63
+ cli.add_argument("--data-dir", type=Path, default=Path(__file__).resolve().parents[1] / "data")
64
+ args = cli.parse_args()
65
+ if args.repeats < 1:
66
+ cli.error("--repeats must be positive")
67
+ fig, ax = plt.subplots(subplot_kw={"projection": "vtk3d"})
68
+ ax.set_autoscale_on(False)
69
+ try:
70
+ results = {name: measure(draw, args.repeats) for name, draw in workloads(ax, args.data_dir).items()}
71
+ finally:
72
+ ax.remove()
73
+ plt.close(fig)
74
+ print(json.dumps({
75
+ "platform": platform.platform(),
76
+ "python": platform.python_version(),
77
+ "numpy": np.__version__,
78
+ "matplotlib": matplotlib.__version__,
79
+ "vtk": vtk.vtkVersion.GetVTKVersion(),
80
+ "results": results,
81
+ }, indent=2))
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
@@ -0,0 +1,276 @@
1
+ """Replot and benchmark guessable/my-mpl-style data with both renderers."""
2
+ from argparse import ArgumentParser
3
+ from importlib.metadata import version
4
+ from io import BytesIO
5
+ import json
6
+ from pathlib import Path
7
+ import platform
8
+ import subprocess
9
+ import sys
10
+ from time import perf_counter
11
+
12
+ import matplotlib
13
+ matplotlib.use("Agg")
14
+ import matplotlib.pyplot as plt
15
+ from matplotlib.colors import LightSource, Normalize
16
+ import numpy as np
17
+ from skimage import __version__ as skimage_version
18
+ from skimage.measure import marching_cubes
19
+ import vtk
20
+
21
+ import mpl_depth_style as m
22
+
23
+
24
+ MPL = "Matplotlib"
25
+ VTK = "mpl-depth-style"
26
+ ELEVATION = 30
27
+ AZIMUTH = -127.5
28
+
29
+
30
+ def _close_figure(figure):
31
+ for ax in figure.axes:
32
+ if isinstance(ax, m.VtkAxes):
33
+ ax.remove()
34
+ plt.close(figure)
35
+
36
+
37
+ def _mesh(root, name):
38
+ with np.load(root/"data"/f"{name}.npz", allow_pickle=False) as data:
39
+ xyz, triangles = data["vertices"], data["elements"]
40
+ values = None
41
+ if name == "cheese":
42
+ x,y,z = xyz.T
43
+ values = x*np.sin(z) + y*np.sin(x*x)
44
+ return name, xyz, triangles, values
45
+
46
+
47
+ def _draw_triangles(ax, renderer, data, native_aa, dpi=100):
48
+ name, xyz, triangles, values = data
49
+ x,y,z = xyz.T
50
+ if values is not None:
51
+ # Match the source example's mean per triangle, including normalization.
52
+ face_values = values[triangles].mean(axis=1)
53
+ norm = Normalize(float(values.min()), float(values.max()))
54
+ if renderer == MPL:
55
+ h = ax.plot_trisurf(x,y,z,triangles=triangles,cmap="viridis",norm=norm,
56
+ antialiased=native_aa,linewidth=0,shade=False)
57
+ h.set_array(face_values)
58
+ return h
59
+ return ax.plot_trisurf(x, y, z, triangles=triangles, values=face_values, association="cell", cmap="viridis", norm=norm)
60
+ if renderer == MPL:
61
+ return ax.plot_trisurf(x,y,z,triangles=triangles,color="#e8eef5",edgecolor="#2b5f8a",
62
+ linewidth=.35,antialiased=native_aa,shade=False)
63
+ # Matplotlib expects points, whereas the VTK draw path uses output pixels.
64
+ return ax.plot_trisurf(x, y, z, triangles=triangles, facecolor="#e8eef5", edgecolor="#2b5f8a", linewidth=.35*dpi/72)
65
+
66
+
67
+ def _axes_parameters(data):
68
+ name,xyz,_,_ = data
69
+ lo,hi = xyz.min(axis=0),xyz.max(axis=0)
70
+ if name == "cheese":
71
+ ticks = ([-1,0,1],)*3
72
+ else:
73
+ lo[2],hi[2] = -.35,.35
74
+ ticks = ([-.8,-.4,0,.4,.8],[-.3,0,.3],[-.3,0,.3])
75
+ return list(zip(lo,hi)), ticks
76
+
77
+
78
+ def _axes(fig, loc, renderer, aa=2):
79
+ settings = {"projection":"3d"} if renderer == MPL else {"projection":"vtk3d","antialiasing":aa}
80
+ return fig.add_subplot(*loc, **settings)
81
+
82
+
83
+ def _format(ax, limits, ticks, source_style=None):
84
+ if source_style is not None:
85
+ source_style(ax,*limits,*ticks)
86
+ else:
87
+ ax.set(xticks=ticks[0],yticks=ticks[1],zticks=ticks[2])
88
+ ax.set(xlim=limits[0],ylim=limits[1],zlim=limits[2])
89
+ ax.set_aspect("equal")
90
+ ax.set_proj_type("ortho")
91
+ ax.view_init(elev=ELEVATION,azim=AZIMUTH)
92
+ ax.set_xlabel("$x$",labelpad=-3)
93
+ ax.set_ylabel("$y$",labelpad=-3)
94
+ ax.set_zlabel("$z$",labelpad=-3)
95
+
96
+
97
+ def _native_iso(ax, coords, volume, light):
98
+ spacing = tuple(c[1]-c[0] for c in coords)
99
+ xyz,tri,_,_ = marching_cubes(volume,0,spacing=spacing,allow_degenerate=False)
100
+ xyz += [c[0] for c in coords]
101
+ ax.plot_trisurf(*xyz.T,triangles=tri,color="#18b83e",linewidth=0,
102
+ antialiased=False,shade=True,lightsource=light)
103
+ return len(tri), np.column_stack((xyz.min(axis=0),xyz.max(axis=0))).tolist()
104
+
105
+
106
+ def render(root, output, meshes):
107
+ sys.path.insert(0,str(root/"src"))
108
+ from my_mpl_style import ax_setting3D, plot_rc
109
+
110
+ with matplotlib.rc_context():
111
+ plot_rc(save_dpi=215,save_bbox="standard")
112
+ fig = plt.figure(figsize=(9.8,8.6))
113
+ fig.subplots_adjust(left=.055,right=.93,bottom=.045,top=.895,wspace=.12,hspace=.15)
114
+ fig.suptitle(r"Triangular meshes $u=x\sin z+y\sin(x^2)$",fontsize=16,y=.975)
115
+ for row,renderer in enumerate((MPL,VTK)):
116
+ for col,data in enumerate(meshes):
117
+ name = data[0]
118
+ ax = _axes(fig,(2,2,row*2+col+1),renderer)
119
+ h = _draw_triangles(ax,renderer,data,native_aa=name=="peanut",dpi=215)
120
+ _format(ax,*_axes_parameters(data),source_style=ax_setting3D)
121
+ title = "Matplotlib" if renderer == MPL else "VTK · 2× supersampling"
122
+ ax.set_title(f"{name} | {title}",fontsize=13,pad=9)
123
+ if name == "cheese":
124
+ cb = fig.colorbar(h,ax=ax,shrink=.66,fraction=.04,pad=.04)
125
+ cb.ax.set_title("$u$",pad=7)
126
+ fig.savefig(output/"trisurf_comparison.png",facecolor="white")
127
+ _close_figure(fig)
128
+
129
+ fig = plt.figure(figsize=(12,8.1))
130
+ fig.subplots_adjust(left=.055,right=.965,bottom=.055,top=.93,wspace=.105,hspace=.15)
131
+ light = LightSource(azdeg=300,altdeg=38)
132
+ iso_data = []
133
+ for col,mean in enumerate((-.2,-.35,-.43)):
134
+ file = root/"data"/f"pfc_3d_{col+1}_T3000.npz"
135
+ with np.load(file,allow_pickle=False) as data:
136
+ coords = [data[a] for a in "xyz"]
137
+ volume = data["u_t3000"]
138
+ ax = _axes(fig,(2,3,col+1),MPL)
139
+ count_native,bounds_native = _native_iso(ax,coords,volume,light)
140
+ _format(ax,[(0,50)]*3,[[0,25,50]]*3,source_style=ax_setting3D)
141
+ ax.set_title(rf"$\bar{{\phi}}={mean:.2f}$ | Matplotlib",fontsize=13,pad=9)
142
+ ax = _axes(fig,(2,3,col+4),VTK)
143
+ # Source marching cubes treats the stored volume as (x,y,z).
144
+ # mpl-depth-style accepts array order (y,x,z).
145
+ h = ax.plot_isosurface(volume.transpose(1, 0, 2), coordinates=coords, level=0,
146
+ facecolor="#18b83e", ambient=.33, diffuse=.67, specular=.06)
147
+ source = vtk.vtkLight()
148
+ source.SetLightTypeToSceneLight()
149
+ source.SetPosition(*light.direction)
150
+ ax.renderer.AddLight(source)
151
+ _format(ax,[(0,50)]*3,[[0,25,50]]*3,source_style=ax_setting3D)
152
+ ax.set_title(rf"$\bar{{\phi}}={mean:.2f}$ | VTK",fontsize=13,pad=9)
153
+ count_vtk = h.data.GetNumberOfPolys()
154
+ bounds_vtk = np.reshape(h.data.GetBounds(),(3,2))
155
+ np.testing.assert_allclose(bounds_vtk,bounds_native,rtol=0,atol=1e-4)
156
+ iso_data.append({"file":file.name,"shape":volume.shape,
157
+ "matplotlib_triangles":count_native,"vtk_triangles":count_vtk,
158
+ "vtk_bounds":bounds_vtk.tolist(),"source_bounds":bounds_native})
159
+ fig.savefig(output/"isosurface_comparison.png",facecolor="white")
160
+ _close_figure(fig)
161
+ return iso_data
162
+
163
+
164
+ def _timed(callback):
165
+ start = perf_counter()
166
+ callback()
167
+ return (perf_counter()-start)*1000
168
+
169
+
170
+ def _summary(values):
171
+ return {"median_ms":round(float(np.median(values)),2),
172
+ "p95_ms":round(float(np.percentile(values,95)),2),
173
+ "samples_ms":[round(x,3) for x in values]}
174
+
175
+
176
+ def _phase_bench(data, renderer, sampling, rotations, repeats, exports, source_style=None):
177
+ name = data[0]
178
+ build,first,rotate,export = [],[],[],[]
179
+ cap = None
180
+ for i in range(repeats):
181
+ fig = plt.figure(figsize=(8,6),dpi=100)
182
+ ax = _axes(fig,(1,1,1),renderer,aa=sampling)
183
+ try:
184
+ _format(ax,*_axes_parameters(data),source_style=source_style)
185
+ start = perf_counter()
186
+ handle = _draw_triangles(ax,renderer,data,bool(sampling),dpi=100)
187
+ build.append((perf_counter()-start)*1000)
188
+ first.append(_timed(fig.canvas.draw))
189
+ if i+1 != repeats:
190
+ continue
191
+ if renderer == VTK:
192
+ cap = [line.strip() for line in ax.window.ReportCapabilities().splitlines()
193
+ if "OpenGL renderer string" in line]
194
+ for offset in np.linspace(-32,32,rotations):
195
+ ax.view_init(elev=ELEVATION,azim=AZIMUTH+offset)
196
+ rotate.append(_timed(fig.canvas.draw))
197
+ if name == "peanut" and renderer == VTK:
198
+ handle.set_linewidth(.35*200/72)
199
+ for j in range(exports):
200
+ ax.view_init(elev=ELEVATION,azim=AZIMUTH+2*(j+1))
201
+ with BytesIO() as stream:
202
+ export.append(_timed(lambda: fig.savefig(stream,format="png",dpi=200)))
203
+ finally:
204
+ _close_figure(fig)
205
+ return {"mesh":name,"vertices":len(data[1]),"triangles":len(data[2]),"renderer":renderer,
206
+ "antialiasing":sampling,"build":_summary(build),"first_canvas_draw":_summary(first),
207
+ "setup_to_first_image":_summary(np.add(build,first)),
208
+ "rotate":_summary(rotate),"png_200_dpi":_summary(export),"gpu":cap}
209
+
210
+
211
+ def _git_head(root):
212
+ return subprocess.run(["git","-C",str(root),"rev-parse","HEAD"],
213
+ check=True,text=True,capture_output=True).stdout.strip()
214
+
215
+
216
+ def main():
217
+ cli = ArgumentParser(description=__doc__)
218
+ cli.add_argument("checkout",type=Path)
219
+ cli.add_argument("output",type=Path)
220
+ cli.add_argument("--mode",choices=("all","render","benchmark"),default="all")
221
+ cli.add_argument("--rotations",type=int,default=12)
222
+ cli.add_argument("--fresh-figures",type=int,default=3)
223
+ cli.add_argument("--exports",type=int,default=3)
224
+ cli.add_argument("--mesh",choices=("all","cheese","peanut"),default="all")
225
+ cli.add_argument("--renderer",choices=("all","matplotlib","vtk"),default="all")
226
+ cli.add_argument("--vtk-aa",type=int,nargs="+",choices=(1,2,3,4),default=[1,2])
227
+ cli.add_argument("--source-style",action="store_true",help="time with my-mpl-style axes on both sides")
228
+ args = cli.parse_args()
229
+ if min(args.rotations,args.fresh_figures,args.exports) < 2:
230
+ cli.error("each timing stage needs at least two samples")
231
+ root = args.checkout.resolve()
232
+ dest = args.output.resolve()
233
+ dest.mkdir(exist_ok=True,parents=True)
234
+ head = _git_head(root)
235
+ meshes = [_mesh(root,key) for key in ("cheese","peanut")]
236
+ if args.mode in ("all","render"):
237
+ geometry = render(root,dest,meshes)
238
+ (dest/"isosurface_geometry.json").write_text(
239
+ json.dumps({"source_commit":head,"geometry":geometry},indent=2)+"\n",encoding="utf-8")
240
+ print("Saved both comparison figures.",flush=True)
241
+ if args.mode in ("all","benchmark"):
242
+ rows = []
243
+ source_style = None
244
+ if args.source_style:
245
+ sys.path.insert(0,str(root/"src"))
246
+ from my_mpl_style import ax_setting3D as source_style
247
+ # Warm the font cache and both renderers on the small mesh first.
248
+ for renderer,aa in ((MPL,True),(VTK,2)):
249
+ f = plt.figure(figsize=(4,3),dpi=100)
250
+ a = _axes(f,(1,1,1),renderer,aa)
251
+ _draw_triangles(a,renderer,meshes[1],True)
252
+ f.canvas.draw()
253
+ _close_figure(f)
254
+ for mesh in (data for data in meshes if args.mesh in ("all",data[0])):
255
+ variants = []
256
+ if args.renderer in ("all","matplotlib"):
257
+ variants.extend([(MPL,False),(MPL,True)])
258
+ if args.renderer in ("all","vtk"):
259
+ variants.extend((VTK,aa) for aa in args.vtk_aa)
260
+ for renderer,aa in variants if mesh[0]=="cheese" else reversed(variants):
261
+ print(f"Timing {mesh[0]} / {renderer} / AA={aa}",flush=True)
262
+ rows.append(_phase_bench(mesh,renderer,aa,args.rotations,args.fresh_figures,args.exports,source_style))
263
+ stats = {"source_commit":head,"platform":platform.platform(),
264
+ "python":platform.python_version(),"matplotlib":matplotlib.__version__,
265
+ "mpl_depth_style":version("mpl-depth-style"),"vtk":vtk.vtkVersion.GetVTKVersion(),
266
+ "numpy":np.__version__,"scikit_image":skimage_version,"backend":"Agg",
267
+ "canvas_px":[800,600],"png_px":[1600,1200],
268
+ "axes_presentation":"reference" if args.source_style else "renderer defaults",
269
+ "rotation_frames":args.rotations,"fresh_figures":args.fresh_figures,
270
+ "exports":args.exports,"results":rows}
271
+ (dest/"trisurf_timings.json").write_text(json.dumps(stats,indent=2)+"\n",encoding="utf-8")
272
+ print("Saved detailed timing samples.",flush=True)
273
+
274
+
275
+ if __name__ == "__main__":
276
+ main()
@@ -0,0 +1,61 @@
1
+ # Triangle mesh and isosurface benchmarks
2
+
3
+ These comparisons were recorded with `mpl3d-vtk` 0.5.0 using the original datasets from [my-mpl-style at `d3ab92f`](https://github.com/guessable/my-mpl-style/tree/d3ab92fcaef3852701dfc2cccd22c90b5c0ecb2c). The upper row of each image uses the built-in Matplotlib `mplot3d` projection. The lower row uses `vtk3d`.
4
+
5
+ ## Triangle meshes
6
+
7
+ Both renderers receive the complete meshes and the same orthographic view. The `cheese` mesh uses the original per-face averages and Viridis normalization. The `peanut` mesh keeps the blue edges and light faces, with the duplicated negative X tick corrected to show the positive endpoint. [Original triangle mesh example](https://github.com/guessable/my-mpl-style/blob/d3ab92fcaef3852701dfc2cccd22c90b5c0ecb2c/examples/tri_surface.py)
8
+
9
+ ![Cheese and peanut meshes. Upper row mplot3d, lower row vtk3d with 2× supersampling](trisurf_comparison.png)
10
+
11
+ [Documentation](../../../docs/api.md#plot_trisurf) · [Source code](../../my_mpl_style.py)
12
+
13
+ ### Rendering time
14
+
15
+ All times are in milliseconds. Columns show medians except for rotation P95. Bold rows pair each original Matplotlib antialiasing setting with the default `vtk3d` 2× supersampling.
16
+
17
+ | Mesh | Triangles | Renderer | Build | First image | Rotation | Rotation P95 | PNG |
18
+ | --- | ---: | --- | ---: | ---: | ---: | ---: | ---: |
19
+ | `cheese` | 307,708 | **mplot3d, AA off** | 25.37 | 879.35 | 820.03 | 882.70 | 960.62 |
20
+ | `cheese` | 307,708 | mplot3d, AA on | 25.92 | 877.90 | 824.67 | 882.20 | 996.11 |
21
+ | `cheese` | 307,708 | **vtk3d, 2× supersampling** | 12.37 | 77.97 | 25.09 | 30.89 | 133.49 |
22
+ | `peanut` | 4,872 | mplot3d, AA off | 0.51 | 45.90 | 39.54 | 43.54 | 101.90 |
23
+ | `peanut` | 4,872 | **mplot3d, AA on** | 0.60 | 47.86 | 39.76 | 41.58 | 110.35 |
24
+ | `peanut` | 4,872 | **vtk3d, 2× supersampling** | 0.49 | 50.85 | 23.99 | 28.34 | 102.10 |
25
+
26
+ The large `cheese` mesh rotates 32.7× faster with `vtk3d` on this host. The smaller `peanut` mesh rotates 1.66× faster, with a slightly longer first draw. Compare the matched rows before applying these results to a different mesh or output size. [Raw samples and environment](trisurf_timings.json)
27
+
28
+ ## Zero isosurfaces
29
+
30
+ Both pipelines extract `φ = 0` from three original 64×64×64 `u_t3000` fields. The original script uses scikit-image marching cubes followed by `plot_trisurf`. The VTK pipeline transposes the first two array axes to `(ny, nx, nz)` and extracts the surfaces with Flying Edges.
31
+
32
+ The paired meshes have identical triangle counts and axis-aligned bounds in this run. Matplotlib shades individual triangle faces. VTK interpolates lighting across vertex normals, which produces smoother lighting in the lower row. [Original isosurface example](https://github.com/guessable/my-mpl-style/blob/d3ab92fcaef3852701dfc2cccd22c90b5c0ecb2c/examples/isosurface.py) · [Geometry checks](isosurface_geometry.json)
33
+
34
+ | Mean φ in the source example | Triangles in either renderer |
35
+ | --- | ---: |
36
+ | −0.20 | 179,402 |
37
+ | −0.35 | 138,060 |
38
+ | −0.43 | 107,440 |
39
+
40
+ ![Three zero isosurfaces. Upper row mplot3d with face shading, lower row vtk3d with interpolated lighting](isosurface_comparison.png)
41
+
42
+ [Documentation](../../../docs/api.md#plot_isosurface) · [Source code](../../my_mpl_style.py)
43
+
44
+ ## Benchmark setup
45
+
46
+ - Windows 11 with an NVIDIA GeForce RTX 2080 Ti. Python 3.13.5, NumPy 2.3.0, Matplotlib 3.11.0, VTK 9.6.1, scikit-image 0.26.0, and `mpl3d-vtk` 0.5.0.
47
+ - One subplot with an 800×600 Agg canvas, the upstream axes style, matched ranges, and identical view angles. PNG export renders at 1600×1200 and encodes to memory.
48
+ - Each variant uses five fresh figures, 20 rotation redraws, and five PNG exports. First image time combines plot construction and its first canvas draw. Rotation measures redraw time. Loading data, importing libraries, writing files, and processing GUI events are outside those intervals.
49
+
50
+ ## Reproduce the comparison
51
+
52
+ Install the local package and scikit-image. Clone the upstream data repository next to this checkout and select the recorded revision.
53
+
54
+ ```sh
55
+ python -m pip install . scikit-image
56
+ git clone https://github.com/guessable/my-mpl-style.git ../my-mpl-style
57
+ git -C ../my-mpl-style checkout d3ab92fcaef3852701dfc2cccd22c90b5c0ecb2c
58
+ python benchmarks/my_mpl_style.py ../my-mpl-style benchmark-output --mode all --source-style --rotations 20 --fresh-figures 5 --exports 5 --vtk-aa 2
59
+ ```
60
+
61
+ The output directory receives both PNGs, the triangle timing samples, and the isosurface geometry checks.