layouttk 0.2.0

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation
//! Python entry points for hierarchy operations. Geometry stays native until returned.
use super::*;
use std::collections::BTreeMap;

#[pyfunction]
fn dependencies(layout: &PyLayout, cell: &str, recursive: bool) -> PyResult<Vec<String>> {
    Ok(layout.inner.dependencies(cell, recursive)?)
}

#[pyfunction]
#[allow(clippy::too_many_arguments)]
fn copy_cell(
    layout: &mut PyLayout,
    source: &str,
    name: &str,
    origin: XY,
    angle_deg: f64,
    magnification: f64,
    reflect_x: bool,
) -> PyResult<()> {
    Ok(layout.inner.copy_cell(
        source,
        name,
        point(origin),
        Transform {
            angle_deg,
            magnification,
            reflect_x,
        },
    )?)
}

#[pyfunction]
#[pyo3(signature=(layout,old,new,update_references=true))]
fn rename_cell(
    layout: &mut PyLayout,
    old: &str,
    new: &str,
    update_references: bool,
) -> PyResult<()> {
    Ok(layout
        .inner
        .rename_definition(old, new, update_references)?)
}

#[pyfunction]
#[pyo3(signature=(layout,name,remove_references,allow_external=false))]
fn remove_cell(
    layout: &mut PyLayout,
    name: &str,
    remove_references: bool,
    allow_external: bool,
) -> PyResult<()> {
    Ok(layout
        .inner
        .remove_definition(name, remove_references, allow_external)?)
}

#[pyfunction]
#[pyo3(signature=(layout,old,new,allow_external=false))]
fn replace_references(
    layout: &mut PyLayout,
    old: &str,
    new: &str,
    allow_external: bool,
) -> PyResult<usize> {
    Ok(layout.inner.retarget_references(old, new, allow_external)?)
}

#[pyfunction]
#[allow(clippy::too_many_arguments)]
#[pyo3(signature=(layout,source,roots,conflict,names,layers,text_layers=None,include_dependencies=true,allow_external=false))]
fn import_cells(
    layout: &mut PyLayout,
    source: &PyLayout,
    roots: Vec<String>,
    conflict: &str,
    names: BTreeMap<String, String>,
    layers: BTreeMap<Tag, Tag>,
    text_layers: Option<BTreeMap<Tag, Tag>>,
    include_dependencies: bool,
    allow_external: bool,
) -> PyResult<BTreeMap<String, String>> {
    use crate::hierarchy::NameConflict;
    let conflict = match conflict {
        "error" => NameConflict::Error,
        "rename" => NameConflict::Rename,
        "replace" => NameConflict::Replace,
        _ => {
            return Err(LayoutError::new_err(
                "conflict must be error, rename or replace",
            ));
        }
    };
    let tags = layer_map(layers);
    let text_tags = text_layers.map(layer_map);
    Ok(layout.inner.import_selection(
        &source.inner,
        &roots,
        crate::hierarchy::ImportOptions {
            conflict,
            names: &names,
            layers: &tags,
            text_layers: text_tags.as_ref(),
            include_dependencies,
            allow_external,
        },
    )?)
}

#[pyfunction]
fn extract_elements(layout: &PyLayout, cell: &str, indices: BTreeSet<usize>) -> PyResult<PyLayout> {
    Ok(PyLayout {
        inner: layout.inner.extract_elements(cell, &indices)?,
    })
}

#[pyfunction]
fn remove_elements(layout: &mut PyLayout, cell: &str, indices: BTreeSet<usize>) -> PyResult<usize> {
    Ok(layout.inner.remove_elements(cell, &indices)?)
}

fn layer_map(mapping: BTreeMap<Tag, Tag>) -> BTreeMap<Layer, Layer> {
    mapping
        .into_iter()
        .map(|(a, b)| (layer(a), layer(b)))
        .collect()
}

