optiwindnet.api¶
Module Contents¶
- class optiwindnet.api.Router[source]¶
Bases:
abc.ABCAbstract base class for routing algorithms in OptiWindNet.
Each Router implementation must define a
route()method.- 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
Routerinstance 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 (
capacityis 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
Land coordinates are provided,Ltakes precedence.Changing coordinate data after creation (
turbinesCand/orsubstationsC) rebuildsLand 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())
- property cables: list[tuple[int, float | int]][source]¶
Set of cable specifications as
[(capacity, linear_cost), ...].
- property polygon: shapely.Polygon | shapely.MultiPolygon | None[source]¶
Shapely (Multi)Polygon that bounds the cable-laying area.
- 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/_Rwere set). The solved-network branch is reached only when_is_stale_SGisFalse, which guarantees_Gexists.
- plot(*args, **kwargs)[source]¶
Plot the optimized network.
By default, this method utilizes the modern vector SVG-based plotting backend (
svgplot()) which returns anSvgReprsuitable for clean interactive inline displays in Jupyter notebooks.To switch to the Matplotlib-based plotting backend (
gplot()), specify theaxparameter as a keyword argument.Note
Passing
ax=Noneexplicitly routes to the Matplotlib backend and automatically instantiates a new figure and axes on the fly, allowing Matplotlib figures to be created without importingmatplotliborpyplotdirectly in the user code.
Plot navigation mesh (planar graph and adjacency).
- update_from_terse_links(terse_links: numpy.ndarray, turbinesC: numpy.ndarray | None = None, substationsC: numpy.ndarray | None = None)[source]¶
Update the network from terse link representation.
Accepts integers or integer-like floats (e.g., 3.0).
- 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_distthat 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.
- 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:
RouterA 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).
- 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 edges are considered equivalent (used by
'biased_EW'and'radial_EW'). Defaults to the constructor’s built-in default (0.02) whenNone.verbose – Enable verbose logging.
- 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, seed: int | None = None, verbose: bool = False, **kwargs)[source]¶
Bases:
RouterA 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 only radial solutions.
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_limitis the exact number of feeders, instead of an upper bound (requiresbalanced=Trueand a single substation).max_retries – Maximum number of retries if a feasible solution is not found.
balanced – Whether to balance turbines/loads across feeders.
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_limitin the worst case.- 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: optiwindnet.MILP.ModelOptions | None = None, verbose: bool = False, **kwargs)[source]¶
Bases:
RouterAn 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.
verbose – Enable verbose logging.
- 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).