Skip to content

carto_flow.symbol_cartogram.layouts.layout_result

Layout result classes for symbol cartograms.

This module defines the immutable LayoutResult that captures the output of layout algorithms, and the Transform dataclass for per-geometry transforms.

Classes:

AlgorithmMetrics dataclass

AlgorithmMetrics(
    converged: bool | None = None,
    iterations: int | None = None,
    final_overlaps: int | None = None,
    algorithm: Any = None,
)

Final scalar summaries common to all layouts.

Attributes:

  • converged (bool or None) –

    Whether the algorithm met its convergence criterion.

  • iterations (int or None) –

    Number of iterations executed.

  • final_overlaps (int or None) –

    Number of overlapping nearest-neighbor pairs at termination.

  • algorithm (Any) –

    Algorithm-specific final scalars (PackingMetrics, FlowDensityMetrics, CentroidMetrics, GridMetrics, etc.).

GridLayoutResult dataclass

GridLayoutResult(
    canonical_symbol: Symbol,
    transforms: list[Transform],
    base_size: float,
    positions: NDArray[floating],
    sizes: NDArray[floating],
    adjacency: NDArray[floating],
    bounds: tuple[float, float, float, float],
    crs: str | None = None,
    layout_type: str = "grid",
    metrics: Any = None,
    history: Any = None,
    valid_mask: NDArray[bool_] | None = None,
    source_indices: NDArray[intp] | None = None,
    group_ids: NDArray[intp] | None = None,
    tiling_result: TilingResult | None = None,
    assignments: NDArray[intp] | None = None,
)

Bases: TiledLayoutResult

Layout result from GridBasedLayout.

LayoutResult dataclass

LayoutResult(
    canonical_symbol: Symbol,
    transforms: list[Transform],
    base_size: float,
    positions: NDArray[floating],
    sizes: NDArray[floating],
    adjacency: NDArray[floating],
    bounds: tuple[float, float, float, float],
    crs: str | None = None,
    layout_type: str = "",
    metrics: Any = None,
    history: Any = None,
    valid_mask: NDArray[bool_] | None = None,
    source_indices: NDArray[intp] | None = None,
    group_ids: NDArray[intp] | None = None,
)

Immutable output from layout algorithm.

Contains canonical symbol and per-geometry transforms, plus the serializable preprocessing data (positions, sizes, adjacency, bounds, crs). The original GeoDataFrame is NOT stored here (too large for serialization).

Attributes:

  • canonical_symbol (Symbol) –

    The base symbol shape for this layout.

  • transforms (list[Transform]) –

    One transform per input geometry.

  • base_size (float) –

    Reference size for scaling.

  • positions (NDArray[floating]) –

    Original centroid positions, shape (n, 2).

  • sizes (NDArray[floating]) –

    Symbol sizes, shape (n,).

  • adjacency (NDArray[floating]) –

    Adjacency matrix from original geometries, shape (n, n).

  • bounds (tuple[float, float, float, float]) –

    Geographic bounds (xmin, ymin, xmax, ymax).

  • crs (str | None) –

    CRS information as WKT string from source GeoDataFrame.

  • layout_type (str) –

    Registry key of the layout that produced the result ("packing", "flow_density", "centroid", "grid", "mosaic"). It records which layout ran, and selects the result class to rebuild when a serialized result is read back with :meth:from_dict.

  • metrics (AlgorithmMetrics | None) –

    Final scalar summaries (converged, iterations, overlaps, algorithm-specific). Populated by all layout types.

  • history (SimulationHistory | None) –

    Per-iteration diagnostics and optional position snapshots. Only populated by iterative layouts (packing, flow density, centroid).

Methods:

  • from_serialized –

    Reconstruct from serialized data.

  • serialize –

    Serialize for persistence.

  • style –

    Apply styling to create symbol cartogram.

converged property

converged: bool | None

Whether the layout algorithm converged.

iterations property

iterations: int | None

Number of iterations executed.

