mable package

Subpackages

Submodules

mable.cargo_bidding module

Classes and functions around companies bidding for cargoes.

class mable.cargo_bidding.MCSTCompany(fleet, name)

Bases: TradingCompany

inform(trades, auction_ledger=None, *args, **kwargs)

The shipping company …

Parameters:
  • trades (list[Trade]) – The list of trades.

  • auction_ledger (AuctionLedger | None) – Outcomes of all cargo auctions in the round.

  • args – Not used.

  • kwargs – Not used.

Returns:

The bids of the company

class mable.cargo_bidding.MeansCompany(fleet, name)

Bases: TradingCompany

inform(trades, auction_ledger=None, *args, **kwargs)

The shipping company …

Parameters:
  • trades (list[Trade]) – The list of trades.

  • auction_ledger (AuctionLedger | None) – Outcomes of all cargo auctions in the round.

  • args – Not used.

  • kwargs – Not used.

Returns:

The bids of the company

Return type:

list[Bid]

class mable.cargo_bidding.TradingCompany(fleet, name)

Bases: SimpleCompany[VesselWithEngine]

__init__(fleet, name)
Parameters:
  • fleet (List[V]) – List of vessels.

  • name (str) – the name of the company

property fleet
Returns:

The company’s fleet.

Return type:

List[VesselWithEngine]

property headquarters
Returns:

The company’s headquarters.

Return type:

CompanyHeadquarters

inform(trades, *args, **kwargs)

The shipping company that bids in cargo auctions.

Parameters:
  • trades (List[Trade]) – The list of trades.

  • args – Not used.

  • kwargs – Not used.

Returns:

The bids of the company

Return type:

List[Bid]

receive(contracts, auction_ledger=None, *args, **kwargs)

Allocate a list of trades to the company.

Parameters:
  • contracts (List[Contract]) – The list of trades.

  • auction_ledger (AuctionLedger | None) – Outcomes of all cargo auctions in the round.

  • args – Not used.

  • kwargs – Not used.

mable.cli module

class mable.cli.ArgumentParserExtensions

Bases: object

Functions for use with the argument parser to parse arguments.

static is_positive_integer(value, parser)

An ArgumentParser argument to check if the provided value is a positive integer.

Parameters:
  • value (str) – The value.

  • parser – The calling sub-parser for an error call if necessary.

Returns:

The int value if it is a positive int. Otherwise, will exit via a parser error.

Return type:

int

static is_valid_file(filename, parser)

An ArgumentParser argument to check if the provided file name corresponds to an existing file.

Parameters:
  • filename (str) – The file name.

  • parser – The calling sub-parser for an error call if necessary.

Returns:

The file name if the file exists. Otherwise, will exit via a parser error.

Return type:

str

mable.cli.handle_exception(exc_type, exc_value, exc_traceback)

Log any exception which is not a KeyboardInterrupt.

mable.cli.main()

Main entry of program. Set arguments for argument parser, loads the settings and searches current directory for compilable tex files. At the end prints help or calls the task selector function to perform one of the tasks.

mable.cli.select_task(parsed_args)

Calls the respective function for the task as specified by the cmd args.

:param _sphinx_paramlinks_mable.cli.select_task.parsed_args:dict

The parameter from the arg parser.

mable.cli.task_metrics_overview(parsed_args)

Generate an overview of the companies’ performance.

Parameters:

parsed_args (dict) – The parameter from the arg parser. - file: str: the name of the file.

mable.engine module

Module of the main engine that runs the simulation (loop).

class mable.engine.EnginePrePostRunner

Bases: object

A framework to run functions before and after engine execution.

abstract run(simulation_engine)
class mable.engine.SimulationEngine(world, shipping_companies, cargo_generation, cargo_market, class_factory, pre_run_cmds=None, post_run_cmds=None, output_directory=None, global_agent_timeout=60, info=None)

Bases: object

Main class to run a simulation.

POST_RUN_CMDS = []
PRE_RUN_CMDS = [<function pre_run_place_vessels>, <function pre_run_inform_vessel_locations>]
__init__(world, shipping_companies, cargo_generation, cargo_market, class_factory, pre_run_cmds=None, post_run_cmds=None, output_directory=None, global_agent_timeout=60, info=None)

Constructor.

Parameters:
  • world (maritime_simulator.simulation_environment.World) – The world environment of the simulation.

  • shipping_companies – [maritime_simulator.transport_operation.ShippingCompany] The list of companies to operate cargo transportation.

  • cargo_generation (Shipping) – The cargo generation object.

  • cargo_market – maritime_simulator.shipping_market.Market The cargo distribution object.

  • class_factory (ClassFactory) – The class generation object.

  • pre_run_cmds – Commands to be executed before the run of the main engine loop. All functions must have one argument to which the SimulationEngine passes itself. Default list is SimulationEngine.PRE_RUN_CMDS which is applied when None is passed.

  • post_run_cmds – Commands to be executed after the run of the main engine loop. All functions must have one argument to which the SimulationEngine passes itself. Default list is SimulationEngine.POST_RUN_CMDS which is applied when None is passed.

  • output_directory (str | None) – The directory for output files. If None, the working directory is used.

  • global_agent_timeout (int) – The timeout used for agent operations.

  • info (str | dict) – Any information on the type or setting of the simulation.

add_new_schedules(company, schedules, time)

Adds new vessel schedules to be applied.

Parameters:
  • company (ShippingCompany) – The company which owns the vessels.

  • schedules (Dict[Vessel, Schedule]) – The schedules.

  • time (int) – The time the schedules are added.

apply_new_schedules(distribution_ledger)

Applies any new existing schedules to the vessels.

Parameters:

distribution_ledger (AuctionLedger) – The outcome of the last auction.

property class_factory
Returns:

maritime_simulator.simulation_generation.ClassFactory The class generation object (the class factory).

property event_queue
Returns:

The worlds event queue.

Return type:

EventQueue

find_company_for_vessel(vessel)

Find the company the vessel belongs to.

Parameters:

vessel (Vessel) – The vessel.

Returns:

The company

get_event_observers()

Return all current event observers. :return: The observers. :rtype: list[EventObserver]

property global_agent_timeout
property headquarters
property info
property market
Returns:

maritime_simulator.shipping_market.Market The cargo distribution object (the cargo market).

property market_authority
notify_event_observer(event, data)

Notify observer about an event that has occurred. :param _sphinx_paramlinks_mable.engine.SimulationEngine.notify_event_observer.event: Event

Some event.

Parameters:

data – EventExecutionData Additional data in conjunction with the event. E.g. data that was produced or changes that were made.

property output_directory
register_event_observer(observer: EventObserver)

Add an observer to the list of observer that are informed about events occurrences. :param _sphinx_paramlinks_mable.engine.SimulationEngine.register_event_observer.observer: maritime_simulator.event_management.EventObserver

The observer to add.

run()

Run a simulation until no events are left to deal with.

Start with adding all cargo events into the event queue.

property shipping
Returns:

maritime_simulator.shipping_market.Shipping The cargo generation object.

property shipping_companies
Returns:

[maritime_simulator.transport_operation.ShippingCompany] The list of companies to operate cargo transportation.

unregister_event_observer(observer: EventObserver)

Remove an observer from the list of observer that are informed about events occurrences. :param _sphinx_paramlinks_mable.engine.SimulationEngine.unregister_event_observer.observer: maritime_simulator.event_management.EventObserver

The observer to remove.

property world
Returns:

The world environment of the simulation.

Return type:

mable.simulation_environment.World

mable.engine.pre_run_inform_vessel_locations(simulation_engine)
mable.engine.pre_run_place_vessels(simulation_engine)

mable.event_management module

Event management module.

class mable.event_management.ArrivalEvent(time, vessel, trade, is_pickup)

Bases: VesselCargoEvent

An event where a vessel arrives for loading or unloading.

distance(engine)

The distance between origin and destination ports. :param _sphinx_paramlinks_mable.event_management.ArrivalEvent.distance.engine: Engine

Simulation engine.

Returns:

float The distance.

event_action(engine)

Informs the vessel about the occurrence of the event and updates its location to the location of the occurrence, i.e. VesselEvent.location()

Parameters:

engine (SimulationEngine) – The simulation engine.

class mable.event_management.CargoAnnouncementEvent(time, cargo_available_time)

Bases: Event

Announces future cargoes

__init__(time, cargo_available_time)
Parameters:
  • time (float) – The occurrence time of the event.

  • info (str) – Some info on the event for logging etc.

event_action(engine)

Announces the cargoes becoming available at a later time and adds the auction to the event queue.

Parameters:

engine (SimulationEngine) – The simulation engine.

class mable.event_management.CargoEvent(time)

Bases: Event

