WeatherRoutingTool.algorithms package

Submodules

WeatherRoutingTool.algorithms.data_utils module

class WeatherRoutingTool.algorithms.data_utils.GridMixin(grid, *args, **kwargs)[source]

Bases: object

TODO: add class description _summary_

coords_to_index(points_as_coords)[source]
get_shuffled_cost()[source]
grid: Dataset
index_to_coords(points_as_indices)[source]
WeatherRoutingTool.algorithms.data_utils.distance(route)[source]

TODO: Where is this function used? Calculates the accumulated distance along a route

Parameters:

route (TODO: add type of route) – Some kind of route

Returns:

Accumulated distance along a route

Return type:

np.array

WeatherRoutingTool.algorithms.data_utils.get_closest(array, value)[source]

Determine and return index of the value in the array which is closest to the given value. If there are multiple values in the array with the same distance to the value, the first/smallest index is used. :param array: array used to search in :type array: numpy.ndarray :param value: value for which the closest value in the array should be found :type value: numeric :return: index :rtype: numpy.int64

WeatherRoutingTool.algorithms.data_utils.time_diffs(speed, route)[source]

WeatherRoutingTool.algorithms.genetic module

class WeatherRoutingTool.algorithms.genetic.Genetic(config: Config)[source]

Bases: RoutingAlg

Genetic Algorithm implementation for Weather Routing Tool

execute_routing(boat: Boat, wt: WeatherCond, constraints_list: ConstraintsList, verbose=False)[source]

Main routing execution function

Parameters:
  • boat (Boat) – Boat config

  • wt (WeatherCond) – Weather conditions for the waypoints

  • constraints_list (ConstraintsList) – List of problem constraints

  • verbose (Optional[bool]) – Verbosity setting for logs

optimize(problem, initial_population, crossover, mutation, duplicates, repair)[source]

Optimization function for the Genetic Algorithm

plot_convergence(res)[source]

Plot the convergence curve (best objective value per generation).

plot_population_per_generation(res, best_route)[source]

Plot figures and save them in WRT_FIGURE_PATH

Parameters:
  • res (pymoo.core.result.Result) – Result of GA minimization

  • best_route (np.ndarray) – Optimum route

plot_running_metric(res)[source]

Plot running metrics

Parameters:

res (pymoo.core.result.Result) – Result object of minimization

print_current_status()[source]

Log messages for running status

print_init()[source]

Log messages to print on algorithm initialization

terminate(res: Result, problem: RoutingProblem)[source]

Genetic Algorithm termination procedures

WeatherRoutingTool.algorithms.genetic.crossover module

class WeatherRoutingTool.algorithms.genetic.crossover.CrossoverBase(prob=0.5)[source]

Bases: Crossover

Base Crossover Class

Kept for consistency and to provide super-class level management of Crossover implementations.

class WeatherRoutingTool.algorithms.genetic.crossover.CrossoverFactory[source]

Bases: object

static get_crossover(config: Config, constraints_list: ConstraintsList)[source]
class WeatherRoutingTool.algorithms.genetic.crossover.OffspringRejectionCrossover(departure_time: datetime, constraints_list: ConstraintsList, prob=0.5)[source]

Bases: CrossoverBase

Offspring-Rejection Crossover Base Class

  • Generate offsprings using sub-class’ implementation of the crossover function

  • Validate if offsprings violate discrete constraints
    • if True, get rid of both offsprings, and return parents

    • if False, return offsprings

Parameters:
  • departure_time (datetime) – Time of ship departure (from config)

  • constraints_list (ConstraintsList) – List of constraints

crossover(p1: ndarray, p2: ndarray) tuple[ndarray, ndarray][source]

Sub-class’ implementation of the crossover function

route_constraint_violations(route: ndarray) ndarray[source]

Check if route breaks any discrete constraints

Parameters:

route – list of waypoints

Dtype route:

np.ndarray

Returns:

Boolean array of constraint violations per waypoint

Return type:

np.ndarray

class WeatherRoutingTool.algorithms.genetic.crossover.PMX(departure_time: datetime, constraints_list: ConstraintsList, prob=0.5)[source]

Bases: OffspringRejectionCrossover

Partially Mapped Crossover

crossover(p1, p2)[source]

Sub-class’ implementation of the crossover function

class WeatherRoutingTool.algorithms.genetic.crossover.RandomizedCrossoversOrchestrator(opts, **kw)[source]

Bases: CrossoverBase

Randomly selects one of the provided crossovers during every call to _do

Parameters:

opts (list[Crossover]) – List of Crossover operators

class WeatherRoutingTool.algorithms.genetic.crossover.SinglePointCrossover(config: Config, patch_type: str = 'gcr', **kw)[source]

Bases: OffspringRejectionCrossover

Single-point Crossover

Parameters:

config (Config) – Configuration for the run

crossover(p1, p2)[source]

Sub-class’ implementation of the crossover function

class WeatherRoutingTool.algorithms.genetic.crossover.TwoPointCrossover(config: Config, patch_type: str = 'gcr', **kw)[source]

Bases: OffspringRejectionCrossover

Two-point Crossover

Parameters:

