Skip to content

Commit a56ab6e

Browse files
formatting
1 parent 747fdce commit a56ab6e

File tree

8 files changed

+84
-83
lines changed

8 files changed

+84
-83
lines changed

tidy3d/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,11 +124,11 @@
124124
FluxTimeDataArray,
125125
HeatDataArray,
126126
IndexedDataArray,
127-
IndexedVoltageDataArray,
128-
IndexedFieldDataArray,
127+
IndexedFieldDataArray,
129128
IndexedFieldTimeDataArray,
130129
IndexedFreqDataArray,
131130
IndexedTimeDataArray,
131+
IndexedVoltageDataArray,
132132
ModeAmpsDataArray,
133133
ModeIndexDataArray,
134134
PointDataArray,
@@ -626,7 +626,7 @@ def set_logging_level(level: str) -> None:
626626
"CellDataArray",
627627
"IndexedDataArray",
628628
"IndexedVoltageDataArray",
629-
"IndexedFieldDataArray",
629+
"IndexedFieldDataArray",
630630
"IndexedFieldTimeDataArray",
631631
"IndexedFreqDataArray",
632632
"IndexedTimeDataArray",

tidy3d/components/data/data_array.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1354,9 +1354,9 @@ class IndexedTimeDataArray(DataArray):
13541354
DATA_ARRAY_MAP = {data_array.__name__: data_array for data_array in DATA_ARRAY_TYPES}
13551355