An event of appearance of cargoes.

__init__(time)
Parameters:
  • time (float) – The occurrence time of the event.

  • info (str) – Some info on the event for logging etc.

event_action(engine)

Collects the cargoes becoming available at the event’s time from the shipping object and passes them to the market for distribution.

Parameters:

engine – Engine The simulation engine.

class mable.event_management.CargoTransferEvent(time, vessel, trade, is_pickup)

Bases: VesselCargoEvent

A loading or unloading event.

distance(engine)

The distance the vessel crosses between the start and the occurrence of the event. :param _sphinx_paramlinks_mable.event_management.CargoTransferEvent.distance.engine: Engine

Simulation engine

Returns:

float The distance.

event_action(engine)

Informs the vessel about the occurrence of the event and updates its location to the location of the occurrence, i.e. VesselEvent.location()

Parameters:

engine (SimulationEngine) – The simulation engine.

class mable.event_management.DurationEvent(time)

Bases: Event

An event that has a duration.

__init__(time)

An unstarted event has a start time of -1.

Parameters:

time (float) – The time at which the event happens/ends.

added_to_queue(engine)

Set start time to current time.

Parameters:

engine (SimulationEngine) – The simulation engine.

has_started()

Indicates if the event has started.

Returns:

True if the started time is set and False otherwise.

Return type:

bool

performed_time()

The duration the event took. Is zero as long as the event hasn’t started.

Returns:

The duration.

Return type:

float

property time_started
class mable.event_management.Event(time, info=None)

Bases: object

One event.

__init__(time, info=None)
Parameters:
  • time (float) – The occurrence time of the event.

  • info (str) – Some info on the event for logging etc.

added_to_queue(engine)

Called when the event is added to the queue. Does nothing on default. :param _sphinx_paramlinks_mable.event_management.Event.added_to_queue.engine: Engine

The simulation engine.

event_action(engine)

Called when the event is happening. This should be at Event.time(). Does nothing on default. :param _sphinx_paramlinks_mable.event_management.Event.event_action.engine: Engine

The simulation engine.

property time

The time of the occurrence event.

Returns:

The time.

Return type:

float

class mable.event_management.EventExecutionData(action_data: Any = None, other_data: Any = None)

Bases: object

Data that is associated with an event occurrence. :param _sphinx_paramlinks_mable.event_management.EventExecutionData.action_data: Data that is directly associated with the occurrence of the event. :type _sphinx_paramlinks_mable.event_management.EventExecutionData.action_data: Any :param _sphinx_paramlinks_mable.event_management.EventExecutionData.other_data: Additional data that is related to the event, the event’s occurrence or system at

the time of the event’s occurrence.

__init__(action_data: Any = None, other_data: Any = None) None
action_data: Any = None
other_data: Any = None
class mable.event_management.EventItem(time: float, event: Event)

Bases: object

Event wrapper for EventQueue.

__init__(time: float, event: Event) None
event: Event
time: float
class mable.event_management.EventObserver

Bases: object

An observer of event occurrences.

abstract notify(engine, event, data)

Notify this observer of an event.

Parameters:
class mable.event_management.EventQueue

Bases: SimulationEngineAware, PriorityQueue[EventItem]

Priority Queue for events.

__init__()
get(block=True, timeout=None)

Removes and returns the next event from the queue.

Parameters:
  • block – See PriorityQueue.get()

  • timeout – See PriorityQueue.get()

Returns:

The event.

Return type:

Event

purge(vessel)

Removes all events associated with a vessel from the queue.

Parameters:

vessel (Vessel) – The vessel.

put(event: Event, block=True, timeout=None)

Adds an event to the queue.

Parameters:
  • event (Event) – The event.

  • block – See PriorityQueue.put()

  • timeout – See PriorityQueue.put()

Raises:
  • ValueError – if the event’s time is infinite.

  • ValueError – if the event’s time is in the past.

remove(event_s)

Removes one or more events from the queue.

Parameters:

event_s (Event | List[Event]) – The event or a list of events.

class mable.event_management.FirstCargoAnnouncementEvent(time, cargo_available_time_second_cargo)

Bases: Event

Announces future cargoes at the start of the simulation before a cargo auction at time 0.

__init__(time, cargo_available_time_second_cargo)
Parameters:
  • time (float) – The occurrence time of the event.

  • info (str) – Some info on the event for logging etc.

event_action(engine)

Announces the cargoes becoming available at a later time and adds the auction to the event queue as well as the auction about events at time 0.

Parameters:

engine (SimulationEngine) – The simulation engine.

class mable.event_management.IdleEvent(time, vessel, location)

Bases: VesselEvent

An event where the vessel is doing nothing.

__init__(time, vessel, location)

Constructor. :param _sphinx_paramlinks_mable.event_management.IdleEvent.time: The occurrence time of the event. :type _sphinx_paramlinks_mable.event_management.IdleEvent.time: float :param _sphinx_paramlinks_mable.event_management.IdleEvent.vessel: The vessel associated with the event. :type _sphinx_paramlinks_mable.event_management.IdleEvent.vessel: Vessel :param _sphinx_paramlinks_mable.event_management.IdleEvent.location: The location where the vessel idles. :type _sphinx_paramlinks_mable.event_management.IdleEvent.location: Location

distance(engine)

Idling passes no distance. :param _sphinx_paramlinks_mable.event_management.IdleEvent.distance.engine: Engine

Simulation engine.

Returns:

float 0 (Zero)

property location

The location of the entirety of the event or where the vessel is when the event happens. Does not have to ensure that the vessel’s current location is returned. :return: Location

The location at event occurrence.

class mable.event_management.TravelEvent(time, vessel, origin, destination)

Bases: VesselEvent

__init__(time, vessel, origin, destination)

Constructor for a vessel that performs a journey. :param _sphinx_paramlinks_mable.event_management.TravelEvent.time: float

The time of the event.

Parameters:
  • vessel – Vessel The vessel associated with the event.

  • origin – Location The location of the vessel when the event starts.

  • destination – Location The location of the vessel when the event occurs.

added_to_queue(engine)

Beside setting the start time the vessel’s location is set to be on journey. :param _sphinx_paramlinks_mable.event_management.TravelEvent.added_to_queue.engine: Engine

The simulation engine.

distance(engine)

The distance between origin and destination. :param _sphinx_paramlinks_mable.event_management.TravelEvent.distance.engine: Engine

Simulation engine.

Returns:

float The distance.

event_action(engine)

Informs the vessel about the occurrence of the event and updates its location to the location of the occurrence, i.e. VesselEvent.location() :param _sphinx_paramlinks_mable.event_management.TravelEvent.event_action.engine: Engine

The simulation engine.

property is_laden

Indicates if the vessel is laden on the voyage.

Only determined once the event has stated. False beforehand. :return: True if laden and False if under ballast.

property location

The destination of the journey. :return: Location

The destination

class mable.event_management.VesselCargoEvent(time, vessel, trade, is_pickup)

Bases: VesselEvent

An event that involves a vessel and a trade.

__init__(time, vessel, trade, is_pickup)

Constructor. :param _sphinx_paramlinks_mable.event_management.VesselCargoEvent.time: time: float

The time of the event.

Parameters:
  • vessel – Vessel The vessel associated with the event.

  • trade – Trade The trade associated with the event.

  • is_pickup – bool Indicate if the event is about the pickup of the cargo at the trade’s origin port of the drop-off at the trade’s destination port.

abstract distance(engine)

The distance the vessel crosses between the start and the occurrence of the event. :param _sphinx_paramlinks_mable.event_management.VesselCargoEvent.distance.engine: Engine

Simulation engine

Returns:

float The distance.

property is_drop_off
Indicate if the event is about the pickup of the cargo at the trade’s origin port of the drop-off at the

trade’s destination port.

Returns:

bool True if event is drop-off, False otherwise.

property is_pickup
Indicate if the event is about the pickup of the cargo at the trade’s origin port of the drop-off at the

trade’s destination port.

Returns:

bool True if event is pickup, False otherwise.

property location

The origin port if it is a pickup and the destination port otherwise. :return: Port

Origin or destination port.

property trade
Returns:

Trade The trade associated with the event.

class mable.event_management.VesselEvent(time, vessel)

Bases: DurationEvent

An event that involves a vessel.

__init__(time, vessel)

Constructor. :param _sphinx_paramlinks_mable.event_management.VesselEvent.time: The occurrence time of the event. :type _sphinx_paramlinks_mable.event_management.VesselEvent.time: float :param _sphinx_paramlinks_mable.event_management.VesselEvent.vessel: The vessel associated with the event. :type _sphinx_paramlinks_mable.event_management.VesselEvent.vessel: Vessel

abstract distance(engine)

