# This code is part of KQCircuits
# Copyright (C) 2021 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).
import ast
import json
from math import inf
import logging
from kqcircuits.pya_resolver import pya
from kqcircuits.simulations.abstract_simulation import AbstractSimulation, get_simulation_layer_by_name
from kqcircuits.simulations.partition_region import PartitionRegion
from kqcircuits.simulations.port import InternalPort, EdgePort
from kqcircuits.util.geometry_helper import (
region_with_merged_polygons,
region_with_merged_points,
merge_points_and_match_on_edges,
)
from kqcircuits.util.geometry_json_encoder import GeometryJsonEncoder
from kqcircuits.util.parameters import Param, pdt
from kqcircuits.simulations.export.util import find_edge_from_point_in_polygons
[docs]
class LayeredSimulation(AbstractSimulation):
"""Base class for layered 2.5 dimensional simulation models.
This class is intended to be subclassed by a simulation implementation; The subclass should implement the
method 'create_geometry' which defines the simulation geometry and materials. The helper function 'insert_layer',
'insert_drop_down_layers', or similar should be called internally to create layers.
"""
partition_regions = Param(
pdt.TypeString,
"Parameters of partition regions as list of dictionaries",
[],
docstring="See constructor of the PartitionRegion class for parameter definitions.",
)
use_ports = Param(pdt.TypeBoolean, "Turn off to disable all ports (for debugging)", True)
port_size = Param(
pdt.TypeDouble,
"Width and height of wave ports",
400.0,
unit="µm",
docstring="The port size can also be set as a list specifying the extensions from the center of "
"the port to left, right, down and up, respectively.",
)
minimum_point_spacing = Param(pdt.TypeDouble, "Tolerance for merging adjacent points in polygon", 0.01, unit="µm")
polygon_tolerance = Param(pdt.TypeDouble, "Tolerance for merging adjacent polygons in a layer", 0.004, unit="µm")
small_shape_area = Param(pdt.TypeDouble, "Area below which shapes will trigger a warning.", 1.0, unit="µm²")
parent_simulation = Param(pdt.TypeNone, "Instance of LayerSimulation subclass to determine excitations", None)
def _compute_simulation_data(self):
"""Builds the simulation model."""
self._data["parent_simulation"] = self.get_parameters()["parent_simulation"]
self.layers = {}
self.ports = []
self.create_geometry()
self._process_layers()
[docs]
def create_geometry(self):
"""Creates the simulation geometry.
This method is to be overridden, and the overriding method should describe self.layers and self.ports needed for
the simulation geometry. It's recommended to use self.insert_layer, self.insert_drop_down_layers, or similar to
add new layers into the model.
"""
def _process_layers(self):
"""Processes layers, ports and partition regions into self._data. Is called after the build method.
Internally,
* calculates bounding box from self.layers
* limits partition regions inside the bounding box
* process altitude of ports if given as face
* determines excitations
* processes layer data and partition regions into self._data["layers"]
* warns or small shapes in self._data["layers"]
* processes port data into self._data["ports"]
* visualizes ports and partition regions in layout layers
"""
self._calculate_bounding_box()
self._data["box"] = self._box
for part in self._parts:
part.limit_box(self._bottom, self._top, self._box, self.layout.dbu)
self._process_ports()
self._split_metal_layers_by_excitation()
self._produce_layer_data()
self._warn_of_small_shapes(self.small_shape_area)
self._produce_port_data()
# Visualise partition regions and ports
for part in self._parts:
# Warn of empty partition regions
if not any(name.endswith(part.name) for name in self._data["layers"]):
logging.warning(f'Partition region "{part.name}" is empty!')
# Visualise partition regions
if part.visualise:
self.visualise_region(part.region, part.name, f"part_reg_{part.name}")
self._visualise_ports()
def _compute_geometry_key(self):
"""Computes a unique hashable object for the geometry. This determines whether the meshing can be reused between
simulations."""
return super()._compute_geometry_key(), *[
json.dumps(self._data[k], cls=GeometryJsonEncoder) for k in ["box", "ports"]
]
[docs]
def simplified_region(self, region, expansion=0.0):
"""Returns a region that is simplified by functions region_with_merged_polygons and region_with_merged_points.
More precisely:
- Merges polygons ignoring gaps that are smaller than self.polygon_tolerance
- Expands/shrinks region by amount given by 'expansion'
- In each polygon of the region, removes points that are closer than self.minimum_point_spacing to other points
"""
return region_with_merged_points(
region_with_merged_polygons(
region, tolerance=self.polygon_tolerance / self.layout.dbu, expansion=expansion / self.layout.dbu
),
tolerance=self.minimum_point_spacing / self.layout.dbu,
)
[docs]
def insert_layer(self, layer_name, region, z0, z1, **params):
"""Adds layer parameters into 'self.layers' if region is non-empty."""
if not region.is_empty():
self.layers[layer_name] = {
"region": region.dup(),
"bottom": self.altitude(min(z0, z1)),
"top": self.altitude(max(z0, z1)),
**params,
}
[docs]
def insert_drop_down_layers(self, stack, z0):
"""Produces the drop-down layer stack-up and adds the layers into 'self.layers'.
Each layer is split into sub-layers by their z-level.
Args:
stack: list of layers in form of tuples containing (region, layer name, thickness, material)
z0: the base z-level for the layer stack-up
"""
levels = {} # existing z-levels based on layers underneath (z-level as key and region as value)
for region, layer_name, thickness, material in stack:
if region.is_empty():
continue
# Split the layer into z-levels
region_levels = {} # the layer region divided into z-levels
non_region_levels = {} # the z-levels outside the layer region
sum_reg = pya.Region()
for z, reg in levels.items():
intersection = reg & region
if not intersection.is_empty():
region_levels[z] = intersection
subtraction = reg - region
if not subtraction.is_empty():
non_region_levels[z] = subtraction
sum_reg += reg
on_base_level = region - sum_reg
if not on_base_level.is_empty():
region_levels[self.altitude(z0)] = on_base_level
# Create collective layer for klayout visualization if the layer is split
if len(region_levels) > 1:
self.cell.shapes(self.layout.layer(get_simulation_layer_by_name(layer_name))).insert(region)
# Apply parts of divided layers into self.layers
for i, (z, reg) in enumerate(sorted(region_levels.items())):
self.insert_layer(
f"{layer_name}_{i}" if len(region_levels) > 1 else layer_name,
reg,
z,
z + thickness,
material=material,
)
# Update existing z-levels dictionary
if thickness != 0.0:
levels = non_region_levels
for z, reg in region_levels.items():
top_z = self.altitude(z + thickness)
if top_z in levels:
levels[top_z] += reg
else:
levels[top_z] = reg
def _calculate_bounding_box(self):
"""Calculates bounding box from self.layers, and stores it into self._box, self._bottom, and self._top."""
self._box, self._bottom, self._top = pya.DBox(), 1e30, -1e30
for data in self.layers.values():
self._box = self._box + data["region"].bbox().to_dtype(self.layout.dbu)
self._bottom = min(self._bottom, data["bottom"])
self._top = max(self._top, data["top"])
def _process_ports(self):
"""Processes the unset terms of self.ports, especially, the altitude port.z is processed."""
for port in self.ports:
if port.z is None:
raise ValueError("Port altitude is not explicitly given.")
def _split_metal_layers_by_excitation(self):
"""Split metal layers in self.layers such that ground and signal metals are separated.
Adds 'excitation' keyword to metal layers. Excitation 0 means ground and other excitations are signals.
The signal numbers start from 1, and they are ordered such that first comes metals connected to ports (ordered
by port number). The floating metals (that are not connected to any port) are also assigned as signals and their
numbering is quite arbitrary after the port metals. Note that the excitation number does not necessarily match
with port numbers.
This function should be called before `_produce_layers`.
"""
def are_connected(part1, part2):
"""Return True only if part1 and part2 are connected."""
for n1, r1 in part1.items():
l1 = self.layers[n1]
for n2, r2 in part2.items():
if n1 == n2:
continue
l2 = self.layers[n2]
if l1["bottom"] <= l2["top"] and l2["bottom"] <= l1["top"] and not r1.interacting(r2).is_empty():
return True
return False
def merge_parts(part1, part2):
"""Merge part1 into part2 and clear part1."""
for n, r in part1.items():
if n in part2:
part2[n].insert(r)
else:
part2[n] = r
part1.clear()
def get_connected_part(pos, height):
"""Return the first part from parts that covers the point of pos and height. Return empty dictionary if
such part does not exist.
"""
for p in parts:
for n, r in p.items():
layer = self.layers[n]
if layer["bottom"] <= height <= layer["top"] and not r.interacting(pya.Edge(pos, pos)).is_empty():
return p
return {}
# create individual part for each metal polygon
metal_names = [n for n, l in self.layers.items() if self.is_metal(l.get("material"))]
parts = [{n: pya.Region(p)} for n in metal_names for p in self.layers[n]["region"].each()]
# combine connected parts
for i in range(1, len(parts)):
for j in range(i):
if are_connected(parts[i], parts[j]):
merge_parts(parts[j], parts[i])
parts = [p for p in parts if p]
# assign excitation to parts
if self.parent_simulation is not None:
# assign excitation based on parent_simulation
excitation_dict = {}
for layer_name, parent_layer in self.parent_simulation._data["layers"].items():
if "excitation" not in parent_layer:
continue
excitation = parent_layer["excitation"]
if excitation not in excitation_dict:
excitation_dict[excitation] = {}
bottom, top = parent_layer["z"], parent_layer["z"] + parent_layer["thickness"]
sim_layer = get_simulation_layer_by_name(layer_name)
region = pya.Region(self.parent_simulation.cell.shapes(self.parent_simulation.layout.layer(sim_layer)))
for p in parts:
for n, r in p.items():
layer = self.layers[n]
if layer["top"] >= bottom and layer["bottom"] <= top and not r.interacting(region).is_empty():
merge_parts(p, excitation_dict[excitation])
break
excitations = [excitation_dict.get(i, {}) for i in range(max(excitation_dict.keys()) + 1)]
else:
# assign excitation based on ports
ports = sorted(self.ports, key=lambda p: p.number) if self.use_ports else []
excitations = [{}]
for port in ports:
signal_z = self.altitude(port.z)
if hasattr(port, "ground_location"):
v_mps = port.signal_location - port.ground_location
v_mps = self.minimum_point_spacing * v_mps / v_mps.abs()
signal_loc = (port.signal_location + v_mps).to_itype(self.layout.dbu)
if not port.floating:
ground_loc = (port.ground_location - v_mps).to_itype(self.layout.dbu)
merge_parts(get_connected_part(ground_loc, signal_z), excitations[0]) # ground excitation
else:
signal_loc = port.signal_location.to_itype(self.layout.dbu)
# append port excitation to excitations if it exists
port_excitation = {}
merge_parts(get_connected_part(signal_loc, signal_z), port_excitation)
if port_excitation:
excitations.append(port_excitation)
# assign remaining parts as ground if they touch edge, bottom, or top of the simulation box
ground_edges = pya.Region(self._box.to_itype(self.layout.dbu)).edges()
for part in parts:
if any(
self.layers[n]["bottom"] <= self._bottom
or self._top <= self.layers[n]["top"]
or not r.interacting(ground_edges).is_empty()
for n, r in part.items()
):
merge_parts(part, excitations[0]) # ground excitation
# assign remaining parts as floating
for part in parts:
floating_excitation = {}
merge_parts(part, floating_excitation)
if floating_excitation:
excitations.append(floating_excitation)
# split metals by excitations
for name in metal_names:
if name.endswith("_metal"): # split base metal layers
for key, part in enumerate(excitations):
if name in part.keys():
n = name.replace("_metal", "_ground" if key == 0 else f"_signal_{key}")
self.layers[n] = {**self.layers[name], "region": part[name], "excitation": key}
del self.layers[name]
else: # split metals with multiple excitations in general
layer_excitations = []
for key, part in enumerate(excitations):
if name in part.keys():
layer_excitations.append(key)
if len(layer_excitations) > 1:
for i, key in enumerate(layer_excitations):
self.layers[f"{name}_{key}"] = {
**self.layers[name],
"region": excitations[key][name],
"excitation": key,
}
del self.layers[name]
else:
self.layers[name]["excitation"] = layer_excitations[0]
def _produce_layer_data(self):
"""Finalizes layers and partition regions and produces layer data into self._data["layers"].
Some rules of process:
* Metals and non-model objects are left without partitioning. We assume that these do not overlap.
* Vacuum or dielectric objects are partitioned if self._parts is not empty. If these objects overlap, the
smaller is subtracted from larger.
* Non-model objects are subtracted from vacuum or dielectric objects only if non-model object is mentioned in
subtract_keys of vacuum or dielectric object.
"""
layers = []
def can_modify(obj):
return obj.get("material") is not None and not self.is_metal(obj["material"])
def are_separate(obj, tool):
"""Returns True if obj and tool do not overlap"""
if obj["bottom"] == obj["top"] and tool["bottom"] == tool["top"]:
if obj["bottom"] != tool["bottom"]:
return True
elif obj["top"] <= tool["bottom"] or tool["top"] <= obj["bottom"]:
return True
return tool["region"].overlapping(obj["region"].sized(-1)).is_empty()
def subtract(obj, lay):
"""Subtracts layers[lay] from obj."""
if lay in obj.get("subtract", set()):
return # already subtracted
tool = layers[lay]
if tool.get("material", None) is None and all(n not in tool["name"] for n in obj.get("subtract_keys", [])):
return # non-material tools are subtracted only if specified in subtract keys
if obj["bottom"] != obj["top"] and tool["bottom"] == tool["top"]:
return # do not subtract sheet from solid
if are_separate(obj, tool):
return # ignore separate objects
obj["subtract"] = obj.get("subtract", set()) | {lay}
def subtract_avoid_hole_grid(obj_region, tool_region):
"""Subtracts the tool region from the object region unless the subtraction creates lots of holes. Avoiding
subtraction with plenty of holes is important for the performance for example in case of lots of vias.
"""
if tool_region.inside(obj_region).count() <= 10 * obj_region.count():
obj_region -= tool_region
def sub_layers(obj, bottom=-inf, top=inf):
"""Returns object divided into sub-layers such that the subtractions in obj['subtract'] are applied.
The return format for sub-layers is a list of tuples containing bottom height, top height, and region.
Only non-empty regions are returned.
"""
# Determine z-intersection between given bottom and top and the object
bottom, top = max(bottom, obj["bottom"]), min(top, obj["top"])
if bottom > top:
return []
# Get sub-layer divisions for all subtracted objects
subtracts_layers = [sub_layers(layers[s], bottom, top) for s in obj.get("subtract", set())]
# Special case for sheet object
if obj["bottom"] == obj["top"]:
z = obj["bottom"]
below_region = obj["region"].dup()
above_region = obj["region"].dup()
for subtract_layers in subtracts_layers:
for b, t, r in subtract_layers:
if b == z == t or b <= z < t:
subtract_avoid_hole_grid(above_region, r)
if b == z == t or b < z <= t:
subtract_avoid_hole_grid(below_region, r)
region = below_region + above_region
return [] if region.sized(-1).is_empty() else [(z, z, region)]
# For solid objects only, define z-intervals for the sub-layers
subtract_zs = {z for subtract_layers in subtracts_layers for b, t, _ in subtract_layers for z in (b, t)}
if bottom == top: # if sheet projection is requested, defines z-intervals above and below
bottom = max([obj["bottom"]] + [z for z in subtract_zs if z < bottom])
top = min([obj["top"]] + [z for z in subtract_zs if top < z])
zs = sorted({bottom, top} | {z for z in subtract_zs if bottom < z < top})
# Return sub-layers for determined z-intervals
_layers = []
for _bottom, _top in zip(zs[:-1], zs[1:]):
region = obj["region"].dup()
for subtract_layers in subtracts_layers:
for b, t, r in subtract_layers:
if b <= _bottom and _top <= t:
subtract_avoid_hole_grid(region, r)
if not region.sized(-1).is_empty():
_layers.append((_bottom, _top, region))
return _layers
def exists(obj):
"""Hardens subtractions and returns True if geometry exists."""
if "subtract" in obj:
_layers = sub_layers(obj)
obj["region"] = pya.Region()
if _layers:
obj["bottom"] = _layers[0][0]
obj["top"] = _layers[-1][1]
for _, _, r in _layers:
obj["region"] += r
obj["region"].merge()
obj["subtract"] = {s for s in obj["subtract"] if not are_separate(obj, layers[s])}
return not obj["region"].is_empty()
def covering_regions(obj, tool):
"""Returns tuple of regions where tool covers obj from above and below, respectively."""
if obj["top"] < tool["bottom"] or tool["top"] < obj["bottom"]:
return pya.Region(), pya.Region()
region = obj["region"] & tool["region"]
if region.is_empty():
return pya.Region(), pya.Region()
above = region.dup() if obj["top"] < tool["top"] else pya.Region()
below = region.dup() if tool["bottom"] < obj["bottom"] else pya.Region()
for s in tool.get("subtract", set()):
s_above, s_below = covering_regions(obj, layers[s])
above -= s_above
below -= s_below
return above, below
layer_list = [{"name": name, **dict(layer.items())} for name, layer in self.layers.items()]
part_list = [
{
"name": part.name,
"bottom": self.altitude(part.z[0]),
"top": self.altitude(part.z[1]),
"region": part.region.dup(),
}
for part in self._parts
if part.face is None
]
# subtract the previous partition region from the latter if covering the z-range
for i, part1 in enumerate(part_list):
for part2 in part_list[i + 1 :]:
if part1["bottom"] <= part2["bottom"] and part2["top"] <= part1["top"]:
part2["region"] -= part1["region"]
merge_points_and_match_on_edges([part["region"] for part in part_list])
for layer in sorted(layer_list, key=lambda x: (can_modify(x), x["top"] - x["bottom"], x["region"].area())):
if can_modify(layer):
# subtract layers that are added to layer_list
for i in range(len(layers)):
subtract(layer, i)
# partition the layer into sub-layers
for part in part_list:
if are_separate(layer, part):
continue # ignore separate objects
intersection = {
"bottom": max(layer["bottom"], part["bottom"]),
"top": min(layer["top"], part["top"]),
"region": layer["region"] & part["region"],
"material": layer.get("material", None),
"subtract_keys": layer.get("subtract_keys", []),
}
for s in layer.get("subtract", set()):
subtract(intersection, s)
if exists(intersection):
layers.append(intersection)
subtract(part, len(layers) - 1)
subtract(layer, len(layers) - 1)
intersection["name"] = (layer["name"] if "used" in part or exists(part) else "") + part["name"]
part["used"] = True
# add non-partitioned parts of the layer
if exists(layer):
layers.append(layer)
merge_points_and_match_on_edges([layer["region"] for layer in layers])
# Indicate background layer for each sheet
for layer in layers:
if can_modify(layer) and layer["bottom"] == layer["top"]:
max_overlap = 0
for solid in layers:
if solid.get("material", None) == layer["material"] and solid["bottom"] < solid["top"]:
overlap = max(r.area() for r in covering_regions(layer, solid))
if overlap > max_overlap:
layer["background"] = solid["name"]
max_overlap = overlap
# produce self.layers from layers
self._data["layers"] = {}
for layer in layers:
if layer["region"].is_empty():
continue # ignore layers with empty region
sim_layer = get_simulation_layer_by_name(layer["name"])
self.cell.shapes(self.layout.layer(sim_layer)).insert(layer["region"])
limit_region = pya.Region(self._box.to_itype(self.layout.dbu)).inside(layer["region"]).is_empty()
subtract = [
layers[n]["name"]
for n in sorted(layer.get("subtract", set()), reverse=True)
if layers[n]["name"] in self._data["layers"]
]
other_keys = {"material", "background", "excitation"}
self._data["layers"][layer["name"]] = {
"z": self.altitude(layer["bottom"]),
"thickness": self.altitude(layer["top"] - layer["bottom"]),
**({"layer": sim_layer.layer} if limit_region else {}),
**{k: v for k, v in layer.items() if k in other_keys and v is not None},
**({"subtract": subtract} if subtract else {}),
}
[docs]
@staticmethod
def altitude(z):
"""Returns rounded value of z to avoid issues due to rounding errors."""
return round(z, 12)
[docs]
def get_parameters(self):
"""Return dictionary with all parameters and their values."""
return {
**super().get_parameters(),
"parent_simulation": self.parent_simulation.name if self.parent_simulation is not None else "",
}
[docs]
def get_partition_regions(self):
"""Returns partition regions for the simulation instance.
If member function not overridden, will simply return whatever was passed as ``partition_regions``, if any.
Can be overridden, for example, to use partition regions defined in kqcircuits.simulations.epr.
"""
return [PartitionRegion(**(ast.literal_eval(r) if isinstance(r, str) else r)) for r in self.partition_regions]
@property
def _parts(self):
"""Dynamic wrapper method to internally get partition regions with possible modifications."""
try:
return self.__parts
except AttributeError:
self.__parts = self.get_partition_regions()
return self.__parts
def _produce_port_data(self):
"""Produces the port data in dictionary form and add the information of port polygon.
Stores the data into self._data["ports"]. Is called after self._produce_layer_data
The port data contains following:
* Items from `Port` instance
* polygon: point coordinates of the port polygon
* signal_edge: point coordinates of the signal edge
* ground_edge: point coordinates of the ground edge
"""
self._data["ports"] = []
if not self.use_ports:
return
# gather port data
dbu = self.layout.dbu
for port in self.ports:
if port.z is None:
continue
port_z = self.altitude(port.z)
# Basic data from Port
p_data = {**port.as_dict()} # Shallow copy to not modify the ports
# Define a 3D polygon for each port
if isinstance(port, EdgePort):
port_size = self.port_size if port.size is None else port.size
ps = port_size if isinstance(port_size, list) else [port_size / 2] * 4
port_z0 = max(port_z - ps[2], self._bottom)
port_z1 = min(port_z + ps[3], self._top)
# Determine which edge this port is on
port_x0 = port_x1 = port.signal_location.x
port_y0 = port_y1 = port.signal_location.y
if abs(port.signal_location.x - self._box.left) < dbu:
port_y0 = max(port.signal_location.y - ps[1], self._box.bottom)
port_y1 = min(port.signal_location.y + ps[0], self._box.top)
elif abs(port.signal_location.x - self._box.right) < dbu:
port_y0 = max(port.signal_location.y - ps[0], self._box.bottom)
port_y1 = min(port.signal_location.y + ps[1], self._box.top)
elif abs(port.signal_location.y - self._box.bottom) < dbu:
port_x0 = max(port.signal_location.x - ps[0], self._box.left)
port_x1 = min(port.signal_location.x + ps[1], self._box.right)
elif abs(port.signal_location.y - self._box.top) < dbu:
port_x0 = max(port.signal_location.x - ps[1], self._box.left)
port_x1 = min(port.signal_location.x + ps[0], self._box.right)
else:
print(self._box, self.box)
raise ValueError(f"Port {port.number} is an EdgePort but not on the edge of the simulation box")
# trim out shielded parts of port polygon
for layer in self._data["layers"].values():
if "excitation" not in layer:
continue # the layer is not metal
if port_z0 < layer["z"] + layer["thickness"] < port_z:
new_z0, new_z1 = layer["z"] + layer["thickness"], port_z1
elif port_z < layer["z"] < port_z1:
new_z0, new_z1 = port_z0, layer["z"]
else:
continue # the metal layer is vertically too far (or on the same face as the port)
if "layer" in layer:
port_box = pya.DBox(port_x0 - dbu, port_y0 - dbu, port_x1 + dbu, port_y1 + dbu) & self._box
layer_region = pya.Region(self.cell.begin_shapes_rec(self.layout.layer(layer["layer"], 0)))
if not (pya.Region(port_box.to_itype(dbu)) - layer_region).is_empty():
continue # the metal layer is not perfectly shielding
port_z0, port_z1 = new_z0, new_z1
p_data["polygon"] = [
[port_x0, port_y0, port_z0],
[port_x1, port_y1, port_z0],
[port_x1, port_y1, port_z1],
[port_x0, port_y0, port_z1],
]
elif isinstance(port, InternalPort):
if hasattr(port, "ground_location"):
try:
# find list of metal polygons at port altitude
region = pya.Region()
for lay in self._data["layers"].values():
if "excitation" in lay and "layer" in lay: # applies only to metal polygons
if lay["z"] <= port_z <= lay["z"] + lay["thickness"]: # z-level should match
region.insert(self.cell.begin_shapes_rec(self.layout.layer(lay["layer"], 0)))
metal_polygons = list(region.each())
# find signal and ground edges from the base metal polygons
_, _, signal_edge = find_edge_from_point_in_polygons(metal_polygons, port.signal_location, dbu)
_, _, ground_edge = find_edge_from_point_in_polygons(metal_polygons, port.ground_location, dbu)
if (
signal_edge.side_of(ground_edge.p1) < 1
or signal_edge.side_of(ground_edge.p2) < 1
or ground_edge.side_of(signal_edge.p1) < 1
or ground_edge.side_of(signal_edge.p2) < 1
):
logging.warning(f"The port {port.number} is not correctly placed between metals")
p_data["polygon"] = [
[signal_edge.x1, signal_edge.y1, port_z],
[signal_edge.x2, signal_edge.y2, port_z],
[ground_edge.x1, ground_edge.y1, port_z],
[ground_edge.x2, ground_edge.y2, port_z],
]
p_data["signal_edge"] = (
(signal_edge.x1, signal_edge.y1, port_z),
(signal_edge.x2, signal_edge.y2, port_z),
)
p_data["ground_edge"] = (
(ground_edge.x1, ground_edge.y1, port_z),
(ground_edge.x2, ground_edge.y2, port_z),
)
except ValueError as e:
logging.warning(
"Unable to create polygon for port %s, because either signal or ground "
"edge is not found.",
port.number,
)
logging.debug(e)
else:
raise ValueError(f"Port {port.number} has unsupported port class {type(port).__name__}")
# Change signal and ground location from DVector to list and add z-component as third term
for location in ["signal_location", "ground_location"]:
if location in p_data:
p_data[location] = [p_data[location].x, p_data[location].y, port_z]
self._data["ports"].append(p_data)
[docs]
def visualise_region(
self,
region: pya.Region,
label: str,
layer: str = "visualisation",
points: list[pya.DPoint] | pya.DPoint | None = None,
) -> None:
"""Visualises given region in a dedicated layer in the preview geometry file.
Arguments:
region: pya.Region to visualise
label: Label of the region, rendered using pya.DText objects
layer: Name of the KLayout layer to place the visualised region
points: pya.DPoint or list of DPoints to place as labels to the region.
By default places one point at the middle of the region's boundary box.
"""
# Not using get_sim_layer since this geometry is not part of any simulation
visualisation_layer = self.layout.layer(layer)
self.cell.shapes(visualisation_layer).insert(region)
if points is None:
points = [region.bbox().to_dtype(self.layout.dbu).center()]
elif isinstance(points, pya.DPoint):
points = [points]
if len(points) <= 1:
self.cell.shapes(visualisation_layer).insert(pya.DText(label, points[0].x, points[0].y))
else:
for i, p in enumerate(points):
self.cell.shapes(visualisation_layer).insert(pya.DText(f"{label}_{i+1}", p.x, p.y))
def _visualise_ports(self):
"""Visualise all ports in a dedicated 'simulation_ports' layer using get_port_data()."""
for port_data in self._data["ports"]:
# Label based on port type
type_label = {"EdgePort": "edge_port", "InternalPort": "internal_port"}
label = f"{type_label.get(port_data['type'], 'unknown_port')}_{port_data['number']}"
label_location = pya.DPoint(*port_data["signal_location"][:2])
# Construct 2D projection from port_data["polygon"] (ignoring z coordinate)
points_2d = [pya.DPoint(*p[:2]) for p in port_data.get("polygon", [])]
# Expand polygon projection outwards from the simulation box in case of EdgePort
if port_data["type"] == "EdgePort":
port_height = max(p[2] for p in port_data["polygon"]) - min(p[2] for p in port_data["polygon"])
point_pairs = [((a - b).length(), a, b) for i, a in enumerate(points_2d) for b in points_2d[i + 1 :]]
distance, p0, p1 = sorted(point_pairs, key=lambda x: x[0])[-1] # select the points furthest apart
normal_vector = pya.DVector(p1.y - p0.y, p0.x - p1.x) / distance
outward_vector = port_height * normal_vector.sprod_sign(p0 - self._box.center()) * normal_vector
points_2d = [p0, p1, p1 + outward_vector, p0 + outward_vector]
# Visualize region
region = pya.Region(pya.DPolygon(points_2d).to_itype(self.layout.dbu))
self.visualise_region(region, label, "simulation_ports", label_location)