optiwindnet.api

Module Contents

class optiwindnet.api.Router[source]

Bases: abc.ABC

Abstract base class for routing algorithms in OptiWindNet.

Each Router implementation must define a route() method.

__repr__() str[source]
abstractmethod route(P: networkx.PlanarEmbedding, A: networkx.Graph, cables: list[tuple[int, float | int]], cables_capacity: int, verbose: bool, **kwargs) tuple[networkx.Graph, networkx.Graph][source]

Run the routing optimization.

Parameters:
  • P – Navigation mesh for the location.

  • A – Graph of available links.

  • cables – set of cable specifications as [(capacity, linear_cost), …].

  • cables_capacity – highest cable capacity in cables.

  • verbose – Whether to print progress/logging info.

  • **kwargs – Additional router-specific parameters.

Returns:

Tuple of (solution topology (selected links), optimized route set).

class optiwindnet.api.WindFarmNetwork(cables: int | list[int] | list[tuple[int, float | int]] | numpy.ndarray, turbinesC: numpy.ndarray | None = None, substationsC: numpy.ndarray | None = None, borderC: numpy.ndarray = np.empty((0, 2), dtype=np.float64), obstacleC_: Sequence[numpy.ndarray] = [], name: str = '', handle: str = '', L: networkx.Graph | None = None, router: Router | None = None, verbose: bool = False)[source]

Wind farm electrical network.

Wrapper of most of OptiWindNet’s functionality (optimization, visualization, cost/length evaluation, and gradient calculation).

An instance represents a wind farm location, which initially contains the number and positions of wind turbines and substations, the delimited area and eventual obstacles. A cable network may be provided or a Router instance may be used to create an optimized network.

Initialize a wind farm electrical network.

Parameters:
  • cables – properties of the available cable types (see Cable Specs below)

  • turbinesC – Turbine coordinates (T, 2): [(x, y), ...].

  • substationsC – Substation coordinates (R, 2): [(x, y), ...].

  • borderC – Polygonal border coordinates (_, 2): [(x, y), ...].

  • obstacleC – One or more polygons for exclusion zones list of (_, 2): [[(x, y), ...], ...].

  • name – Human-readable instance name. Defaults to “”.

  • handle – Short instance identifier. Defaults to “”.

  • L – Location geometry (takes precedence over coordinate inputs).

  • router – Routing algorithm instance. Defaults to EWRouter.

  • buffer_dist – Buffer distance to dilate borders / erode obstacles. Defaults to 0.

Cable Specs (capacity is in number of turbines):
  • List of 2-tuple cable specifications: [(capacity, linear_cost), ...].

  • List of capacity per cable type: [capacity, ...].

  • Maximum capacity of all available cables (single value): capacity.

Note

  • If both L and coordinates are provided, L takes precedence.

  • Changing coordinate data after creation (turbinesC and/or substationsC) rebuilds L and refreshes the navigation mesh and available links.

Example:

wfn = WindFarmNetwork(
  cables=[(3, 100.0), (5, 150.0)],
  turbinesC=np.array([[0, 0], [1, 0], [0, 1]]),
  substationsC=np.array([[10, 0]]),
)
wfn.optimize()
print(wfn.cost(), wfn.length())
name = ''[source]

Instance name.

handle = ''[source]

Short instance identifier.

property router: Router[source]

Router instance used for optimization.

property cables: list[tuple[int, float | int]][source]

Set of cable specifications as [(capacity, linear_cost), ...].

verbose = False[source]

Enable verbose logging.

property L: networkx.Graph[source]

Location geometry (turbines, substations, borders, obstacles).

property polygon: shapely.Polygon | shapely.MultiPolygon | None[source]

Shapely (Multi)Polygon that bounds the cable-laying area.

property P: networkx.PlanarEmbedding[source]

Triangular mesh over L (navigation mesh).

property A: networkx.Graph[source]

Available links graph (search space).

property S: networkx.Graph[source]

Solution topology (selected links).

property G: networkx.Graph[source]

Optimized network with cable routes and types.

property buffer_dist: float[source]

Buffer distance applied to dilate borders / erode obstacles.

cost() float[source]

Get the total cost of the optimized network.

length() float[source]

Get the total cable length of the optimized network.

plot_original_vs_buffered(**kwargs) matplotlib.axes.Axes | None[source]

Plot original and buffered borders and obstacles on a single plot.

Parameters:

**kwargs – passed to matplotlib’s pyplot.figure()

Returns:

matplotlib Axes instance.

classmethod from_own_yaml(filepath: str, **kwargs)[source]

Create a WindFarmNetwork instance from an OptiWindNet (OWN) YAML file.