config (Config) – Configuration for the run

crossover(p1, p2)[source]

Sub-class’ implementation of the crossover function

WeatherRoutingTool.algorithms.genetic.population module

class WeatherRoutingTool.algorithms.genetic.population.FromGeojsonPopulation(routes_dir: str, default_route, constraints_list, pop_size)[source]

Bases: Population

Genetic population from a directory of routes

Note

Routes are expected to be named in the following format: route_{1..N}.json

example: route_1.json, route_2.json, route_3.json, …

Parameters:

routes_dir (str) – Directory pointing to the routes folder

generate(problem, n_samples, **kw)[source]
class WeatherRoutingTool.algorithms.genetic.population.GridBasedPopulation(default_route, grid, constraints_list, pop_size)[source]

Bases: GridMixin, Population

Make initial population for genetic algorithm based on a grid and associated cost values

Notes on the inheritance:
  • GridMixin has to be inherited first because Sampling isn’t designed for multiple inheritance

  • implemented approach: https://stackoverflow.com/a/50465583, scenario 2

  • call print(GridBasedPopulation.mro()) to see the method resolution order

generate(problem, n_samples, **kw)[source]
class WeatherRoutingTool.algorithms.genetic.population.IsoFuelPopulation(config: Config, boat: Boat, default_route, constraints_list, pop_size)[source]

Bases: Population

Population generation using the IsoFuel algorithm

Produces initial routes using the IsoFuel algorithm’s ISOCHRONE_NUMBER_OF_STEPS configuration. If the number of generated routes is lesser than the expected n_samples number of individuals, the last produced route is repeated until the required number of individuals are met

generate(problem, n_samples, **kw)[source]
class WeatherRoutingTool.algorithms.genetic.population.Population(default_route: list, constraints_list: list, pop_size: int)[source]

Bases: Sampling

Base Population Class

check_validity(routes)[source]

Check whether the waypoints of the routes violate constraints. Raise a warning for each single route that violates constraints. Raise an error, if more than 50% of all routes violate constraints.

Parameters:

routes – array of routes for initial population

generate(problem, n_samples, **kw)[source]
class WeatherRoutingTool.algorithms.genetic.population.PopulationFactory[source]

Bases: object

static get_population(config: Config, boat: Boat, constraints_list: ConstraintsList, wt: WeatherCond) Population[source]

WeatherRoutingTool.algorithms.genetic.mutation module

class WeatherRoutingTool.algorithms.genetic.mutation.MutationBase(prob=1.0, prob_var=None, **kwargs)[source]

Bases: Mutation

Base Mutation Class

Kept for consistency and to provide super-class level management of Mutation implementations.

mutate(problem, X, **kw)[source]
class WeatherRoutingTool.algorithms.genetic.mutation.MutationFactory[source]

Bases: object

static get_mutation(config: Config) Mutation[source]
class WeatherRoutingTool.algorithms.genetic.mutation.NoMutation(prob=1.0, prob_var=None, **kwargs)[source]

Bases: MutationBase

Empty Mutation class for testing

mutate(problem, X, **kw)[source]
class WeatherRoutingTool.algorithms.genetic.mutation.RandomMutationsOrchestrator(opts, **kw)[source]

Bases: MutationBase

Select a mutation operator at random and apply it over the population

Parameters:

opts (list[Mutation]) – List of Mutation classes

class WeatherRoutingTool.algorithms.genetic.mutation.RandomWalkMutation(gcr_dist: float = 10000.0, n_updates: int = 10, **kw)[source]

Bases: MutationBase

Moves a random waypoint in an individual in the direction of a random bearing by a distance specified by the gcr_dist parameter. The entire task is repeated n_updates number of times to produce substantial variation.

Parameters:
  • gcr_dist (float) – The distance by which to move the point

  • n_updates (int) – Number of iterations to repeat the random walk operation

mutate(problem, X, **kw)[source]
random_walk(point: tuple[float, float], dist: float = 10000.0, bearing: float = 45.0) tuple[float, float][source]

Pick an N4 neighbour of a waypoint

Parameters:
  • point (tuple[float, float]) – (lat, lon) in degrees.

  • dist (float) – distance in meters

  • bearing (float) – Azimuth in degrees (clockwise from North)

Returns:

(lat, lon) in degrees.

Return type:

tuple[float, float]

class WeatherRoutingTool.algorithms.genetic.mutation.RouteBlendMutation(prob=1.0, prob_var=None, **kwargs)[source]

Bases: MutationBase

Generates a bezier curve between two randomly selected indices and infills it with 2x the number of waypoints previously present in the selected range.

static bezier_curve(control_points, n_points=100)[source]

Generate a Bezier curve given control points.

Parameters:
  • control_points (np.ndarray) – List of (x, y) control points

  • n_points (int) – Number of points on the curve

Returns:

Array of shape (n_points, 2) with curve coordinates

Return type:

np.ndarray

mutate(problem, X, **kw)[source]

WeatherRoutingTool.algorithms.genetic.patcher module

class WeatherRoutingTool.algorithms.genetic.patcher.GreatCircleRoutePatcher(dist: float = 100000.0)[source]

Bases: PatcherBase

