layouttk 0.4.1

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation
//! File-level inventory and verification on the integer database grid.

use crate::geometry::{self, BooleanOp, Ring};
use crate::{Cell, Element, Format, Layer, Layout, ReadOptions, Result};
use serde::Serialize;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::path::Path;

pub use crate::hierarchy::windows::{ClipOptions, Window, clip_file};

#[derive(Default, Serialize)]
pub struct CellInventory {
    pub name: String,
    pub shape_layers: BTreeSet<Layer>,
    pub text_layers: BTreeSet<Layer>,
    pub dependencies: BTreeSet<String>,
    pub stored_shapes: u64,
    pub stored_texts: u64,
    pub stored_references: u64,
    pub local_shape_occurrences: u64,
    pub local_text_occurrences: u64,
    pub local_reference_placements: u64,
}

#[derive(Serialize)]
pub struct Inventory {
    pub format: &'static str,
    pub name: String,
    pub dbu_nm: f64,
    pub dbu_meters: f64,
    pub top_cells: Vec<String>,
    pub selected_top: Option<String>,
    /// Union of direct layers across the returned definitions.
    pub shape_layers: BTreeSet<Layer>,
    pub text_layers: BTreeSet<Layer>,
    pub external_references: BTreeSet<String>,
    pub cells: Vec<CellInventory>,
}

fn count(total: &mut u64, amount: u64) -> Result<()> {
    *total = total
        .checked_add(amount)
        .ok_or_else(|| crate::Error::invalid("inventory count exceeds u64"))?;
    Ok(())
}

/// Count stored records and direct repetition occurrences without retaining shape data.
/// With a root, report its entire dependency closure. An unselected layout may
/// be a fragment and report external targets; a selected root must be complete.
pub fn inventory(
    options: ReadOptions<'_>,
    path: impl AsRef<Path>,
    top: Option<&str>,
) -> Result<Inventory> {
    let mut rows = BTreeMap::<usize, CellInventory>::new();
    let (graph, format) = options.read_filtered(File::open(path)?, true, &mut |cell, record| {
        let row = rows.entry(cell).or_default();
        let (element, occurrences) = match record.unadorned() {
            Element::Reference { array, .. } => {
                count(&mut row.stored_references, 1)?;
                count(
                    &mut row.local_reference_placements,
                    array.as_ref().map_or(1, crate::Repetition::count),
                )?;
                return Ok(true);
            }
            Element::Repeated { element, array } => (element.unadorned(), array.count()),
            element => (element, 1),
        };
        if let Some(layer) = element.layer() {
            if matches!(element, Element::Text { .. }) {
                row.text_layers.insert(layer);
                count(&mut row.stored_texts, 1)?;
                count(&mut row.local_text_occurrences, occurrences)?;
            } else {
                row.shape_layers.insert(layer);
                count(&mut row.stored_shapes, 1)?;
                count(&mut row.local_shape_occurrences, occurrences)?;
            }
        }
        Ok(false)
    })?;
    let selected = top
        .map(|name| {
            let mut names: BTreeSet<_> = graph.dependencies(name, true)?.into_iter().collect();
            names.insert(name.to_owned());
            Ok::<_, crate::Error>(names)
        })
        .transpose()?;
    let mut cells = Vec::new();
    for (index, cell) in graph.cells.iter().enumerate() {
        if selected
            .as_ref()
            .is_some_and(|names| !names.contains(&cell.name))
        {
            continue;
        }
        let mut row = rows.remove(&index).unwrap_or_default();
        row.name.clone_from(&cell.name);
        row.dependencies.extend(cell.elements.iter().filter_map(
            |element| match element.unadorned() {
                Element::Reference { cell, .. } => Some(cell.clone()),
                _ => None,
            },
        ));
        cells.push(row);
    }
    let unresolved = graph.external_references();
    let external_references = cells
        .iter()
        .flat_map(|row| row.dependencies.iter())
        .filter(|name| unresolved.contains(name.as_str()))
        .cloned()
        .collect();
    Ok(Inventory {
        format: match format {
            Format::Gdsii => "gds",
            Format::Oasis => "oas",
        },
        name: graph.name.clone(),
        dbu_nm: graph.dbu_meters * 1e9,
        dbu_meters: graph.dbu_meters,
        top_cells: graph.summary().top_cells,
        selected_top: top.map(str::to_owned),
        shape_layers: cells
            .iter()
            .flat_map(|row| row.shape_layers.iter().copied())
            .collect(),
        text_layers: cells
            .iter()
            .flat_map(|row| row.text_layers.iter().copied())
            .collect(),
        external_references,
        cells,
    })
}

