Skip to content

Commit 55938f2

Browse files
committed
Lazy import matplotlib and scipy to allow minimal install
1 parent a0c3cfe commit 55938f2

File tree

12 files changed

+70
-38
lines changed

12 files changed

+70
-38
lines changed

tidy3d/components/autograd/functions.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from autograd.numpy.numpy_jvps import broadcast
77
from autograd.numpy.numpy_vjps import unbroadcast_f
88
from numpy.typing import NDArray
9-
from scipy.interpolate import RegularGridInterpolator
109

1110
from .types import InterpolationType
1211

@@ -127,6 +126,8 @@ def interpn(
127126
--------
128127
`scipy.interpolate.interpn <https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.interpn.html>`_
129128
"""
129+
from scipy.interpolate import RegularGridInterpolator
130+
130131
if method == "nearest":
131132
interp_fn = _evaluate_nearest
132133
elif method == "linear":

tidy3d/components/data/data_array.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
from typing import Any, Dict, List, Mapping, Union
77

88
import autograd.numpy as anp
9-
import dask
109
import h5py
1110
import numpy as np
1211
import xarray as xr
@@ -256,6 +255,8 @@ def from_file(cls, fname: str, group_path: str) -> Self:
256255

257256
def __hash__(self) -> int:
258257
"""Generate hash value for a :class:.`DataArray` instance, needed for custom components."""
258+
import dask
259+
259260
token_str = dask.base.tokenize(self)
260261
return hash(token_str)
261262

tidy3d/components/data/dataset.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,12 @@
99
import numpy as np
1010
import pydantic.v1 as pd
1111
import xarray as xr
12-
from matplotlib import pyplot as plt
13-
from matplotlib.tri import Triangulation
12+
13+
try:
14+
from matplotlib import pyplot as plt
15+
from matplotlib.tri import Triangulation
16+
except ImportError:
17+
pass
1418

1519
from ...constants import PICOSECOND_PER_NANOMETER_PER_KILOMETER, inf
1620
from ...exceptions import DataError, Tidy3dNotImplementedError, ValidationError

tidy3d/components/eme/simulation.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44

55
from typing import Dict, List, Literal, Optional, Tuple, Union
66

7-
import matplotlib as mpl
7+
try:
8+
import matplotlib as mpl
9+
except ImportError:
10+
pass
811
import numpy as np
912
import pydantic.v1 as pd
1013

tidy3d/components/geometry/base.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,11 @@
1111
import pydantic.v1 as pydantic
1212
import shapely
1313
import xarray as xr
14-
from matplotlib import patches
14+
15+
try:
16+
from matplotlib import patches
17+
except ImportError:
18+
pass
1519

1620
from ...constants import LARGE_NUMBER, MICROMETER, RADIAN, fp_eps, inf
1721
from ...exceptions import (

tidy3d/components/geometry/polyslab.py

+13-17
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import pydantic.v1 as pydantic
1111
import shapely
1212
from autograd.tracer import getval, isbox
13-
from matplotlib import path
1413

1514
from ...constants import LARGE_NUMBER, MICROMETER, fp_eps
1615
from ...exceptions import SetupError, ValidationError
@@ -478,6 +477,11 @@ def inside(
478477
with the same shape which is ``True`` for every point in zip(x, y, z) that is inside the
479478
volume of the :class:`Geometry`, and ``False`` otherwise.
480479
480+
Note
481+
----
482+
For slanted sidewalls, this function only works if x, y, and z are arrays produced by a
483+
``meshgrid call``, i.e. 3D arrays and each is constant along one axis.
484+
481485
Parameters
482486
----------
483487
x : np.ndarray[float]
@@ -523,13 +527,9 @@ def inside(
523527

524528
# vertical sidewall
525529
if math.isclose(self.sidewall_angle, 0):
526-
# face_polygon = self.make_shapely_polygon(self.reference_polygon)
527-
# fun_contain = contains_pointwise(face_polygon)
528-
# contains_vectorized = np.vectorize(fun_contain, signature="(n)->()")
529-
poly_path = path.Path(self.reference_polygon)
530-
contains_vectorized = poly_path.contains_points
531-
points_stacked = np.stack((xs_slab, ys_slab), axis=1)
532-
inside_polygon_slab = contains_vectorized(points_stacked)
530+
face_polygon = shapely.Polygon(self.reference_polygon)
531+
shapely.prepare(face_polygon)
532+
inside_polygon_slab = shapely.contains_xy(face_polygon, x=xs_slab, y=ys_slab)
533533
inside_polygon[inside_height] = inside_polygon_slab
534534
# slanted sidewall, offsetting vertices at each z
535535
else:
@@ -550,15 +550,11 @@ def _move_axis_reverse(arr):
550550
vertices_z = self._shift_vertices(
551551
self.middle_polygon, _move_axis(dist)[0, 0, z_i]
552552
)[0]
553-
# face_polygon = self.make_shapely_polygon(vertices_z)
554-
# fun_contain = contains_pointwise(face_polygon)
555-
# contains_vectorized = np.vectorize(fun_contain, signature="(n)->()")
556-
poly_path = path.Path(vertices_z)
557-
contains_vectorized = poly_path.contains_points
558-
points_stacked = np.stack(
559-
(x_axis[:, :, 0].flatten(), y_axis[:, :, 0].flatten()), axis=1
560-
)
561-
inside_polygon_slab = contains_vectorized(points_stacked)
553+
face_polygon = shapely.Polygon(vertices_z)
554+
shapely.prepare(face_polygon)
555+
xs = x_axis[:, :, 0].flatten()
556+
ys = y_axis[:, :, 0].flatten()
557+
inside_polygon_slab = shapely.contains_xy(face_polygon, x=xs, y=ys)
562558
inside_polygon_axis[:, :, z_i] = inside_polygon_slab.reshape(x_axis.shape[:2])
563559
inside_polygon = _move_axis_reverse(inside_polygon_axis)
564560
else:

tidy3d/components/heat_charge/simulation.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,11 @@
77

88
import numpy as np
99
import pydantic.v1 as pd
10-
from matplotlib import colormaps
10+
11+
try:
12+
from matplotlib import colormaps
13+
except ImportError:
14+
pass
1115

1216
from ...constants import VOLUMETRIC_HEAT_RATE, inf
1317
from ...exceptions import SetupError

tidy3d/components/parameter_perturbation.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,10 @@
66
from abc import ABC, abstractmethod
77
from typing import Callable, List, Optional, Tuple, Union
88

9-
import matplotlib.pyplot as plt
9+
try:
10+
import matplotlib.pyplot as plt
11+
except ImportError:
12+
pass
1013
import numpy as np
1114
import pydantic.v1 as pd
1215

tidy3d/components/scene.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@
55
from typing import Dict, List, Optional, Set, Tuple, Union
66

77
import autograd.numpy as np
8-
import matplotlib as mpl
9-
import matplotlib.pylab as plt
8+
9+
try:
10+
import matplotlib as mpl
11+
import matplotlib.pylab as plt
12+
from mpl_toolkits.axes_grid1 import make_axes_locatable
13+
except ImportError:
14+
pass
1015
import pydantic.v1 as pd
11-
from mpl_toolkits.axes_grid1 import make_axes_locatable
1216

1317
from ..constants import CONDUCTIVITY, THERMAL_CONDUCTIVITY, inf
1418
from ..exceptions import SetupError, Tidy3dError

tidy3d/components/simulation.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,12 @@
99
from typing import Dict, List, Optional, Set, Tuple, Union
1010

1111
import autograd.numpy as np
12-
import matplotlib as mpl
12+
13+
try:
14+
import matplotlib as mpl
15+
except ImportError:
16+
pass
17+
1318
import pydantic.v1 as pydantic
1419
import xarray as xr
1520

tidy3d/components/types.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@
99
from typing_extensions import Literal
1010
import autograd.numpy as np
1111
import pydantic.v1 as pydantic
12-
from matplotlib.axes import Axes
12+
13+
try:
14+
from matplotlib.axes import Axes
15+
except ImportError:
16+
Axes = None
1317
from shapely.geometry.base import BaseGeometry
1418
from typing_extensions import Annotated
1519

tidy3d/components/viz.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,18 @@
66
from html import escape
77
from typing import Any
88

9-
import matplotlib.pyplot as plt
10-
import matplotlib.ticker as ticker
119
import pydantic.v1 as pd
12-
from matplotlib.patches import ArrowStyle, PathPatch
13-
from matplotlib.path import Path
10+
11+
try:
12+
import matplotlib.pyplot as plt
13+
import matplotlib.ticker as ticker
14+
from matplotlib.patches import ArrowStyle, PathPatch
15+
from matplotlib.path import Path
16+
17+
# default arrow style
18+
arrow_style = ArrowStyle.Simple(head_length=12, head_width=9, tail_width=4)
19+
except ImportError:
20+
arrow_style = None
1421
from numpy import array, concatenate, inf, ones
1522

1623
from ..constants import UnitScaling
@@ -161,10 +168,6 @@ class PlotParams(AbstractPlotParams):
161168
STRUCTURE_EPS_CMAP = "gist_yarg"
162169
STRUCTURE_HEAT_COND_CMAP = "gist_yarg"
163170

164-
# default arrow style
165-
arrow_style = ArrowStyle.Simple(head_length=12, head_width=9, tail_width=4)
166-
167-
168171
"""=================================================================================================
169172
Descartes modified from https://pypi.org/project/descartes/ for Shapely >= 1.8.0
170173

0 commit comments

Comments
 (0)