Skip to content

Commit 0157ce9

Browse files
committed
fix validation of CustomGridBoundaries
1 parent ff2f598 commit 0157ce9

File tree

3 files changed

+28
-0
lines changed

3 files changed

+28
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
3030
- If `ModeSpec.angle_rotation=True` for a mode object, validate that the structure rotation can be successfully done. Also, error if the medium cannot be rotated (e.g. anisotropic or custom medium), which would previously have just produced wrong results.
3131
- Characteristic impedance calculations in the `ImpedanceCalculator` using definitions that rely on flux, which were giving incorrect results for lossy transmission lines.
3232
- Fixed handling of symmetry when creating adjoint field sources and added warning when broken up adjoint simulations do not have the same symmetry as the forward simulation.
33+
- Validation for `CustomGridBoundaries`, which was previously allowing unsorted arrays and arrays with less than two entries.
3334

3435
### Changed
3536
- Relaxed bounds checking of path integrals during `WavePort` validation.

tests/test_components/test_grid_spec.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -544,3 +544,13 @@ def test_uniform_grid_dl_validation(dl, expect_exception):
544544
grid_spec=td.GridSpec.uniform(dl=dl),
545545
run_time=1e-12,
546546
)
547+
548+
549+
def test_custom_grid_boundary_validation():
550+
"""Tests that the 'coords' is at least length 2 and sorted in ascending order."""
551+
552+
with pytest.raises(pydantic.ValidationError):
553+
_ = td.CustomGridBoundaries(coords=[10])
554+
555+
with pytest.raises(pydantic.ValidationError):
556+
_ = td.CustomGridBoundaries(coords=[9, 10, 9, 10, 11, 9, 8])

tidy3d/components/grid/grid_spec.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,23 @@ def estimated_min_dl(
419419

420420
return min(np.diff(self.coords))
421421

422+
@pd.validator("coords", always=True)
423+
def _validate_coords(cls, val):
424+
"""
425+
Ensure 'coords' is sorted and has at least 2 entries.
426+
"""
427+
if len(val) < 2:
428+
raise SetupError("You must supply at least 2 entries for 'coords'.")
429+
# Ensure coords is sorted
430+
positive_diff = np.diff(val) > 0
431+
if not np.all(positive_diff):
432+
violations = np.where(np.diff(val) <= 0)[0] + 1
433+
raise SetupError(
434+
"'coords' must be strictly increasing (sorted in ascending order). "
435+
f"The entries at the following indices violated this requirement: {violations}."
436+
)
437+
return val
438+
422439

423440
class CustomGrid(GridSpec1d):
424441
"""Custom 1D grid supplied as a list of grid cell sizes centered on the simulation center.

0 commit comments

Comments
 (0)