The distance the vessel crosses between the start and the occurrence of the event. :param _sphinx_paramlinks_mable.event_management.VesselEvent.distance.engine: Engine

Simulation engine

Returns:

float The distance.

event_action(engine)

Informs the vessel about the occurrence of the event and updates its location to the location of the occurrence, i.e. VesselEvent.location()

Parameters:

engine (SimulationEngine) – The simulation engine.

abstract property location

The location of the entirety of the event or where the vessel is when the event happens. Does not have to ensure that the vessel’s current location is returned. :return: Location

The location at event occurrence.

property vessel
class mable.event_management.VesselLocationInformationEvent(time, vessel, location)

Bases: VesselEvent

An event that informs about the location of a vessel.

__init__(time, vessel, location)

Constructor. :param _sphinx_paramlinks_mable.event_management.VesselLocationInformationEvent.time: float

The time of the event.

Parameters:
  • vessel – Vessel The vessel associated with the event.

  • location – The location of the vessel.

distance(engine)

Always zero since no distance is crossed. :param _sphinx_paramlinks_mable.event_management.VesselLocationInformationEvent.distance.engine: Engine

Simulation engine

Returns:

float The distance.

property location

The location of the vessel at the specified time.

Returns:

Location The location at event occurrence.

mable.global_setup module

mable.global_setup.done()

mable.instructions module

Classes to create and process simulation instructions.

class mable.instructions.Specifications(specifications)

Bases: object

A set of instructions that specify the run of a simulation.

class Builder

Bases: object

A builder to create specifications in parts.

__init__()
add_cargo_distribution(*args, **kwargs)

Add instruction for a cargo distribution/market object. :param _sphinx_paramlinks_mable.instructions.Specifications.Builder.add_cargo_distribution.args:

Positional args.

Parameters:

kwargs – Keyword args.

add_cargo_generation(*args, **kwargs)

Add instruction for a cargo generation/shipping object.

Parameters:
  • args – Positional args.

  • kwargs – Keyword args.

add_company(*args, **kwargs)

Add instruction for a cargo transportation company. :param _sphinx_paramlinks_mable.instructions.Specifications.Builder.add_company.args:

Positional args.

Parameters:

kwargs – Keyword args.

add_random_specifications(*args, **kwargs)

Set the random specifications.

Parameters:
  • args – Positional args.

  • kwargs – Keyword args.

add_shipping_network(*args, **kwargs)

Add instruction for a network/operational space object :param _sphinx_paramlinks_mable.instructions.Specifications.Builder.add_shipping_network.args:

Positional args.

Parameters:

kwargs – Keyword args.

build()
__init__(specifications)
get(key)

Return the args under the key. If the key is not present in the specifications a tuple of an empty list and an empty dict are returned, i.e. ([], {}). :param _sphinx_paramlinks_mable.instructions.Specifications.get.key:

The key.

Returns:

As specified.

classmethod init_from_json_string(specs_string)

Load and initiated specifications from a json string. :param _sphinx_paramlinks_mable.instructions.Specifications.init_from_json_string.specs_string: :return:

mable.metrics module

A module to support the collection of metrics for a simulation.

class mable.metrics.GlobalMetricsCollector

Bases: MetricsCollector

A metrics collector that collects metrics for the entire operational space.

add_co2_emissions(vessel, emissions)

TODO :param _sphinx_paramlinks_mable.metrics.GlobalMetricsCollector.add_co2_emissions.vessel: :param _sphinx_paramlinks_mable.metrics.GlobalMetricsCollector.add_co2_emissions.emissions: :return:

add_cost(vessel, cost)

TODO :param _sphinx_paramlinks_mable.metrics.GlobalMetricsCollector.add_cost.vessel: :param _sphinx_paramlinks_mable.metrics.GlobalMetricsCollector.add_cost.cost: :return:

add_fuel_consumption(vessel, consumption)

TODO finish when clear how consumption is computed :param _sphinx_paramlinks_mable.metrics.GlobalMetricsCollector.add_fuel_consumption.vessel: :param _sphinx_paramlinks_mable.metrics.GlobalMetricsCollector.add_fuel_consumption.consumption: :return:

add_route_point(location, vessel)
class mable.metrics.MetricDict

Bases: dict

A dict that works with VesselKeys by transforming them into string representations of the tuples (see VesselKey.key_tuple()).

class mable.metrics.MetricsCollector

Bases: JsonAble, SimulationEngineAware

An object to collect company level and vessel level metrics. Each vessel and company can have collections of metrics via specifiable keys.

__init__()
add_company_numeric_metric(company, key, value)

Add a numeric metric for a company. The value is added to the value in the collections of metrics for the specified company under the specified key. If it is the first time the metric is added it is initialised as zero before adding the value. :param _sphinx_paramlinks_mable.metrics.MetricsCollector.add_company_numeric_metric.company:

The company

Parameters:
  • key – The key.

  • value – The value. Anything that specifies __iadd__ or __add__.

add_dual_numeric_metric(vessel, key, value)

Add a numeric metric for a vessel and its company. The value is added to the value in the collections of metrics for the specified vessel and the vessel’s company under the specified key. If it is the first time the metric is added it is initialised as zero before adding the value. :param _sphinx_paramlinks_mable.metrics.MetricsCollector.add_dual_numeric_metric.vessel:

The vessel

Parameters:
  • key – The key.

  • value – The value. Anything that specifies __iadd__ or __add__.

add_global_company_list_metric(key, value)

Add a global list metric. :param _sphinx_paramlinks_mable.metrics.MetricsCollector.add_global_company_list_metric.key:

The key.

Parameters:

value – The value.

get_company_id(company, create_id_if_not_exists=True)

Get the id of the specified company. If create_id_if_not_exists exists (default) a new key is created if no id for the specified company is known. :param _sphinx_paramlinks_mable.metrics.MetricsCollector.get_company_id.company:

The company.

Parameters:

create_id_if_not_exists – bool Indicated if a new id should be created if non exists.

Returns:

int The id of the company.

Raises:

KeyError – If no id for the specified company is known and create_id_if_not_exists is False.

get_vessel_id(vessel, company=None, create_both_ids_if_not_exists=True)

Get the key of the specified vessel. If create_id_if_not_exists exists (default) a new key is created if no id for the specified vessel is known. This extends to the company if the company is not yet known. If new keys are generated and the company is not specified, i.e. parameter is set to None, an attempt is made to determine the company based on all shipping company’s fleets. :param _sphinx_paramlinks_mable.metrics.MetricsCollector.get_vessel_id.vessel:

The vessel.

Parameters:
  • company – The company.

  • create_both_ids_if_not_exists – bool Indicated if new ids should be created if non exists.

Returns:

VesselKey The key of the company.

Raises:
  • KeyError – If no key for the specified vessel is known and create_id_if_not_exists is False.

  • ValueError – If new keys are supposed to be generated but the company is not specified nor could a company be determined.

to_json()

A dict of the company and the vessel metrics. :return: dict

{“company_metrics”: <companies’ metrics>, “vessel_metrics”: <vessels’ metrics>}

class mable.metrics.RegionalMetricsCollector

Bases: MetricsCollector

A metrics collector that collects metrics for subdivision of the operational space.

add_fuel_consumption(vessel, consumption, region)
class mable.metrics.VesselKey(company_id, vessel_id)

Bases: JsonAble

A vessel key that is the compound of the id of a company and an id for the vessel.

__init__(company_id, vessel_id)

Constructor. :param _sphinx_paramlinks_mable.metrics.VesselKey.company_id: int

The id of the company the vessel belongs to.

Parameters:

vessel_id – int The id of the vessel.

property company_id
property key_tuple
Returns:

(int, int) The tuple of the company id and the vessel id (in this order).

property vessel_id

mable.observers module

Simulation observation related classes and functions.

class mable.observers.AuctionMetricsObserver

Bases: MetricsObserver

notify(engine, event, data)

Notify this observer of an event.

Parameters:
class mable.observers.AuctionOutcomeObserver

Bases: EventObserver

An observer that logs allocated trades.

notify(engine, event, data)

Notify this observer of an event.

Parameters:
class mable.observers.AuctionOutcomePrintObserver(logger)

Bases: EventObserver

A logger that prints detailed information about the auction outcomes for mable.competition.generation.AuctionCargoEvent().

__init__(logger)
notify(engine, event, data)

Notify this observer of an event.

Parameters:
class mable.observers.EventFuelPrintObserver(logger)

Bases: EventObserver

__init__(logger)
notify(engine, event, data)

Notify this observer of an event.

Parameters:
class mable.observers.LogRunner(run_logger, message)

Bases: EnginePrePostRunner

__init__(run_logger, message)
run(simulation_engine)
class mable.observers.MetricsObserver

Bases: EventObserver