#[pyfunction]
#[pyo3(signature=(layout,mapping,cells=None,text_mapping=None))]
fn remap_layers(
    layout: &mut PyLayout,
    mapping: BTreeMap<Tag, Tag>,
    cells: Option<BTreeSet<String>>,
    text_mapping: Option<BTreeMap<Tag, Tag>>,
) -> PyResult<usize> {
    let tags = layer_map(mapping);
    let text_tags = text_mapping.map(layer_map);
    Ok(layout
        .inner
        .remap_tags(&tags, text_tags.as_ref(), cells.as_ref())?)
}

#[pyfunction]
#[pyo3(signature=(layout,cell,depth,limit,transform_labels=true))]
fn placed_elements<'py>(
    py: Python<'py>,
    layout: &PyLayout,
    cell: &str,
    depth: Option<usize>,
    limit: usize,
    transform_labels: bool,
) -> PyResult<Vec<Bound<'py, PyDict>>> {
    py.detach(|| {
        layout
            .inner
            .place_with_text_style(cell, depth, limit, false, transform_labels)
    })?
    .iter()
    .map(|v| element_dict(py, v))
    .collect()
}

#[pyfunction]
#[pyo3(signature=(layout,cell,depth,limit,discard_reference_properties))]
fn flatten_cell(
    py: Python<'_>,
    layout: &mut PyLayout,
    cell: &str,
    depth: Option<usize>,
    limit: usize,
    discard_reference_properties: bool,
) -> PyResult<()> {
    Ok(py.detach(|| {
        layout
            .inner
            .flatten_cell(cell, depth, limit, discard_reference_properties)
    })?)
}

#[pyfunction]
#[allow(clippy::too_many_arguments)]
fn transform_elements(
    layout: &mut PyLayout,
    source: &str,
    target: &str,
    indices: BTreeSet<usize>,
    origin: XY,
    angle_deg: f64,
    magnification: f64,
    reflect_x: bool,
    replace: bool,
) -> PyResult<()> {
    Ok(layout.inner.transform_elements(
        source,
        target,
        &indices,
        point(origin),
        Transform {
            angle_deg,
            magnification,
            reflect_x,
        },
        replace,
    )?)
}

#[pyfunction]
#[pyo3(signature=(layout,cell,depth,limit,tolerance))]
fn area_by_layer(
    py: Python<'_>,
    layout: &PyLayout,
    cell: &str,
    depth: Option<usize>,
    limit: usize,
    tolerance: f64,
) -> PyResult<BTreeMap<Tag, f64>> {
    Ok(py
        .detach(|| layout.inner.area_by_layer(cell, depth, limit, tolerance))?
        .into_iter()
        .map(|(l, area)| ((l.number, l.datatype), area))
        .collect())
}

#[pyfunction]
#[pyo3(signature=(layout,cell,depth,limit,tolerance))]
fn bounds_in(
    py: Python<'_>,
    layout: &PyLayout,
    cell: &str,
    depth: Option<usize>,
    limit: usize,
    tolerance: f64,
) -> PyResult<Option<(XY, XY)>> {
    Ok(py
        .detach(|| layout.inner.bounds_in(cell, depth, limit, tolerance))?
        .map(|(a, b)| (coords(a), coords(b))))
}

#[pyfunction]
#[pyo3(signature=(layout,cell,depth,limit,tolerance,tag))]
fn polygon_contours(
    py: Python<'_>,
    layout: &PyLayout,
    cell: &str,
    depth: Option<usize>,
    limit: usize,
    tolerance: f64,
    tag: Option<Tag>,
) -> PyResult<Vec<(Tag, Vec<XY>)>> {
    Ok(py.detach(|| -> crate::Result<Vec<_>> {
        let mut out = Vec::new();
        for e in layout.inner.placed_elements(cell, depth, limit, false)? {
            if let Some(l) = e.layer()
                && tag.is_none_or(|t| t == (l.number, l.datatype))
            {
                let points = crate::hierarchy::element_outline(&e, tolerance)?;
                if !points.is_empty() {
                    out.push((
                        (l.number, l.datatype),
                        points.into_iter().map(coords).collect(),
                    ));
                }
            }
        }
        Ok(out)
    })?)
}