Produce a set of waypoints along the Great Circle Route between src and dst.

Parameters:

dist (float) – Dist between each waypoint in the Great Circle Route

dist: float
patch(src: tuple, dst: tuple) ndarray[source]

Generate equi-distant waypoints across the Great Circle Route from src to dst

Parameters:
  • src (tuple[float, float]) – Source waypoint as (lat, lon) pair

  • dst (tuple[float, float]) – Destination waypoint as (lat, lon) pair

Returns:

List of waypoints along the great circle (lat, lon)

Return type:

np.array[tuple[float, float]]

class WeatherRoutingTool.algorithms.genetic.patcher.GreatCircleRoutePatcherSingleton(*args, **kwargs)[source]

Bases: GreatCircleRoutePatcher

Implementation class for GreatCircleRoutePatcher that allows only a single instance.

class WeatherRoutingTool.algorithms.genetic.patcher.IsofuelPatcher(base_config: Config, n_routes: str = 'single')[source]

Bases: PatcherBase

Use the IsoFuel algorithm to produce a route between src and dst.

Intuition behind having this as a class: 1. The Isofuel path finding component can be quite expensive during the

preparation stage (defining map, loading data, etc.). Having setup and execution as separate components could help speed things up.

Parameters:
  • config (Config) – Configuration for the run

  • n_routes (str) – Type of response expected. Either “single” or “multiple”

boat: Boat
config: Config
constraints_list: ConstraintsList
n_routes: int
patch(src, dst, departure_time: datetime = None)[source]

Produce a set of waypoints between src and dst using the IsoFuel algorithm.

Parameters:
  • src (tuple[float, float]) – Source waypoint as (lat, lon) pair

  • dst (tuple[float, float]) – Destination waypoint as (lat, lon) pair

  • departure_time (datetime) – departure time from src

Returns:

List of waypoints or list of multiple routes connecting src and dst

Return type:

np.array[tuple[float, float]] or list[np.array[tuple[float, float]]]

water_depth: WaterDepth
wt: WeatherCond
class WeatherRoutingTool.algorithms.genetic.patcher.IsofuelPatcherSingleton(*args, **kwargs)[source]

Bases: IsofuelPatcher

Implementation class for IsofuelPatcher that allows only a single instance.

class WeatherRoutingTool.algorithms.genetic.patcher.PatcherBase(*args, **kwargs)[source]

Bases: object

Base class for route patching

patch(src: tuple, dst: tuple)[source]

Obtain waypoints between src and dst.

Parameters:
  • src (tuple[float, float]) – Source coords as (lat, lon)

  • dst (tuple[float, float]) – Destination coords as (lat, lon)

class WeatherRoutingTool.algorithms.genetic.patcher.SingletonBase[source]

Bases: type

TODO: make this thread-safe Base class for Singleton implementation of patcher methods.

This is the implementation of a metaclass for those classes for which only a single instance shall be available during runtime.

WeatherRoutingTool.algorithms.genetic.repair module

class WeatherRoutingTool.algorithms.genetic.repair.ChainedRepairsOrchestrator(order)[source]

Bases: Repair

Executes repairs in the order they are entered in

Parameters:

order (list[Repair]) – List of Repair implementations to execute in that order

class WeatherRoutingTool.algorithms.genetic.repair.ConstraintViolationRepair(config: Config, constraints_list, **kw)[source]

Bases: RepairBase

Repair routes by finding a feasible route between constraint violations

Parameters:

config (Config) – Configuration for the run

repairfn(problem, X, **kw)[source]

Implemenation of the repair function

class WeatherRoutingTool.algorithms.genetic.repair.RepairBase(config: Config)[source]

Bases: Repair

Base Repair class

Kept for consistency and to provide super-class level management of Repair implementations.

Parameters:

config (Config) – Configuration for the run

repairfn(problem, X, **kw)[source]

Implemenation of the repair function

class WeatherRoutingTool.algorithms.genetic.repair.RepairFactory[source]

Bases: object

static get_repair(config: Config, constraints_list: ConstraintsList)[source]
class WeatherRoutingTool.algorithms.genetic.repair.WaypointsInfillRepair(config: Config)[source]

Bases: RepairBase

Repair routes by infilling them with equi-distant points when adjacent points are farther than the specified distance resolution (gcr_dist)

repairfn(problem, X, **kw)[source]

Implemenation of the repair function

WeatherRoutingTool.algorithms.genetic.utils module

class WeatherRoutingTool.algorithms.genetic.utils.RouteDuplicateElimination(cmp_func=None, **kwargs)[source]

Bases: ElementwiseDuplicateElimination

Custom duplicate elimination strategy for routing problem.

is_equal(a, b)[source]
WeatherRoutingTool.algorithms.genetic.utils.gcr_distance(src, dst) float[source]

Return the Great Circle distance between src and dst

Parameters:
  • src (tuple[float, float]) – Source coords as (lat, lon)

  • dst (tuple[float, float]) – Destination coords as (lat, lon)

Returns:

Distance between src and dst in meters

Return type:

float

WeatherRoutingTool.algorithms.genetic.utils.geojson_from_route(route: list[tuple[float, float]], save_to: str | None = None) dict[source]