__init__()
static calculate_consumption(engine, event)
property metrics
notify(engine, event, data)

Notify this observer of an event.

Parameters:
class mable.observers.TradeDeliveryObserver

Bases: EventObserver

An observer that logs completed trades.

notify(engine, event, data)

Notify this observer of an event.

Parameters:

mable.shipping_market module

All cargo generation and distribution related classes.

class mable.shipping_market.AuctionAllocationResult(ledger: AuctionLedger, unallocated_trades: List[Trade])

Bases: object

__init__(ledger: AuctionLedger, unallocated_trades: List[Trade]) None

Method generated by attrs for class AuctionAllocationResult.

ledger: AuctionLedger
unallocated_trades: List[Trade]
class mable.shipping_market.AuctionLedger(shipping_companies)

Bases: object

A ledger that collects the auction outcomes.

__init__(shipping_companies)
Parameters:

shipping_companies (List[TradingCompany]) – A list of all shipping companies.

get_trades_for_company_copy(shipping_company)

The trades allocated to a specific company.

Parameters:

shipping_company (TradingCompany) – The specific company.

Returns:

A lost of the trades.

Return type:

List[Trade]

property keys
property ledger
Returns:

The full ledger as a dict of the trades indexed by the company names.

Return type:

Dict[ShippingCompany, List[Contract]]

property sanitised_ledger

A full copy of the ledger as a dict of the trades indexed by the company names.

Returns:

The ledger.

Return type:

Dict[str, List[Contract]]

class mable.shipping_market.AuctionMarket(*args, **kwargs)

Bases: Market, SimulationEngineAware

A market which auctions of trades.

__init__(*args, **kwargs)
static distribute_trades(time, trades, shipping_companies, timeout=60)

Distribute trades on a second price auction basis. The shipping companies are informed (ShippingCompany.receive) of the trades they get allocated via Contracts. All allocations are also returned.

Parameters:
  • time (float) – The time of occurrence.

  • trades (list[Trade]) – The list of trades.

  • shipping_companies (list[TradingCompany]) – The list of shipping companies.

  • timeout (int) – The time to give every company to process the trade information. Default is 60 seconds.

Returns:

All allocated traded per company.

Return type:

AuctionLedger

static inform_future_trades(trades, time, shipping_companies, timeout=60)

Informs the shipping companies of upcoming trades.

Parameters:
  • trades (List[Trade]) – The list of trades.

  • time – The time when the trades will be allocated, e.g. auctioned off.

  • shipping_companies (List[ShippingCompany]) – The list of shipping companies.

  • timeout (int) – The time to give every company to process the trade information. Default is 60 seconds.

class mable.shipping_market.Contract(*, payment: float, trade: Trade, fulfilled: bool = False)

Bases: JsonAble

A cargo transportation contract. :param _sphinx_paramlinks_mable.shipping_market.Contract.payment: The amount which is paid for the transportation. :type _sphinx_paramlinks_mable.shipping_market.Contract.payment: float :param _sphinx_paramlinks_mable.shipping_market.Contract.trade: The trade the company has to transport. :type _sphinx_paramlinks_mable.shipping_market.Contract.trade: Trade

__init__(*, payment: float, trade: Trade, fulfilled: bool = False) None

Method generated by attrs for class Contract.

copy()
fulfilled: bool
payment: float
to_json()
Returns:

Any A json encodable object.

trade: Trade
class mable.shipping_market.Market(*args, **kwargs)

Bases: object

A market to distribute the trades.

abstract __init__(*args, **kwargs)
abstract static distribute_trades(time, trades, shipping_companies)

Conducts the distribution of trades at specified time to the shipping companies.

Parameters:
  • time – float The time of occurrence.

  • trades – [Trade] The list of trades.

  • shipping_companies – [ShippingCompany] The list of shipping companies.

class mable.shipping_market.Shipping(*args, **kwargs)

Bases: SimulationEngineAware

A unit to generate and/or manage the occurrence of cargo events.

__init__(*args, **kwargs)

Constructor. Calls initialise_trades() with all args and kwargs. :param _sphinx_paramlinks_mable.shipping_market.Shipping.args:

Positional args.

Parameters:

kwargs – Keyword args.

add_to_all_trades(trades)