overlaps property

overlaps: Any

Per-iteration overlap counts from simulation history.

from_serialized classmethod

from_serialized(data: dict[str, Any]) -> LayoutResult

Reconstruct from serialized data.

Parameters:

  • data (dict) –

    Serialized layout result from serialize().

Returns:

Examples:

>>> import json
>>> serialized = json.load(open("layout.json"))
>>> result = LayoutResult.from_serialized(serialized)
>>> cartogram = result.style(symbol="circle")

serialize

serialize() -> dict[str, Any]

Serialize for persistence.

Returns:

  • dict –

    Serialized representation of the layout result.

Notes

All data is serialized including positions, sizes, adjacency, bounds, crs. The original GeoDataFrame is NOT stored - it must be provided separately when attribute merging is needed via SymbolCartogram.to_geodataframe().

Examples:

>>> import json
>>> result = create_layout(gdf, "population")
>>> serialized = result.serialize()
>>> json.dump(serialized, open("layout.json", "w"))

style

style(
    styling: Styling | None = None, **kwargs
) -> SymbolCartogram

Apply styling to create symbol cartogram.

Parameters:

  • styling (Styling or None, default: None ) –

    Pre-configured Styling object.

  • **kwargs –

    Convenience kwargs for simple cases (symbol, scale, etc.) Creates a temporary Styling object internally.

Returns:

MosaicLayoutResult dataclass

MosaicLayoutResult(
    canonical_symbol: Symbol,
    transforms: list[Transform],
    base_size: float,
    positions: NDArray[floating],
    sizes: NDArray[floating],
    adjacency: NDArray[floating],
    bounds: tuple[float, float, float, float],
    crs: str | None = None,
    layout_type: str = "mosaic",
    metrics: Any = None,
    history: Any = None,
    valid_mask: NDArray[bool_] | None = None,
    source_indices: NDArray[intp] | None = None,
    group_ids: NDArray[intp] | None = None,
    tiling_result: TilingResult | None = None,
    assignments: NDArray[intp] | None = None,
    tiles_gdf: Any = None,
    regions_gdf: Any = None,
    counts: NDArray[intp] | None = None,
    core_tile_indices: NDArray[intp] | None = None,
    pool_tile_indices: NDArray[intp] | None = None,
)

Bases: TiledLayoutResult

Layout result from MosaicLayout.

Attributes:

  • tiles_gdf (GeoDataFrame | None) –

    Tile-level GeoDataFrame with geometry_id column.

  • regions_gdf (GeoDataFrame | None) –

    Region-level GeoDataFrame with tile_count and target_count.

  • counts (NDArray[intp] | None) –

    Target tile count per geometry, shape (n_geometries,).

  • core_tile_indices (NDArray[intp] | None) –

    Indices of tiles whose overlap with the study union reached min_overlap_frac (the calibrated core pool).

  • pool_tile_indices (NDArray[intp] | None) –

    Indices of all tiles in the solver pool (core + extra rings). Useful for visualizing which tiles were available to the solver.

SimulationHistory dataclass

SimulationHistory(
    positions: list[NDArray[floating]] | None = None,
    overlaps: NDArray[intp] | None = None,
    algorithm: Any = None,
)

Per-iteration arrays common to all iterative layouts.

Attributes:

  • positions (list[ndarray] | None) –

    Position snapshots, each of shape (n, 2). Only populated when save_history=True.

  • overlaps (ndarray | None) –

    Per-iteration overlap count. Shape: (n_iters,).

  • algorithm (Any) –

    Algorithm-specific per-iteration arrays (PackingHistory or FlowDensityHistory depending on the layout used).

Methods:

  • __len__ –

    Number of recorded iterations.

__len__

__len__() -> int

Number of recorded iterations.

TiledLayoutResult dataclass