Generate geojson from list of waypoints

Parameters:
  • route (list[tuple[float, float]]) – List of waypoints

  • save_to (str) – Specify path to save the geojson to

Returns:

Geojson dictionary

Return type:

dict

WeatherRoutingTool.algorithms.genetic.utils.get_constraints(route, constraint_list)[source]

Get sum of constraint violations of all waypoints of the provided route

Parameters:
  • route (np.ndarray) – List of waypoints

  • constraints_list (ConstraintsList) – List of constraints configured by the config

WeatherRoutingTool.algorithms.genetic.utils.get_constraints_array(route: ndarray, constraint_list) ndarray[source]

Return constraint violation per waypoint in route

Parameters:

route (np.ndarray) – Candidate array of waypoints

Returns:

Array of constraint violations

WeatherRoutingTool.algorithms.genetic.utils.great_circle_distance(src, dst) float[source]

Measure great circle distance between src and dst waypoints

Parameters:
  • src (tuple[float, float]) – Source waypoint as (lat, lon) pair

  • dst (tuple[float, float]) – Destination waypoint as (lat, lon) pair

Returns:

Great circle distance between src and dst

Return type:

float

WeatherRoutingTool.algorithms.genetic.utils.is_neg_constraints(lat, lon, time, constraint_list)[source]

Check if the given point is constrained by the constraints_list

Parameters:
  • lat (float) – Latitude of the point

  • lat – Longitude of the point

  • time (datetime.datetime) – Datetime of the provided point data

  • constraints_list (ConstraintsList) – Constraints list passed in by the config

WeatherRoutingTool.algorithms.genetic.utils.route_from_geojson(dt: dict) list[tuple[float, float]][source]

Parse list of waypoints from geojson dict

Parameters:

dt (dict) – Geojson dictionary

Returns:

List of waypoints as (lat, lon) pair

Return type:

list[tuple[float, float]]

WeatherRoutingTool.algorithms.genetic.utils.route_from_geojson_file(path: str) list[tuple[float, float]][source]

Parse route from geojson file

Parameters:

path (str) – Path to geojson file

Returns:

List of waypoints as a (lat, lon) pair

Return type:

list[tuple[float, float]]

WeatherRoutingTool.algorithms.isobased module

class WeatherRoutingTool.algorithms.isobased.IsoBased(config)[source]

Bases: RoutingAlg

Base class for algorithms that are based on traveling with constant fuel/time/etc.

The class initiates the main evaluation steps that are necessary for IsoBased algorithms. The function execute_routing is the core of the implementation. It iterates over individual routing steps and initiates the main evaluations which are:

  • define a set of route segments that is to be tested (function: define_courses_per_step)

  • estimate the fuel consumption rate at the start of the route segments based on weather conditions and ship type (function: estimate_fuel_consumption, calls Ship module)

  • move the ship considering that a fixed amount of fuel/time/etc can be consumed (function: move_boat)

  • evaluate possible constraints (function: check_constraints, calls Constraints module)

  • select routes that maximise/minimise the evaluation criterion (function: pruning)

The class also considers positive constraints like waypoints that need to be passed (function: check_for_positive_constraints).

The variables that charactarise a single routing step are stored in a RoutingStep object. Error and state descriptions are stored in an IsoBasedStatus object. For further evaluation of the error status by the user, an error code is returned by the main function execute_routing.

The history of the routing procedure is stored in a selection of np.ndarrays with dimension MxN (variables with suffix ‘per_step’) and np.ndarrays with dimension N (variables with prefix ‘full’) whereby ‘M’ corresponds to the current number of routing steps and ‘N’ corresponds to the current number of courses +1. The dimensions of these arrays aren’t static; for every routing step, a row is added on top of the matrices (functions with prefix ‘update’).

Parameters:
  • ncount (int) – total number of routing steps

  • count (int) – current routing step

  • start_temp (tuple (lat, lon)) – temporary starting point considering intermediate waypoints

  • finish_temp (tuple (lat, lon)) – temporary arrival point considering intermediate waypoints

  • grc_course_temp – course of grand circle route towards temporary arrival point

  • lats_per_step ((M,N) np.ndarray N=courses+1, M=steps (M decreasing)) – latitudes per routing step and test route

  • lons_per_step ((M,N) np.ndarray N=courses+1, M=steps (M decreasing)) – longitudes per routing step and test route

  • course_per_step ((M,N) np.ndarray N=courses+1, M=steps (M decreasing)) – courses per routing step and test route; angle convention: 0-360°

  • dist_per_step ((M,N) np.ndarray N=courses+1, M=steps (M decreasing)) – geodesic distance travelled per routing step and test route

  • shipparams_per_step (ShipParams) – ship parameters (fuel rate, power consumption …) per routing step and test route

  • starttime_per_step ((M,N) np.ndarray (datetime object) N=courses+1, M=steps (M decreasing)) – start time for every routing step

  • absolutefuel_per_step ((M,N) np.ndarray N=courses+1, M=steps (M decreasing)) – absolute fuel consumed for every route at certain routing step

  • full_dist_traveled – full distance traveled for every test route

  • full_time_traveled – full travel time for every test route

  • time – current datetime for every test route

  • course_segments (int) – number of course segments in the range of -180° to 180°

  • course_increments_deg (int) – increment between different courses

  • prune_sector_deg_half (int) – angular range of course that is considered for pruning (only one half, 0-180°)

  • prune_segments – number of course bins that are used for pruning

  • prune_symmetry_axis (str) – method to define pruning symmetry axis

  • prune_groups (str) – method to define grouping of route segments before the pruning

  • minimisation_criterion (str) – minimisation criterion

  • desired_number_of_routes (int) – number of routes requested for multiple-routes approach

  • current_number_of_routes (int) – current number of routes in case of multiple-routes approach

  • current_step_routes (pd.DataFrame)

  • next_step_routes (pd.DataFrame)

  • route_list (list[RouteParams]) – list of routes in case of multiple-routes approach

  • status (IsoBasedStatus) – container for status and error information

  • routing_step (RoutingStep) – container for variables for single routing step

