Skip to content

carto_flow.flow_cartogram.options

Configuration options and status enums for morphing algorithms.

Configuration classes for controlling cartogram generation behavior.

Classes:

Examples:

>>> from carto_flow.flow_cartogram import MorphOptions
>>>
>>> # Use preset configurations
>>> options = MorphOptions.preset_fast()
>>>
>>> # Or customize parameters
>>> options = MorphOptions(grid_size=256, n_iter=100, mean_tol=0.05)

MorphOptions dataclass

MorphOptions(
    grid: Optional[Grid] = None,
    grid_size: int
    | tuple[int | None, int | None]
    | None = 256,
    grid_margin: float = 0.5,
    grid_square: bool = False,
    dt: float = 0.2,
    n_iter: int = 500,
    recompute_every: int | None = 10,
    snapshot_every: int | None = None,
    mean_tol: float = 0.05,
    max_tol: float = 0.1,
    Dx: float = 1.0,
    Dy: float = 1.0,
    anisotropy: Optional[VelocityModulator] = None,
    density_mod: Optional[DensityModulator] = None,
    area_scale: float = 1.0,
    prescale_components: bool = False,
    save_internals: bool = False,
    show_progress: bool = True,
    progress_message: str | None = None,
    benchmark: bool = False,
    parallel_fft: bool | int = False,
    parallel_density: bool | int = False,
    stall_patience: int | None = 5,
)

Configuration options for morphing algorithms with comprehensive validation.

This class validates all options to ensure numerical stability and logical consistency for cartogram generation algorithms. Validation occurs during construction, direct attribute assignment, and when creating modified copies.

Grid specification (in order of precedence): 1. grid: Pre-constructed Grid object (highest precedence) 2. grid_size + grid_margin + grid_square: Construction parameters 3. Default: 100x100 grid if nothing specified

Note

When 'grid' is provided, 'grid_size', 'grid_margin', and 'grid_square' are ignored.

Validation
  • All numeric parameters are validated for type and range constraints
  • Logical consistency between related parameters is enforced
  • Invalid values raise MorphOptionsValidationError with detailed messages
  • Validation occurs on construction, direct assignment, and copy operations

Methods:

  • __post_init__ –

    Validate options after dataclass initialization.

  • __setattr__ –

    Validate individual fields when assigned directly.

  • copy_with –

    Create a copy of this MorphOptions instance with specified options overridden.

  • get_grid –

    Get the Grid object for computation with clear precedence.

  • preset_balanced –

    Create options with balanced speed/quality trade-off.

  • preset_fast –

    Create options optimized for quick preview.

  • preset_high_quality –

    Create options optimized for publication-quality results.

Attributes:

  • benchmark (bool) –

    Record per-phase wall-clock time inside the morphing loop.

  • parallel_density (bool | int) –

    Control thread count for the density rasterisation phase (ThreadPoolExecutor).

  • parallel_fft (bool | int) –

    Control FFTW thread count for the velocity (Poisson solve) phase.

  • prescale_components (bool) –

    Pre-scale each connected component to its target total area before morphing.

  • stall_patience (int | None) –

    Maximum number of iterations to allow error to increase before considering algorithm stalled.

benchmark class-attribute instance-attribute

benchmark: bool = False

Record per-phase wall-clock time inside the morphing loop.

When True, a Benchmark object is attached to the returned Cartogram as cartogram.benchmark. Useful for diagnosing which phase dominates runtime and whether parallelism overhead outweighs its benefit.

parallel_density class-attribute instance-attribute

parallel_density: bool | int = False

Control thread count for the density rasterisation phase (ThreadPoolExecutor).

Whether threading helps depends on geometry count and grid size:

  • Few large geometries (e.g. ~50 states, grid_size ≥ 1024): ~1.4x speedup
  • Many small geometries (e.g. ~430 districts): threading is slower because Future-submission overhead exceeds per-geometry work

  • False: serial density loop

  • True: all available cores (os.cpu_count())
  • N (int > 1): exactly N worker threads

parallel_fft class-attribute instance-attribute

parallel_fft: bool | int = False