Add all trades from a list of trades to the list of known shippable trades. :param _sphinx_paramlinks_mable.shipping_market.Shipping.add_to_all_trades.trades: :type _sphinx_paramlinks_mable.shipping_market.Shipping.add_to_all_trades.trades: List[Time :return:

get_trades(time)

Get trades for a specific time.

Parameters:

time (float) – The time.

Returns:

The list of trades.

Return type:

List[Trade]

get_trading_times()

All times at which new cargoes will become available. :return: list

The list of times.

abstract initialise_trades(*args, **kwargs)

Generate all trades.

class mable.shipping_market.SimpleMarket(*args, **kwargs)

Bases: Market, SimulationEngineAware

A simple market which gives the first shipping company all requested trades.

__init__(*args, **kwargs)
static distribute_trades(time, trades, shipping_companies)

Distribute trades to the first shipping company. The company is first informed about all trades and is expected to return a list of requested trades which are then directly allocated to the company. The shipping :param _sphinx_paramlinks_mable.shipping_market.SimpleMarket.distribute_trades.time: float

The time of occurrence.

Parameters:
  • trades – [Trade] The list of trades.

  • shipping_companies – [ShippingCompany] The list of shipping companies.

class mable.shipping_market.StaticShipping(*args, **kwargs)

Bases: Shipping

A shipping unit that simply takes a list of trades.

initialise_trades(*args, **kwargs)

Initialises the shipping with a list of trades. :param _sphinx_paramlinks_mable.shipping_market.StaticShipping.initialise_trades.args:

args[0] should be a list of specifications for trades.

Parameters:

kwargs – kwargs[“class_factory”] should be a :py:class`ClassFactory` or any object with a function ‘generate_trade’ to generate a trades from specifications.

class mable.shipping_market.TimeWindowTrade(*, origin_port: Port | str, destination_port: Port | str, amount: float, cargo_type: Hashable = None, time: int = 0, probability: float = 1, status: TradeStatus = TradeStatus.UNKNOWN, time_window: list = [None, None, None, None])

Bases: Trade

A trade with time windows.

The time windows are represented by four values. The first two are the pick-up window consisting of the earliest arrival for pick-up and the latest arrival for pick-up. The second two are the drop-off window consisting of the earliest arrival for drop-off and the latest arrival for drop-off. Flexibility or no restrictions are indicated by None.

Parameters:

time_window (List[Union[int, None]]) – The time windows for delivery.

For additional parameters see Trade

__init__(*, origin_port: Port | str, destination_port: Port | str, amount: float, cargo_type: Hashable = None, time: int = 0, probability: float = 1, status: TradeStatus = TradeStatus.UNKNOWN, time_window: list = [None, None, None, None]) None

Method generated by attrs for class TimeWindowTrade.

clean_window()
Returns:

The clean time windows, i.e. a list of the four time points provided by the clean versions: earliest_pickup(), latest_pickup(), earliest_drop_off() and latest_drop_off().

property earliest_drop_off
Returns:

The earliest drop-off time or None if the vessel can arrive at early as desired.

Return type:

Union[int, None]

property earliest_drop_off_clean
Returns:

If None 0 is returned. Otherwise, see earliest_drop_off()

Return type:

int

property earliest_pickup
Returns:

The earliest pick-up time or None if the vessel can arrive at early as desired.

Return type:

Union[int, None]

property earliest_pickup_clean
Returns:

If None 0 is returned. Otherwise, see earliest_pickup()

Return type:

int

property latest_drop_off
Returns:

The latest drop-off time or None if the vessel can arrive as late as desired.

Return type:

Union[int, None]

property latest_drop_off_clean
Returns:

If None math.inf is returned. Otherwise, see latest_drop_off()

Type:

Union[int, math.inf]

property latest_pickup
Returns:

The latest pick-up time or None if the vessel can arrive as late as desired.

Return type:

Union[int, None]

property latest_pickup_clean
Returns:

If None math.inf is returned. Otherwise, see latest_pickup()

Type:

Union[int, math.inf]

time_window: list
class mable.shipping_market.Trade(*, origin_port: Port | str, destination_port: Port | str, amount: float, cargo_type: Hashable = None, time: int = 0, probability: float = 1, status: TradeStatus = TradeStatus.UNKNOWN)

Bases: JsonAble

A trade opportunity specifying a cargo that shall be transported.

Parameters:
  • origin_port (Union[Port, str]) – The origin of the trade where the cargo has to be picked up.

  • destination_port (Union[Port, str]) – The destination of the trade where the cargo has to be dropped off.

  • amount (float) – The amount of cargo to be transported.

  • cargo_type (Hashable) – The type of cargo.

  • time (int) – The time that trade becomes available for allocation or a market etc.

__init__(*, origin_port: Port | str, destination_port: Port | str, amount: float, cargo_type: Hashable = None, time: int = 0, probability: float = 1, status: TradeStatus = TradeStatus.UNKNOWN) None

Method generated by attrs for class Trade.

amount: float
cargo_type: Hashable
destination_port: Port | str
origin_port: Port | str
probability: float
status: TradeStatus
time: int
to_json()
Returns:

Any A json encodable object.

class mable.shipping_market.TradeStatus(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: Enum

ACCEPTED = 3
NOT_REALISED = 2
REJECTED = 4
UNKNOWN = 1

mable.simulation_de_serialisation module

class mable.simulation_de_serialisation.DataClass(current_class: Type[DataProtocol])

Bases: object

Parent class for all data classes, i.e. classes that are going to be serialized and deserialised.

__init__(current_class: Type[DataProtocol]) None

Method generated by attrs for class DataClass.

current_class: Type[DataProtocol]
class mable.simulation_de_serialisation.DataProtocol(*args, **kwargs)

Bases: Protocol

Data: Type[SchemaProtocol]
__init__(*args, **kwargs)
class mable.simulation_de_serialisation.DataSchema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool | None = None, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)

Bases: Schema

opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
class mable.simulation_de_serialisation.DynamicNestedField(*, load_default: ~typing.Any = <marshmallow.missing>, missing: ~typing.Any = <marshmallow.missing>, dump_default: ~typing.Any = <marshmallow.missing>, default: ~typing.Any = <marshmallow.missing>, data_key: str | None = None, attribute: str | None = None, validate: ~typing.Callable[[~typing.Any], ~typing.Any] | ~typing.Iterable[~typing.Callable[[~typing.Any], ~typing.Any]] | None = None, required: bool = False, allow_none: bool | None = None, load_only: bool = False, dump_only: bool = False, error_messages: dict[str, str] | None = None, metadata: ~typing.Mapping[str, ~typing.Any] | None = None, **additional_metadata)

Bases: Field

A field that allows to serialize and deserialize nested classes with an inner class ‘Data’ being a descendant of DataClass which in turn has an inner class ‘Schema’ being a descendant of DataSchema.

class mable.simulation_de_serialisation.SchemaProtocol(*args, **kwargs)

Bases: Protocol

Schema: Type[DataSchema]
__init__(*args, **kwargs)
class mable.simulation_de_serialisation.SimulationSpecification

Bases: object

A class to hold all specific classes that are part of the export and import to create runnable simulations.

classmethod get(name) Type[D]

Get a class by a specified name. :param _sphinx_paramlinks_mable.simulation_de_serialisation.SimulationSpecification.get.name: The name. :type _sphinx_paramlinks_mable.simulation_de_serialisation.SimulationSpecification.get.name: str :return: The component class. :raises KeyError: If no class is registered under the specified name.

classmethod register(name, component_cls: Type[D])

Register a class under a specified name. :param _sphinx_paramlinks_mable.simulation_de_serialisation.SimulationSpecification.register.name: The name. :type _sphinx_paramlinks_mable.simulation_de_serialisation.SimulationSpecification.register.name: str :param _sphinx_paramlinks_mable.simulation_de_serialisation.SimulationSpecification.register.component_cls: The component class.

classmethod register_by_type_name(component_cls: Type[D])

Register a class under its name, i.e. __name__. :param _sphinx_paramlinks_mable.simulation_de_serialisation.SimulationSpecification.register_by_type_name.component_cls: The component class. :return:

mable.simulation_environment module

Classes and functions for the environment in which the simulation takes place.

class mable.simulation_environment.SimulationEngineAware

Bases: object

Helper class to provide a reference to and the setting of the simulation engine.

__init__()
set_engine(engine)

WARNING: Part of internal simulation logic. Only allowed to be called by the simulation!

Set the simulation engine.

Parameters:

engine (SimulationEngine) – The simulation engine.

class mable.simulation_environment.World(network, event_queue, random)

Bases: SimulationEngineAware

The overall setting of the simulation including among other things the space/network and the event queue. Also keeps track of the current time.

__init__(network, event_queue, random)
Parameters:
  • network (ShippingNetwork) – The space/network of operation.

  • event_queue (EventQueue) – The event queue.

  • random – A random to use wherever randomness is needed.

property current_time
Returns:

float The current time in the simulation.

do_events_exists()

Returns if there are events left to deal with.

Returns:

True if there are still events and false otherwise.

Return type:

bool

property event_queue
Returns:

The event queue.

Return type:

EventQueue

get_next_event()

Removes and return the next event of the queue. Also sets the current time to the time of the event occurrence.

Returns:

The event.

property network
Returns:

The space/network of operation.

Return type:

ShippingNetwork

property random
Returns:

The random to use wherever randomness is needed.

set_engine(engine)

Make the simulation engine know to the world and the event queue. :param _sphinx_paramlinks_mable.simulation_environment.World.set_engine.engine: SimulationEngine

The engine.

mable.simulation_generation module

Module for the generation of simulations and all classes within.

class mable.simulation_generation.ClassFactory

Bases: object

A class that provides simple functions which return an instance of the required class.

This class’ functions are intended to be overridden to replace the types used to generate the simulation or any used or constituting objects within. Any function should simply be a call to the class’ constructor passing on any positional or keyword arguments: def generate_<unit>(*args, **kwargs):

return <Unit>(*args, **kwargs)

static generate_cargo_capacity(*args, **kwargs)

Generates a cargo capacity (cargo hold). Default: py:class:maritime_simulator.transport_operation.CargoCapacity. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_cargo_capacity.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The cargo capacity.

static generate_company(*args, **kwargs)

Generates a company. Default: py:class:maritime_simulator.transport_operation.SimpleCompany. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_company.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The company.

static generate_engine(*args, **kwargs)

Generates a simulation engine. Default: py:class:maritime_simulator.engine.SimulationEngine. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_engine.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The engine.

static generate_event_arrival(*args, **kwargs)

Generates an arrival event. Default: py:class:maritime_simulator.event_management.ArrivalEvent.

Parameters:
  • args – Positional args.

  • kwargs – Keyword args.

Returns:

The event.

static generate_event_cargo(*args, **kwargs)

Generates a cargo event. Default: py:class:maritime_simulator.event_management.CargoEvent.

Parameters:
  • args – Positional args.

  • kwargs – Keyword args.

Returns:

The event.

static generate_event_cargo_transfer(*args, **kwargs)

Generates a cargo transfer event. Default: py:class:maritime_simulator.event_management.CargoTransferEvent. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_event_cargo_transfer.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The event.

static generate_event_idling(*args, **kwargs)

Generates an idling event. Default: py:class:maritime_simulator.event_management.IdleEvent. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_event_idling.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The event.

static generate_event_location_info(*args, **kwargs)

Generates a vessel location information event. Default: py:class:maritime_simulator.event_management.VesselLocationInformationEvent. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_event_location_info.args:

Positional args. - Default see py:func:maritime_simulator.event_management.VesselLocationInformationEvent.__init__

  • time: The time of the event

  • vessel: The vessel

  • location: The location of the vessel

Parameters:

kwargs – Keyword args.

Returns:

The event.

static generate_event_queue(*args, **kwargs)

Generates an event queue. Default: py:class:maritime_simulator.engine.SimulationEngine. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_event_queue.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The event queue.

static generate_event_travel(*args, **kwargs)

Generates a travel event. Default: py:class:maritime_simulator.event_management.TravelEvent. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_event_travel.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The event.

static generate_location(*args, **kwargs)

Generates a location. Default: py:class:mable.simulation_space.universe.Location. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_location.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The network.

static generate_market(*args, **kwargs)

Generates a market. Default: py:class:maritime_simulator.shipping_market.SimpleMarket. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_market.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The market.

static generate_network(*args, **kwargs)

Generates a network (space). Default: py:class:mable.simulation_space.structure.UnitShippingNetwork.

Parameters:
  • args – Positional args.

  • kwargs – Keyword args.

Returns:

The network.

static generate_port(*args, **kwargs)

Generates a port. Default: py:class:mable.simulation_space.universe.Port. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_port.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The port.

static generate_random(*args, **kwargs)

Generate a random. Default: py:class:random.Random with provided seed or seed 0 if non is provided. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_random.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The random.

static generate_shipping(*args, **kwargs)

Generates a shipping (cargo generation) unit. Default: py:class:maritime_simulator.shipping_market.StaticShipping. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_shipping.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The shipping.

static generate_trade(*args, **kwargs)

Generates a trade (cargo). Default: py:class:maritime_simulator.shipping_market.Trade. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_trade.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The trade.

static generate_vessel(*args, **kwargs)

Generates a vessel. Default: py:class:maritime_simulator.transport_operation.SimpleVessel. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_vessel.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The vessel.

static generate_world(*args, **kwargs)

Generates a world. Default: py:class:maritime_simulator.simulation_environment.World. :param _sphinx_paramlinks_mable.simulation_generation.ClassFactory.generate_world.args:

Positional args.

Parameters:

kwargs – Keyword args.

Returns:

The world.

class mable.simulation_generation.SimulationBuilder(class_factory, specifications)

Bases: object

A unit to translate simulation instructions into a simulation engine.

The main function to use is :py:func`generate_engine` which should call the function to generate the subunits. The functions for the subunits all return self in order to allow easy concatenation of the generation process.

__init__(class_factory, specifications)

Constructor. :param _sphinx_paramlinks_mable.simulation_generation.SimulationBuilder.class_factory: ClassFactory

The class factory.

Parameters:

specifications – Specifications for a simulation.

generate_engine(*args, **kwargs)

Generates an engine from the specifications by generating all units in turn. Order: random, network, world, shipping_companies, shipping(cargo generation), market (shipping allocation). :return:

The simulation engine.

generate_fleet(*args, **kwargs)

Generates the fleet of vessels of one company based on a list of vessel specifications and SimulationFactory.generate_vessel(). :param _sphinx_paramlinks_mable.simulation_generation.SimulationBuilder.generate_fleet.args:

Positional args. The first argument should be a list of vessel instructions.

Parameters:

kwargs – Keyword args.

Returns:

A list of vessels.

generate_market(*args, **kwargs)

Generates the market (cargo distribution) unit based on the specification information and the class factory’s ClassFactory.generate_market(). :param _sphinx_paramlinks_mable.simulation_generation.SimulationBuilder.generate_market.args:

Positional args. (Most likely no arguments since the args from the specifications are used. But can be used for further instructions from generate_engine().)

Parameters:

kwargs – Keyword args. (Most likely no arguments since the kwargs from the specifications are used. But can be used for further instructions from generate_engine().)

Returns:

self

generate_network(*args, **kwargs)

Generates the network (space) including the ports based on the specification information and the class factory’s ClassFactory.generate_network() and ClassFactory.generate_port(), respectively. :param _sphinx_paramlinks_mable.simulation_generation.SimulationBuilder.generate_network.args:

Positional args. (Most likely no arguments since the args from the specifications are used. But can be used for further instructions from generate_engine().)

Parameters:

kwargs – Keyword args. (Most likely no arguments since the kwargs from the specifications are used. But can be used for further instructions from generate_engine().)

Returns:

self

generate_random(*args, **kwargs)

Generates a random based on the specification information and the class factory’s ClassFactory.generate_random(). :param _sphinx_paramlinks_mable.simulation_generation.SimulationBuilder.generate_random.args:

Positional args. (Most likely no arguments since the args from the specifications are used. But can be used for further instructions from generate_engine().)

Parameters:

kwargs – Keyword args. (Most likely no arguments since the kwargs from the specifications are used. But can be used for further instructions from generate_engine().)

Returns:

self

generate_shipping(*args, **kwargs)

Generates the shipping (cargo generation) unit based on the specification information and the class factory’s ClassFactory.generate_shipping(). :param _sphinx_paramlinks_mable.simulation_generation.SimulationBuilder.generate_shipping.args:

Positional args. (Most likely no arguments since the args from the specifications are used. But can be used for further instructions from generate_engine().)

Parameters:

kwargs – Keyword args. (Most likely no arguments since the kwargs from the specifications are used. But can be used for further instructions from generate_engine().)

Returns:

self

generate_shipping_companies(*args, **kwargs)

Generates the shipping companies including the vessels based on the specification information and the class factory’s ClassFactory.generate_company() and SimulationFactory.generate_fleet(), respectively. :param _sphinx_paramlinks_mable.simulation_generation.SimulationBuilder.generate_shipping_companies.args:

Positional args. (Most likely no arguments since the args from the specifications are used. But can be used for further instructions from generate_engine().)

Parameters:

kwargs – Keyword args. (Most likely no arguments since the kwargs from the specifications are used. But can be used for further instructions from generate_engine().)

Returns:

self

generate_vessel(*args, **kwargs)

Generates one vessel using based on class factory’s ClassFactory.generate_vessel(). :param _sphinx_paramlinks_mable.simulation_generation.SimulationBuilder.generate_vessel.args:

Positional args.

Parameters:

kwargs – Keyword args. Should include ‘location’ and ‘capacities_and_loading_rates’.

Returns:

A vessel.

generate_world(*args, **kwargs)

Generates the world based on the specification information and the class factory’s ClassFactory.generate_world(). Requires network, event queue and random to be already generated. :param _sphinx_paramlinks_mable.simulation_generation.SimulationBuilder.generate_world.args:

Positional args. (Most likely no arguments since the args from the specifications are used. But can be used for further instructions from generate_engine().)

Parameters:

kwargs – Keyword args. (Most likely no arguments since the kwargs from the specifications are used. But can be used for further instructions from generate_engine().)

Returns:

self

set_engines(engine, *args, **kwargs)

Makes the engine known to the units constituting the simulation.

On default called by generate_engine() as the last step.

All units should be maritime_simulator.util.JsonAble which is used to set the engine. :param _sphinx_paramlinks_mable.simulation_generation.SimulationBuilder.set_engines.engine:

The simulation engine.

Parameters:
  • args – Positional args.

  • kwargs – Keyword args.

mable.transport_operation module

Classes for shipping companies.

class mable.transport_operation.Bid(*, amount: float, trade: Trade, company: ShippingCompany = None)

Bases: object

A bid for cargo transportation. :param _sphinx_paramlinks_mable.transport_operation.Bid.amount:

The amount for which the bidding company is willing to transport the cargo

Parameters:

trade (Trade) – The trade the company is diffing for.

__init__(*, amount: float, trade: Trade, company: ShippingCompany = None) None

Method generated by attrs for class Bid.

amount: float
company: ShippingCompany
trade: Trade
class mable.transport_operation.CargoCapacity(cargo_type: Hashable, loading_rate: float, capacity: float)

Bases: JsonAble

Parameters:
  • cargo_type (Hashable) – The type of cargo.

  • loading_rate (float) – The amount of tonnes (un)loadable in one hour.

  • capacity (float) – The capacity in tonnes (t).

class Data(current_class: Type[DataProtocol], cargo_type: Hashable, loading_rate: float, capacity: float)

Bases: DataClass

class Schema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool | None = None, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)