absolutefuel_per_step: ndarray
branch_based_pruning() ndarray[source]

Perform branch-based pruning.

Group routes according to the starting points of the last routing segment, i.e. routes that originate from the origin in the last step form a group called “branch”. The indices of the routes with maximum travel distance for every branch are collected in an array which is returned.

Returns:

indices of routes with maximum distance per branch

Return type:

np.ndarray

check_bearing()[source]

TODO: add description :return:

check_constraints(constraint_list)[source]

Evaluate whether the new route segments violate constraints.

The characteristics of the new route segments are sent to the Constraints module for evaluation. The variable routing_step is updated accordingly.

Parameters:

constraint_list (ConstraintsList) – list of constraints

check_course_def()[source]

Perform sanity checks for ‘per_step’ variables.

check_destination()[source]
check_for_positive_constraints(constraint_list)[source]
check_land_ahoy(ship_params, bs)[source]

Check whether any of the test routes can reach the destination.

For every test route, the travel distance of the current routing step is compared to the distance to the (temporary) destination. If the latter distance is smaller, this very route is propagated to the destination.

check_positive_power()[source]
check_settings()[source]
check_status(shipparams_per_step_status, route_name)[source]
collect_routes()[source]

Collect all routes if any has been propagated to destination.

In case of standard algorithm execution (desired_number_of_routes = 1), the status is updated accordingly.

In case the algorithm has been configured to find multiple routes (desired_number_of_routes > 1): - it is checked whether the requested number of routes has been found - all route found in the current routing step are written to file - the status is updated accordingly - the algorithm is configured to find further routes if necessary

count: int
course_increments_deg: int
course_per_step: ndarray
course_segments: int
courses_based_pruning(bins: ndarray) tuple[ndarray, ndarray, ndarray][source]

Perform courses-based pruning

A histogram is filled with the maximum travel distance (argument: statistic = np.nanmax) in dependence of bins of all courses of the route segments in the current routing step. The bin content, bin edges and the bin numbers are returned.

Parameters:

bins (np.ndarray) – bin edges of the histogram

Returns:

bin content, bin edges and bin numbers

Return type:

tuple[np.ndarray, np.ndarray, np.ndarray]

current_number_of_routes: int
current_position()[source]
current_step_routes: DataFrame
define_courses()[source]

Initialise variables that store the routing history for the next routing step.

All variables that store the routing history are extended to match the dimension M = N_routes x course_segments. Variables for single coordinate pairs are repeated for different course segments. The routing_step object is initialised for the current routing step.

define_courses_per_step()[source]
define_initial_variants()[source]
depart_from_waypoint(constraints_list)[source]

Initialise variables that store the routing history when departing from an intermediate waypoint.

Parameters:

constraints_list (ConstraintsList) – list of constraints

desired_number_of_routes: int
dist_per_step: ndarray
estimate_fuel_consumption(boat: Boat)[source]

Initiate the estimation of the fuel consumption by the Ship module.

Parameters:

boat (Boat) – boat object for fuel estimation

Returns:

boat speed, calculated ship parameters

Return type:

float, ShipParams

execute_routing(boat: Boat, wt: WeatherCond, constraints_list: ConstraintsList, verbose=False)[source]

Core function for the initialisation of important evaluations of IsoBased algorithms.

The function iterates over individual routing steps and initiates the main routing evaluations which are: - define a set of route segments that is to be tested (function: define_courses_per_step) - estimate the fuel consumption rate at the start of the route segments based on weather conditions and ship type (function: estimate_fuel_consumption, calls Ship module) - move the ship considering that a fixed amount of fuel/time/etc can be consumed (function: move_boat) - evaluate possible constraints (function: check_constraints, calls Constraints module) - select routes that maximise/minimise the evaluation criterion (function: pruning) The class also considers positive constraints like waypoints that need to be passed (function: check_for_positive_constraints).

In case of successful algorithm execution, the function returns a RouteParams object. It performs evaluations considering the individual routing states. It catches errors, returns an error code as well as the best route at the state of the routing algorithm, at which the error occurred. In case the algorithm is configured to find multiple routes (ISOCHRONE_NUMBER_OF_ROUTES>1), this function returns the best route while all routes that have been found are written to separate json files.