#[pyfunction]
fn reference_layout(layout: &PyLayout, cell: &str, index: usize) -> PyResult<PyLayout> {
    Ok(PyLayout {
        inner: layout.inner.reference_layout(cell, index)?,
    })
}
#[pyfunction]
#[pyo3(signature=(layout,roots,include_dependencies=true,allow_external=false,regrid_factor=1,target_grid=None))]
fn extract_cells(
    layout: &PyLayout,
    roots: Vec<String>,
    include_dependencies: bool,
    allow_external: bool,
    regrid_factor: u32,
    target_grid: Option<(f64, String)>,
) -> PyResult<PyLayout> {
    let mut inner = layout
        .inner
        .select_cells(&roots, include_dependencies, allow_external)?;
    if regrid_factor != 1 {
        inner = inner.regrid_selection(regrid_factor, allow_external)?;
    } else if let Some((dbu, rounding)) = target_grid {
        let policy = match rounding.as_str() {
            "exact" => crate::GridRounding::Exact,
            "nearest" => crate::GridRounding::Nearest,
            _ => {
                return Err(LayoutError::new_err(
                    "rounding must be 'exact' or 'nearest'",
                ));
            }
        };
        inner = inner.resample_selection(dbu, policy, allow_external)?;
    }
    Ok(PyLayout { inner })
}
#[pyfunction]
#[pyo3(signature=(layout,cell,depth,text))]
fn tags_at_depth(
    py: Python<'_>,
    layout: &PyLayout,
    cell: &str,
    depth: Option<usize>,
    text: Option<bool>,
) -> PyResult<BTreeSet<Tag>> {
    Ok(py
        .detach(|| layout.inner.tags_at_depth(cell, depth, text))?
        .into_iter()
        .map(|l| (l.number, l.datatype))
        .collect())
}
#[pyfunction]
fn reference_boxes(
    py: Python<'_>,
    layout: &PyLayout,
    cell: &str,
    depth: usize,
    limit: usize,
    tolerance: f64,
) -> PyResult<Vec<(String, Vec<XY>)>> {
    Ok(py
        .detach(|| layout.inner.reference_boxes(cell, depth, limit, tolerance))?
        .into_iter()
        .map(|(s, v)| (s, v.into_iter().map(coords).collect()))
        .collect())
}
pub(super) fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(extract_elements, m)?)?;
    m.add_function(wrap_pyfunction!(reference_layout, m)?)?;
    m.add_function(wrap_pyfunction!(extract_cells, m)?)?;
    m.add_function(wrap_pyfunction!(tags_at_depth, m)?)?;
    m.add_function(wrap_pyfunction!(reference_boxes, m)?)?;
    m.add_function(wrap_pyfunction!(dependencies, m)?)?;
    m.add_function(wrap_pyfunction!(transform_elements, m)?)?;
    m.add_function(wrap_pyfunction!(area_by_layer, m)?)?;
    m.add_function(wrap_pyfunction!(bounds_in, m)?)?;
    m.add_function(wrap_pyfunction!(polygon_contours, m)?)?;
    m.add_function(wrap_pyfunction!(copy_cell, m)?)?;
    m.add_function(wrap_pyfunction!(rename_cell, m)?)?;
    m.add_function(wrap_pyfunction!(remove_cell, m)?)?;
    m.add_function(wrap_pyfunction!(replace_references, m)?)?;
    m.add_function(wrap_pyfunction!(import_cells, m)?)?;
    m.add_function(wrap_pyfunction!(remove_elements, m)?)?;
    m.add_function(wrap_pyfunction!(remap_layers, m)?)?;
    m.add_function(wrap_pyfunction!(placed_elements, m)?)?;
    m.add_function(wrap_pyfunction!(flatten_cell, m)?)?;
    Ok(())
}