Skip to content

Commit d13592f

Browse files
Break forwards incompatible methods, pending new funct
1 parent ec06455 commit d13592f

File tree

3 files changed

+2
-448
lines changed

3 files changed

+2
-448
lines changed

tidy3d/plugins/smatrix/component_modelers/base.py

Lines changed: 1 addition & 114 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ class AbstractComponentModeler(ABC, Tidy3dBaseModel):
7070
"near zero frequency. Setting this to ``False`` results in an unmodified Gaussian "
7171
"pulse spectrum which can have a nonzero DC component.",
7272
)
73-
73+
7474
@pd.validator("simulation", always=True)
7575
def _sim_has_no_sources(cls, val):
7676
"""Make sure simulation has no sources as they interfere with tool."""
@@ -101,117 +101,13 @@ def _task_name(port: Port, mode_index: Optional[int] = None) -> str:
101101
return f"smatrix_{port.name}_{mode_index}"
102102
return f"smatrix_{port.name}"
103103

104-
@cached_property
105-
def sim_dict(self) -> dict[str, Simulation]:
106-
"""Generate all the :class:`.Simulation` objects for the S matrix calculation."""
107-
108-
def to_file(self, fname: str) -> None:
109-
"""Exports :class:`AbstractComponentModeler` instance to .yaml, .json, or .hdf5 file
110-
111-
Parameters
112-
----------
113-
fname : str
114-
Full path to the .yaml or .json file to save the :class:`AbstractComponentModeler` to.
115-
116-
Example
117-
-------
118-
>>> modeler.to_file(fname='folder/sim.json') # doctest: +SKIP
119-
"""
120-
121-
batch_cached = self._cached_properties.get("batch")
122-
if batch_cached is not None:
123-
jobs_cached = batch_cached._cached_properties.get("jobs")
124-
if jobs_cached is not None:
125-
jobs = {}
126-
for key, job in jobs_cached.items():
127-
task_id = job._cached_properties.get("task_id")
128-
jobs[key] = job.updated_copy(task_id_cached=task_id)
129-
batch_cached = batch_cached.updated_copy(jobs_cached=jobs)
130-
self = self.updated_copy(batch_cached=batch_cached)
131-
super(AbstractComponentModeler, self).to_file(fname=fname) # noqa: UP008
132-
133-
@cached_property
134-
def batch(self) -> Batch:
135-
""":class:`.Batch` associated with this component modeler."""
136-
# TODO properly refactor, plugins data types should not have web methods.
137-
from tidy3d.web.api.container import Batch
138-
139-
if self.batch_cached is not None:
140-
return self.batch_cached
141-
142-
# first try loading the batch from file, if it exists
143-
batch_path = self._batch_path
144-
145-
if os.path.exists(batch_path):
146-
return Batch.from_file(fname=batch_path)
147-
148-
return Batch(
149-
simulations=self.sim_dict,
150-
folder_name=self.folder_name,
151-
callback_url=self.callback_url,
152-
verbose=self.verbose,
153-
solver_version=self.solver_version,
154-
)
155-
156-
@cached_property
157-
def batch_path(self) -> str:
158-
"""Path to the batch saved to file."""
159-
return self.batch._batch_path(path_dir=self.path_dir)
160-
161-
@cached_property
162-
def batch_data(self) -> BatchData:
163-
"""The :class:`.BatchData` associated with the simulations run for this component modeler."""
164-
return self.batch.run(path_dir=self.path_dir)
165-
166-
def get_path_dir(self, path_dir: str) -> None:
167-
"""Check whether the supplied 'path_dir' matches the internal field value."""
168-
169-
if path_dir != self.path_dir and path_dir != DEFAULT_DATA_DIR:
170-
raise ValueError(
171-
f"'path_dir' of '{path_dir}' passed, but 'ComponentModeler.path_dir' is "
172-
f"{self.path_dir}. Moving forward, only the 'ComponentModeler.path_dir' will be "
173-
"used internally, please update your scripts accordingly to avoid passing this "
174-
"value to methods. "
175-
)
176-
177-
return self.path_dir
178-
179-
@cached_property
180-
def _batch_path(self) -> str:
181-
"""Where we store the batch for this :class:`AbstractComponentModeler` instance after the run."""
182-
return os.path.join(self.path_dir, "batch" + str(hash(self)) + ".hdf5")
183-
184-
def _run_sims(self, path_dir: str = DEFAULT_DATA_DIR) -> BatchData:
185-
"""Run :class:`.Simulation` for each port and return the batch after saving."""
186-
_ = self.get_path_dir(path_dir)
187-
self.batch.to_file(self._batch_path)
188-
batch_data = self.batch_data
189-
return batch_data
190-
191104
def get_port_by_name(self, port_name: str) -> Port:
192105
"""Get the port from the name."""
193106
ports = [port for port in self.ports if port.name == port_name]
194107
if len(ports) == 0:
195108
raise Tidy3dKeyError(f'Port "{port_name}" not found.')
196109
return ports[0]
197110

198-
@abstractmethod
199-
def _construct_smatrix(self, batch_data: BatchData) -> DataArray:
200-
"""Post process :class:`.BatchData` to generate scattering matrix."""
201-
202-
@abstractmethod
203-
def _internal_construct_smatrix(self, batch_data: BatchData) -> DataArray:
204-
"""Post process :class:`.BatchData` to generate scattering matrix, for internal use only."""
205-
206-
def run(self, path_dir: str = DEFAULT_DATA_DIR) -> DataArray:
207-
"""Solves for the scattering matrix of the system."""
208-
_ = self.get_path_dir(path_dir)
209-
return self._construct_smatrix()
210-
211-
def load(self, path_dir: str = DEFAULT_DATA_DIR) -> DataArray:
212-
"""Load a scattering matrix from saved :class:`.BatchData` object."""
213-
return self.run(path_dir=path_dir)
214-
215111
@staticmethod
216112
def inv(matrix: DataArray):
217113
"""Helper to invert a port matrix."""
@@ -266,13 +162,4 @@ def _shift_value_signed(self, port: Union[Port, WavePort]) -> float:
266162
new_pos = grid_centers[shifted_index]
267163
return new_pos - port_position
268164