Parameters:
  • boat (Ship) – Ship object

  • wt (WeatherCond) – Weather data

  • constraints_list (ConstraintsList) – List of constraints

  • verbose (bool, optional) – sets verbosity, defaults to False

Returns:

calculated route

Return type:

RouteParams

expand_axis_for_intermediate()[source]
final_pruning()[source]
find_every_route_reaching_destination()[source]

Collect all test routes that can be propagated to the destination (multiple-routes approach).

This function collects all routes reaching the destination in the current routing step. It - creates a pd.DataFrame with the latitudes, longitudes, travel distance, distance to destination and fuel

consumption of the current routing segments

  • stores the index order of the original ‘per_step’ arrays for later reference as axis with name ‘st_index’

  • groups the variables of the DataFrame according to matching starting points of the routing segment

  • stores only the best routes per branch that reach the destination in the ‘current_step_routes’ dataframe.

  • stores all routes that do not reach the destination in the ‘next_step_routes’ dataframe for further evaluation

find_routes_reaching_destination_in_current_step(remaining_routes=0)[source]

Rank routes that reach the destination and write them to file (multiple-routes approach).

The number of routes that are selected is specified by the variable remaining_routes. If the figure path is set, the routes are plotted.

Parameters:

remaining_routes (int, optional) – specifies how many routes shall be selected

finish_temp: tuple
full_dist_traveled: ndarray
full_time_traveled: ndarray
gcr_course_temp: tuple
get_current_lats()[source]
get_current_lons()[source]
get_current_speed()[source]
get_delta_variables(boat, wind, bs)[source]
get_delta_variables_netCDF_last_step(boat, wind, bs)[source]
get_final_index()[source]
get_pruned_indices_statistics(bin_stat: ndarray, bin_edges: ndarray, trim: bool) list[int][source]

Collect routes whose travel distance matches the maximum bin entries in the pruning histogram.

Parameters:
  • bin_stat (np.ndarray) – bin content of the pruning histogram which is the maximum travel distance per bin

  • bin_edges (np.ndarray) – bin edges of the pruning histogram

  • trim (bool) – omit bins with zero bin content for the pruning

Returns:

list of indices of best routes

Return type:

list[int]

get_wind_functions(wt)[source]
init_fig(water_depth, map_size, showDepth=True)[source]
larger_direction_based_pruning(bins: ndarray) tuple[ndarray, ndarray, ndarray][source]

Perform larger-direction-based pruning.

Define an angle referred to as ‘larger direction’ which is the azimuthal angle from the starting point of the test routes towards the current position. A histogram is filled with the maximum travel distance (argument: statistic = np.nanmax) in dependence of bins of the larger direction. The bin content, bin edges and the bin numbers are returned.

Parameters:

bins (np.ndarray) – bin edges of the histogram

Returns:

bin content, bin edges and bin numbers

Return type:

tuple[np.ndarray, np.ndarray, np.ndarray]

lats_per_step: ndarray
lons_per_step: ndarray
make_route_object(idxs)[source]

Generates RouteParams object from ‘per_step’ variables based on index of test route (multiple-routes approach).

Parameters:

idxs (int) – index of test route

minimisation_criterion: str
move_boat(bs, ship_params)[source]

Move boat to new position based on estimated fuel consumption (or similar).

The travel time, fuel consumption and travel distance are estimated and stored in routing_step. Based on these variables, the new ship position is determined without considering constraints. If the ship can reach its (temporary) destination for one test route, all variables of this route are propagated to the destination.

Parameters:
  • bs (float) – boat speed

  • ship_params (ShipParams) – ship parameters (fuel consumption, …)

ncount: int
next_step_routes: DataFrame
plot_routes(idxs)[source]

Plot every complete individual route that is reaching the destination (multiple-routes approach).

Parameters:

idxs (int) – loop index

print_current_status()[source]
print_init()[source]
print_shape()[source]
prune_groups: str
prune_sector_deg_half: int
prune_segments: int
prune_symmetry_axis: str
pruning(trim: bool, bins: ndarray) None[source]

Perform pruning.

Call the methods for larger-direction based, courses-based and branch-based pruning which determine the indices of the routes which perform best after this routing step. Slice the arrays that store the history of the routing procedure such that only the best routes survive.

Parameters:
  • trim (bool, optional) – omit bins with zero bin content for the pruning, defaults to True

  • bins (np.ndarray) – bin edges for the pruning

Raises:
  • ValueError – if no routes are available for the pruning

  • IndexError – if any array can not be sliced according to the indices that have been found

pruning_gcr_centered(trim: bool = True) None[source]

Initiate pruning with the grand circle route as the symmetry axis.

First, the symmetry axis for the binning of the pruning is determined. To do so, it is assumed that the ship travels from the starting point (or last intermediate waypoint) of the routes in the direction of the azimuthal angle gcr_course_temp for the mean full travel distance of all routes. The azimuthal angle of the waypoint that is found in this way towards the destination (or next intermediate waypoint) is defined as the symmetry axis of the pruning i.e. the bins are centered around it. These bins are fed into the function ‘pruning’ for further evaluation.