classmethod from_yaml(filepath: str, **kwargs)[source]

Deprecated: use from_own_yaml() instead.

classmethod from_pbf(filepath: pathlib.Path | str, **kwargs)[source]

Create a WindFarmNetwork instance from a .OSM.PBF file.

classmethod from_windIO(filepath: pathlib.Path | str, **kwargs)[source]

Create a WindFarmNetwork instance from WindIO yaml file.

__repr__() str[source]

Concise one-line summary for console/debugging.

Defensive by design: instance attributes are getattr-guarded so the repr never raises, even on a partially-initialized instance (e.g. if __init__() aborted before _T/_R were set). The solved-network branch is reached only when _is_stale_SG is False, which guarantees _G exists.

plot(*args, **kwargs)[source]

Plot the optimized network.

By default, this method utilizes the modern vector SVG-based plotting backend (svgplot()) which returns an SvgRepr suitable for clean interactive inline displays in Jupyter notebooks.

To switch to the Matplotlib-based plotting backend (gplot()), specify the ax parameter as a keyword argument.

Note

Passing ax=None explicitly routes to the Matplotlib backend and automatically instantiates a new figure and axes on the fly, allowing Matplotlib figures to be created without importing matplotlib or pyplot directly in the user code.

plot_location(**kwargs)[source]

Plot the original location geometry.

Plot available links from planar embedding.

plot_navigation_mesh(**kwargs)[source]

Plot navigation mesh (planar graph and adjacency).

Plot link selection (tentative feeder routes).

Get a compact representation of the solution.

By default the representation contains topology S and can be routed again against updated coordinates. With routed=True it contains the exact routeset G, including contour and detour clone mappings.

Update the network from terse link representation.

A topology-scoped value is routed against this network’s location; a routeset-scoped value restores its recorded contour and detour paths. Plain arrays remain accepted for topology input and may contain integers or integer-like floats (e.g., 3.0). Pass topology with a plain array when radial/branched identity must be retained.

get_network()[source]

Export the optimized network as a structured array.

map_detour_vertex()[source]

Map detour vertices back to their original coordinate indices.

merge_obstacles_into_border()[source]
add_buffer(buffer_dist)[source]

Dilate the cable-laying area by buffer_dist.

Useful if boundaries are not strictly enforced during optimization. This may happen if boundary compliance is achieved through the application of penalties for violations. OptiWindNet will fail if turbines are outside the border, so choose a buffer_dist that is greater than the maximum single step in position.

Parameters:

buffer_dist – Buffer distance to dilate borders / erode obstacles.

gradient(turbinesC=None, substationsC=None, gradient_type='length')[source]

Compute length/cost gradients with respect to node positions.

optimize(turbinesC=None, substationsC=None, router=None, verbose=False)[source]

Optimize electrical network.

solution_info()[source]

Get model and solver information of the latest solution (runtime, objective, gap, etc.).

class optiwindnet.api.EWRouter(maxiter: int = 10000, feeder_route: str = 'segmented', method: str = 'biased_EW', bias_margin: float | None = None, verbose: bool = False, **kwargs)[source]

Bases: Router

A lightweight, ultra-fast router for electrical network optimization.

  • Uses a modified Esau-Williams (EW) heuristic (segmented or straight feeders).

  • Produces solutions in milliseconds, suitable for quick solutions or warm starts.

Create a Esau-Williams-based router.

Available Methods:
'esau_williams'

Esau-Williams C-MST heuristic modified to avoid crossings (EW).

'biased_EW'

EW with a bias towards moving radially (root-ward) on quasi-ties.

'rootlust'

EW with a tunable root-ward bias that increases as capacity decreases.

'radial_EW'

EW variant that produces radial subtrees (simple paths from root).

'ringed'

Closes each subtree into a ring: both endpoints connect to the same root (two feeders) joined at a zero-load link. cables_capacity is the per-arm limit, so a ring holds up to twice as many terminals. Unions are ranked by their total saving — the feeders shed at the two joined endpoints minus the connecting edge’s length (Clarke-Wright style) — with a bias_margin window favoring the more root-ward union on quasi-ties.

Parameters:
  • maxiter – Maximum iterations.

  • feeder_route – Feeder routing mode ('segmented' or 'straight').

  • method – one of the Available Methods, defaults to 'biased_EW').

  • bias_margin – Fractional margin within which candidates are considered equivalent, resolving the quasi-tie root-ward (used by 'biased_EW', 'radial_EW' and 'ringed'; for 'ringed' the margin is a fraction of the best union saving rather than the edge extent). Defaults to the constructor’s built-in default (0.02) when None.

  • verbose – Enable verbose logging.

