taxi_simulator package¶
Submodules¶
taxi_simulator.cli module¶
Console script for taxi_simulator.
taxi_simulator.coordinator module¶
-
class
taxi_simulator.coordinator.
CoordinatorAgent
(agentjid, password, http_port, ip_address)[source]¶ Bases:
spade.agent.Agent
Coordinator agent that manages the requests between taxis and passengers
-
add_passenger
(agent)[source]¶ Adds a new
PassengerAgent
to the store.Parameters: agent ( PassengerAgent
) – the instance of the PassengerAgent to be added
-
add_strategy
(strategy_class)[source]¶ Injects the strategy by instantiating the
strategy_class
. Since thestrategy_class
inherits fromspade.Behaviour.Behaviour
, the new strategy is added as a behaviour to the agent.Parameters: strategy_class (class) – the class to be instantiated.
-
add_taxi
(agent)[source]¶ Adds a new
TaxiAgent
to the store.Parameters: agent ( TaxiAgent
) – the instance of the TaxiAgent to be added
-
async_create_agent
(cls: type, name: str, password: str, position: List[float], target: Optional[List[float]], speed: Optional[float])[source]¶ Coroutine to create an agent.
Parameters: - cls (class) – class of the agent (TaxiAgent or PassengerAgent)
- name (str) – name of the agent
- password (str) – password of the agent
- position (list) – initial coordinates of the agent
- target (list, optional) – destination coordinates of the agent
- speed (float, optional) – speed of the vehicle
-
clean_controller
(request)[source]¶ Web controller that resets the simulator to a clean state.
Returns: no template is returned since this is an AJAX controller, a dict with status=done Return type: dict
-
clear_stopped_agents
()[source]¶ Removes from the taxi and passenger sets every agent that is stopped.
-
create_agent
(cls, name, password, position, target=None, speed=None)[source]¶ Create an agent of type
cls
(TaxiAgent or PassengerAgent).Parameters: - cls (class) – class of the agent (TaxiAgent or PassengerAgent)
- name (str) – name of the agent
- password (str) – password of the agent
- position (list) – initial coordinates of the agent
- target (list, optional) – destination coordinates of the agent
- speed (float, optional) – speed of the vehicle
-
create_agents_batch
(cls: type, number: int) → None[source]¶ Creates a batch of agents.
Parameters: - cls (class) – class of the agent to create
- number (int) – size of the batch
-
download_stats_excel_controller
(request)[source]¶ Web controller that returns an Excel file with the simulation results.
Returns: a Response of type “attachment” with the file content. Return type: Response
-
download_stats_json_controller
(request)[source]¶ Web controller that returns a JSON file with the simulation results.
Returns: a Response of type “attachment” with the file content. Return type: Response
-
entities_controller
(request)[source]¶ Web controller that returns a dict with the entities of the simulator and their statuses.
Example of the entities returned data:
{ "passengers": [ { "status": 24, "taxi": "taxi2@127.0.0.1", "dest": [ 39.463356, -0.376463 ], "waiting": 3.25, "position": [ 39.460568, -0.352529 ], "id": "michaelstewart" } ], "taxis": [ { "status": 11, "passenger": "michaelstewart@127.0.0.1", "assignments": 1, "path": [ [ 39.478328, -0.406712 ], [ 39.478317, -0.406814 ], [ 39.460568, -0.352529 ] ], "dest": [ 39.460568, -0.352529 ], "position": [ 39.468131, -0.39685 ], "speed": 327.58, "id": "taxi2", "distance": "6754.60" } ], "stats": { "totaltime": "-1.00", "waiting": "3.25", "finished": False, "is_running": True }, "tree": { "name": "Agents", "children": [ { "count": "1", "name": "Taxis", "children": [ { "status": 11, "name": " taxi2", "icon": "fa-taxi" } ] }, { "count": "1", "name": "Passengers", "children": [ { "status": 24, "name": " michaelstewart", "icon": "fa-user" } ] } ] }, "authenticated": False }
Returns: no template is returned since this is an AJAX controller, a dict with the list of taxis, the list of passengers, the tree view to be showed in the sidebar and the stats of the simulation. Return type: dict
-
generate_tree
()[source]¶ Generates the tree view in JSON format to be showed in the sidebar.
Returns: a dict with all the agents in the simulator, with their name, status and icon. Return type: dict
-
get_passenger_stats
()[source]¶ Creates a dataframe with the simulation stats of the passengers The dataframe includes for each passenger its name, waiting time, total time and status.
Returns: the dataframe with the passengers stats. Return type: pandas.DataFrame
-
get_simulation_time
()[source]¶ Returns the elapsed simulation time to the current time. If the simulation is not started it returns 0.
Returns: the whole simulation time. Return type: float
-
get_stats
()[source]¶ Generates the stats of the simulation in JSON format.
Examples:
{ "totaltime": "12.25", "waiting": "3.25", "finished": False, "is_running": True }
Returns: a dict with the total time, waiting time, is_running and finished values Return type: dict
-
get_stats_dataframes
()[source]¶ Collects simulation stats and returns 3 dataframes with the information: A general dataframe with the average information, a dataframe with the taxi’s information and a dataframe with the passenger’s information. :returns: avg df, taxi df and passenger df :rtype: pandas.Dataframe, pandas.Dataframe, pandas.Dataframe
-
get_taxi_stats
()[source]¶ Creates a dataframe with the simulation stats of the taxis The dataframe includes for each taxi its name, assignments, traveled distance and status.
Returns: the dataframe with the taxis stats. Return type: pandas.DataFrame
-
index_controller
(request)[source]¶ Web controller that returns the index page of the simulator.
Returns: the name of the template, the data to be pre-processed in the template Return type: dict
-
is_simulation_finished
()[source]¶ Checks whether the simulation has finished or not. A simulation is finished if all passengers are at their destinations. If there is no passengers the simulation is not finished.
Returns: whether the simulation has finished or not. Return type: bool
-
passenger_agents
¶ Gets the dict of registered passengers
Returns: a dict of PassengerAgent
with the name in the keyReturn type: dict
-
request_path
(origin, destination)[source]¶ Requests a path to the RouteAgent.
Parameters: - origin (list) – the origin coordinates (lon, lat)
- destination (list) – the target coordinates (lon, lat)
Returns: the path as a list of points, the distance of the path, the estimated duration of the path
Return type: list, float, float
-
run_controller
(request)[source]¶ Web controller that starts the simulator.
Returns: no template is returned since this is an AJAX controller, an empty data dict is returned Return type: dict
-
set_strategies
(coordinator_strategy, taxi_strategy, passenger_strategy)[source]¶ Gets the strategy strings and loads their classes. This strategies are prepared to be injected into any new taxi or passenger agent.
Parameters: - coordinator_strategy (str) – the path to the coordinator strategy
- taxi_strategy (str) – the path to the taxi strategy
- passenger_strategy (str) – the path to the passenger strategy
-
stop_agents_controller
(request)[source]¶ Web controller that stops all the passenger and taxi agents.
Returns: no template is returned since this is an AJAX controller, a dict with status=done Return type: dict
-
taxi_agents
¶ Gets the dict of registered taxis
Returns: a dict of TaxiAgent
with the name in the keyReturn type: dict
-
-
class
taxi_simulator.coordinator.
CoordinatorStrategyBehaviour
[source]¶ Bases:
taxi_simulator.utils.StrategyBehaviour
Class from which to inherit to create a coordinator strategy. You must overload the
_process()
method- Helper functions:
-
get_passenger_agents
()[source]¶ Gets the list of registered passengers
Returns: a list of PassengerAgent
Return type: list
taxi_simulator.helpers module¶
Helpers module
These functions are useful for the develop of new strategies.
-
exception
taxi_simulator.helpers.
AlreadyInDestination
[source]¶ Bases:
Exception
This exception is raised when an agent wants to move to a destination where it is already there.
-
exception
taxi_simulator.helpers.
PathRequestException
[source]¶ Bases:
Exception
This exception is raised when a path could not be computed.
-
taxi_simulator.helpers.
are_close
(coord1, coord2, tolerance=10)[source]¶ Checks wheter two points are close or not. The tolerance is expressed in meters.
Parameters: - coord1 (list) – a coordinate (longitude, latitude)
- coord2 (list) – another coordinate (longitude, latitude)
- tolerance (int) – tolerance in meters
Returns: whether the two coordinates are closer than tolerance or not
Return type: bool
-
taxi_simulator.helpers.
distance_in_meters
(coord1, coord2)[source]¶ Returns the distance between two coordinates in meters.
Parameters: - coord1 (list) – a coordinate (longitude, latitude)
- coord2 – another coordinate (longitude, latitude)
Returns: distance meters between the two coordinates
Return type: float
taxi_simulator.passenger module¶
-
class
taxi_simulator.passenger.
PassengerAgent
(agentjid, password, loop=None)[source]¶ Bases:
spade.agent.Agent
-
add_strategy
(strategy_class)[source]¶ Sets the strategy for the passenger agent.
Parameters: strategy_class ( PassengerStrategyBehaviour
) – The class to be used. Must inherit fromPassengerStrategyBehaviour
-
get_pickup_time
()[source]¶ Returns the time that the passenger was waiting to be picked up since it has been assigned to a taxi.
Returns: The time that the passenger was waiting to a taxi since it has been assigned. Return type: float
-
get_position
()[source]¶ Returns the current position of the passenger.
Returns: the coordinates of the current position of the passenger (lon, lat) Return type: list
-
get_waiting_time
()[source]¶ Returns the time that the agent was waiting for a taxi, from its creation until it gets into a taxi.
Returns: The time the passenger was waiting. Return type: float
-
is_in_destination
()[source]¶ Checks if the passenger has arrived to its destination.
Returns: whether the passenger is at its destination or not Return type: bool
-
request_path
(origin, destination)[source]¶ Requests a path between two points (origin and destination) using the RouteAgent service.
Parameters: - origin (list) – the coordinates of the origin of the requested path
- destination (list) – the coordinates of the end of the requested path
Returns: A list of points that represent the path from origin to destination, the distance and the estimated duration
Return type: list, float, float
-
set_coordinator
(coordinator_id)[source]¶ Sets the coordinator JID address :param coordinator_id: the coordinator jid :type coordinator_id: str
-
set_id
(agent_id)[source]¶ Sets the agent identifier :param agent_id: The new Agent Id :type agent_id: str
-
set_position
(coords=None)[source]¶ Sets the position of the passenger. If no position is provided it is located in a random position.
Parameters: coords (list) – a list coordinates (longitude and latitude)
-
set_route_agent
(route_id)[source]¶ Sets the route agent JID address :param route_id: the route agent jid :type route_id: str
-
set_target_position
(coords=None)[source]¶ Sets the target position of the passenger (i.e. its destination). If no position is provided the destination is setted to a random position.
Parameters: coords (list) – a list coordinates (longitude and latitude)
-
to_json
()[source]¶ Serializes the main information of a passenger agent to a JSON format. It includes the id of the agent, its current position, the destination coordinates of the agent, the current status, the taxi that it has assigned (if any) and its waiting time.
Returns: a JSON doc with the main information of the passenger. Example:
{ "id": "cphillips", "position": [ 39.461327, -0.361839 ], "dest": [ 39.460599, -0.335041 ], "status": 24, "taxi": "ghiggins@127.0.0.1", "waiting": 13.45 }
Return type: dict
-
-
class
taxi_simulator.passenger.
PassengerStrategyBehaviour
[source]¶ Bases:
taxi_simulator.utils.StrategyBehaviour
Class from which to inherit to create a taxi strategy. You must overload the
run
coroutine- Helper functions:
send_request
accept_taxi
refuse_taxi
-
accept_taxi
(taxi_id)[source]¶ Sends a
spade.message.Message
to a taxi to accept a travel proposal. It uses the REQUEST_PROTOCOL and the ACCEPT_PERFORMATIVE.Parameters: taxi_id (str) – The Agent JID of the taxi
-
refuse_taxi
(taxi_id)[source]¶ Sends an
spade.message.Message
to a taxi to refuse a travel proposal. It uses the REQUEST_PROTOCOL and the REFUSE_PERFORMATIVE.Parameters: taxi_id (str) – The Agent JID of the taxi
-
send_request
(content=None)[source]¶ Sends an
spade.message.Message
to the coordinator to request a taxi. It uses the REQUEST_PROTOCOL and the REQUEST_PERFORMATIVE. If no content is set a default content with the passenger_id, origin and target coordinates is used.Parameters: content (dict) – Optional content dictionary
-
class
taxi_simulator.passenger.
TravelBehaviour
[source]¶ Bases:
spade.behaviour.CyclicBehaviour
This is the internal behaviour that manages the movement of the passenger. It is triggered when the taxi informs the passenger that it is going to the passenger’s position until the passenger is droppped in its destination.
taxi_simulator.protocol module¶
protocol and performative constants
taxi_simulator.route module¶
-
class
taxi_simulator.route.
RouteAgent
(agentjid, password)[source]¶ Bases:
spade.agent.Agent
The RouteAgent receives request for paths, queries an OSRM server and returns the information. It also caches the queries to avoid overloading the OSRM server.
-
class
RequestRouteBehaviour
[source]¶ Bases:
spade.behaviour.CyclicBehaviour
This cyclic behaviour listens for route requests from other agents. When a message is received it answers with the path.
-
get_route
(origin, destination)[source]¶ Checks the cache for a path, if not found then it queries the OSRM server.
Parameters: - origin (list) – origin coordinate (longitude, latitude)
- destination (list) – target coordinate (longitude, latitude)
Returns: a dict with three keys: path, distance and duration
Return type: dict
-
static
request_route_to_server
(origin, destination)[source]¶ Queries the OSRM for a path.
Parameters: - origin (list) – origin coordinate (longitude, latitude)
- destination (list) – target coordinate (longitude, latitude)
Returns: list, float, float = the path, the distance of the path and the estimated duration
-
class
taxi_simulator.scenario module¶
taxi_simulator.simulator module¶
-
class
taxi_simulator.simulator.
SimulationConfig
[source]¶ Bases:
object
Dataclass to store the
Simulator
config
-
class
taxi_simulator.simulator.
Simulator
(config)[source]¶ Bases:
object
The Simulator. It manages all the simulation processes. Tasks done by the simulator at initialization:
- Create the XMPP server
- Run the SPADE backend
- Run the coordinator and route agents.
- Create agents passed as parameters (if any).
- Create agents defined in scenario (if any).
After these tasks are done in the Simulator constructor, the simulation is started when the
run
method is called.-
collect_stats
()[source]¶ Collects stats from all participant agents and from the simulation and stores it in three dataframes.
-
get_stats
()[source]¶ Returns the dataframes collected by
collect_stats()
Returns: average df, passengers df and taxi df Return type: pandas.DataFrame
,pandas.DataFrame
,pandas.DataFrame
-
is_simulation_finished
()[source]¶ Checks if the simulation is finished. A simulation is finished if the max simulation time has been reached or when the coordinator says it.
Returns: whether the simulation is finished or not. Return type: bool
-
stop
()[source]¶ Finishes the simulation and prints simulation stats. Tasks done when a simulation is stopped:
- Stop participant agents.
- Print stats.
- Stop Route agent.
- Stop Coordinator agent.
-
time_is_out
()[source]¶ Checks if the max simulation time has been reached.
Returns: whether the max simulation time has been reached or not. Return type: bool
-
write_excel
(filename)[source]¶ Writes the collected data by
collect_stats
in an excel file.Parameters: filename (str) – name of the excel file.
taxi_simulator.strategies module¶
-
class
taxi_simulator.strategies.
AcceptAlwaysStrategyBehaviour
[source]¶ Bases:
taxi_simulator.taxi.TaxiStrategyBehaviour
The default strategy for the Taxi agent. By default it accepts every request it receives if available.
-
class
taxi_simulator.strategies.
AcceptFirstRequestTaxiBehaviour
[source]¶ Bases:
taxi_simulator.passenger.PassengerStrategyBehaviour
The default strategy for the Passenger agent. By default it accepts the first proposal it receives.
-
class
taxi_simulator.strategies.
DelegateRequestTaxiBehaviour
[source]¶ Bases:
taxi_simulator.coordinator.CoordinatorStrategyBehaviour
The default strategy for the Coordinator agent. By default it delegates all requests to all taxis.
taxi_simulator.strategies_fsm module¶
-
class
taxi_simulator.strategies_fsm.
FSMTaxiStrategyBehaviour
[source]¶ Bases:
spade.behaviour.FSMBehaviour
-
class
taxi_simulator.strategies_fsm.
TaxiMovingState
[source]¶ Bases:
taxi_simulator.taxi.TaxiStrategyBehaviour
,spade.behaviour.State
-
class
taxi_simulator.strategies_fsm.
TaxiWaitingForApprovalState
[source]¶ Bases:
taxi_simulator.taxi.TaxiStrategyBehaviour
,spade.behaviour.State
-
class
taxi_simulator.strategies_fsm.
TaxiWaitingState
[source]¶ Bases:
taxi_simulator.taxi.TaxiStrategyBehaviour
,spade.behaviour.State
taxi_simulator.taxi module¶
-
class
taxi_simulator.taxi.
TaxiAgent
(agentjid, password, loop=None)[source]¶ Bases:
spade.agent.Agent
-
class
MovingBehaviour
(period, start_at=None)[source]¶ Bases:
spade.behaviour.PeriodicBehaviour
This is the internal behaviour that manages the movement of the taxi. It is triggered when the taxi has a new destination and the periodic tick is recomputed at every step to show a fine animation. This moving behaviour includes to update the taxi coordinates as it moves along the path at the specified speed.
-
add_strategy
(strategy_class)[source]¶ Sets the strategy for the taxi agent.
Parameters: strategy_class ( TaxiStrategyBehaviour
) – The class to be used. Must inherit fromTaxiStrategyBehaviour
-
arrived_to_destination
()[source]¶ Informs that the taxi has arrived to its destination. It recomputes the new destination and path if picking up a passenger or drops it and goes to WAITING status again.
-
cancel_passenger
(data=None)[source]¶ Sends a message to the current assigned passenger to cancel the assignment.
Parameters: data (dict, optional) – Complementary info about the cancellation
-
get_position
()[source]¶ Returns the current position of the passenger.
Returns: the coordinates of the current position of the passenger (lon, lat) Return type: list
-
inform_passenger
(status, data=None)[source]¶ Sends a message to the current assigned passenger to inform her about a new status.
Parameters: - status (int) – The new status code
- data (dict, optional) – complementary info about the status
-
is_in_destination
()[source]¶ Checks if the taxi has arrived to its destination.
Returns: whether the taxi is at its destination or not Return type: bool
-
move_to
(dest)[source]¶ Moves the taxi to a new destination.
Parameters: dest (list) – the coordinates of the new destination (in lon, lat format) Raises: AlreadyInDestination
– if the taxi is already in the destination coordinates.
-
request_path
(origin, destination)[source]¶ Requests a path between two points (origin and destination) using the RouteAgent service.
Parameters: - origin (list) – the coordinates of the origin of the requested path
- destination (list) – the coordinates of the end of the requested path
Returns: A list of points that represent the path from origin to destination, the distance and the estimated duration
Return type: list, float, float
Examples
>>> path, distance, duration = await self.request_path(origin=[0,0], destination=[1,1]) >>> print(path) [[0,0], [0,1], [1,1]] >>> print(distance) 2.0 >>> print(duration) 3.24
-
set_coordinator
(coordinator_id)[source]¶ Sets the coordinator JID address :param coordinator_id: the coordinator jid :type coordinator_id: str
-
set_position
(coords=None)[source]¶ Sets the position of the taxi. If no position is provided it is located in a random position.
Parameters: coords (list) – a list coordinates (longitude and latitude)
-
set_route_agent
(route_id)[source]¶ Sets the route agent JID address :param route_id: the route agent jid :type route_id: str
-
set_speed
(speed_in_kmh)[source]¶ Sets the speed of the taxi.
Parameters: speed_in_kmh (float) – the speed of the taxi in km per hour
-
to_json
()[source]¶ Serializes the main information of a taxi agent to a JSON format. It includes the id of the agent, its current position, the destination coordinates of the agent, the current status, the speed of the taxi (in km/h), the path it is following (if any), the passenger that it has assigned (if any), the number of assignments if has done and the distance that the taxi has traveled.
Returns: a JSON doc with the main information of the taxi. Example:
{ "id": "cphillips", "position": [ 39.461327, -0.361839 ], "dest": [ 39.460599, -0.335041 ], "status": 24, "speed": 1000, "path": [[0,0], [0,1], [1,0], [1,1], ...], "passenger": "ghiggins@127.0.0.1", "assignments": 2, "distance": 3481.34 }
Return type: dict
-
class
-
class
taxi_simulator.taxi.
TaxiStrategyBehaviour
[source]¶ Bases:
taxi_simulator.utils.StrategyBehaviour
Class from which to inherit to create a taxi strategy. You must overload the
`run
coroutine- Helper functions:
pick_up_passenger
send_proposal
cancel_proposal
-
cancel_proposal
(passenger_id, content=None)[source]¶ Send a
spade.message.Message
to cancel a proposal. If the content is empty the proposal is sent without content.Parameters: - passenger_id (str) – the id of the passenger
- content (dict, optional) – the optional content of the message
-
pick_up_passenger
(passenger_id, origin, dest)[source]¶ Starts a TRAVEL_PROTOCOL to pick up a passenger and get him to his destination. It automatically launches all the travelling process until the passenger is delivered. This travelling process includes to update the taxi coordinates as it moves along the path at the specified speed.
Parameters: - passenger_id (str) – the id of the passenger
- origin (list) – the coordinates of the current location of the passenger
- dest (list) – the coordinates of the target destination of the passenger
-
send_proposal
(passenger_id, content=None)[source]¶ Send a
spade.message.Message
with a proposal to a passenger to pick up him. If the content is empty the proposal is sent without content.Parameters: - passenger_id (str) – the id of the passenger
- content (dict, optional) – the optional content of the message
taxi_simulator.utils module¶
-
class
taxi_simulator.utils.
RequestRouteBehaviour
(msg: spade.message.Message, origin: list, destination: list, route_agent: str)[source]¶ Bases:
spade.behaviour.OneShotBehaviour
A one-shot behaviour that is executed to request for a new route to the route agent.
-
class
taxi_simulator.utils.
StrategyBehaviour
[source]¶ Bases:
spade.behaviour.CyclicBehaviour
The behaviour that all parent strategies must inherit from. It complies with the Strategy Pattern.
-
taxi_simulator.utils.
avg
(array)[source]¶ Makes the average of an array without Nones. :param array: a list of floats and Nones :type array: list
Returns: the average of the list without the Nones. Return type: float
-
taxi_simulator.utils.
chunk_path
(path, speed_in_kmh)[source]¶ Splits the path into smaller chunks taking into account the speed.
Parameters: - path (list) – the original path. A list of points (lon, lat)
- speed_in_kmh (float) – the speed in km per hour at which the path is being traveled.
Returns: a new path equivalent (to the first one), that has at least the same number of points.
Return type: list
-
taxi_simulator.utils.
load_class
(class_path)[source]¶ Tricky method that imports a class form a string.
Parameters: class_path (str) – the path where the class to be imported is. Returns: the class imported and ready to be instantiated. Return type: class
-
taxi_simulator.utils.
request_path
(agent, origin, destination, route_id)[source]¶ Sends a message to the RouteAgent to request a path
Parameters: - agent – the agent who is requesting the path
- origin (list) – a list with the origin coordinates [longitude, latitude]
- destination (list) – a list with the target coordinates [longitude, latitude]
- route_id (str) – name of the route agent
Returns: - a list of points (longitude and latitude) representing the path,
the distance of the path in meters, a estimation of the duration of the path
Return type: list, float, float
Examples
>>> path, distance, duration = request_path(an_agent, origin=[0,0], destination=[1,1]) >>> print(path) [[0,0], [0,1], [1,1]] >>> print(distance) 2.0 >>> print(duration) 3.24
Module contents¶
Top-level package for Taxi Simulator.