simfleet package

Submodules

simfleet.cli module

Console script for SimFleet.

simfleet.config module

class simfleet.config.SimfleetConfig(filename=None, name=None, max_time=None, verbose=None)[source]

Bases: object

A scenario object reads a file with a JSON representation of a scenario and is used to create the participant agents.

load_config(filename)[source]
num_customers
num_managers
num_stations
num_transport
simfleet.config.hide_passwords(item, key=None)[source]

simfleet.customer module

class simfleet.customer.CustomerAgent(agentjid, password)[source]

Bases: spade.agent.Agent

get_pickup_time()[source]

Returns the time that the customer was waiting to be picked up since it has been assigned to a transport.

Returns:The time that the customer was waiting to a transport since it has been assigned.
Return type:float
get_position()[source]

Returns the current position of the customer.

Returns:the coordinates of the current position of the customer (lon, lat)
Return type:list
get_waiting_time()[source]

Returns the time that the agent was waiting for a transport, from its creation until it gets into a transport.

Returns:The time the customer was waiting.
Return type:float
is_in_destination()[source]

Checks if the customer has arrived to its destination.

Returns:whether the customer is at its destination or not
Return type:bool
is_ready()[source]
request_path(origin, destination)[source]

Requests a path between two points (origin and destination) using the route server.

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
run_strategy()[source]

import json Runs the strategy for the customer agent.

set_directory(directory_id)[source]

Sets the directory JID address :param directory_id: the DirectoryAgent jid :type directory_id: str

set_fleet_type(fleet_type)[source]

Sets the type of fleet to be used.

Parameters:fleet_type (str) – the type of the fleet to be used
set_fleetmanager(fleetmanagers)[source]

Sets the fleetmanager JID address :param fleetmanagers: the fleetmanager jid :type fleetmanagers: str

set_icon(icon)[source]
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 customer. If no position is provided it is located in a random position.

Parameters:coords (list) – a list coordinates (longitude and latitude)
set_route_host(route_host)[source]

Sets the route host server address :param route_host: the route host server address :type route_host: str

set_target_position(coords=None)[source]

Sets the target position of the customer (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)
setup()[source]

Setup agent before startup. This coroutine may be overloaded.

to_json()[source]

Serializes the main information of a customer 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 transport that it has assigned (if any) and its waiting time.

Returns:a JSON doc with the main information of the customer.

Example:

{
    "id": "cphillips",
    "position": [ 39.461327, -0.361839 ],
    "dest": [ 39.460599, -0.335041 ],
    "status": 24,
    "transport": "ghiggins@127.0.0.1",
    "waiting": 13.45
}
Return type:dict
total_time()[source]

Returns the time since the customer was activated until it reached its destination.

Returns:the total time of the customer’s simulation.
Return type:float
class simfleet.customer.CustomerStrategyBehaviour[source]

Bases: simfleet.utils.StrategyBehaviour

Class from which to inherit to create a transport strategy. You must overload the run coroutine

Helper functions:
  • send_request
  • accept_transport
  • refuse_transport
accept_transport(transport_id)[source]

Sends a spade.message.Message to a transport to accept a travel proposal. It uses the REQUEST_PROTOCOL and the ACCEPT_PERFORMATIVE.

Parameters:transport_id (str) – The Agent JID of the transport
on_start()[source]

Initializes the logger and timers. Call to parent method if overloaded.

refuse_transport(transport_id)[source]

Sends an spade.message.Message to a transport to refuse a travel proposal. It uses the REQUEST_PROTOCOL and the REFUSE_PERFORMATIVE.

Parameters:transport_id (str) – The Agent JID of the transport
run()[source]

Body of the behaviour. To be implemented by user.

send_get_managers(content=None)[source]

Sends an spade.message.Message to the DirectoryAgent to request a managers. It uses the QUERY_PROTOCOL and the REQUEST_PERFORMATIVE. If no content is set a default content with the type_service that needs :param content: Optional content dictionary :type content: dict

send_request(content=None)[source]

Sends an spade.message.Message to the fleetmanager to request a transport. It uses the REQUEST_PROTOCOL and the REQUEST_PERFORMATIVE. If no content is set a default content with the customer_id, origin and target coordinates is used.

Parameters:content (dict) – Optional content dictionary
class simfleet.customer.TravelBehaviour[source]

Bases: spade.behaviour.CyclicBehaviour

