Basic trip over a real-world graph¶
In this notebook, we set up a basic simulation where one vessel moves over a real-world graph. The vessel will sail from a location in the Maasvlakte, to a location in the Port of Moerdijk.
0. Import libraries¶
# package(s) used for creating and geo-locating the graph
import networkx as nx
import shapely
# package(s) related to the simulation (creating the vessel, running the simulation)
import datetime
import simpy
import opentnsim
import opentnsim.fis as fis
from opentnsim.core.logutils import logbook2eventtable
from opentnsim.core.plotutils import generate_vessel_gantt_chart
# package(s) needed for inspecting the output
import pandas as pd
import geopandas as gpd
# plot libraries
import folium
print("This notebook is executed with OpenTNSim version {}".format(opentnsim.__version__))This notebook is executed with OpenTNSim version 1.3.7
1. Define object classes¶
# make your preferred Vessel class out of available mix-ins.
Vessel = type(
"Vessel",
(
opentnsim.core.Identifiable, # allows to give the object a name and a random ID,
opentnsim.core.Movable, # allows the object to move, with a fixed speed, while logging this activity
),
{}
)2. Create graph¶
Next we create a network (a graph) along which the vessel can move. For this case we use the Fairway Information System graph, and make the vessel sail from a container terminal at the Maasvlakte to an container terminal at the Port of Moerdijk.
# load the processed version from the Fairway Information System graph provided by Rijkswaterstaat
FG = fis.load_network(version="0.3")maasvlakte = shapely.Point(4.0566946, 51.9471624)
moerdijk = shapely.Point(4.5944738, 51.6829037)nodes_gdf = gpd.GeoDataFrame(FG.nodes.values(), index=FG.nodes.keys())distances, idx = nodes_gdf.sindex.nearest(maasvlakte)
maasvlakte_node = nodes_gdf.iloc[idx[0]]
distances, idx = nodes_gdf.sindex.nearest(moerdijk)
moerdijk_node = nodes_gdf.iloc[idx[0]]route = nx.shortest_path(FG, maasvlakte_node.name, moerdijk_node.name, weight='length_m')# Create a map centered between the two points
m = folium.Map(location=[51.83, 4.33], zoom_start = 10, tiles="cartodb positron")
for edge in FG.edges(data = True):
points_x = list(edge[2]["geometry"].coords.xy[0])
points_y = list(edge[2]["geometry"].coords.xy[1])
line = []
for i, _ in enumerate(points_x):
line.append((points_y[i], points_x[i]))
if edge[0] in route and edge[1] in route:
folium.PolyLine(line, color = "red", weight = 3, popup = edge[2]["Name"]).add_to(m)
else:
folium.PolyLine(line, color = "black", weight = 3, popup = edge[2]["Name"]).add_to(m)
for node in FG.nodes(data = True):
point = list(node[1]["geometry"].coords.xy)
folium.CircleMarker(location=[point[1][0],point[0][0]], color='black',fill_color = "black", fill=True, radus = 1, popup = node[0]).add_to(m)
# Add round marker for Maasvlakte with popup
folium.CircleMarker(
location=[maasvlakte_node.Y, maasvlakte_node.X],
radius=8,
color='green',
fill=True,
fill_color='green',
fill_opacity=0.7,
popup='Maasvlakte'
).add_to(m)
# Add round marker for Moerdijk with popup
folium.CircleMarker(
location=[moerdijk_node.Y, moerdijk_node.X],
radius=8,
color='blue',
fill=True,
fill_color='blue',
fill_opacity=0.7,
popup='Moerdijk'
).add_to(m)
# Display the map
m3. Run simulation¶
def mission(env, vessel):
"""
Method that defines the mission of the vessel.
In this case:
keep moving along the path until its end point is reached
"""
while True:
yield from vessel.move()
if vessel.geometry == nx.get_node_attributes(env.graph, "geometry")[vessel.route[-1]]:
break# start simpy environment
simulation_start = datetime.datetime(2024, 1, 1, 0, 0, 0)
env = simpy.Environment(initial_time=simulation_start.timestamp())
env.epoch = simulation_start
# add graph to environment
env.graph = FG
# create vessel from a dict
path = route
data_vessel = {
"env": env, # needed for simpy simulation
"name": "Vessel", # required by Identifiable
"geometry": env.graph.nodes[path[0]]['geometry'], # required by Locatable
"route": path, # required by Routeable
"v": 1, # required by Movable, 1 m/s to check if the distance is covered in the expected time
} #
# create an instance of the Vessel class using the input dict data_vessel
vessel = Vessel(**data_vessel)
# start the simulation
env.process(mission(env, vessel))
env.run()4. Inspect output¶
We can now inspect the simulation output by inspecting the vessel.logbook. Note that the Log mix-in was included when we added Movable. The vessel.logbook keeps track of the moving activities of the vessel. For each discrete event OpenTNSim logs an event message, the start/stop time and the location. The vessel.logbook is of type dict. For convenient inspection it can be loaded into a Pandas dataframe.
# load the logbook data into a dataframe
df = pd.DataFrame.from_dict(vessel.logbook)
print("'{}' logbook data:".format(vessel.name))
print('')
display(df)'Vessel' logbook data:
The inspection of the logbook data shows that Vessel moved from its origin (Node 0) to its destination (Node 1). The print statements show that the length of the route from Node 0 to Node 1 is exactly 100 km. At a given speed of 1 m/s the trip duration should be exactly 100000 seconds, as is indeed shown to be the case.
df_eventtable = logbook2eventtable([vessel])
df_eventtable.head(3)generate_vessel_gantt_chart(df_eventtable)duration = df_eventtable['duration (s)'].sum()
distance = df_eventtable['distance (m)'].sum()
print('{} sailed {:.1f} m in {:.1f} s, which is {}'.format(vessel.name, distance, duration, str(datetime.timedelta(seconds=duration))))Vessel sailed 61035.4 m in 61035.4 s, which is 16:57:15.383138