Skip to content

feat: add validation for units #2335

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 30, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions tests/test_components/test_grid_spec.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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,
)
13 changes: 13 additions & 0 deletions tidy3d/components/grid/grid_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down