|
| 1 | +"""Typed containers for autograd traced field metadata.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +from typing import Any, Callable |
| 7 | + |
| 8 | +import pydantic.v1 as pydantic |
| 9 | + |
| 10 | +from tidy3d.components.autograd.types import AutogradFieldMap, dict_ag |
| 11 | +from tidy3d.components.base import Tidy3dBaseModel |
| 12 | +from tidy3d.components.types import ArrayLike, tidycomplex |
| 13 | + |
| 14 | + |
| 15 | +class Tracer(Tidy3dBaseModel): |
| 16 | + """Representation of a single traced element within a model.""" |
| 17 | + |
| 18 | + path: tuple[Any, ...] = pydantic.Field( |
| 19 | + ..., |
| 20 | + title="Path to the traced object in the model dictionary.", |
| 21 | + ) |
| 22 | + data: float | tidycomplex | ArrayLike = pydantic.Field(..., title="Tracing data") |
| 23 | + |
| 24 | + |
| 25 | +class FieldMap(Tidy3dBaseModel): |
| 26 | + """Collection of traced elements.""" |
| 27 | + |
| 28 | + tracers: tuple[Tracer, ...] = pydantic.Field( |
| 29 | + ..., |
| 30 | + title="Collection of Tracers.", |
| 31 | + ) |
| 32 | + |
| 33 | + @property |
| 34 | + def to_autograd_field_map(self) -> AutogradFieldMap: |
| 35 | + """Convert to ``AutogradFieldMap`` autograd dictionary.""" |
| 36 | + return dict_ag({tracer.path: tracer.data for tracer in self.tracers}) |
| 37 | + |
| 38 | + @classmethod |
| 39 | + def from_autograd_field_map(cls, autograd_field_map: AutogradFieldMap) -> FieldMap: |
| 40 | + """Initialize from an ``AutogradFieldMap`` autograd dictionary.""" |
| 41 | + tracers = [] |
| 42 | + for path, data in autograd_field_map.items(): |
| 43 | + tracers.append(Tracer(path=path, data=data)) |
| 44 | + return cls(tracers=tuple(tracers)) |
| 45 | + |
| 46 | + |
| 47 | +def _encoded_path(path: tuple[Any, ...]) -> str: |
| 48 | + """Return a stable JSON representation for a traced path.""" |
| 49 | + return json.dumps(list(path), separators=(",", ":"), ensure_ascii=True) |
| 50 | + |
| 51 | + |
| 52 | +class TracerKeys(Tidy3dBaseModel): |
| 53 | + """Collection of traced field paths.""" |
| 54 | + |
| 55 | + keys: tuple[tuple[Any, ...], ...] = pydantic.Field( |
| 56 | + ..., |
| 57 | + title="Collection of tracer keys.", |
| 58 | + ) |
| 59 | + |
| 60 | + def encoded_keys(self) -> list[str]: |
| 61 | + """Return the JSON-encoded representation of keys.""" |
| 62 | + return [_encoded_path(path) for path in self.keys] |
| 63 | + |
| 64 | + @classmethod |
| 65 | + def from_field_mapping( |
| 66 | + cls, |
| 67 | + field_mapping: AutogradFieldMap, |
| 68 | + *, |
| 69 | + sort_key: Callable[[tuple[Any, ...]], str] | None = None, |
| 70 | + ) -> TracerKeys: |
| 71 | + """Construct keys from an autograd field mapping.""" |
| 72 | + if sort_key is None: |
| 73 | + sort_key = _encoded_path |
| 74 | + |
| 75 | + sorted_paths = tuple(sorted(field_mapping.keys(), key=sort_key)) |
| 76 | + return cls(keys=sorted_paths) |
0 commit comments