Bases: DataSchema

opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
__init__(current_class: Type[DataProtocol], cargo_type: Hashable, loading_rate: float, capacity: float) None

Method generated by attrs for class CargoCapacity.Data.

capacity: float
cargo_type: Hashable
loading_rate: float
__init__(cargo_type: Hashable, loading_rate: float, capacity: float) None
capacity: float
cargo_type: Hashable
loading_rate: float
to_json()
Returns:

Any A json encodable object.

class mable.transport_operation.CargoContainer(capacity, loading_rate)

Bases: object

A capacity limited container for cargo.

__init__(capacity, loading_rate)
Parameters:
  • capacity (float) – The capacity of the container.

  • loading_rate (float) – The rate at which the container can be loaded and unloaded.

property amount
Returns:

The current amount of cargo.

Return type:

float

property capacity
Returns:

The capacity of the hold.

Return type:

float

property loading_rate
Returns:

The rate at which the container can be loaded and unloaded.

Return type:

float

class mable.transport_operation.CargoHold(capacities: List[CargoCapacity])

Bases: object

A cargo hold for several cargo containers that can be loaded and unloaded.

__init__(capacities: List[CargoCapacity])

Constructor. :param _sphinx_paramlinks_mable.transport_operation.CargoHold.capacities: List[CargoCapacity]

A list of the types, capacities and loading rates of the cargo containers.

available_cargo_types()

A list of the cargo types of the containers in this cargo hold.

Returns:

The list of cargo types.

get_capacity(cargo_type)

The capacity of the cargo container of the specified type.

Parameters:

cargo_type (Hashable) – The cargo type.

Returns:

The capacity.

Return type:

float

get_current_load(cargo_type)

The current amount in the cargo container of the specified type.

Parameters:

cargo_type (Hashable) – The cargo type.

Returns:

The amount of cargo.

Return type:

float

get_loading_rate(cargo_type)

The loading rate of the cargo container of the specified type.

Parameters:

cargo_type – The cargo type.

Returns:

The loading rate.

Return type:

float

is_empty()

Checks if no cargo of any possible types is loaded. :return: True if for no cargo type any amount is loaded. Otherwise, False. :rtype: bool