#[derive(Serialize)]
pub struct LayerDifference {
    pub layer: Layer,
    pub differing_contours: usize,
}

#[derive(Serialize)]
pub struct CellDifference {
    pub cell: String,
    pub missing: bool,
    pub placements: bool,
    pub shapes: bool,
    pub texts: bool,
    pub properties: bool,
}

#[derive(Serialize)]
pub struct Verification {
    pub left_top: String,
    pub right_top: String,
    pub dbu_nm: f64,
    pub dbu_meters: f64,
    pub tolerance_dbu: f64,
    pub geometry_equal: bool,
    pub stored_equal: bool,
    pub library_properties_differ: bool,
    pub cell_differences: Vec<CellDifference>,
    pub layer_differences: Vec<LayerDifference>,
}

fn bare_kind(e: &Element) -> usize {
    match e.unadorned() {
        Element::Repeated { element, .. } => bare_kind(element),
        Element::Reference { .. } => 0,
        Element::Text { .. } => 2,
        _ => 1,
    }
}

fn compare_cell(name: &str, left: Option<&Cell>, right: Option<&Cell>) -> Option<CellDifference> {
    let mut difference = CellDifference {
        cell: name.into(),
        missing: left.is_none() || right.is_none(),
        placements: false,
        shapes: false,
        texts: false,
        properties: false,
    };
    if let (Some(a), Some(b)) = (left, right) {
        let same = |kind| {
            let supported = |e: &&Element| bare_kind(e) == kind;
            a.elements
                .iter()
                .filter(supported)
                .map(Element::unadorned)
                .eq(b.elements.iter().filter(supported).map(Element::unadorned))
        };
        difference.placements = !same(0);
        difference.shapes = !same(1);
        difference.texts = !same(2);
        fn attributed(c: &Cell) -> impl Iterator<Item = (usize, &[crate::Property])> {
            c.elements
                .iter()
                .enumerate()
                .filter_map(|(index, element)| {
                    let properties = element.properties();
                    (!properties.is_empty()).then_some((index, properties))
                })
        }
        difference.properties = a.properties != b.properties
            || a.name_properties != b.name_properties
            || !attributed(a).eq(attributed(b));
    }
    (difference.missing
        || difference.placements
        || difference.shapes
        || difference.texts
        || difference.properties)
        .then_some(difference)
}

fn selected_top(layout: &Layout, top: Option<&str>) -> Result<String> {
    if let Some(top) = top {
        return Ok(top.into());
    }
    let roots = layout.summary().top_cells;
    match roots.as_slice() {
        [root] => Ok(root.clone()),
        _ => Err(crate::Error::invalid(
            "select an explicit top for a file without exactly one root",
        )),
    }
}

/// Outline filled shapes in the root coordinates, preserving each shape's fill under reflection.
pub fn placed_rings(
    layout: &Layout,
    top: &str,
    limit: usize,
    tolerance: f64,
) -> Result<BTreeMap<Layer, Vec<Ring>>> {
    let mut result = BTreeMap::<_, Vec<_>>::new();
    for element in layout.placed_elements(top, None, limit, false)? {
        if bare_kind(&element) != 1 {
            continue;
        }
        let ring = crate::hierarchy::element_outline(&element, tolerance)?;
        // Each stored polygon is a filled object. Normalize it individually
        // so that negative winding from a mirrored placement cannot cancel a neighbor.
        if ring.len() >= 3 {
            let normalized = geometry::boolean(&[ring], &[], BooleanOp::Union)?;
            result
                .entry(element.layer().expect("shape layer"))
                .or_default()
                .extend(normalized);
        }
    }
    Ok(result)
}

