diff --git a/lint.py b/lint.py index f47068bef3..4e7aa628ce 100644 --- a/lint.py +++ b/lint.py @@ -35,7 +35,7 @@ def main(): results = Run([path], do_exit=False) - final_score = results.linter.stats["global_note"] + final_score = results.linter.stats.global_note if final_score < threshold: diff --git a/setup.py b/setup.py index 75c2a24122..320fd01318 100644 --- a/setup.py +++ b/setup.py @@ -2,26 +2,26 @@ from distutils.util import convert_path -PACKAGE_NAME = 'tidy3d' -PIP_NAME = 'tidy3d-beta' -REPO_NAME = 'tidy3d' +PACKAGE_NAME = "tidy3d" +PIP_NAME = "tidy3d-beta" +REPO_NAME = "tidy3d" version = {} -version_path = convert_path(f'{PACKAGE_NAME}/version.py') +version_path = convert_path(f"{PACKAGE_NAME}/version.py") with open(version_path) as version_file: exec(version_file.read(), version) -print(version['__version__']) +print(version["__version__"]) with open("README.md", "r", encoding="utf-8") as fh: long_description = fh.read() -with open('requirements.txt') as f: +with open("requirements.txt") as f: required = f.read().splitlines() setuptools.setup( name=PIP_NAME, - version=version['__version__'], + version=version["__version__"], author="Tyler Hughes", author_email="tyler@flexcompute.com", description="A fast FDTD solver", @@ -39,5 +39,5 @@ # package_dir={"": ""}, packages=[PACKAGE_NAME], python_requires=">=3.6", - install_requires=required -) \ No newline at end of file + install_requires=required, +) diff --git a/tests/test_components.py b/tests/test_components.py index 3f0ff67103..a93d7b7555 100644 --- a/tests/test_components.py +++ b/tests/test_components.py @@ -174,7 +174,9 @@ def test_sim_grid_size(caplog, grid_size, log_level): size=(0, 0, 0), polarization="Ex", ) - _ = Simulation(size=(1, 1, 1), grid_size=(0.01, 0.01, grid_size), structures=[box], sources=[src]) + _ = Simulation( + size=(1, 1, 1), grid_size=(0.01, 0.01, grid_size), structures=[box], sources=[src] + ) assert_log_level(caplog, log_level) diff --git a/tidy3d/components/data.py b/tidy3d/components/data.py index ad36236d58..7e5c0d0764 100644 --- a/tidy3d/components/data.py +++ b/tidy3d/components/data.py @@ -840,7 +840,7 @@ def plot_field( # pylint:disable=too-many-arguments, too-many-locals freq: float = None, time: float = None, eps_alpha: float = 0.2, - robust : bool = True, + robust: bool = True, ax: Ax = None, **kwargs, ) -> Ax: diff --git a/tidy3d/components/geometry.py b/tidy3d/components/geometry.py index 9ca5643333..aff82472e1 100644 --- a/tidy3d/components/geometry.py +++ b/tidy3d/components/geometry.py @@ -11,7 +11,7 @@ from descartes import PolygonPatch from .base import Tidy3dBaseModel -from .types import Literal, Bound, Size, Coordinate, Axis, Coordinate2D, ArrayLike +from .types import Bound, Size, Coordinate, Axis, Coordinate2D, ArrayLike from .types import Vertices, Ax, Shapely from .viz import add_ax_if_none from ..log import Tidy3dKeyError, SetupError, ValidationError diff --git a/tidy3d/components/medium.py b/tidy3d/components/medium.py index dd240ee424..b4e0d2b05e 100644 --- a/tidy3d/components/medium.py +++ b/tidy3d/components/medium.py @@ -7,7 +7,7 @@ import numpy as np from .base import Tidy3dBaseModel -from .types import PoleAndResidue, Literal, Ax, FreqBound, ComplexNumber +from .types import PoleAndResidue, Ax, FreqBound from .viz import add_ax_if_none from .validators import validate_name_str diff --git a/tidy3d/components/monitor.py b/tidy3d/components/monitor.py index 7501b596ac..3d2d79e9de 100644 --- a/tidy3d/components/monitor.py +++ b/tidy3d/components/monitor.py @@ -3,14 +3,13 @@ from typing import List, Union import pydantic -import numpy as np -from .types import Literal, Ax, Direction, EMField, ArrayLike, FieldType +from .types import Literal, Ax, Direction, EMField, ArrayLike from .geometry import Box -from .validators import assert_plane, validate_name_str +from .validators import assert_plane from .mode import ModeSpec from .viz import add_ax_if_none, MonitorParams -from ..log import SetupError, ValidationError +from ..log import SetupError from ..constants import HERTZ, SECOND @@ -99,20 +98,20 @@ def stop_greater_than_start(cls, val, values): class AbstractFieldMonitor(Monitor, ABC): """:class:`Monitor` that records electromagnetic field data as a function of x,y,z.""" - fields: List = pydantic.Field( + fields: List[EMField] = pydantic.Field( ["Ex", "Ey", "Ez", "Hx", "Hy", "Hz"], title="Field Components", description="Collection of field components to store in the monitor.", ) - def surfaces(self) -> List["AbstractFieldMonitor"]: + def surfaces(self) -> List["AbstractFieldMonitor"]: #pylint: disable=too-many-locals """Returns a list of 6 monitors corresponding to each surface of the field monitor. - The output monitors are stored in the order [x-, x+, y-, y+, z-, z+], where x, y, and z denote - which axis is perpendicular to that surface, while "-" and "+" denote the direction of the - normal vector of that surface. Each output monitor will have the same frequency/time data as the calling - object. Its name will be that of the calling object appended with the above symbols. - E.g., if the calling object's name is "field", the x+ monitor's name will be "field_x+". - Does not work when the calling monitor has zero volume. + The output monitors are stored in the order [x-, x+, y-, y+, z-, z+], where x, y, and z + denote which axis is perpendicular to that surface, while "-" and "+" denote the direction + of the normal vector of that surface. Each output monitor will have the same frequency/time + data as the calling object. Its name will be that of the calling object appended with the + above symbols. E.g., if the calling object's name is "field", the x+ monitor's name will be + "field_x+". Does not work when the calling monitor has zero volume. Returns ------- @@ -142,8 +141,8 @@ def surfaces(self) -> List["AbstractFieldMonitor"]: (center_x, self_bmin[1], center_z), # y- (center_x, self_bmax[1], center_z), # y+ (center_x, center_y, self_bmin[2]), # z- - (center_x, center_y, self_bmax[2]), - ) # z+ + (center_x, center_y, self_bmax[2]), # z+ + ) surface_sizes = ( (0.0, size_y, size_z), # x- @@ -151,8 +150,8 @@ def surfaces(self) -> List["AbstractFieldMonitor"]: (size_x, 0.0, size_z), # y- (size_x, 0.0, size_z), # y+ (size_x, size_y, 0.0), # z- - (size_x, size_y, 0.0), - ) # z+ + (size_x, size_y, 0.0), # z+ + ) surface_names = ( self.name + "_x-", diff --git a/tidy3d/components/structure.py b/tidy3d/components/structure.py index 08f678d72e..ba54fb34ee 100644 --- a/tidy3d/components/structure.py +++ b/tidy3d/components/structure.py @@ -36,7 +36,7 @@ class Structure(Tidy3dBaseModel): _name_validator = validate_name_str() @add_ax_if_none - def plot( + def plot( # pylint:disable=missing-function-docstring self, x: float = None, y: float = None, z: float = None, ax: Ax = None, **patch_kwargs ) -> Ax: diff --git a/tidy3d/components/types.py b/tidy3d/components/types.py index 7a04d81897..95784439c1 100644 --- a/tidy3d/components/types.py +++ b/tidy3d/components/types.py @@ -43,7 +43,8 @@ def __truediv__(self, other): # built in instance of Inf () -inf = LARGE_NUMBER # comment out to use Inf(). +inf = LARGE_NUMBER # pylint:disable=invalid-name +# TODO: use inf as a reserved quantity for plotting, etc. # inf = Inf() @@ -51,32 +52,39 @@ def __truediv__(self, other): class ComplexNumber(pydantic.BaseModel): + """Complex number with a well defined schema.""" + real: float imag: float @property - def z(self): + def as_complex(self): + """return complex representation of ComplexNumber.""" return self.real + 1j * self.imag -class tidycomplex(complex): +class tidycomplex(complex): # pylint: disable=invalid-name + """complex type that we can use in our models.""" + @classmethod def __get_validators__(cls): + """Defines which validator function to use for NumpyArray.""" yield cls.validate @classmethod - def validate(cls, value, field): + def validate(cls, value): + """What gets called when you construct a tidycomplex.""" if isinstance(value, ComplexNumber): - return value.z - elif isinstance(value, dict): + return value.as_complex + if isinstance(value, dict): c = ComplexNumber(**value) - return c.z - else: - return cls(value) + return c.as_complex + return cls(value) @classmethod def __modify_schema__(cls, field_schema): + """Sets the schema of NumpyArray.""" field_schema.update(ComplexNumber.schema()) @@ -154,41 +162,49 @@ class Array(np.ndarray, metaclass=ArrayMeta): """type of numpy array with annotated type (Array[float], Array[complex])""" +""" note: + ^ this is the best way to declare numpy types if you know dtype. + for example: ``field_amps: Array[float] = np.random.random(5)``. +""" + + class NumpyArray(pydantic.BaseModel): + """Wrapper around numpy arrays that has a well defined json schema.""" + data_list: List @property def arr(self): + """Contructs a numpy array representation of the NumpyArray.""" return np.array(self.data_list) -class tidynumpy(np.ndarray): +class tidynumpy(np.ndarray): # pylint: disable=invalid-name + """Numpy array type that we can use in place of np.ndarray.""" + @classmethod def __get_validators__(cls): + """Defines which validator function to use for NumpyArray.""" yield cls.validate @classmethod - def validate(cls, value, field): + def validate(cls, value): + """What gets called when you construct a tidynumpy.""" if isinstance(value, NumpyArray): return value.arr - elif isinstance(value, dict): - n = NumpyArray(**value) - return n.arr - elif isinstance(value, list): + if isinstance(value, dict): + numpy_array = NumpyArray(**value) + return numpy_array.arr + if isinstance(value, list): return value - else: - return np.array(value) + return np.array(value) @classmethod def __modify_schema__(cls, field_schema): + """Sets the schema of NumpyArray.""" field_schema.update(NumpyArray.schema()) -""" note: - ^ this is the best way to declare numpy types if you know dtype. - for example: ``field_amps: Array[float] = np.random.random(5)``. -""" - ArrayLike = Union[tidynumpy, NumpyArray, List] diff --git a/tidy3d/web/auth.py b/tidy3d/web/auth.py index f1b8e445f5..7737aefe86 100644 --- a/tidy3d/web/auth.py +++ b/tidy3d/web/auth.py @@ -88,7 +88,7 @@ def get_credentials() -> None: set_authentication_config(email, password) break - except Exception as e: # pylint:disable=broad-except + except Exception: # pylint:disable=broad-except raise AuthenticationError( "Error: Failed to log in with new username and password." ) from None diff --git a/tidy3d/web/webapi.py b/tidy3d/web/webapi.py index 0f78a115a5..d32892a50e 100644 --- a/tidy3d/web/webapi.py +++ b/tidy3d/web/webapi.py @@ -7,7 +7,6 @@ from datetime import datetime import logging -import h5py import requests from rich.console import Console from rich.progress import Progress