This is the internal behaviour that manages the movement of the customer. It is triggered when the transport informs the customer that it is going to the customer’s position until the customer is dropped in its destination.

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

simfleet.directory module

class simfleet.directory.DirectoryAgent(agentjid, password)[source]

Bases: spade.agent.Agent

run_strategy()[source]

Runs the strategy for the directory agent.

set_id(agent_id)[source]

Sets the agent identifier

Parameters:agent_id (str) – The new agent id
setup()[source]

Setup agent before startup. This coroutine may be overloaded.

class simfleet.directory.DirectoryStrategyBehaviour[source]

Bases: simfleet.utils.StrategyBehaviour

Class from which to inherit to create a directory strategy.

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

send_negative(agent_id)[source]

Sends a message to the current assigned manager/station to cancel the registration.

Parameters:agent_id (str) – the id of the manager/station
send_services(agent_id, type_service)[source]

Send a message to the customer or transport with the current information of the type of service they need.

Parameters:
  • agent_id (str) – the id of the manager/station
  • type_service (str) – the type of service
class simfleet.directory.RegistrationBehaviour[source]

Bases: spade.behaviour.CyclicBehaviour

add_service(content)[source]

Adds a new service to the store.

Parameters:content (dict) – content to be added
on_start()[source]

Coroutine called before the behaviour is started.

remove_service(service_type, agent)[source]

Erase a service from the store.

Parameters:
  • service_type (str) – the service type to be erased
  • agent (str) – an str with the jid of the agent to be erased
run()[source]

Body of the behaviour. To be implemented by user.

send_confirmation(agent_id)[source]

Send a spade.message.Message with an acceptance to manager/station to register in the dictionary

simfleet.fleetmanager module

class simfleet.fleetmanager.FleetManagerAgent(agentjid, password)[source]

Bases: spade.agent.Agent

FleetManager agent that manages the requests between transports and customers

clear_agents()[source]

Resets the set of transports and customers. Resets the simulation clock.

is_ready()[source]
run_strategy()[source]

Runs the strategy for the transport agent.

set_directory(directory_id)[source]

Sets the directory JID address :param directory_id: the DirectoryAgent jid :type directory_id: str

set_fleet_type(fleet_type)[source]

Sets the type of service to the fleet :param type_service: type of service :type type_service: str

set_icon(icon)[source]
set_id(agent_id)[source]

Sets the agent identifier

Parameters:agent_id (str) – The new Agent Id
set_registration(status)[source]

Sets the status of registration :param status: True if the transport agent has registered or False if not :type status: boolean

setup()[source]

Setup agent before startup. This coroutine may be overloaded.

class simfleet.fleetmanager.FleetManagerStrategyBehaviour[source]

Bases: simfleet.utils.StrategyBehaviour

Class from which to inherit to create a coordinator strategy. You must overload the _process() method

Helper functions:
get_transport_agents()[source]

Gets the list of registered transports

Returns:a list of TransportAgent
Return type:list
on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

send_registration()[source]

Send a spade.message.Message with a proposal to directory to register.

class simfleet.fleetmanager.TransportRegistrationForFleetBehaviour[source]

Bases: spade.behaviour.CyclicBehaviour

accept_registration(agent_id)[source]

Send a spade.message.Message with an acceptance to transport to register in the fleet.

add_transport(agent)[source]

Adds a new TransportAgent to the store.

Parameters:agent (TransportAgent) – the instance of the TransportAgent to be added
on_start()[source]

Coroutine called before the behaviour is started.

reject_registration(agent_id)[source]

Send a spade.message.Message with an acceptance to transport to register in the fleet.

remove_transport(key)[source]

Erase a TransportAgent to the store.

Parameters:agent (TransportAgent) – the instance of the TransportAgent to be erased
run()[source]

Body of the behaviour. To be implemented by user.

simfleet.helpers module

Helpers module

These functions are useful for the develop of new strategies.

exception simfleet.helpers.AlreadyInDestination[source]

Bases: Exception

This exception is raised when an agent wants to move to a destination where it is already there.

exception simfleet.helpers.PathRequestException[source]

Bases: Exception

This exception is raised when a path could not be computed.

simfleet.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

simfleet.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

simfleet.helpers.kmh_to_ms(speed_in_kmh)[source]

Convert kilometers/hour to meters/second.