/// Compare the selected dependency trees by stored records and placed mask XOR separately.
/// Stored comparison uses cell name and record order. Geometry uses exact grid XOR
/// after conversion of native paths and circles with the requested outline tolerance.
pub fn verify(
    options: ReadOptions<'_>,
    left: impl AsRef<Path>,
    right: impl AsRef<Path>,
    left_top: Option<&str>,
    right_top: Option<&str>,
    limit: usize,
    tolerance: f64,
) -> Result<Verification> {
    if limit == 0 {
        return Err(crate::Error::invalid(
            "verification expansion limit must be positive",
        ));
    }
    if !tolerance.is_finite() || tolerance <= 0.0 {
        return Err(crate::Error::invalid(
            "tolerance must be positive and finite",
        ));
    }
    let mut left = options.read(left)?;
    let mut right = options.read(right)?;
    let left_top = selected_top(&left, left_top)?;
    let right_top = selected_top(&right, right_top)?;
    let grid = left.dbu_meters;
    if (grid - right.dbu_meters).abs() > grid.max(right.dbu_meters) * 1e-12 {
        return Err(crate::Error::invalid(format!(
            "incompatible database units ({} nm and {} nm); regrid explicitly before verification",
            grid * 1e9,
            right.dbu_meters * 1e9
        )));
    }
    left.retain_tree(&left_top)?;
    right.retain_tree(&right_top)?;
    let cell_names: BTreeSet<_> = left
        .cells
        .iter()
        .chain(&right.cells)
        .map(|cell| cell.name.as_str())
        .collect();
    let left_cells: BTreeMap<_, _> = left
        .cells
        .iter()
        .map(|cell| (cell.name.as_str(), cell))
        .collect();
    let right_cells: BTreeMap<_, _> = right
        .cells
        .iter()
        .map(|cell| (cell.name.as_str(), cell))
        .collect();
    let cell_differences: Vec<_> = cell_names
        .into_iter()
        .filter_map(|name| {
            compare_cell(
                name,
                left_cells.get(name).copied(),
                right_cells.get(name).copied(),
            )
        })
        .collect();
    let library_properties_differ = left.properties != right.properties
        || left.layer_names != right.layer_names
        || left.table_properties != right.table_properties;
    let mut layer_differences = Vec::new();
    if cell_differences
        .iter()
        .any(|row| row.missing || row.placements || row.shapes)
    {
        let a = placed_rings(&left, &left_top, limit, tolerance)?;
        let b = placed_rings(&right, &right_top, limit, tolerance)?;
        let tags: BTreeSet<_> = a.keys().chain(b.keys()).copied().collect();
        for layer in tags {
            let left_rings = a.get(&layer).map(Vec::as_slice).unwrap_or_default();
            let right_rings = b.get(&layer).map(Vec::as_slice).unwrap_or_default();
            if left_rings != right_rings {
                let xor = geometry::boolean(left_rings, right_rings, BooleanOp::Xor)?;
                if !xor.is_empty() {
                    layer_differences.push(LayerDifference {
                        layer,
                        differing_contours: xor.len(),
                    });
                }
            }
        }
    }
    Ok(Verification {
        left_top,
        right_top,
        dbu_nm: grid * 1e9,
        dbu_meters: grid,
        tolerance_dbu: tolerance,
        geometry_equal: layer_differences.is_empty(),
        stored_equal: cell_differences.is_empty() && !library_properties_differ,
        library_properties_differ,
        cell_differences,
        layer_differences,
    })
}