13561356
IndexedDataArrayTypes = Union[
1357-
IndexedDataArray,
1358-
IndexedVoltageDataArray,
1359-
IndexedFieldDataArray,
1357+
IndexedDataArray,
1358+
IndexedVoltageDataArray,
1359+
IndexedFieldDataArray,
13601360
IndexedFieldTimeDataArray,
13611361
IndexedFreqDataArray,
13621362
IndexedTimeDataArray,

tidy3d/components/data/dataset.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from __future__ import annotations
44

55
from abc import ABC, abstractmethod
6-
from typing import Any, Callable, Dict, Union, Tuple, Optional
6+
from typing import Any, Callable, Dict, Optional, Tuple, Union
77

88
import numpy as np
99
import pydantic.v1 as pd
@@ -316,13 +316,13 @@ def apply_phase(self, phase: float) -> AbstractFieldDataset:
316316
class ElectromagneticSurfaceFieldDataset(AbstractFieldDataset, ABC):
317317
"""Stores a collection of E and H fields with x, y, z components."""
318318

319-
E: Tuple[Optional[TriangularSurfaceDataset], Optional[TriangularSurfaceDataset]] = pd.Field(
319+
E: Tuple[Optional[TriangularSurfaceDataset], Optional[TriangularSurfaceDataset]] = pd.Field(
320320
(None, None),
321321
title="E",
322322
description="Spatial distribution of the electric field on the internal and external sides of the surface.",
323323
)
324324

325-
H: Tuple[Optional[TriangularSurfaceDataset], Optional[TriangularSurfaceDataset]] = pd.Field(
325+
H: Tuple[Optional[TriangularSurfaceDataset], Optional[TriangularSurfaceDataset]] = pd.Field(
326326
(None, None),
327327
title="H",
328328
description="Spatial distribution of the magnetic field on the internal and external sides of the surface.",
@@ -346,7 +346,7 @@ def field_components(self) -> Dict[str, DataArray]:
346346
@property
347347
def current_density(self) -> ElectromagneticSurfaceFieldDataset:
348348
"""Surface current density."""
349-
349+
350350
h_diff = 0
351351
template = None
352352
# we assume that is data is None it means field is zero on that side (e.g. PEC)
@@ -358,8 +358,10 @@ def current_density(self) -> ElectromagneticSurfaceFieldDataset:
358358
template = self.H[1]
359359

360360
if template is None:
361-
raise ValueError("Could not calculate current density: the dataset does not contain H field information.")
362-
361+
raise ValueError(
362+
"Could not calculate current density: the dataset does not contain H field information."
363+
)
364+
363365
return template.updated_copy(values=xr.cross(h_diff, self.normal.values, dim="axis"))
364366

365367
@property
@@ -379,7 +381,7 @@ def symmetry_eigenvalues(self) -> Dict[str, Callable[[Axis], float]]:
379381
Hy=lambda dim: +1 if (dim == 1) else -1,
380382
Hz=lambda dim: +1 if (dim == 2) else -1,
381383
)
382-
384+
383385

384386
class ModeSolverDataset(ElectromagneticFieldDataset):
385387
"""Dataset storing scalar components of E and H fields as a function of freq. and mode_index.

tidy3d/components/data/monitor_data.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -89,11 +89,11 @@
8989
AbstractFieldDataset,
9090
Dataset,
9191
ElectromagneticFieldDataset,
92+
ElectromagneticSurfaceFieldDataset,
9293
FieldDataset,
9394
FieldTimeDataset,
9495
ModeSolverDataset,
9596
PermittivityDataset,
96-
ElectromagneticSurfaceFieldDataset,
9797
)
9898
from .utils import TriangularSurfaceDataset
9999

@@ -200,7 +200,14 @@ def get_amplitude(x) -> complex:
200200
class AbstractFieldData(MonitorData, AbstractFieldDataset, ABC):
201201
"""Collection of scalar fields with some symmetry properties."""
202202

203-
monitor: Union[FieldMonitor, FieldTimeMonitor, PermittivityMonitor, ModeMonitor, SurfaceFieldMonitor, SurfaceFieldTimeMonitor]
203+
monitor: Union[
204+
FieldMonitor,
205+
FieldTimeMonitor,
206+
PermittivityMonitor,
207+
ModeMonitor,
208+
SurfaceFieldMonitor,
209+
SurfaceFieldTimeMonitor,
210+
]
204211

205212
symmetry: Tuple[Symmetry, Symmetry, Symmetry] = pd.Field(
206213
(0, 0, 0),
@@ -1392,7 +1399,9 @@ def _symmetry_update_dict(self) -> Dict:
13921399
raise Tidy3dNotImplementedError("Surface monitors currently do not support symmetry.")
13931400

13941401

1395-
class ElectromagneticSurfaceFieldData(AbstractSurfaceFieldData, ElectromagneticSurfaceFieldDataset, ABC):
1402+
class ElectromagneticSurfaceFieldData(
1403+
AbstractSurfaceFieldData, ElectromagneticSurfaceFieldDataset, ABC
1404+
):
13961405
"""Collection of electromagnetic fields on a surface."""
13971406

13981407
@property
@@ -1412,12 +1421,12 @@ def poynting(self) -> Tuple[TriangularSurfaceDataset, TriangularSurfaceDataset]:
14121421
poynting = [None, None]
14131422
for ind in range(2):
14141423
if self.E[ind] is not None and self.H[ind] is not None:
1415-
14161424
e_field = self.E[ind]
14171425
h_field = self.H[ind]
14181426

14191427
poynting[ind] = e_field.updated_copy(
1420-
values=0.5 * np.real(xr.cross(e_field.values, np.conj(h_field.values), dim="axis"))
1428+
values=0.5
1429+
* np.real(xr.cross(e_field.values, np.conj(h_field.values), dim="axis"))
14211430
)
14221431

14231432
return poynting
@@ -1467,7 +1476,9 @@ def normalize(self, source_spectrum_fn: Callable[[float], complex]) -> FieldData
14671476
if field_data[ind] is not None:
14681477
src_amps = source_spectrum_fn(field_data[ind].values.f)
14691478
fields_norm[field_name][ind] = field_data[ind].updated_copy(
1470-
values=(field_data[ind].values / src_amps).astype(field_data[ind].values.dtype)
1479+
values=(field_data[ind].values / src_amps).astype(
1480+
field_data[ind].values.dtype
1481+
)
14711482
)
14721483

14731484
return self.copy(update=fields_norm)
@@ -1504,7 +1515,6 @@ def poynting(self) -> ScalarFieldTimeDataArray:
15041515
poynting = [None, None]
15051516
for ind in range(2):
15061517
if self.E[ind] is not None and self.H[ind] is not None:
1507-
15081518
e_field = self.E[ind]
15091519
h_field = self.H[ind]
15101520

tidy3d/components/data/unstructured/base.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
import pydantic.v1 as pd
1111
from xarray import DataArray as XrDataArray
1212

13-
from tidy3d.components.base import cached_property, skip_if_fields_missing, Tidy3dBaseModel
13+
from tidy3d.components.base import Tidy3dBaseModel, cached_property, skip_if_fields_missing
1414
from tidy3d.components.data.data_array import (
1515
DATA_ARRAY_MAP,
1616
CellDataArray,
@@ -366,9 +366,7 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
366366
# Only support operations with a scalar or an unstructured grid dataset of the same spatial dimensionality
367367
if not (
368368
isinstance(x, numbers.Number)
369-
or (
370-
isinstance(x, type(self)) and x._point_dims() == self._point_dims()
371-
)
369+
or (isinstance(x, type(self)) and x._point_dims() == self._point_dims())
372370
):
373371
raise Tidy3dNotImplementedError(
374372
f"Cannot perform arithmetic operations between instances of different classes ({type(self)} and {type(x)})."
@@ -377,9 +375,7 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
377375
# Defer to the implementation of the ufunc on unwrapped values.
378376
inputs = tuple(x.values if isinstance(x, type(self)) else x for x in inputs)
379377
if out:
380-
kwargs["out"] = tuple(
381-
x.values if isinstance(x, type(self)) else x for x in out
382-
)
378+
kwargs["out"] = tuple(x.values if isinstance(x, type(self)) else x for x in out)
383379
result = getattr(ufunc, method)(*inputs, **kwargs)
384380

385381
if type(result) is tuple:
@@ -410,7 +406,7 @@ def abs(self) -> UnstructuredDataset:
410406
def conj(self) -> UnstructuredDataset:
411407
"""Complex conjugate value of dataset."""
412408
return self.updated_copy(values=self.values.conj())
413-
409+
414410
def norm(self, dim) -> UnstructuredDataset:
415411
"""Compute vector norm along a given dimension."""
416412
return self.updated_copy(values=np.sqrt(self.values.dot(self.values.conj(), dim=dim).real))
@@ -922,7 +918,7 @@ def isel(
922918
key: value if isinstance(value, list) else [value] for key, value in sel_kwargs.items()
923919
}
924920
return self.updated_copy(values=self.values.isel(**sel_kwargs_only_lists))
925-
921+
926922

927923
class UnstructuredGridDataset(UnstructuredDataset, np.lib.mixins.NDArrayOperatorsMixin, ABC):
928924
"""Abstract base for datasets that store unstructured grid data."""

tidy3d/components/data/unstructured/surface.py

Lines changed: 31 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -9,32 +9,27 @@
99

1010
try:
1111
from matplotlib import pyplot as plt
12-
from matplotlib.tri import Triangulation
1312
except ImportError:
1413
pass
1514

15+
from matplotlib import colormaps
16+
from matplotlib.colors import Normalize
1617
from xarray import DataArray as XrDataArray
1718

1819
from tidy3d.components.base import cached_property
1920
from tidy3d.components.data.data_array import (
2021
CellDataArray,
21-
IndexedDataArray,
22+
IndexedDataArrayTypes,
2223
PointDataArray,
23-
SpatialDataArray,
24-
IndexedDataArrayTypes
2524
)
26-
from tidy3d.components.types import ArrayLike, Ax, Axis, Bound
27-
from tidy3d.components.viz import add_ax_3d_if_none, equal_aspect, plot_params_grid
28-
from tidy3d.constants import inf
25+
from tidy3d.components.types import ArrayLike, Ax, Axis
26+
from tidy3d.components.viz import add_ax_3d_if_none, equal_aspect
2927
from tidy3d.exceptions import DataError, Tidy3dNotImplementedError
30-
from tidy3d.log import log
3128
from tidy3d.packaging import requires_vtk, vtk
3229

3330
from .base import (
3431
UnstructuredDataset,
3532
)
36-
from matplotlib.colors import Normalize
37-
from matplotlib import colormaps
3833

3934

4035
class TriangularSurfaceDataset(UnstructuredDataset):
@@ -148,8 +143,8 @@ def sel(
148143
method: Literal["None", "nearest", "pad", "ffill", "backfill", "bfill"] = None,
149144
**sel_kwargs,
150145
) -> Union[TriangularSurfaceDataset, XrDataArray]:
151-
"""Extract/interpolate data along one or more spatial or non-spatial directions.
152-
Currently works only for non-spatial dimensions through additional arguments.
146+
"""Extract/interpolate data along one or more spatial or non-spatial directions.
147+
Currently works only for non-spatial dimensions through additional arguments.
153148
Selection along non-spatial dimensions is forwarded to
154149
.sel() xarray function. Parameter 'method' applies only to non-spatial dimensions.
155150
@@ -173,18 +168,19 @@ def sel(
173168
"""
174169

175170
if any(comp is not None for comp in [x, y, z]):
176-
raise Tidy3dNotImplementedError("Surface datasets do not support selection along x, y, or z yet.")
177-
171+
raise Tidy3dNotImplementedError(
172+
"Surface datasets do not support selection along x, y, or z yet."
173+
)
174+
178175
return self._non_spatial_sel(method=method, **sel_kwargs)
179-
176+
180177
def get_cell_volumes(self):
181178
"""Get areas associated to each cell of the grid."""
182179
v0 = self.points[self.cells.sel(vertex_index=0)]
183180
e01 = self.points[self.cells.sel(vertex_index=1)] - v0
184181
e02 = self.points[self.cells.sel(vertex_index=2)] - v0
185182

186183
return 0.5 * np.abs(np.cross(e01, e02))
187-
188184

189185
""" Plotting """
190186

@@ -246,7 +242,7 @@ def plot(
246242
"Use '.sel()' to select a single field from available dimensions "
247243
f"{self._values_coords_dict} before plotting."
248244
)
249-
245+
250246
face_colors = None
251247
face_alpha = 0
252248
edge_colors = None
@@ -256,16 +252,16 @@ def plot(
256252
values_avg = np.mean(self.values.data.ravel()[self.cells.data], axis=1)
257253
face_colors = colormaps[cmap](norm(values_avg))
258254
face_alpha = 1
259-
255+
260256
if grid:
261257
edge_colors = "k"
262258

263259
plot_obj = ax.plot_trisurf(
264-
self.points.data[:, 0],
265-
self.points.data[:, 1],
266-
self.points.data[:, 2],
267-
triangles=self.cells.data,
268-
fc=face_colors,
260+
self.points.data[:, 0],
261+
self.points.data[:, 1],
262+
self.points.data[:, 2],
263+
triangles=self.cells.data,
264+
fc=face_colors,
269265
ec=edge_colors,
270266
alpha=face_alpha,
271267
# cmap=cmap,
@@ -283,7 +279,7 @@ def plot(
283279
if buffer is not None:
284280
bounds = np.array(self.bounds)
285281
size = np.linalg.norm(bounds[1] - bounds[0])
286-
282+
287283
ax.set_xlim(bounds[0][0] - buffer * size, bounds[1][0] + buffer * size)
288284
ax.set_ylim(bounds[0][1] - buffer * size, bounds[1][1] + buffer * size)
289285
ax.set_zlim(bounds[0][2] - buffer * size, bounds[1][2] + buffer * size)
@@ -310,7 +306,7 @@ def quiver(
310306
cbar_kwargs: Dict = None,
311307
quiver_kwargs: Dict = None,
312308
) -> Ax:
313-
"""Plot the associated data as quiver plot. Field ``values`` must have length 3 along
309+
"""Plot the associated data as quiver plot. Field ``values`` must have length 3 along
314310
the dimension representing x, y, and z components.
315311
316312
Parameters
@@ -352,7 +348,7 @@ def quiver(
352348
"Use '.sel()' to select a single field from available dimensions "
353349
f"{self._values_coords_dict} before plotting."
354350
)
355-
351+
356352
# compute max magnitude of vecotr field
357353
mag = np.sqrt(self.values.dot(self.values.conj(), dim=dim).real)
358354
mag_max = np.max(mag)
@@ -364,19 +360,19 @@ def quiver(
364360
u = self.values.sel(**{dim: 0}).real.data[::downsampling] * scale_factor.data
365361
v = self.values.sel(**{dim: 1}).real.data[::downsampling] * scale_factor.data
366362
w = self.values.sel(**{dim: 2}).real.data[::downsampling] * scale_factor.data
367-
363+
368364
if color == "magnitude":
369-
clr = plt.colormaps[cmap](1 - mag.data[::downsampling].ravel()/mag_max.data)
365+
clr = plt.colormaps[cmap](1 - mag.data[::downsampling].ravel() / mag_max.data)
370366
else:
371367
clr = color
372368
plot_obj = ax.quiver(
373-
self.points.sel(axis=0).data[::downsampling],
374-
self.points.sel(axis=1).data[::downsampling],
369+
self.points.sel(axis=0).data[::downsampling],
370+
self.points.sel(axis=1).data[::downsampling],
375371
self.points.sel(axis=2).data[::downsampling],
376-
u.ravel(),
377-
v.ravel(),
378-
w.ravel(),
379-
color=clr,
372+
u.ravel(),
373+
v.ravel(),
374+
w.ravel(),
375+
color=clr,
380376
**quiver_kwargs,
381377
)
382378

@@ -390,7 +386,7 @@ def quiver(
390386
if buffer is not None:
391387
bounds = np.array(self.bounds)
392388
size = np.linalg.norm(bounds[1] - bounds[0])
393-
389+
394390
ax.set_xlim(bounds[0][0] - buffer * size, bounds[1][0] + buffer * size)
395391
ax.set_ylim(bounds[0][1] - buffer * size, bounds[1][1] + buffer * size)
396392
ax.set_zlim(bounds[0][2] - buffer * size, bounds[1][2] + buffer * size)

tidy3d/components/data/unstructured/tetrahedral.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,6 @@
99
from xarray import DataArray as XrDataArray
1010

1111
from tidy3d.components.base import cached_property
12-
from tidy3d.components.data.data_array import (
13-
CellDataArray,
14-
IndexedDataArray,
15-
PointDataArray,
16-
)
1712
from tidy3d.components.types import ArrayLike, Axis, Bound, Coordinate
1813
from tidy3d.exceptions import DataError
1914
from tidy3d.packaging import requires_vtk, vtk

0 commit comments

Comments
 (0)