load_cargo(cargo_type, amount)

Loads the specified amount of cargo in the container of the type.

Parameters:
  • cargo_type (Hashable) – The cargo type.

  • amount (float) – The amount to load.

Raises:

ValueError – if the amount is negative.

unload_cargo(cargo_type, amount)

Unloads the specified amount of cargo in the container of the type.

Parameters:
  • cargo_type (str) – The cargo type.

  • amount (float) – The amount to unload.

Raises:

ValueError – if the amount is negative.

class mable.transport_operation.CargoHoldSchema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool | None = None, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)

Bases: Schema

opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
class mable.transport_operation.ScheduleProposal(schedules: Dict[Vessel, Schedule], scheduled_trades: List[Trade], costs: Dict[Trade, float])

Bases: object

A proposed schedule including a number of trades.

Parameters:
  • schedules (Dict[Vessel, Schedule]) – The proposed schedules indexed by the vessels.

  • scheduled_trades (List[Trade]) – A list of trades that are scheduled within the vessel’s schedules.

__init__(schedules: Dict[Vessel, Schedule], scheduled_trades: List[Trade], costs: Dict[Trade, float]) None
costs: Dict[Trade, float]
scheduled_trades: List[Trade]
schedules: Dict[Vessel, Schedule]
class mable.transport_operation.ShippingCompany(fleet, name)

Bases: SimulationEngineAware, Generic[V]

Interface for a shipping company.

class Data(current_class: Type[DataProtocol], fleet: list[Data], name: str)

Bases: DataClass

class Schema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool | None = None, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)

Bases: DataSchema

opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
__init__(current_class: Type[DataProtocol], fleet: list[Data], name: str) None

Method generated by attrs for class ShippingCompany.Data.

fleet: list[Data]
name: str
__init__(fleet, name)

Constructor. :param _sphinx_paramlinks_mable.transport_operation.ShippingCompany.fleet: List of vessels. :type _sphinx_paramlinks_mable.transport_operation.ShippingCompany.fleet: List[V]

property fleet
Returns:

The vessels of the current fleet.

Return type:

List[V]

classmethod get_class()
abstract inform(*args, **kwargs)

Inform the shipping company of trades that are coming available. :param _sphinx_paramlinks_mable.transport_operation.ShippingCompany.inform.args: Positional args for additional arguments in subclasses. :param _sphinx_paramlinks_mable.transport_operation.ShippingCompany.inform.kwargs: Keyword args for additional arguments in subclasses. :return: A response to the information about cargoes, e.g. a list of cargoes the company is interested in.

property name
abstract pre_inform(*args, **kwargs)

Inform the shipping company of trades that are available at a future time. No response expected.

Parameters:
  • args – Positional args for additional arguments in subclasses.

  • kwargs – Keyword args for additional arguments in subclasses.

abstract receive(*args, **kwargs)

An allocation of trades to the shipping company . :param _sphinx_paramlinks_mable.transport_operation.ShippingCompany.receive.args: Positional args for additional arguments in subclasses. :param _sphinx_paramlinks_mable.transport_operation.ShippingCompany.receive.kwargs: Keyword args for additional arguments in subclasses.

set_engine(engine)

Make the simulation engine know to the company and all its vessels. :param _sphinx_paramlinks_mable.transport_operation.ShippingCompany.set_engine.engine: SimulationEngine

The engine.

class mable.transport_operation.SimpleCompany(fleet, name)

Bases: ShippingCompany[V]

A simple company.

__init__(fleet, name)
Parameters:
  • fleet (List[V]) – List of vessels.

  • name (str) – the name of the company

apply_schedules(schedules)

Applies the schedules to the vessels.

If any schedule is invalid it will not be applied.

Parameters:

schedules (Dict[Vessel, Schedule]) – The schedules to apply indexed by the vessels.

get_arrival_time(port, schedule, vessel)

Calculates the arrival time of the vessel at the port. If the specified schedule has events it is assumed that the vessel is in the location of the last event. Otherwise, the vessels current position is used.

Parameters:
  • port – The port

  • schedule (Schedule _sphinx_paramlinks_mable.transport_operation.SimpleCompany.get_arrival_time.| None) – The schedule or None

  • vessel (Vessel) – The vessel.

Returns:

The arrival time

Return type:

float

inform(trades, *args, **kwargs)

The shipping company tries to schedule the cargoes into the schedules of the fleet. Any trades that fit into the vessels’ schedules are returned as trades the company can/wants to transport.

Parameters:
  • trades (List[Trade]) – The list of trades.

  • args – Not used.

  • kwargs – Not used.

Returns:

A response to the information about cargoes, e.g. a list of cargoes the company is interested in.

pre_inform(trades, time)

Inform the shipping company of trades that are available at a future time. No response expected.

Parameters:
  • trades (List[Trade]) – The trades coming in the future.

  • time (int) – The time when the trades will be allocated.

propose_schedules(trades)

Tries to generate new schedules based on the vessels’ current schedules and the specified trades. Trades are attempted to schedule by simply finding the first vessel that can transport the cargo after finishing the current schedule.

Parameters:

trades (List[Trade]) – The trades.

Returns:

The schedule proposals.

Return type:

ScheduleProposal

receive(trades, *args, **kwargs)

Allocate a list of trades to the company. If the trades are all trades that where requested by SimpleCompany.inform() the previously generated schedules will be used. Otherwise, new schedules will be created.

Parameters:
  • trades (List[Trade]) – The list of trades.

  • args – Not used.

  • kwargs – Not used.

class mable.transport_operation.SimpleVessel(capacities_and_loading_rates, location, speed, keep_journey_log=True, name=None, company=None)

Bases: Vessel

A vessel with a fixed travel time.

class Data(current_class: Type[DataProtocol], capacities_and_loading_rates: List[Data], location: str | None, keep_journey_log: bool, name: str, speed: float)

Bases: Data

class Schema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool | None = None, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)

Bases: Schema

opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
__init__(current_class: Type[DataProtocol], capacities_and_loading_rates: List[Data], location: str | None, keep_journey_log: bool, name: str, speed: float) None

Method generated by attrs for class SimpleVessel.Data.

speed: float
__init__(capacities_and_loading_rates, location, speed, keep_journey_log=True, name=None, company=None)
Parameters:
  • capacities_and_loading_rates (List[CargoCapacity]) – A list of the types, capacities and loading rates of the cargo containers.

  • location – The location of the vessel at creation.

  • speed (float) – The speed of the vessel.

  • keep_journey_log (bool) – If true the vessel keeps a log of event occurrences that affected the vessel.

  • name (str) – The name of the vessel.

  • company (ShippingCompany[V]) – The company that owns the vessel.

get_loading_time(cargo_type, amount, *args, **kwargs)

Returns the time in hours the vessel requires to load the specified amount of the specified cargo based on the loading rate of the cargo hold.

Parameters:
  • cargo_type (Hashable) – The cargo type.

  • amount (float) – The amount.

  • args – Positional args for additional arguments in subclasses.

  • kwargs – Keyword args for additional arguments in subclasses.

Returns:

The time

Return type:

float

get_travel_time(distance, *args, **kwargs)

The time in hours the vessel requires to traverse the specified distance determined by the vessel’s speed.

Parameters:
  • distance (float) – The distance

  • args – Positional args for additional arguments in subclasses.

  • kwargs – Keyword args for additional arguments in subclasses.

Returns:

The time

Return type:

float

property speed
Returns:

The speed of the vessel.

Return type:

float

to_json()
class mable.transport_operation.Vessel(capacities_and_loading_rates, location, keep_journey_log=True, name=None, company=None)

Bases: SimulationEngineAware

A vessel to travel and transport cargo.

class Data(current_class: Type[DataProtocol], capacities_and_loading_rates: List[Data], location: str | None, keep_journey_log: bool, name: str)

Bases: DataClass

class Schema(*, only: Sequence[str] | AbstractSet[str] | None = None, exclude: Sequence[str] | AbstractSet[str] = (), many: bool | None = None, context: dict | None = None, load_only: Sequence[str] | AbstractSet[str] = (), dump_only: Sequence[str] | AbstractSet[str] = (), partial: bool | Sequence[str] | AbstractSet[str] | None = None, unknown: str | None = None)

Bases: DataSchema

opts: SchemaOpts = <marshmallow.schema.SchemaOpts object>
__init__(current_class: Type[DataProtocol], capacities_and_loading_rates: List[Data], location: str | None, keep_journey_log: bool, name: str) None

Method generated by attrs for class Vessel.Data.

