Source code for kqcircuits.simulations.abstract_simulation

# This code is part of KQCircuits
# Copyright (C) 2026 IQM Finland Oy
#
# This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program. If not, see
# https://www.gnu.org/licenses/gpl-3.0.html.
#
# The software distribution should follow IQM trademark policy for open-source software
# (meetiqm.com/iqm-open-source-trademark-policy). IQM welcomes contributions to the code.
# Please see our contribution agreements for individuals (meetiqm.com/iqm-individual-contributor-license-agreement)
# and organizations (meetiqm.com/iqm-organization-contributor-license-agreement).


from abc import ABC, abstractmethod
import ast
import logging
import json
from typing import Any

from kqcircuits.elements.element import Element
from kqcircuits.pya_resolver import pya
from kqcircuits.util.parameters import Param, pdt
from kqcircuits.util.library_helper import load_libraries

simulation_layer_dict = {}

load_libraries()  # allows parameter overrides from defaults.py


[docs] def get_simulation_layer_by_name(layer_name: str) -> pya.LayerInfo: """Returns layer info of given name. If layer doesn't exist, a new layer is created. New layers are created with data type = 0 and layer numbering starts from 1000.""" if layer_name not in simulation_layer_dict: simulation_layer_dict[layer_name] = pya.LayerInfo(len(simulation_layer_dict) + 1000, 0, layer_name) return simulation_layer_dict[layer_name]
[docs] class AbstractSimulation(ABC): """Abstract base class for all simulation classes, including cross-section and 3D simulations.""" LIBRARY_NAME = None # This is needed by some methods inherited from Element. # Parameters name = Param(pdt.TypeString, "Name of the simulation", "Simulation") units = Param(pdt.TypeString, "Unit of length", "um") material_dict = Param( pdt.TypeString, "Dictionary of dielectric materials", "{'silicon': {'permittivity': 11.45}}", docstring="Contains the material names as keys and material properties as values. If the material property has " "positive value for keyword 'conductivity' or contains keyword 'london_penetration_depth', the material is " "considered as metal. Otherwise, the material is considered as dielectric. The material names 'vacuum' and " "'pec' (perfect electric conductor) are excluded and they can be used without defining them explicitly. The " "property keyword 'permittivity' is fully supported and keywords 'conductivity', 'dielectric_loss_tangent', " "'permeability', 'magnetic_loss_tangent', and 'london_penetration_depth' are partly supported depending on the " "solver.", ) extra_json_data = Param( pdt.TypeNone, "Extra data in dict form to store in resulting JSON", None, docstring="This field may be used to store 'virtual' parameters useful for your simulations", ) def __init__(self, layout, cell=None, **kwargs): """Common constructor for simulation classes. Any parameter can be passed as a keyword argument. Args: layout: the layout on which to create the simulation cell: top cell for the simulation. If not given, a new cell will be created. """ if layout is None or not isinstance(layout, pya.Layout): error_text = "Cannot create simulation with invalid or nil layout." error = ValueError(error_text) logging.error(error_text) raise error self.layout = layout schema = type(self).get_schema() # Apply kwargs or default value for parameter, item in schema.items(): if parameter in kwargs: setattr(self, parameter, kwargs[parameter]) else: setattr(self, parameter, item.default) unused_kwargs = set(kwargs.keys()) - set(schema.keys()) if unused_kwargs: logging.warning(f"Trying to set parameters which do not exist: {unused_kwargs} for {self.name}") self.cell = layout.create_cell(self.name) if cell is None else cell self._data = {} self._compute_simulation_data() self._geometry_key = self._compute_geometry_key() self._geometry_hash = hash(self._geometry_key) # hash is computed to speed up the equality comparison # Inherit specific methods get_schema = classmethod(Element.get_schema.__func__) @abstractmethod def _compute_simulation_data(self): """Builds the simulation model. Is called from __init__. This method is to be overridden, and the overriding method should modify self.data to contain everything needed for the simulation model. Keywords 'name', 'units', and 'material_dict' are processed outside this method. """ def _compute_geometry_key(self): """Compute a unique hashable object for the geometry. This determines whether the meshing can be reused between simulations.""" layer_data = [] for name, data in self._data["layers"].items(): layer_info = get_simulation_layer_by_name(name) layer_index = self.layout.layer(layer_info) shapes_data = tuple(l.shape().to_s() for l in self.cell.begin_shapes_rec(layer_index)) layer_data.append((layer_info.to_s(), shapes_data, tuple(data.items()))) return json.dumps(layer_data)
[docs] def geometry_equals_to(self, other) -> bool: """Returns whether the geometries of self and other are identical.""" if not isinstance(other, AbstractSimulation): raise TypeError(f"Cannot compare simulation with {type(other)}.") return self._geometry_hash == other._geometry_hash and self._geometry_key == other._geometry_key
[docs] def get_material_dict(self) -> dict[str, dict]: """Return material_dict as dictionary.""" return ast.literal_eval(self.material_dict) if isinstance(self.material_dict, str) else self.material_dict
[docs] def check_material_dict(self) -> dict[str, dict]: """Check that used materials are defined in material_dict and return material_dict as dictionary.""" materials = {layer["material"] for layer in self._data["layers"].values() if "material" in layer} mater_dict = self.get_material_dict() for name in materials: if name not in mater_dict and name not in ["pec", "vacuum", None]: raise ValueError(f"Material '{name}' used but not defined in {self.__class__.__name__}.material_dict") return mater_dict
[docs] def is_metal(self, material: str) -> bool: """Return True if material is metal and False otherwise""" if material == "pec": return True material_definition = self.get_material_dict().get(material, {}) return material_definition.get("conductivity", 0) > 0 or "london_penetration_depth" in material_definition
[docs] def get_parameters(self): """Return dictionary with all parameters and their values.""" return {param: getattr(self, param) for param in type(self).get_schema()}
[docs] def get_simulation_data(self) -> dict[str, Any]: """Return the simulation data in dictionary form.""" return { "simulation_name": self.name, "units": self.units, "material_dict": self.check_material_dict(), **self._data, }
[docs] def get_layers(self) -> list[pya.LayerInfo]: """Returns simulation layer numbers in list. Only return layers that are in use.""" return [pya.LayerInfo(d["layer"], 0) for d in self._data["layers"].values() if "layer" in d]
def _warn_of_small_shapes(self, small_shape_area: float): """Warns of small shapes in simulation layers.""" if small_shape_area <= 0.0: return for name, layer in self._data["layers"].items(): if "layer" not in layer: continue shapes = self.cell.shapes(self.layout.layer(layer["layer"], 0)) for shape in shapes.each(): area = shape.darea() # area in µm² if area < small_shape_area: logging.warning( f"Layer '{name}' of simulation '{self.name}' contains a small shape of {round(area, 3)} µm² " f"with bounding box {shape.dbbox()}." )