269-
def sim_data_by_task_name(self, task_name: str) -> SimulationData:
270-
"""Get the simulation data by task name, avoids emitting warnings from the ``Simulation``."""
271-
log_level_cache = config.logging_level
272-
config.logging_level = "ERROR"
273-
sim_data = self.batch_data[task_name]
274-
config.logging_level = log_level_cache
275-
return sim_data
276-
277-
278165
AbstractComponentModeler.update_forward_refs()

tidy3d/plugins/smatrix/component_modelers/modal.py

Lines changed: 1 addition & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -72,20 +72,6 @@ class ComponentModeler(AbstractComponentModeler):
7272
:class:`ComponentModeler`. ``run_only`` contains the scattering matrix indices that the user wants to run as a
7373
source. If any indices are excluded, they will not be run."""
7474

75-
verbose: bool = pd.Field(
76-
False,
77-
title="Verbosity",
78-
description="Whether the :class:`.ComponentModeler` should print status and progressbars.",
79-
)
80-
81-
callback_url: str = pd.Field(
82-
None,
83-
title="Callback URL",
84-
description="Http PUT url to receive simulation finish event. "
85-
"The body content is a json file with fields "
86-
"``{'id', 'status', 'name', 'workUnit', 'solverVersion'}``.",
87-
)
88-
8975
@pd.validator("simulation", always=True)
9076
def _sim_has_no_sources(cls, val):
9177
"""Make sure simulation has no sources as they interfere with tool."""
@@ -271,80 +257,4 @@ def get_max_mode_indices(matrix_elements: tuple[str, int]) -> int:
271257
max_mode_index_out = get_max_mode_indices(self.matrix_indices_monitor)
272258
max_mode_index_in = get_max_mode_indices(self.matrix_indices_source)
273259

274-
return max_mode_index_out, max_mode_index_in
275-
276-
def _construct_smatrix(self) -> ModalPortDataArray:
277-
"""Post process :class:`.BatchData` to generate scattering matrix."""
278-
return self._internal_construct_smatrix(batch_data=self.batch_data)
279-
280-
def _internal_construct_smatrix(self, batch_data: BatchData) -> ModalPortDataArray:
281-
"""Post process :class:`.BatchData` to generate scattering matrix, for internal use only."""
282-
283-
max_mode_index_out, max_mode_index_in = self.max_mode_index
284-
num_modes_out = max_mode_index_out + 1
285-
num_modes_in = max_mode_index_in + 1
286-
port_names_out, port_names_in = self.port_names
287-
288-
values = np.zeros(
289-
(len(port_names_out), len(port_names_in), num_modes_out, num_modes_in, len(self.freqs)),
290-
dtype=complex,
291-
)
292-
coords = {
293-
"port_out": port_names_out,
294-
"port_in": port_names_in,
295-
"mode_index_out": range(num_modes_out),
296-
"mode_index_in": range(num_modes_in),
297-
"f": np.array(self.freqs),
298-
}
299-
s_matrix = ModalPortDataArray(values, coords=coords)
300-
301-
# loop through source ports
302-
for col_index in self.matrix_indices_run_sim:
303-
port_name_in, mode_index_in = col_index
304-
port_in = self.get_port_by_name(port_name=port_name_in)
305-
306-
sim_data = batch_data[self._task_name(port=port_in, mode_index=mode_index_in)]
307-
308-
for row_index in self.matrix_indices_monitor:
309-
port_name_out, mode_index_out = row_index
310-
port_out = self.get_port_by_name(port_name=port_name_out)
311-
312-
# directly compute the element
313-
mode_amps_data = sim_data[port_out.name].copy().amps
314-
dir_out = "-" if port_out.direction == "+" else "+"
315-
amp = mode_amps_data.sel(
316-
f=coords["f"], direction=dir_out, mode_index=mode_index_out
317-
)
318-
source_norm = self._normalization_factor(port_in, sim_data)
319-
s_matrix_elements = np.array(amp.data) / np.array(source_norm)
320-
s_matrix.loc[
321-
{
322-
"port_in": port_name_in,
323-
"mode_index_in": mode_index_in,
324-
"port_out": port_name_out,
325-
"mode_index_out": mode_index_out,
326-
}
327-
] = s_matrix_elements
328-
329-
# element can be determined by user-defined mapping
330-
for (row_in, col_in), (row_out, col_out), mult_by in self.element_mappings:
331-
port_out_from, mode_index_out_from = row_in
332-
port_in_from, mode_index_in_from = col_in
333-
coords_from = {
334-
"port_in": port_in_from,
335-
"mode_index_in": mode_index_in_from,
336-
"port_out": port_out_from,
337-
"mode_index_out": mode_index_out_from,
338-
}
339-
340-
port_out_to, mode_index_out_to = row_out
341-
port_in_to, mode_index_in_to = col_out
342-
coords_to = {
343-
"port_in": port_in_to,
344-
"mode_index_in": mode_index_in_to,
345-
"port_out": port_out_to,
346-
"mode_index_out": mode_index_out_to,
347-
}
348-
s_matrix.loc[coords_to] = mult_by * s_matrix.loc[coords_from].values
349-
350-
return s_matrix
260+
return max_mode_index_out, max_mode_index_in

0 commit comments

Comments
 (0)