From 6581ec3c87ed99687b1b73895b305e4c933a3d0e Mon Sep 17 00:00:00 2001 From: rahul-flex Date: Mon, 28 Apr 2025 13:18:23 -0400 Subject: [PATCH] feat: add validation for units --- CHANGELOG.md | 3 +++ tests/test_components/test_grid_spec.py | 26 +++++++++++++++++++++++++ tidy3d/components/grid/grid_spec.py | 13 +++++++++++++ 3 files changed, 42 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 976afecf87..6cb2e1dd58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- Validation check for unit error in grid spacing. + ### Changed - Supplying autograd-traced values to geometric fields (`center`, `size`) of simulations, monitors, and sources now logs a warning and falls back to the static value instead of erroring. - Attempting to differentiate server-side field projections now raises a clear error instead of silently failing. diff --git a/tests/test_components/test_grid_spec.py b/tests/test_components/test_grid_spec.py index 534f1e339f..73096b289c 100644 --- a/tests/test_components/test_grid_spec.py +++ b/tests/test_components/test_grid_spec.py @@ -1,6 +1,7 @@ """Tests GridSpec.""" import numpy as np +import pydantic.v1 as pydantic import pytest import tidy3d as td from tidy3d.exceptions import SetupError @@ -515,3 +516,28 @@ def test_domain_mismatch(): boundary_spec=td.BoundarySpec.pml(), ) z = sim.grid.boundaries.z + + +@pytest.mark.parametrize( + ("dl", "expect_exception"), + [ + (1e-8, True), # Below 1e-7 => fail + (1e-7, False), # Exactly at lower bound => pass + (0.0, True), # Zero => fail + ], +) +def test_uniform_grid_dl_validation(dl, expect_exception): + """Test the validator that checks 'dl' is between 1e-7 and 3e8 µm.""" + if expect_exception: + with pytest.raises(pydantic.ValidationError): + _ = td.Simulation( + size=(1, 1, 1), + grid_spec=td.GridSpec.uniform(dl=dl), + run_time=1e-12, + ) + else: + _ = td.Simulation( + size=(1, 1, 1), + grid_spec=td.GridSpec.uniform(dl=dl), + run_time=1e-12, + ) diff --git a/tidy3d/components/grid/grid_spec.py b/tidy3d/components/grid/grid_spec.py index 2a5b9ff5e6..469560700d 100644 --- a/tidy3d/components/grid/grid_spec.py +++ b/tidy3d/components/grid/grid_spec.py @@ -276,6 +276,19 @@ class UniformGrid(GridSpec1d): units=MICROMETER, ) + @pd.validator("dl", always=True) + def _validate_dl(cls, val): + """ + Ensure 'dl' is not too small. + """ + if val < 1e-7: + raise SetupError( + f"Uniform grid spacing 'dl' is {val} µm. " + "Please check your units! For more info on Tidy3D units, see: " + "https://docs.flexcompute.com/projects/tidy3d/en/latest/faq/docs/faq/What-are-the-units-used-in-the-simulation.html" + ) + return val + def _make_coords_initial( self, axis: Axis,