Parameters:speed_in_kmh (float) – speed in kilometers/hour
Returns:the speed in meters/second
Return type:float
simfleet.helpers.random_position()[source]

Returns a random position inside the map.

Returns:a point (longitude and latitude)
Return type:list

simfleet.protocol module

protocol and performative constants

simfleet.simulator module

class simfleet.simulator.DelayedLaunchBehaviour(agents, *args, **kwargs)[source]

Bases: spade.behaviour.TimeoutBehaviour

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.simulator.SimulatorAgent(config, agentjid='simulator@localhost', password='simulator123j3')[source]

Bases: spade.agent.Agent

The Simulator. It manages all the simulation processes. Tasks done by the simulator at initialization:

  1. Create the XMPP server
  2. Run the SPADE backend
  3. Run the directory agent.
  4. 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.

add_customer(agent)[source]

Adds a new CustomerAgent to the store.

Parameters:agent (CustomerAgent) – the instance of the CustomerAgent to be added
add_manager(agent)[source]

Adds a new FleetManagerAgent to the store.

Parameters:agent (FleetManagerAgent) – the instance of the FleetManagerAgent to be added
add_station(agent)[source]

Adds a new StationAgent to the store.

Parameters:agent (StationAgent) – the instance of the StationAgent to be added
add_transport(agent)[source]

Adds a new TransportAgent to the store.

Parameters:agent (TransportAgent) – the instance of the TransportAgent to be added
all_customers_in_destination()[source]

Checks whether the simulation has finished or not. A simulation is finished if all customers are at their destinations. If there is no customers the simulation is not finished.