TiledLayoutResult(
    canonical_symbol: Symbol,
    transforms: list[Transform],
    base_size: float,
    positions: NDArray[floating],
    sizes: NDArray[floating],
    adjacency: NDArray[floating],
    bounds: tuple[float, float, float, float],
    crs: str | None = None,
    layout_type: str = "",
    metrics: Any = None,
    history: Any = None,
    valid_mask: NDArray[bool_] | None = None,
    source_indices: NDArray[intp] | None = None,
    group_ids: NDArray[intp] | None = None,
    tiling_result: TilingResult | None = None,
    assignments: NDArray[intp] | None = None,
)

Bases: LayoutResult

Base for grid and mosaic layouts that carry tiling-specific data.

Attributes:

  • tiling_result (TilingResult | None) –

    Tiling polygons, transforms, and adjacency. Set at creation; None immediately after from_serialized() until restored by SymbolCartogram.load().

  • assignments (NDArray[intp] | None) –

    Per-tile geometry index. Shape (n_valid_tiles,).

Methods:

  • plot_tiling –

    Visualize the tiling grid underlying this layout result.

plot_tiling

plot_tiling(
    cartogram: SymbolCartogram | None = None,
    ax: Axes | None = None,
    show_symbols: bool = True,
    show_assigned: bool = True,
    show_unassigned: bool = True,
    show_pool: bool = False,
    assigned_color: str = "#d4e6f1",
    unassigned_color: str = "#f5f5f5",
    core_edgecolor: str = "#e6972a",
    ring_edgecolor: str = "#d9534f",
    tile_edgecolor: str = "#999999",
    tile_linewidth: float = 0.5,
    pool_linewidth: float = 1.5,
    tile_alpha: float = 0.5,
    **kwargs: Any,
) -> TilingPlotResult

Visualize the tiling grid underlying this layout result.

Parameters:

  • cartogram (SymbolCartogram, default: None ) –

    If provided and show_symbols=True, overlays symbol geometries.

  • ax (Axes, default: None ) –

    Axes to plot on. Created if not provided.

  • show_symbols (bool, default: True ) –

    Overlay symbol geometries. Requires cartogram. Default True.

  • show_assigned (bool, default: True ) –

    Show occupied tiles. Default True.

  • show_unassigned (bool, default: True ) –

    Show empty tiles. Default True.

  • show_pool (bool, default: False ) –

    Use edge color to mark solver-pool membership on every tile (MosaicLayoutResult only). Core tiles get core_edgecolor and extra-ring tiles get ring_edgecolor regardless of whether they are assigned; tiles outside the pool keep tile_edgecolor. Default False.

  • core_edgecolor (str, default: '#e6972a' ) –

    Edge color for core tiles when show_pool = True. Default amber.

  • ring_edgecolor (str, default: '#d9534f' ) –

    Edge color for extra-ring tiles when show_pool = True. Default salmon.

  • pool_linewidth (float, default: 1.5 ) –

    Line width for pool-tile borders. Default 1.5.

  • **kwargs (Any, default: {} ) –

    Forwarded to cartogram.plot() when show_symbols=True.

Transform dataclass

Transform(
    position: tuple[float, float] = (0.0, 0.0),
    rotation: float = 0.0,
    scale: float = 1.0,
    reflection: bool = False,
)

Transformation applied to a symbol.

Note: This is an internal class that stores rotation in radians. User-facing APIs (Styling, TransformedSymbol) use degrees for convenience.

Attributes:

  • position (tuple[float, float]) –

    Center position (x, y) for the symbol.

  • rotation (float) –

    Rotation angle in radians (counter-clockwise). Default: 0.0 User-facing APIs accept degrees and convert internally.

  • scale (float) –

    Scale multiplier. Default: 1.0

  • reflection (bool) –

    Whether to reflect the symbol about the vertical axis. Default: False

Methods:

  • compose –

    Compose this transform with another.

compose

compose(other: Transform) -> Transform

Compose this transform with another.

The resulting transform applies this transform first, then the other.

Parameters:

  • other (Transform) –

    Transform to apply after this one.

Returns: