Skip to content

Commit faf0199

Browse files
Starting to remove incompatibiltiies
1 parent 8acd1a6 commit faf0199

File tree

3 files changed

+1
-498
lines changed

3 files changed

+1
-498
lines changed

tidy3d/plugins/smatrix/component_modelers/base.py

Lines changed: 0 additions & 164 deletions
Original file line numberDiff line numberDiff line change
@@ -71,57 +71,6 @@ class AbstractComponentModeler(ABC, Tidy3dBaseModel):
7171
"pulse spectrum which can have a nonzero DC component.",
7272
)
7373

74-
folder_name: str = pd.Field(
75-
"default",
76-
title="Folder Name",
77-
description="Name of the folder for the tasks on web.",
78-
)
79-
80-
verbose: bool = pd.Field(
81-
False,
82-
title="Verbosity",
83-
description="Whether the :class:`.AbstractComponentModeler` should print status and progressbars.",
84-
)
85-
86-
callback_url: str = pd.Field(
87-
None,
88-
title="Callback URL",
89-
description="Http PUT url to receive simulation finish event. "
90-
"The body content is a json file with fields "
91-
"``{'id', 'status', 'name', 'workUnit', 'solverVersion'}``.",
92-
)
93-
94-
path_dir: str = pd.Field(
95-
DEFAULT_DATA_DIR,
96-
title="Directory Path",
97-
description="Base directory where data and batch will be downloaded.",
98-
)
99-
100-
solver_version: str = pd.Field(
101-
None,
102-
title="Solver Version",
103-
description_str="Custom solver version to use. "
104-
"If not supplied, uses default for the current front end version.",
105-
)
106-
107-
# TODO properly refactor, plugins should not have web methods.
108-
batch_cached: Batch = pd.Field(
109-
None,
110-
title="Batch (Cached)",
111-
description="DEPRECATED: Optional field to specify ``batch``. Only used as a workaround internally "
112-
"so that ``batch`` is written when ``.to_file()`` and then the proper batch is loaded "
113-
"from ``.from_file()``. We recommend leaving unset as setting this field along with "
114-
"fields that were not used to create the task will cause errors.",
115-
)
116-
117-
@pd.root_validator(pre=False)
118-
def _warn_deprecation_2_10(cls, values):
119-
log.warning(
120-
"ℹ️ ⚠️ Backwards compatibility will be broken for all the ComponentModeler classes in tidy3d version 2.10. Migration documentation will be provided, and existing functionality can be accessed in a different way.",
121-
log_once=True,
122-
)
123-
return values
124-
12574
@pd.validator("simulation", always=True)
12675
def _sim_has_no_sources(cls, val):
12776
"""Make sure simulation has no sources as they interfere with tool."""
@@ -152,117 +101,13 @@ def _task_name(port: Port, mode_index: Optional[int] = None) -> str:
152101
return f"smatrix_{port.name}_{mode_index}"
153102
return f"smatrix_{port.name}"
154103

155-
@cached_property
156-
def sim_dict(self) -> dict[str, Simulation]:
157-
"""Generate all the :class:`.Simulation` objects for the S matrix calculation."""
158-
159-
def to_file(self, fname: str) -> None:
160-
"""Exports :class:`AbstractComponentModeler` instance to .yaml, .json, or .hdf5 file
161-
162-
Parameters
163-
----------
164-
fname : str
165-
Full path to the .yaml or .json file to save the :class:`AbstractComponentModeler` to.
166-
167-
Example
168-
-------
169-
>>> modeler.to_file(fname='folder/sim.json') # doctest: +SKIP
170-
"""
171-
172-
batch_cached = self._cached_properties.get("batch")
173-
if batch_cached is not None:
174-
jobs_cached = batch_cached._cached_properties.get("jobs")
175-
if jobs_cached is not None:
176-
jobs = {}
177-
for key, job in jobs_cached.items():
178-
task_id = job._cached_properties.get("task_id")
179-
jobs[key] = job.updated_copy(task_id_cached=task_id)
180-
batch_cached = batch_cached.updated_copy(jobs_cached=jobs)
181-
self = self.updated_copy(batch_cached=batch_cached)
182-
super(AbstractComponentModeler, self).to_file(fname=fname) # noqa: UP008
183-
184-
@cached_property
185-
def batch(self) -> Batch:
186-
""":class:`.Batch` associated with this component modeler."""
187-
# TODO properly refactor, plugins data types should not have web methods.
188-
from tidy3d.web.api.container import Batch
189-
190-
if self.batch_cached is not None:
191-
return self.batch_cached
192-
193-
# first try loading the batch from file, if it exists
194-
batch_path = self._batch_path
195-
196-
if os.path.exists(batch_path):
197-
return Batch.from_file(fname=batch_path)
198-
199-
return Batch(
200-
simulations=self.sim_dict,
201-
folder_name=self.folder_name,
202-
callback_url=self.callback_url,
203-
verbose=self.verbose,
204-
solver_version=self.solver_version,
205-
)
206-
207-
@cached_property
208-
def batch_path(self) -> str:
209-
"""Path to the batch saved to file."""
210-
return self.batch._batch_path(path_dir=self.path_dir)
211-
212-
@cached_property
213-
def batch_data(self) -> BatchData:
214-
"""The :class:`.BatchData` associated with the simulations run for this component modeler."""
215-
return self.batch.run(path_dir=self.path_dir)
216-
217-
def get_path_dir(self, path_dir: str) -> None:
218-
"""Check whether the supplied 'path_dir' matches the internal field value."""
219-
220-
if path_dir != self.path_dir and path_dir != DEFAULT_DATA_DIR:
221-
raise ValueError(
222-
f"'path_dir' of '{path_dir}' passed, but 'ComponentModeler.path_dir' is "
223-
f"{self.path_dir}. Moving forward, only the 'ComponentModeler.path_dir' will be "
224-
"used internally, please update your scripts accordingly to avoid passing this "
225-
"value to methods. "
226-
)
227-
228-
return self.path_dir
229-
230-
@cached_property
231-
def _batch_path(self) -> str:
232-
"""Where we store the batch for this :class:`AbstractComponentModeler` instance after the run."""
233-
return os.path.join(self.path_dir, "batch" + str(hash(self)) + ".hdf5")
234-
235-
def _run_sims(self, path_dir: str = DEFAULT_DATA_DIR) -> BatchData:
236-
"""Run :class:`.Simulation` for each port and return the batch after saving."""
237-
_ = self.get_path_dir(path_dir)
238-
self.batch.to_file(self._batch_path)
239-
batch_data = self.batch_data
240-
return batch_data
241-
242104
def get_port_by_name(self, port_name: str) -> Port:
243105
"""Get the port from the name."""
244106
ports = [port for port in self.ports if port.name == port_name]
245107
if len(ports) == 0:
246108
raise Tidy3dKeyError(f'Port "{port_name}" not found.')
247109
return ports[0]
248110

249-
@abstractmethod
250-
def _construct_smatrix(self, batch_data: BatchData) -> DataArray:
251-
"""Post process :class:`.BatchData` to generate scattering matrix."""
252-
253-
@abstractmethod
254-
def _internal_construct_smatrix(self, batch_data: BatchData) -> DataArray:
255-
"""Post process :class:`.BatchData` to generate scattering matrix, for internal use only."""
256-
257-
def run(self, path_dir: str = DEFAULT_DATA_DIR) -> DataArray:
258-
"""Solves for the scattering matrix of the system."""
259-
_ = self.get_path_dir(path_dir)
260-
return self._construct_smatrix()
261-
262-
def load(self, path_dir: str = DEFAULT_DATA_DIR) -> DataArray:
263-
"""Load a scattering matrix from saved :class:`.BatchData` object."""
264-
return self.run(path_dir=path_dir)
265-
266111
@staticmethod
267112
def inv(matrix: DataArray):
268113
"""Helper to invert a port matrix."""
@@ -317,13 +162,4 @@ def _shift_value_signed(self, port: Union[Port, WavePort]) -> float:
317162
new_pos = grid_centers[shifted_index]
318163
return new_pos - port_position
319164

320-
def sim_data_by_task_name(self, task_name: str) -> SimulationData:
321-
"""Get the simulation data by task name, avoids emitting warnings from the ``Simulation``."""
322-
log_level_cache = config.logging_level
323-
config.logging_level = "ERROR"
324-
sim_data = self.batch_data[task_name]
325-
config.logging_level = log_level_cache
326-
return sim_data
327-
328-
329165
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)