Parameters:

trim (bool, optional) – omit bins with zero bin content for the pruning, defaults to True

pruning_headings_centered(trim: bool = True) None[source]

Initiate pruning with a symmetry axis that is determined from the spread of courses.

First, the symmetry axis for the binning of the pruning is determined as the median of the courses of all route segments from the current routing step. Bins are centered around this symmetry axis and the resulting binning is fed into the function ‘pruning’ for further evaluation.

Parameters:

trim (bool, optional) – omit bins with zero bin content for the pruning, defaults to True

pruning_per_step(trim: bool = True) None[source]

Initiate pruning. Decide between pruning methods with different symmetry axis.

revert_to_previous_step()[source]

Revert arrays to previous routing step if all routes are constrained for current step (multiple-routes approach)

route_list: list
routes_from_previous_step()[source]

Collect routes for previous step if all routes are constrained for current step (multiple-routes approach).

When all routes are constrained, unique routes until the current constrained routing step are found here. Then, the unique routes are written into json files and plotted.

routing_step: RoutingStep
set_course_segments(seg, inc)[source]
set_minimisation_criterion(min_str)[source]
set_next_step_routes()[source]

Update all arrays of test routes that need to be further processed (multiple-routes approach).

set_pruning_settings(sector_deg_half, seg, prune_groups, prune_symmetry_axis='gcr')[source]
shipparams_per_step: ShipParams
start_temp: tuple
starttime_per_step: ndarray
status: IsoBasedStatus
terminate(**kwargs)[source]

TODO: add description

Returns:

Calculated route as a RouteParams object ready to be returned to the user

Return type:

RouteParams

time: ndarray
tune_multiple_routes_prunig() str[source]

Tune pruning group for multiple-routes approach

Returns:

pruning group

Return type:

str

update(ship_params)[source]

Update all variables that store the routing history for the new position considering the constraints.

Parameters:

ship_params (ShipParams) – ship parameters

update_dist(delta_time, bs)[source]
update_fig(status)[source]
update_fuel(fuel_rate)[source]
update_position()[source]

Update the current position of the ship

update_shipparams(ship_params_single_step)[source]

Update ShipParams object.

update_time()[source]
class WeatherRoutingTool.algorithms.isobased.IsoBasedStatus[source]

Bases: object

Class to store status and error descriptions of IsoBased algorithms.

This class defines status and error descriptions as well as error codes. At the beginning of the routing procedure, the state is set to “routing” and the error to “no_error”.

Params available states:

pre-defined status descriptions

Params available errors:

pre-defined error descriptions

Params state:

current routing state

Params error:

error status

Params needs_further_routing:

information about whether further routing steps are necessary

available_errors: dict
available_states: list
error: str
get_error_code() int[source]

Returns error code.

name: str
needs_further_routing: bool
print()[source]
set_error_str(error_str: str) None[source]

Updates error state.

Raises:

ValueError – if error state is not implemented.

state: str
update_state(state_request: str) None[source]

Updates status description.

Raises:

ValueError – if status description is not implemented

class WeatherRoutingTool.algorithms.isobased.RoutingStep[source]

Bases: object

Class for storing parameters that characterise a single routing step for IsoBased algorithms.

Parameters:
  • lats – latitude values for the start and arrival point of the routing step

  • lons – longitude values for the start and arrival point of the routing step

  • courses – courses set at the starting point of the routing step

  • departure_time – departure times of all routes from the starting point

  • delta_time – travel time

  • delta_fuel – fuel consumption

  • is_constrained – information on constraint violations

Type:

np.ndarray, rows: latitudes for start (index = 0) and arrival points (index=1), columns: latitudes for different routes

Type:

np.ndarray, rows: longitudes for start (index = 0) and arrival points (index=1), columns: longitudes for different routes

Type:

np.ndarray

Type:

np.ndarray

Type:

timedelta

Type:

float

Type:

bool

courses: ndarray
delta_dist: float
delta_fuel: float
delta_time: timedelta
departure_time: ndarray
get_courses() ndarray[source]

Get courses set at starting point.

get_end_point(coord: str = 'all')[source]

Get the coordinates of the arrival point.

Parameters:

coord (str) – coordinate(s) that is/are requested. Can be ‘lat’, ‘lon’, ‘all. Defaults to ‘all’.

Returns:

coordinate(s) of arrival point

Return type:

float or tuple in the form of (longitudes, latitudes)

Raises:

ValueError – if coord is not implemented

get_start_point(coord: str = 'all')[source]

Get the coordinates of the starting point.

Parameters:

coord – coordinate(s) that is/are requested. Can be ‘lat’, ‘lon’, ‘all. Defaults to ‘all’.

Type:

str

Returns:

coordinate(s) of starting point

Return type:

float or tuple in the form of (longitudes, latitudes)

Raises:

ValueError – if coord is not implemented

get_time() ndarray[source]

Get departure time from starting point.

init_step(lats_start: ndarray, lons_start: ndarray, courses: ndarray, time: ndarray) None[source]

Initialise the class object at the start of each routing step.