capacities_and_loading_rates: List[Data]
keep_journey_log: bool
location: str | None
name: str
__init__(capacities_and_loading_rates, location, keep_journey_log=True, name=None, company=None)
Parameters:
  • capacities_and_loading_rates (List[CargoCapacity]) – A list of the types, capacities and loading rates of the cargo containers.

  • location – The location of the vessel at creation.

  • keep_journey_log (bool) – If true the vessel keeps a log of event occurrences that affected the vessel.

  • name (str) – The name of the vessel.

  • company (ShippingCompany[V]) – The company that owns the vessel.

property capacities_and_loading_rates

A list of CargoCapacity of the current cargo hold.

Returns:

The list.

Return type:

List[CargoCapacity]

capacity(cargo_type)

The capacity of the cargo container of the specified type.

Parameters:

cargo_type (Hashable) – The cargo type.

Returns:

The capacity.

Return type:

float

copy_hold()

Create a deep copy of the current cargo hold.

Returns:

The copy of the cargo hold.

current_load(cargo_type)

The current amount in the cargo container of the specified type.

Parameters:

cargo_type (Hashable) – The cargo type.

Returns:

The amount of cargo.

Return type:

float

event_occurrence(event)

WARNING: Part of internal simulation logic. Only allowed to be called by the simulation!

Informs the vessel about the occurrence of an event. This has to be the vessel’s next event.

Parameters:

event – The event.

Raises:

ValueError – if the event is not the next event.

abstract get_loading_time(cargo_type, amount, *args, **kwargs)

Returns the time in hours the vessel requires to load the specified amount of the specified cargo.

Parameters:
  • cargo_type (Hashable) – The cargo type.

  • amount (float) – The amount.

  • args – Positional args for additional arguments in subclasses.

  • kwargs – Keyword args for additional arguments in subclasses.

Returns:

The time

Return type:

float

abstract get_travel_time(distance, *args, **kwargs)

Returns the time in hours the vessel requires to traverse the specified distance.

Parameters:
  • distance (float) – The distance

  • args – Positional args for additional arguments in subclasses.

  • kwargs – Keyword args for additional arguments in subclasses.

Returns:

The time

Return type:

float

has_any_load()

Indicates if any of the cargo containers of the hold contain load.

Returns:

True if any one of the cargo container has load and False otherwise.

Return type:

bool

has_next_event()

Checks if there is at least one event in the schedule.

Returns:

True is there is an event in the schedule and False otherwise.

Return type:

bool

property journey_log

The current log of events pertaining the vessel.

Returns:

[VesselEvent]

load_cargo(cargo_type, amount)

WARNING: Part of internal simulation logic. Only allowed to be called by the simulation!

Loads the specified amount of cargo in the container of the type.

Parameters:
  • cargo_type (Hashable) – The cargo type.

  • amount (float) – The amount to load.

Raises:

ValueError – if the amount is negative.

loadable_cargo_types()

Indicates which cargo types can be loaded into the cargo hold.

Returns:

List of cargo types.

Return type:

List[Hashable]

property location
Returns:

The current location.

Return type:

Location | OnJourney

log_journey_log_event(log_entry)

WARNING: Part of internal simulation logic. Only allowed to be called by the simulation!

Log an entry in the journey log.

Parameters:

log_entry (VesselEvent) – The entry to make

property name
Returns:

The name of the vessel.

Return type:

str

property schedule
Returns:

A copy of the vessel’s current schedule.

Return type:

Schedule

set_engine(engine)

WARNING: Part of internal simulation logic. Only allowed to be called by the simulation!

Set the simulation engine.

Parameters:

engine (SimulationEngine) – The simulation engine.

start_next_event()

WARNING: Part of internal simulation logic. Only allowed to be called by the simulation!

Starts the next event in schedule. The event is also added to the event queue. However, does not check if (if any) preceding next event has occurred nor tidies the event queue of any such event.

unload_cargo(cargo_type, amount)

WARNING: Part of internal simulation logic. Only allowed to be called by the simulation!

Unloads the specified amount of cargo in the container of the type.

Parameters:
  • cargo_type (str) – The cargo type.

  • amount (float) – The amount to unload.

Raises:

ValueError – if the amount is negative.

mable.transportation_scheduling module

Shipping operation

class mable.transportation_scheduling.CurrentState(*, current_time: float, current_location: Location, current_cargo_hold: dict, vessel: Vessel, engine: SimulationEngine, is_valid: bool = True)

Bases: object

The current state of a vessel including location and cargo loading.

__init__(*, current_time: float, current_location: Location, current_cargo_hold: dict, vessel: Vessel, engine: SimulationEngine, is_valid: bool = True) None

Method generated by attrs for class CurrentState.

current_cargo_hold: dict
current_location: Location
current_time: float
engine: SimulationEngine
is_valid: bool
vessel: Vessel
class mable.transportation_scheduling.Schedule(vessel, current_time=0, creation_time=0, schedule=None)

Bases: SimulationEngineAware

The schedule of a vessel.

__init__(vessel, current_time=0, creation_time=0, schedule=None)

Note: Requires the engine to be set to work.

Parameters:
  • vessel (Vessel) – The vessel for which the schedule is.

  • schedule – Used for creating schedule copies (see schedule_copy()).

Should be None for all purposes.

add_relocation(port, index_in_schedule=None)

Add a relocation into the schedule.

Parameters:
  • port (Port) – The port to relocate to.

  • index_in_schedule (int) – The index of the relocation in the schedule.

Raises:

ValueError if the index is wrong.

add_transportation(trade, location_pick_up=None, location_drop_off=None)

Add a transportation into the schedule.

Parameters:
  • trade (Trade) – The task’s associated trade.

  • location_pick_up (int) – The location of the pick-up task in the order of all tasks.

  • location_drop_off (int) – The location of the drop-off task in the order of all tasks.

Raises:

ValueError if the pick-up and drop-off indices are wrong.

completion_time()

Determine the time when the schedule completes.

Returns:

The completion time.

Return type:

float

copy()

Create a copy that contains the reference to the vessel but creates a deep copy of the actual schedule.

Returns:

The copy

Return type:

Schedule

get(idx, default=None)
get_insertion_points()

Get the points where tasks can be inserted.

Returns:

List of insertion points.

Return type:

List[int]

get_scheduled_trades()

List of all trades that are scheduled to be transported.

Returns:

The trades.

Return type:

List[Trade]

get_simple_schedule()

Produce a simple overview of the schedule in the form of a list with drop off/pick up indicator and associated cargo, e.g. [(‘PICK_UP’, <trade>), (‘DROP_OFF’, <trade>)].

Returns:

The simple overview.

Return type:

List[Tuple[str, Trade]]

classmethod init_with_engine(vessel, current_time, engine)
next()

Get the next scheduled location or None if the schedule is empty.

Returns:

The next stop.

pop()

Pop the next scheduled location.

Returns:

The next stop.

verify_schedule()

Verify that a schedule can be completed in time and without over-/under-loading the cargo hold. This is convenience function that combines verify_schedule_time() and verify_schedule_cargo().

Returns:

True if the timing and the cargo load are valid over all tasks and associated trades. Otherwise, False.

Return type:

bool

verify_schedule_cargo()

Verifies that the schedule’s cargo loading and unloading is possible. The verification is done via simulating all loading and unloading events.

Returns:

True is the schedule is valid, False otherwise.

Return type:

bool

verify_schedule_time()

Verifies that the schedule’s timing is possible. A schedule is valid is it has no negative cycles.

Returns:

True is the schedule is valid, False otherwise.

Return type:

bool

class mable.transportation_scheduling.TransportationSourceDestinationIndicator(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: IntEnum

DROP_OFF = 1
PICK_UP = 0
class mable.transportation_scheduling.TransportationStartFinishIndicator(value, names=<not given>, *values, module=None, qualname=None, type=None, start=1, boundary=None)

Bases: IntEnum

FINISH = 1
START = 0

mable.util module

Util module including: - Json encoding - Time formatting

class mable.util.JsonAble

Bases: object

Ensures that a class is transformable into a json. On default that means an objects __dict__ is json dumped.

__init__()
to_json()
Returns:

Any A json encodable object.

class mable.util.JsonAbleEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Bases: JSONEncoder

An encoder for settings with JsonAble classes.

default(obj)

If the object is of type JsonAble the jsonAble.to_json() function is called. :param _sphinx_paramlinks_mable.util.JsonAbleEncoder.default.obj: Any

An object that is either json encodable by default or that is JsonAble.

Returns:

The result of jsonAble.to_json() or json.JSONEncoder.default()

mable.util.format_time(time)

Formats a decimal time assumed to be hours in to a string of roughly days and hours. After days are determined the remaining hours are round to one decimal place.

Parameters:

time (float) – Time in hours.

Returns:

str ‘~<days> day(s) <hours> hour(s)’

Module contents