Returns:`
bool: whether the simulation has finished or not.
assigning_fleet_icon(fleet_type, default=None)[source]
async_create_agents_batch_customer(agents: list) → List[source]
async_create_agents_batch_station(agents: list) → List[source]
async_create_agents_batch_transport(agents: list) → List[source]
async_start_agent(agent)[source]
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_agents()[source]

Resets the set of transports and customers. Resets the simulation clock.

clear_stopped_agents()[source]

Removes from the transport and customer sets every agent that is stopped.

collect_stats()[source]

Collects stats from all participant agents and from the simulation and stores it in three dataframes.

create_customer_agent(name, password, fleet_type, position, strategy=None, target=None, delayed=False)[source]

Create a customer agent.

Parameters:
  • name (str) – name of the agent
  • password (str) – password of the agent
  • fleet_type (str) – type of he fleet to be or demand
  • position (list) – initial coordinates of the agent
  • strategy (class, optional) – strategy class of the agent
  • target (list, optional) – destination coordinates of the agent
  • delayed (bool, optional) – launching of the agent delayed or not
create_directory_agent(name, password)[source]
create_fleetmanager_agent(name, password, fleet_type, strategy=None, icon=None)[source]
create_station_agent(name, password, position, power, places, strategy=None)[source]

Create a customer agent.

Parameters:
  • name (str) – name of the agent
  • password (str) – password of the agent
  • position (list) – initial coordinates of the agent
  • power (int) – power of the station agent in kW
  • places (int) – destination coordinates of the agent
  • strategy (class, optional) – strategy class of the agent
create_transport_agent(name, password, fleet_type, fleetmanager, position, strategy=None, speed=None, autonomy=None, current_autonomy=None, delayed=False)[source]
customer_agents

Gets the dict of registered customers

Returns:a dict of CustomerAgent with the name in the key
Return type:dict
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:

{
    "customers": [
        {
            "status": 24,
            "transport": "transport2@127.0.0.1",
            "dest": [ 39.463356, -0.376463 ],
            "waiting": 3.25,
            "position": [ 39.460568, -0.352529 ],
            "id": "michaelstewart"
        }
    ],
    "transports": [
        {
            "status": 11,
            "customer": "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": "transport2",
            "distance": "6754.60"
        }
    ],
    "stats": {
        "totaltime": "-1.00",
        "waiting": "3.25",
        "finished": False,
        "is_running": True
    },
    "tree": {
        "name": "Agents",
        "children": [
            {
                "count": "1",
                "name": "Transports",
                "children": [ { "status": 11, "name": " transport2", "icon": "fa-transport" } ]
            },
            {
                "count": "1",
                "name": "Customers",
                "children": [ { "status": 24, "name": " michaelstewart", "icon": "fa-user" } ]
            }
        ]
    },
    "authenticated": False,
    "stations": [
        {
            "status": 24,
            "position": [ 39.460568, -0.352529 ],
            "id": "michaelstewart"
        }
    ],
}
Returns:no template is returned since this is an AJAX controller, a dict with the list of transports, the list of customers, the tree view to be showed in the sidebar and the stats of the simulation.
Return type:dict
gather_batch(all_coroutines)[source]
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_customer_stats()[source]

Creates a dataframe with the simulation stats of the customers The dataframe includes for each customer its name, waiting time, total time and status.

Returns:the dataframe with the customers stats.
Return type:pandas.DataFrame
get_directory()[source]
get_manager_stats()[source]

Creates a dataframe with the simulation stats of the customers The dataframe includes for each customer its name, waiting time, total time and status.

Returns:the dataframe with the customers 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_station_stats()[source]

Creates a dataframe with the simulation stats of the customers The dataframe includes for each customer its name, waiting time, total time and status.

Returns:the dataframe with the customers stats.
Return type:pandas.DataFrame
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 transport’s information and a dataframe with the customer’s information. :returns: avg df, transport df and customer df :rtype: pandas.Dataframe, pandas.Dataframe, pandas.Dataframe

get_transport_stats()[source]

Creates a dataframe with the simulation stats of the transports The dataframe includes for each transport its name, assignments, traveled distance and status.

Returns:the dataframe with the transports 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
init_controller(request)[source]
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 fleetmanager says it.

Returns:whether the simulation is finished or not.
Return type:bool
load_icons(filename)[source]
load_scenario()[source]

Load the information from the preloaded scenario through the SimfleetConfig class

manager_agents

Gets the dict of registered FleetManager

Returns:a dict of FleetManagerAgents with the name in the key
Return type:dict
print_stats()[source]

Prints the dataframes collected by collect_stats.

request_path(origin, destination)[source]

Requests a path to the route server.

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()[source]

Starts the simulation

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_default_strategies(fleetmanager_strategy, transport_strategy, customer_strategy, directory_strategy, station_strategy)[source]

Gets the strategy strings and loads their classes. This strategies are prepared to be injected into any new transport or customer agent.

Parameters:
  • fleetmanager_strategy (str) – the path to the fleetmanager strategy
  • transport_strategy (str) – the path to the transport strategy
  • customer_strategy (str) – the path to the customer strategy
  • directory_strategy (str) – the path to the directory strategy
  • station_strategy (str) – the path to the station strategy
set_directory(agent)[source]
set_icon(agent, icon, default=None)[source]
setup()[source]

Setup agent before startup. This coroutine may be overloaded.

station_agents

Gets the dict of registered stations

Returns:a dict of StationAgent with the name in the key
Return type:dict
stop()[source]

Finishes the simulation and prints simulation stats. Tasks done when a simulation is stopped:

  1. Stop participant agents.
  2. Print stats.
  3. Stop fleetmanager agent.
stop_agents()[source]

Stops the simulator and all the agents

stop_agents_controller(request)[source]

Web controller that stops all the customer and transport agents.

Returns:no template is returned since this is an AJAX controller, a dict with status=done
Return type:dict
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
transport_agents

Gets the dict of registered transports

Returns:a dict of TransportAgent with the name in the key
Return type:dict
write_excel(filename)[source]

Writes the collected data by collect_stats in an excel file.

Parameters:filename (str) – name of the excel file.
write_file(filename, fileformat='json')[source]

Writes the dataframes collected by collect_stats in JSON or Excel format.

Parameters:
  • filename (str) – name of the output file to be written.
  • fileformat (str) – format of the output file. Choices: json or excel
write_json(filename)[source]

Writes the collected data by collect_stats in a json file.

Parameters:filename (str) – name of the json file.

simfleet.station module

class simfleet.station.ChargeBehaviour(start_at, transport_id)[source]

Bases: spade.behaviour.TimeoutBehaviour

charging_complete()[source]

Send a message to the transport agent that the vehicle load has been completed

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.station.RegistrationBehaviour[source]

Bases: spade.behaviour.CyclicBehaviour

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

send_registration()[source]

Send a spade.message.Message with a proposal to directory to register.

set_registration(decision)[source]
class simfleet.station.StationAgent(agentjid, password)[source]

Bases: spade.agent.Agent

assigning_place()[source]

Set a space in the charging station for the transport that has been accepted, when the available spaces are zero, the status will change to BUSY_STATION

charging_transport(need, transport_id)[source]
deassigning_place()[source]

Leave a space of the charging station, when the station has free spaces, the status will change to FREE_STATION

get_available_places()[source]
get_position()[source]

Returns the current position of the station.

Returns:the coordinates of the current position of the customer (lon, lat)
Return type:list
get_power()[source]
get_status()[source]
is_ready()[source]
run_strategy()[source]

Sets the strategy for the transport agent.

send(msg)[source]
set_available_places(places)[source]
set_directory(directory_id)[source]

Sets the directory JID address :param directory_id: the DirectoryAgent jid :type directory_id: str

set_icon(icon)[source]
set_id(agent_id)[source]

Sets the agent identifier

Parameters:agent_id (str) – The new Agent Id
set_position(coords=None)[source]

Sets the position of the station. If no position is provided it is located in a random position.

Parameters:coords (list) – a list coordinates (longitude and latitude)
set_power(charge)[source]
set_registration(status)[source]

Sets the status of registration :param status: True if the transport agent has registered or False if not :type status: boolean

set_status(state='FREE_STATION')[source]
set_type(station_type)[source]
setup()[source]

Setup agent before startup. This coroutine may be overloaded.

to_json()[source]

Serializes the main information of a station 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 transport that it has assigned (if any) and its waiting time.

Returns:a JSON doc with the main information of the station.

Example:

{
    "id": "cphillips",
    "position": [ 39.461327, -0.361839 ],
    "status": True,
    "places": 10,
    "power": 10
}
Return type:dict
class simfleet.station.StationStrategyBehaviour[source]

Bases: simfleet.utils.StrategyBehaviour

Class from which to inherit to create a station strategy. You must overload the run() method

Helper functions:
  • get_transport_agents()
accept_transport(transport_id)[source]

Sends a spade.message.Message to a transport to accept a travel proposal for charge. It uses the REQUEST_PROTOCOL and the ACCEPT_PERFORMATIVE.

Parameters:transport_id (str) – The Agent JID of the transport
on_start()[source]

Coroutine called before the behaviour is started.

refuse_transport(transport_id)[source]

Sends an spade.message.Message to a transport to refuse a travel proposal for charge. It uses the REQUEST_PROTOCOL and the REFUSE_PERFORMATIVE.

Parameters:transport_id (str) – The Agent JID of the transport
run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.station.TravelBehaviour[source]

Bases: spade.behaviour.CyclicBehaviour

This is the internal behaviour that manages the inform of the station. It is triggered when the transport informs the station that it is going to the customer’s position until the customer is droppped in its destination.

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

simfleet.strategies module

class simfleet.strategies.AcceptAlwaysStrategyBehaviour[source]

Bases: simfleet.transport.TransportStrategyBehaviour

The default strategy for the Transport agent. By default it accepts every request it receives if available.

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.strategies.AcceptFirstRequestBehaviour[source]

Bases: simfleet.customer.CustomerStrategyBehaviour

The default strategy for the Customer agent. By default it accepts the first proposal it receives.

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.strategies.DelegateRequestBehaviour[source]

Bases: simfleet.fleetmanager.FleetManagerStrategyBehaviour

The default strategy for the FleetManager agent. By default it delegates all requests to all transports.

run()[source]

Body of the behaviour. To be implemented by user.

simfleet.strategies_fsm module

class simfleet.strategies_fsm.AcceptFirstRequestBehaviour[source]

Bases: simfleet.customer.CustomerStrategyBehaviour

The default strategy for the Customer agent. By default it accepts the first proposal it receives.

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.strategies_fsm.DelegateRequestBehaviour[source]

Bases: simfleet.fleetmanager.FleetManagerStrategyBehaviour

The default strategy for the FleetManager agent. By default it delegates all requests to all transports.

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.strategies_fsm.FSMTransportStrategyBehaviour[source]

Bases: spade.behaviour.FSMBehaviour

setup()[source]
class simfleet.strategies_fsm.TransportChargingState[source]

Bases: simfleet.transport.TransportStrategyBehaviour, spade.behaviour.State

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.strategies_fsm.TransportInStationState[source]

Bases: simfleet.transport.TransportStrategyBehaviour, spade.behaviour.State

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.strategies_fsm.TransportMovingToCustomerState[source]

Bases: simfleet.transport.TransportStrategyBehaviour, spade.behaviour.State

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.strategies_fsm.TransportMovingToStationState[source]

Bases: simfleet.transport.TransportStrategyBehaviour, spade.behaviour.State

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.strategies_fsm.TransportNeedsChargingState[source]

Bases: simfleet.transport.TransportStrategyBehaviour, spade.behaviour.State

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.strategies_fsm.TransportWaitingForApprovalState[source]

Bases: simfleet.transport.TransportStrategyBehaviour, spade.behaviour.State

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.strategies_fsm.TransportWaitingState[source]

Bases: simfleet.transport.TransportStrategyBehaviour, spade.behaviour.State

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

simfleet.transport module

class simfleet.transport.RegistrationBehaviour[source]

Bases: spade.behaviour.CyclicBehaviour

on_start()[source]

Coroutine called before the behaviour is started.

run()[source]

Body of the behaviour. To be implemented by user.

send_registration()[source]

Send a spade.message.Message with a proposal to manager to register.

class simfleet.transport.TransportAgent(agentjid, password)[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 transport. It is triggered when the transport 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 transport coordinates as it moves along the path at the specified speed.

run()[source]

Body of the behaviour. To be implemented by user.

arrived_to_destination()[source]

Informs that the transport has arrived to its destination. It recomputes the new destination and path if picking up a customer or drops it and goes to WAITING status again.

arrived_to_station(station_id=None)[source]

Informs that the transport has arrived to its destination. It recomputes the new destination and path if picking up a customer or drops it and goes to WAITING status again.

begin_charging()[source]
calculate_km_expense(origin, start, dest=None)[source]
cancel_customer(data=None)[source]

Sends a message to the current assigned customer to cancel the assignment.

Parameters:data (dict, optional) – Complementary info about the cancellation
drop_customer()[source]

Drops the customer that the transport is carring in the current location.

drop_station()[source]

Drops the customer that the transport is carring in the current location.

get_autonomy()[source]
get_position()[source]

Returns the current position of the customer.

Returns:the coordinates of the current position of the customer (lon, lat)
Return type:list
inform_customer(status, data=None)[source]

Sends a message to the current assigned customer to inform her about a new status.

Parameters:
  • status (int) – The new status code
  • data (dict, optional) – complementary info about the status
inform_station(data=None)[source]

Sends a message to the current assigned customer to inform her about a new status.

Parameters:
  • status (int) – The new status code
  • data (dict, optional) – complementary info about the status
is_customer_in_transport()[source]
is_free()[source]
is_in_destination()[source]

Checks if the transport has arrived to its destination.

Returns:whether the transport is at its destination or not
Return type:bool
is_ready()[source]
move_to(dest)[source]

Moves the transport to a new destination.

Parameters:dest (list) – the coordinates of the new destination (in lon, lat format)
Raises:AlreadyInDestination – if the transport is already in the destination coordinates.
needs_charging()[source]
request_access_station()[source]
request_path(origin, destination)[source]

Requests a path between two points (origin and destination) using the route server.

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
run_strategy()[source]

Sets the strategy for the transport agent.

Parameters:strategy_class (TransportStrategyBehaviour) – The class to be used. Must inherit from TransportStrategyBehaviour
send(msg)[source]
set(key, value)[source]

Stores a knowledge item in the agent knowledge base.

Parameters:
  • name (str) – name of the item
  • value (object) – value of the item
set_autonomy(autonomy, current_autonomy=None)[source]
set_directory(directory_id)[source]

Sets the directory JID address :param directory_id: the DirectoryAgent jid :type directory_id: str

set_fleet_type(fleet_type)[source]
set_fleetmanager(fleetmanager_id)[source]

Sets the fleetmanager JID address :param fleetmanager_id: the fleetmanager jid :type fleetmanager_id: str

set_icon(icon)[source]
set_id(agent_id)[source]

Sets the agent identifier

Parameters:agent_id (str) – The new Agent Id
set_initial_position(coords)[source]
set_km_expense(expense=0)[source]
set_position(coords=None)[source]

Sets the position of the transport. If no position is provided it is located in a random position.

Parameters:coords (list) – a list coordinates (longitude and latitude)
set_registration(status, content=None)[source]

Sets the status of registration :param status: True if the transport agent has registered or False if not :type status: boolean :param content: :type content: dict

set_route_host(route_host)[source]

Sets the route host server address :param route_host: route host server address :type route_host: str

set_speed(speed_in_kmh)[source]

Sets the speed of the transport.

Parameters:speed_in_kmh (float) – the speed of the transport in km per hour
setup()[source]

Setup agent before startup. This coroutine may be overloaded.

sleep(seconds)[source]
step()[source]

Advances one step in the simulation

to_json()[source]

Serializes the main information of a transport 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 transport (in km/h), the path it is following (if any), the customer that it has assigned (if any), the number of assignments if has done and the distance that the transport has traveled.

Returns:a JSON doc with the main information of the transport.

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], ...],
    "customer": "ghiggins@127.0.0.1",
    "assignments": 2,
    "distance": 3481.34
}
Return type:dict
transport_charged()[source]
watch_value(key, callback)[source]

Registers an observer callback to be run when a value is changed

Parameters:
  • key (str) – the name of the value
  • callback (function) – a function to be called when the value changes. It receives two arguments: the old and the new value.
class simfleet.transport.TransportStrategyBehaviour[source]

Bases: simfleet.utils.StrategyBehaviour

Class from which to inherit to create a transport strategy. You must overload the `run coroutine