The arguments initialise the variables for the starting point. The variables for the arrival point are set to arrays containing None. The variables for the starting point can come with any shape; the shape of all other arrays will be adjusted, accordingly. The array for the constraint information is initialised to be ‘False’ for all routes.

Parameters:
  • lats – new latitude values

  • lons – new longitude values

  • courses – new courses

  • time – new departure time

Type:

np.ndarray

Type:

np.ndarray

Type:

np.ndarray

Type:

np.ndrarray

is_constrained: ndarray
lats: ndarray
lons: ndarray
print() None[source]
update_constraints(constraints: ndarray) None[source]

Update the constraint information.

update_delta_variables(delta_fuel: float, delta_time: timedelta, delta_dist: float) None[source]

Update variables for fuel consumption, travel time and travel distance.

update_end_step(lats: ndarray, lons: ndarray) None[source]

Update class variables for the arrival point while routing is ongoing.

The shape of the arguments has to match the shape that has been chosen for the initialisation.

Parameters:
  • lats – new latitude values

  • lons – new longitude values

Type:

np.ndarray

Type:

np.ndarray

update_start_step(lats: ndarray, lons: ndarray, courses: ndarray, time: ndarray) None[source]

Update class variables for the departure point while routing is ongoing.

The shape of the arguments has to match the shape that has been chosen for the initialisation.

Parameters:
  • lats – new latitude values

  • lons – new longitude values

  • courses – new courses

  • time – new departure time

Type:

np.ndarray

Type:

np.ndarray

Type:

np.ndarray

Type:

np.ndrarray

WeatherRoutingTool.algorithms.isochrone module

class WeatherRoutingTool.algorithms.isochrone.IsoChrone(start, finish, time, delta_time)[source]

Bases: IsoBased

TODO: add description (Is this algorithm in use? It is not possible to choose it in the config.) _summary_

check_isochrones(route: RouteParams)[source]

Check route for equal time intervals

Parameters:

route (RouteParams) – Currently considered routes

Raises:

ValueError – If time intervall between every step of the route isn’t 3600 s

delta_time: int
get_delta_variables(boat, wind, bs)[source]
get_dist(bs)[source]

WeatherRoutingTool.algorithms.isofuel module

class WeatherRoutingTool.algorithms.isofuel.IsoFuel(config)[source]

Bases: IsoBased

IsoFuel inherits from IsoBased and is based on the principle of routing steps that are equal in fuel consumption

check_isochrones(route: RouteParams)[source]
delta_fuel: float
determine_timespread(delta_time)[source]

TODO: add description _summary_

Parameters:

delta_time (_type_) – _description_

final_pruning()[source]

TODO: add description _summary_

Raises:

Exception – _description_

get_delta_variables(boat, wind, bs)[source]

returns fuel (= power) [W], dist [m], delta_time [s], delta_fuel [Ws]

Parameters:
  • boat (Boat) – boat object

  • wind – wind

  • bs (numeric) – boat speed

Returns:

Return type:

tuple

get_delta_variables_netCDF(ship_params, bs)[source]

returns fuel (= power) [W], dist [m], delta_time [s], delta_fuel [Ws]

Parameters:
  • ship_params – ShipParams

  • bs (numeric) – boat speed

Returns:

Return type:

tuple

get_delta_variables_netCDF_last_step(ship_params, bs)[source]

returns fuel (= power) [W], dist [m], delta_time [s], delta_fuel [Ws]

Parameters:
  • ship_params – ShipParams

  • bs (numeric) – boat speed

Returns:

Return type:

tuple

get_dist(bs, delta_time)[source]
get_time(bs, dist)[source]

Calculate time [s] from boat speed and distance

Parameters:
  • bs (numeric) – boat speed

  • dist (numeric) – distance

Returns:

time needed to travel the given distance with the given speed

Return type:

numeric

print_init()[source]
update_time()[source]

WeatherRoutingTool.algorithms.routingalg module

class WeatherRoutingTool.algorithms.routingalg.RoutingAlg(config)[source]

Bases: object

Mother class of all routing algorithms defining basic attributes and methods

calculate_gcr(start, finish)[source]

Calculate distance between start and end according to Vincenty’s approach, return dictionary

check_destination()[source]
check_for_positive_constraints(constraint_list)[source]
check_positive_power()[source]
departure_time: datetime
execute_routing(boat: Boat, wt: WeatherCond, constraints_list: ConstraintsList, verbose=False)[source]
fig: <module 'matplotlib.figure' from '/opt/hostedtoolcache/Python/3.13.7/x64/lib/python3.13/site-packages/matplotlib/figure.py'>
figure_path: str
finish: tuple
gcr_course: float
gcr_dist: float
init_fig(**kwargs)[source]
print_current_status()[source]
print_init()[source]
route_ensemble: list
start: tuple
terminate(**kwargs)[source]
update_fig()[source]

WeatherRoutingTool.algorithms.routingalg_factory module

class WeatherRoutingTool.algorithms.routingalg_factory.RoutingAlgFactory[source]

Bases: object

Class for generating a routing algorithm object based on the ALGORITHM_TYPE defined in the config

static get_routing_alg(config)[source]

Module contents