Control FFTW thread count for the velocity (Poisson solve) phase.

FFT parallelism benefits emerge at grid_size ≥ 1024 (~1.2x) and become substantial at ≥ 2048 (~1.8-2x). At smaller grids, thread-launch overhead exceeds the benefit. Displacement and area phases always run serially.

  • False: 1 FFT thread (serial)
  • True: max(cpu_count()-1, 1) threads
  • N (int > 1): exactly N threads (capped at cpu_count()-1)

prescale_components class-attribute instance-attribute

prescale_components: bool = False

Pre-scale each connected component to its target total area before morphing.

When True, the algorithm detects groups of adjacent geometries (connected components) and uniformly scales each group so its total area equals the area implied by the global target density. This reduces distortion of the outer boundary during morphing, especially for maps with multiple disconnected regions (e.g., archipelagos, separate land masses). By pre-scaling components to their target areas, the algorithm can focus on redistributing density within each component rather than applying large global transformations that can excessively distort the outer boundary.

stall_patience class-attribute instance-attribute

stall_patience: int | None = 5

Maximum number of iterations to allow error to increase before considering algorithm stalled.

If None, stall detection is disabled and the algorithm will run until convergence or maximum iterations. If 0, algorithm will stall immediately if error increases.

__post_init__

__post_init__()

Validate options after dataclass initialization.

__setattr__

__setattr__(name: str, value) -> None

Validate individual fields when assigned directly.

copy_with

copy_with(**kwargs) -> MorphOptions

Create a copy of this MorphOptions instance with specified options overridden.

Parameters:

  • **kwargs –

    Keyword arguments corresponding to MorphOptions fields to override

Returns:

  • MorphOptions –

    New MorphOptions instance with the specified options overridden

Examples:

Create new options with different iteration count and time step:

>>> new_opts = opts.copy_with(n_iter=200, dt=0.15)

Create options with different tolerance values:

>>> strict_opts = opts.copy_with(mean_tol=0.01, max_tol=0.02)

Chain multiple modifications:

>>> final_opts = opts.copy_with(n_iter=150).with_options(dt=0.1)

get_grid

get_grid(bounds: tuple[float, float, float, float]) -> Grid

Get the Grid object for computation with clear precedence.

Parameters:

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

    Bounding box as (min_x, min_y, max_x, max_y)

Returns:

  • Grid –

    Grid object for spatial discretization

preset_balanced classmethod

preset_balanced() -> MorphOptions

Create options with balanced speed/quality trade-off.

Default production setting suitable for most use cases.

Returns:

Examples:

>>> options = MorphOptions.preset_balanced()
>>> result = morph_gdf(gdf, 'population', options=options)

preset_fast classmethod

preset_fast() -> MorphOptions

Create options optimized for quick preview.

Uses lower grid resolution, fewer iterations, and looser tolerances for fast interactive exploration.

Returns:

Examples:

>>> options = MorphOptions.preset_fast()
>>> result = morph_gdf(gdf, 'population', options=options)

preset_high_quality classmethod

preset_high_quality() -> MorphOptions

Create options optimized for publication-quality results.

Uses higher grid resolution, more iterations, and stricter tolerances for maximum accuracy.

Returns:

Examples:

>>> options = MorphOptions.preset_high_quality()
>>> result = morph_gdf(gdf, 'population', options=options)

MorphOptionsConsistencyError

Bases: MorphOptionsError

Logical consistency errors between related fields.

MorphOptionsError

Bases: ValueError

Base exception for MorphOptions validation errors.

MorphOptionsValidationError

Bases: MorphOptionsError

Field validation errors (type, range, format).

MorphStatus

Bases: str, Enum

Status values for morphing operations.

Inherits from str for backward compatibility with string comparisons.

Values

ORIGINAL : str Original unmorphed state (no morphing performed) CONVERGED : str Algorithm converged within tolerance thresholds STALLED : str Algorithm stopped improving (error increasing) COMPLETED : str Algorithm completed all iterations without converging RUNNING : str Algorithm is still running (intermediate status) FAILED : str Algorithm failed due to an error