tidy3d.Tidy3dBaseModel#
- class Tidy3dBaseModel[source]#
Bases:
BaseModelBase pydantic model that all Tidy3d components inherit from. Defines configuration for handling data structures as well as methods for importing, exporting, and hashing tidy3d objects. For more details on pydantic base models, see: Pydantic models
Methods
coerce numpy scalars / size-1 arrays to native Python scalars, but only for fields whose annotations allow scalars.
copy([deep, validate, update])Return a copy of the model.
dict_from_file(fname[, group_path, ...])Loads a dictionary containing the model from a .yaml, .json, .hdf5, or .hdf5.gz file.
dict_from_hdf5(fname[, group_path, ...])Loads a dictionary containing the model contents from a .hdf5 file.
dict_from_hdf5_gz(fname[, group_path, ...])Loads a dictionary containing the model contents from a .hdf5.gz file.
dict_from_json(fname)Load dictionary of the model from a .json file.
dict_from_yaml(fname)Load dictionary of the model from a .yaml file.
find_paths(target_field_name[, ...])Finds paths to nested model instances that have a specific field, optionally matching a value.
find_submodels(target_type)Finds all unique nested instances of a specific Tidy3D model type within this model.
from_file(fname[, group_path, lazy, on_load])Loads a
Tidy3dBaseModelfrom .yaml, .json, .hdf5, or .hdf5.gz file.from_hdf5(fname[, group_path, custom_decoders])Loads
Tidy3dBaseModelinstance to .hdf5 file.from_hdf5_gz(fname[, group_path, ...])Loads
Tidy3dBaseModelinstance to .hdf5.gz file.from_json(fname, **model_validate_kwargs)Load a
Tidy3dBaseModelfrom .json file.from_yaml(fname, **model_validate_kwargs)Loads
Tidy3dBaseModelfrom .yaml file.generate_docstring([show_default_args, ...])Generates a docstring for a Tidy3D model.
get_sub_model(group_path, model_dict)Get the sub model for a given group path.
Return a mapping
{hash(submodel): [field_path, ...]}for every nestedTidy3dBaseModelinside this model.get_tuple_group_name(index)Get the group name of a tuple element.
get_tuple_index(key_name)Get the index into the tuple based on its group name.
help([methods])Prints message describing the fields and methods of a
Tidy3dBaseModel.model_rebuild(*[, force, raise_errors, ...])Try to rebuild the pydantic-core schema for the model.
to_file(fname)Exports
Tidy3dBaseModelinstance to .yaml, .json, or .hdf5 fileto_hdf5(fname[, custom_encoders])Exports
Tidy3dBaseModelinstance to .hdf5 file.to_hdf5_gz(fname[, custom_encoders])Exports
Tidy3dBaseModelinstance to .hdf5.gz file.to_json(fname)Exports
Tidy3dBaseModelinstance to .json fileVersion of object with all autograd-traced fields removed.
to_yaml(fname)Exports
Tidy3dBaseModelinstance to .yaml file.tuple_to_dict(tuple_values)How we generate a dictionary mapping new keys to tuple values for hdf5.
updated_copy([path, deep, validate])Make copy of a component instance with
**kwargsindicating updated field values.- classmethod model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None)[source]#
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Args:
force: Whether to force the rebuilding of the model schema, defaults to False. raise_errors: Whether to raise errors, defaults to True. _parent_namespace_depth: The depth level of the parent namespace, defaults to 2. _types_namespace: The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod coerce_numpy_scalars_for_model(data)[source]#
coerce numpy scalars / size-1 arrays to native Python scalars, but only for fields whose annotations allow scalars.
- copy(deep=True, *, validate=True, update=None)[source]#
Return a copy of the model.
- Parameters:
deep (bool = True) – Whether to make a deep copy first (same as v1).
validate (bool = True) – If
True, run full Pydantic validation on the copied data.update (Optional[Mapping[str, Any]] = None) – Optional mapping of fields to overwrite (passed straight through to
model_copy(update=...)).
- updated_copy(path=None, *, deep=True, validate=True, **kwargs)[source]#
Make copy of a component instance with
**kwargsindicating updated field values.Note
If
pathis supplied, applies the updated copy with the update performed on the sub- component corresponding to the path. For indexing into a tuple or list, use the integer value.Example
>>> sim = simulation.updated_copy(size=new_size, path=f"structures/{i}/geometry")
- find_paths(target_field_name, target_field_value=<object object>)[source]#
Finds paths to nested model instances that have a specific field, optionally matching a value.
The paths are string representations like
"structures/0/geometry", designed for direct use with theupdated_copy()method to modify specific parts of this model. An empty string""in the returned list indicates that this model instance itself (the onefind_pathsis called on) matches the criteria.- Parameters:
target_field_name (str) – The name of the attribute (field) to search for within nested
Tidy3dBaseModelinstances. For example,"name"or"permittivity".target_field_value (Any, optional) – If provided, only paths to model instances where
target_field_namealso has this specific value will be returned. If omitted, paths are returned if thetarget_field_nameexists, regardless of its value.
- Returns:
A sorted list of unique string paths. Each path points to a
Tidy3dBaseModelinstance that possesses thetarget_field_name(and optionally matchestarget_field_value).- Return type:
Example
>>> # Assume 'sim' is a Tidy3D simulation object >>> # Find all geometries named "waveguide" >>> paths = sim.find_paths(target_field_name="name", target_field_value="waveguide") >>> # paths might be ['structures/0', 'structures/3'] >>> # Update the size of the first found "waveguide" >>> new_sim = sim.updated_copy(path=paths[0], size=(1.0, 0.5, 0.22))
- find_submodels(target_type)[source]#
Finds all unique nested instances of a specific Tidy3D model type within this model.
This method traverses the model structure and collects all instances that are of the
target_type(e.g.,Structure,Medium,Box). Uniqueness is determined by the model’s content. The order of models in the returned list corresponds to their first encounter during a depth-first traversal.- Parameters:
target_type (Tidy3dBaseModel) – The specific Tidy3D class (e.g.,
Structure,Medium,Box) to search for. This class must be a subclass ofTidy3dBaseModel.- Returns:
A list of unique instances found within this model that are of the provided
target_type.- Return type:
Example
>>> # Assume 'sim' is a Tidy3D Simulation object >>> # Find all Structure instances within the simulation >>> all_structures = sim.find_submodels(td.Structure) >>> for struct in all_structures: ... print(f"Structure: {struct.name}, medium: {struct.medium}")
>>> # Find all Box geometries within the simulation >>> all_boxes = sim.find_submodels(td.Box) >>> for box in all_boxes: ... print(f"Found Box with size: {box.size}")
>>> # Find all Medium instances (useful for checking materials) >>> all_media = sim.find_submodels(td.Medium) >>> # Note: This would find td.Medium instances, but not td.PECMedium or td.PoleResidue >>> # unless they inherit directly from td.Medium and not just Tidy3dBaseModel or td.AbstractMedium. >>> # To find all medium types, one might search for td.AbstractMedium if that's a common base.
- help(methods=False)[source]#
Prints message describing the fields and methods of a
Tidy3dBaseModel.- Parameters:
methods (bool = False) – Whether to also print out information about object’s methods.
Example
>>> simulation.help(methods=True)
- classmethod from_file(fname, group_path=None, lazy=False, on_load=None, **parse_obj_kwargs)[source]#
Loads a
Tidy3dBaseModelfrom .yaml, .json, .hdf5, or .hdf5.gz file.- Parameters:
fname (PathLike) – Full path to the file to load the
Tidy3dBaseModelfrom.group_path (Optional[str] = None) – Path to a group inside the file to use as the base level. Only for hdf5 files. Starting / is optional.
lazy (bool = False) – Whether to load the actual data (
lazy=False) or return a proxy that loads the data when accessed (lazy=True).on_load (Optional[Callable[[Any], None]] = None) – Callback function executed once the model is fully materialized. Only used if
lazy=True. The callback is invoked with the loaded instance as its sole argument, enabling post-processing such as validation, logging, or warnings checks.**model_validate_kwargs – Keyword arguments passed to pydantic’s
model_validatemethod when loading model.
- Returns:
An instance of the component class calling
load.- Return type:
Self
Example
>>> simulation = Simulation.from_file(fname='folder/sim.json')
- classmethod dict_from_file(fname, group_path=None, *, load_data_arrays=True)[source]#
Loads a dictionary containing the model from a .yaml, .json, .hdf5, or .hdf5.gz file.
- Parameters:
fname (PathLike) – Full path to the file to load the
Tidy3dBaseModelfrom.group_path (str, optional) – Path to a group inside the file to use as the base level.
- Returns:
A dictionary containing the model.
- Return type:
Example
>>> simulation = Simulation.from_file(fname='folder/sim.json')
- to_file(fname)[source]#
Exports
Tidy3dBaseModelinstance to .yaml, .json, or .hdf5 file- Parameters:
fname (PathLike) – Full path to the .yaml or .json file to save the
Tidy3dBaseModelto.
Example
>>> simulation.to_file(fname='folder/sim.json')
- classmethod from_json(fname, **model_validate_kwargs)[source]#
Load a
Tidy3dBaseModelfrom .json file.- Parameters:
fname (PathLike) – Full path to the .json file to load the
Tidy3dBaseModelfrom.- Returns:
Self – An instance of the component class calling load.
**model_validate_kwargs – Keyword arguments passed to pydantic’s
model_validatemethod.
Example
>>> simulation = Simulation.from_json(fname='folder/sim.json')
- classmethod dict_from_json(fname)[source]#
Load dictionary of the model from a .json file.
- Parameters:
fname (PathLike) – Full path to the .json file to load the
Tidy3dBaseModelfrom.- Returns:
A dictionary containing the model.
- Return type:
Example
>>> sim_dict = Simulation.dict_from_json(fname='folder/sim.json')
- to_json(fname)[source]#
Exports
Tidy3dBaseModelinstance to .json file- Parameters:
fname (PathLike) – Full path to the .json file to save the
Tidy3dBaseModelto.
Example
>>> simulation.to_json(fname='folder/sim.json')
- classmethod from_yaml(fname, **model_validate_kwargs)[source]#
Loads
Tidy3dBaseModelfrom .yaml file.- Parameters:
fname (PathLike) – Full path to the .yaml file to load the
Tidy3dBaseModelfrom.**model_validate_kwargs – Keyword arguments passed to pydantic’s
model_validatemethod.
- Returns:
An instance of the component class calling from_yaml.
- Return type:
Self
Example
>>> simulation = Simulation.from_yaml(fname='folder/sim.yaml')
- classmethod dict_from_yaml(fname)[source]#
Load dictionary of the model from a .yaml file.
- Parameters:
fname (PathLike) – Full path to the .yaml file to load the
Tidy3dBaseModelfrom.- Returns:
A dictionary containing the model.
- Return type:
Example
>>> sim_dict = Simulation.dict_from_yaml(fname='folder/sim.yaml')
- to_yaml(fname)[source]#
Exports
Tidy3dBaseModelinstance to .yaml file.- Parameters:
fname (PathLike) – Full path to the .yaml file to save the
Tidy3dBaseModelto.
Example
>>> simulation.to_yaml(fname='folder/sim.yaml')
- classmethod tuple_to_dict(tuple_values)[source]#
How we generate a dictionary mapping new keys to tuple values for hdf5.
- classmethod get_sub_model(group_path, model_dict)[source]#
Get the sub model for a given group path.
- classmethod dict_from_hdf5(fname, group_path='', custom_decoders=None, load_data_arrays=True)[source]#
Loads a dictionary containing the model contents from a .hdf5 file.
- Parameters:
fname (PathLike) – Full path to the .hdf5 file to load the
Tidy3dBaseModelfrom.group_path (str, optional) – Path to a group inside the file to selectively load a sub-element of the model only.
custom_decoders (List[Callable]) – List of functions accepting (fname: str, group_path: str, model_dict: dict, key: str, value: Any) that store the value in the model dict after a custom decoding.
- Returns:
Dictionary containing the model.
- Return type:
Example
>>> sim_dict = Simulation.dict_from_hdf5(fname='folder/sim.hdf5')
- classmethod from_hdf5(fname, group_path='', custom_decoders=None, **model_validate_kwargs)[source]#
Loads
Tidy3dBaseModelinstance to .hdf5 file.- Parameters:
fname (PathLike) – Full path to the .hdf5 file to load the
Tidy3dBaseModelfrom.group_path (str, optional) – Path to a group inside the file to selectively load a sub-element of the model only. Starting / is optional.
custom_decoders (List[Callable]) – List of functions accepting (fname: str, group_path: str, model_dict: dict, key: str, value: Any) that store the value in the model dict after a custom decoding.
**model_validate_kwargs – Keyword arguments passed to pydantic’s
model_validatemethod.
Example
>>> simulation = Simulation.from_hdf5(fname='folder/sim.hdf5')
- to_hdf5(fname, custom_encoders=None)[source]#
Exports
Tidy3dBaseModelinstance to .hdf5 file.- Parameters:
fname (Union[PathLike, BytesIO]) – Full path to the .hdf5 file or buffer to save the
Tidy3dBaseModelto.custom_encoders (List[Callable]) – List of functions accepting (fname: str, group_path: str, value: Any) that take the
valuesupplied and write it to the hdf5fnameatgroup_path.
Example
>>> simulation.to_hdf5(fname='folder/sim.hdf5')
- classmethod dict_from_hdf5_gz(fname, group_path='', custom_decoders=None, load_data_arrays=True)[source]#
Loads a dictionary containing the model contents from a .hdf5.gz file.
- Parameters:
fname (PathLike) – Full path to the .hdf5.gz file to load the
Tidy3dBaseModelfrom.group_path (str, optional) – Path to a group inside the file to selectively load a sub-element of the model only.
custom_decoders (List[Callable]) – List of functions accepting (fname: str, group_path: str, model_dict: dict, key: str, value: Any) that store the value in the model dict after a custom decoding.
- Returns:
Dictionary containing the model.
- Return type:
Example
>>> sim_dict = Simulation.dict_from_hdf5(fname='folder/sim.hdf5.gz')
- classmethod from_hdf5_gz(fname, group_path='', custom_decoders=None, **model_validate_kwargs)[source]#
Loads
Tidy3dBaseModelinstance to .hdf5.gz file.- Parameters:
fname (PathLike) – Full path to the .hdf5.gz file to load the
Tidy3dBaseModelfrom.group_path (str, optional) – Path to a group inside the file to selectively load a sub-element of the model only. Starting / is optional.
custom_decoders (List[Callable]) – List of functions accepting (fname: str, group_path: str, model_dict: dict, key: str, value: Any) that store the value in the model dict after a custom decoding.
**model_validate_kwargs – Keyword arguments passed to pydantic’s
model_validatemethod.
Example
>>> simulation = Simulation.from_hdf5_gz(fname='folder/sim.hdf5.gz')
- to_hdf5_gz(fname, custom_encoders=None)[source]#
Exports
Tidy3dBaseModelinstance to .hdf5.gz file.- Parameters:
fname (Union[PathLike, BytesIO]) – Full path to the .hdf5.gz file or buffer to save the
Tidy3dBaseModelto.custom_encoders (List[Callable]) – List of functions accepting (fname: str, group_path: str, value: Any) that take the
valuesupplied and write it to the hdf5fnameatgroup_path.
Example
>>> simulation.to_hdf5_gz(fname='folder/sim.hdf5.gz')