Helper functions:
  • pick_up_customer
  • send_proposal
  • cancel_proposal
cancel_proposal(customer_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:
  • customer_id (str) – the id of the customer
  • content (dict, optional) – the optional content of the message
charge_allowed()[source]
check_and_decrease_autonomy(customer_orig, customer_dest)[source]
go_to_the_station(station_id, dest)[source]

Starts a TRAVEL_PROTOCOL to pick up a customer and get him to his destination. It automatically launches all the travelling process until the customer is delivered. This travelling process includes to update the transport coordinates as it moves along the path at the specified speed.

Parameters:
  • station_id (str) – the id of the customer
  • dest (list) – the coordinates of the target destination of the customer
has_enough_autonomy(customer_orig, customer_dest)[source]
on_start()[source]

Coroutine called before the behaviour is started.

pick_up_customer(customer_id, origin, dest)[source]

Starts a TRAVEL_PROTOCOL to pick up a customer and get him to his destination. It automatically launches all the travelling process until the customer is delivered. This travelling process includes to update the transport coordinates as it moves along the path at the specified speed.

Parameters:
  • customer_id (str) – the id of the customer
  • origin (list) – the coordinates of the current location of the customer
  • dest (list) – the coordinates of the target destination of the customer
run()[source]

Body of the behaviour. To be implemented by user.

send_confirmation_travel(station_id)[source]
send_get_stations(content=None)[source]
send_proposal(customer_id, content=None)[source]

Send a spade.message.Message with a proposal to a customer to pick up him. If the content is empty the proposal is sent without content.

Parameters:
  • customer_id (str) – the id of the customer
  • content (dict, optional) – the optional content of the message

simfleet.utils module

class simfleet.utils.RequestRouteBehaviour(msg: spade.message.Message, origin: list, destination: list, route_host: str)[source]

Bases: spade.behaviour.OneShotBehaviour

A one-shot behaviour that is executed to request for a new route to the route agent.

run()[source]

Body of the behaviour. To be implemented by user.

class simfleet.utils.StrategyBehaviour[source]

Bases: spade.behaviour.CyclicBehaviour

The behaviour that all parent strategies must inherit from. It complies with the Strategy Pattern.

simfleet.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
simfleet.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

simfleet.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
simfleet.utils.request_path(agent, origin, destination, route_host)[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_host (str) – name of the route host server
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(agent, origin=[0,0], destination=[1,1])
>>> print(path)
[[0,0], [0,1], [1,1]]
>>> print(distance)
2.0
>>> print(duration)
3.24
simfleet.utils.request_route_to_server(origin, destination, route_host='http://router.project-osrm.org/')[source]

Queries the OSRM for a path.

Parameters:
  • origin (list) – origin coordinate (longitude, latitude)
  • destination (list) – target coordinate (longitude, latitude)
  • route_host (string) – route to host server of OSRM service
Returns:

list, float, float = the path, the distance of the path and the estimated duration

simfleet.utils.status_to_str(status_code)[source]

Translates an int status code to a string that represents the status

Parameters:status_code (int) – the code of the status
Returns:the string that represents the status
Return type:str
simfleet.utils.unused_port(hostname)[source]

Return a port that is unused on the current host.

Module contents

Top-level package for SimFleet.