verbose = False[source]
maxiter = 10000[source]
feeder_route = 'segmented'[source]
method = 'biased_EW'[source]
bias_margin = None[source]
route(P, A, cables, cables_capacity, verbose=False, **kwargs)[source]

Run the routing optimization.

Parameters:
  • P – Navigation mesh for the location.

  • A – Graph of available links.

  • cables – set of cable specifications as [(capacity, linear_cost), …].

  • cables_capacity – highest cable capacity in cables.

  • verbose – Whether to print progress/logging info.

  • **kwargs – Additional router-specific parameters.

Returns:

Tuple of (solution topology (selected links), optimized route set).

class optiwindnet.api.HGSRouter(time_limit: float, feeder_limit: int | None = None, feeder_exact: bool = False, max_retries: int = 10, balanced: bool = False, ringed: bool = False, seed: int | None = None, verbose: bool = False, **kwargs)[source]

Bases: Router

A fast router based on Hybrid Genetic Search (HGS-CVRP).

Uses the method and implementation by Vidal, 2022:

Vidal, T. (2022). Hybrid genetic search for the CVRP: Open-source implementation and SWAP* neighborhood. Computers & Operations Research, 140, 105643. https://doi.org/10.1016/j.cor.2021.105643

  • Balances solution quality and runtime.

  • Produces radial solutions, or RINGED (cycle) solutions with ringed=True.

Create an HGS-based router.

Parameters:
  • time_limit – Maximum runtime for a single HGS run (in seconds).

  • feeder_limit – Maximum number of feeders allowed (ignored if multiple substations); the exact number if feeder_exact.

  • feeder_exact – Whether feeder_limit is the exact number of feeders, instead of an upper bound (requires balanced=True and a single substation).

  • max_retries – Maximum number of retries if a feasible solution is not found.

  • balanced – Whether to balance turbines/loads across feeders.

  • ringed – Whether to produce a RINGED topology (cycles) instead of a radial one. HGS then solves the closed CVRP, so each ring holds up to 2 * cables_capacity turbines (two arms of cables_capacity each).

  • seed – Set the seed of the pseudo-random number generator (reproducibility).

  • verbose – Enable verbose logging.

Note

The total runtime may reach up to (max_retries + 1) * time_limit in the worst case.

time_limit[source]
verbose = False[source]
max_retries = 10[source]
feeder_limit = None[source]
feeder_exact = False[source]
balanced = False[source]
ringed = False[source]
seed = None[source]
route(P, A, cables, cables_capacity, verbose=False, **kwargs)[source]

Run the routing optimization.

Parameters:
  • P – Navigation mesh for the location.

  • A – Graph of available links.

  • cables – set of cable specifications as [(capacity, linear_cost), …].

  • cables_capacity – highest cable capacity in cables.

  • verbose – Whether to print progress/logging info.

  • **kwargs – Additional router-specific parameters.

Returns:

Tuple of (solution topology (selected links), optimized route set).

class optiwindnet.api.MILPRouter(solver_name: str, time_limit: float, mip_gap: float, solver_options: dict | None = None, model_options: collections.abc.Mapping[str, Any] | None = None, verbose: bool = False, **kwargs)[source]

Bases: Router

An exact router using mathematical programming.

  • Uses a Mixed-Integer Linear Programming (MILP) model of the problem.

  • Produces provably optimal or near-optimal networks (with quality metrics).

  • Requires a longer runtime than heuristics- and meta-heuristics-based routers.

Create a MILP-based router.

Parameters:
  • solver_name – Name of solver (e.g., 'gurobi', 'cbc', 'ortools', 'cplex', 'highs', 'scip').

  • time_limit – Maximum runtime (seconds).

  • mip_gap – Relative MIP optimality gap tolerance.

  • solver_options – Extra solver-specific options.

  • model_options – Options for the MILP model. A plain mapping is coerced into a ModelOptions.

  • verbose – Enable verbose logging.

default_heuristic = 'rootlust'[source]
time_limit[source]
mip_gap[source]
solver_name[source]
solver_options[source]
model_options[source]
verbose = False[source]
solver[source]
route(P, A, cables, cables_capacity, verbose=False, S_warm=None, S_warm_has_detour=False, num_retries: int = 2, **kwargs)[source]

Run the routing optimization.

Parameters:
  • P – Navigation mesh for the location.

  • A – Graph of available links.

  • cables – set of cable specifications as [(capacity, linear_cost), …].

  • cables_capacity – highest cable capacity in cables.

  • verbose – Whether to print progress/logging info.

  • **kwargs – Additional router-specific parameters.

Returns:

Tuple of (solution topology (selected links), optimized route set).