Skip to content

Commit 882e730

Browse files
feat(viz): Tidy3D Matplotlib Styles on Import (#2428)
* add automatic tidy3d matplotlib styles * refactor utils to remove get_hex_formatted_string function that is used only once * add unit test for setting the matplotlib styles on import * add changelog entry and export for the the reset_previous_style function * add docstring to rcParams test * add test for validating the material library rich representation * cleanup unused imports * fix formatting issues * move viz.py into its own module to prepare for refactoring * add the flexcompute tint palette * cleanup viz structure * refactor: split up large viz.py and add documentation * refactor: re-add fix to plot_sim_3d * fix: rename reset_previous_style to restore_matplotlib_rcparams * fix: typo * fix: move tidy3d style into mplstyle file * revert typo * fix: resolve merge conflict * fix: use exact module * fix: lint issues
1 parent e047cc6 commit 882e730

File tree

19 files changed

+3974
-511
lines changed

19 files changed

+3974
-511
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1414
- Added `eps_lim` keyword argument to `Simulation.plot_eps()` for manual control over the permittivity color limits.
1515
- Added `thickness` parameter to `LossyMetalMedium` for computing surface impedance of a thin conductor.
1616
- `priority` field in `Structure` and `MeshOverrideStructure` for setting the behavior in structure overlapping region. When its value is `None`, the priority is automatically determined based on the material property and simulation's `structure_priority_mode`.
17+
- Automatically apply `matplotlib` styles when importing `tidy3d` which can be reverted via the `td.restore_matplotlib_rcparams()` function.
1718

1819
### Fixed
1920
- Fixed bug in broadband adjoint source creation when forward simulation had a pulse amplitude greater than 1 or a nonzero pulse phase.

docs/api/index.rst

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ API |:computer:|
3333
constants
3434
abstract_base
3535
abstract_models
36+
viz
3637

3738
.. include:: /api/simulation.rst
3839
.. include:: /api/boundary_conditions.rst
@@ -58,4 +59,5 @@ API |:computer:|
5859
.. include:: /api/plugins/index.rst
5960
.. include:: /api/constants.rst
6061
.. include:: /api/abstract_base.rst
61-
.. include:: /api/abstract_models.rst
62+
.. include:: /api/abstract_models.rst
63+
.. include:: /api/viz.rst

docs/api/viz.rst

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
.. currentmodule:: tidy3d
2+
3+
Visualization and Plotting
4+
==========================
5+
6+
.. autosummary::
7+
:toctree: _autosummary/
8+
:template: module.rst
9+
10+
tidy3d.restore_matplotlib_rcparams
11+
tidy3d.VisualizationSpec

pyproject.toml

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ classifiers = [
1717
"Operating System :: OS Independent",
1818
]
1919
documentation = "https://docs.flexcompute.com/projects/tidy3d/en/latest/"
20+
include = [{ path = "tidy3d/style.mplstyle", format = ["sdist", "wheel"] }]
2021

2122
[tool.poetry.urls]
2223
"Bug Tracker" = "https://github.com/flexcompute/tidy3d/issues"
@@ -82,8 +83,8 @@ pyswarms = { version = "*", optional = true }
8283

8384
# pytorch
8485
torch = [
85-
{ version = "^2.2.0", source = "PyPI", platform = "darwin", optional = true },
86-
{ version = "^2.2.0", source = "torch-cpu", platform = "!=darwin", optional = true },
86+
{ version = "^2.2.0", source = "PyPI", platform = "darwin", optional = true },
87+
{ version = "^2.2.0", source = "torch-cpu", platform = "!=darwin", optional = true },
8788
]
8889

8990
# scikit-rf
@@ -275,7 +276,7 @@ ignore = [
275276
# TODO: remove --assert=plain when https://github.com/scipy/scipy/issues/22236 is resolved
276277
addopts = "--cov=tidy3d --doctest-modules -n auto --dist worksteal --assert=plain -m 'not numerical' "
277278
markers = [
278-
"numerical: marks numerical tests for adjoint gradients that require running simulations (deselect with '-m \"not numerical\"')",
279+
"numerical: marks numerical tests for adjoint gradients that require running simulations (deselect with '-m \"not numerical\"')",
279280
]
280281
env = ["MPLBACKEND=Agg", "OMP_NUM_THREADS=1"]
281282
doctest_optionflags = "NORMALIZE_WHITESPACE ELLIPSIS"

tests/test_components/test_viz.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import pytest
77
import tidy3d as td
88
from tidy3d import Box, Medium, Simulation, Structure
9-
from tidy3d.components.viz import Polygon, set_default_labels_and_title
9+
from tidy3d.components.viz import Polygon, restore_matplotlib_rcparams, set_default_labels_and_title
1010
from tidy3d.constants import inf
1111
from tidy3d.exceptions import Tidy3dKeyError
1212

@@ -222,7 +222,7 @@ def plot_with_multi_viz_spec(alphas, facecolors, edgecolors, rng, use_viz_spec=T
222222

223223
def test_no_matlab_install(monkeypatch):
224224
"""Test that the `VisualizationSpec` only throws a warning on validation if matplotlib is not installed."""
225-
monkeypatch.setattr("tidy3d.components.viz.MATPLOTLIB_IMPORTED", False)
225+
monkeypatch.setattr("tidy3d.components.viz.visualization_spec.MATPLOTLIB_IMPORTED", False)
226226

227227
EXPECTED_WARNING_MSG_PIECE = (
228228
"matplotlib was not successfully imported, but is required to validate colors"
@@ -330,3 +330,10 @@ def test_sim_plot_structures_fill():
330330
for patch in structure_patches[:1]:
331331
assert patch.get_fill(), "Should be filled when True"
332332
assert patch.get_facecolor() != "none", "Face color should be set"
333+
334+
335+
def test_tidy3d_matplotlib_style_application_on_import():
336+
"""Test restore_matplotlib_rcparams() to reset the automatically applied matplotlib.rcParams"""
337+
assert mpl.rcParams.get("axes.edgecolor") == "#ECEBEA"
338+
restore_matplotlib_rcparams()
339+
assert mpl.rcParams.get("axes.edgecolor") == mpl.rcParamsDefault.get("axes.edgecolor")

tests/test_material_library/test_material_library.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Tests material library functions and pretty printing"""
22

33
import tidy3d as td
4+
from rich.console import Console
45
from tidy3d.material_library.material_library import MaterialItemUniaxial
56

67

@@ -9,6 +10,12 @@ def test_material_library_summary():
910
print(td.material_library)
1011

1112

13+
def test_material_library_rich_console():
14+
"""Test the rich representation of the material library which validates its styles etc."""
15+
console = Console()
16+
console.print(td.material_library)
17+
18+
1219
def test_material_summary():
1320
"""Test the string method for each material in the material library."""
1421

tidy3d/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@
360360
SpaceTimeModulation,
361361
)
362362
from .components.transformation import RotationAroundAxis
363-
from .components.viz import VisualizationSpec
363+
from .components.viz import VisualizationSpec, restore_matplotlib_rcparams
364364

365365
# config
366366
from .config import config
@@ -649,6 +649,7 @@ def set_logging_level(level: str) -> None:
649649
"PECConformal",
650650
"SurfaceImpedance",
651651
"VisualizationSpec",
652+
"restore_matplotlib_rcparams",
652653
"EMESimulation",
653654
"EMESimulationData",
654655
"EMEMonitor",

0 commit comments

Comments
 (0)