Simulation

The simulation module is home to the core class in fdsim: the Simulator. The Simulator is the main interface for setting up simulation runs and experiments and takes care of employing other classes and modules when necessary.

class simulation.Simulator(incidents, deployments, stations, resource_allocation, load_response_data=True, load_time_matrix=True, save_response_data=False, save_time_matrix=False, vehicle_types=['TS', 'RV', 'HV', 'WO'], location_coords=None, predictor='basic', max_target=18, start_time=None, end_time=None, data_dir='data', osrm_host='http://192.168.56.101:5000', location_col='hub_vak_bk', big_vehicles=['TS'], big_min_ts=3, big_types=['Binnenbrand', 'Buitenbrand', 'Hulpverlening algemeen'], verbose=True)[source]

Main simulator class that simulates incidents and reponses at the fire department.

Parameters:
  • incidents (pd.DataFrame) – The incident data.
  • deployments (pd.DataFrame) – The deployment data.
  • stations (pd.DataFrame) – The station information including coordinates and station names.
  • resource_allocation (pd.DataFrame) – The allocation of vehicles and crews to stations. Expected columns: [“kazerne”, “TS”, “RV”, “HV”, “WO”, “TS_crew_ft”, “TS_crew_pt”, “RVHV_crew_ft”, “RVHV_crew_pt”, “WO_crew_ft”, “WO_crew_pt”].
  • load_response_data (boolean, optional) – Whether to load preprocessed response data from disk (True) or to calculate it using OSRM.
  • load_time_matrix (boolean, optional) – Whether to load the matrix of travel durations from disk (True) or to calculate it using OSRM.
  • save_response_data (boolean, optional) – Whether to save the prepared response data with OSRM estimates to disk.
  • save_time_matrix (boolean, optional) – Whether to save the matrix of travel durations to disk.
  • vehicle_types (array-like of strings, optional) – The vehicle types to incorporate in the simulation. Optional, defaults to [“TS”, “RV”, “HV”, “WO”].
  • location_coords (dict, optional) – The coordinates of all relevant locations like {‘loc’ -> (lon, lat)}. The keys (locations) must be strings.
  • predictor (str, optional) – Type of predictor to use. Defaults to ‘prophet’, which uses Facebook’s Prophet package to forecast incident rate per incident type based on trend and yearly, weekly, and daily patterns.
  • max_target (int, optional, default: 18) – The maximum response time target in minutes. This is used as the target for priority 1 incidents that do not have a more strict norm (i.e., fires).
  • start_time (Timestamp or str (convertible to timestamp), optional) – The start of the time period to simulate. If None, forecasts from the end of the data. Defaults to None.
  • end_time (Timestamp or str (convertible to timestamp), optional) – The end of the time period to simulate. If None, forecasts until one year after the end of the data. Defaults to None.
  • data_dir (str, optional) – The path to the directory where data should be loaded from and saved to. Defaults to ‘/data/’.
  • osrm_host (str, optional) – URL to the OSRM API, defaults to ‘http://192.168.56.101:5000
  • location_col (str, optional) – The name of the column that identifies the demand locations, defaults to ‘hub_vak_bk’. This is also the only currently supported value.
  • verbose (boolean, optional) – Whether to print progress updates to the console during computations.

Examples

The Simulator class takes four datasets as inputs. One with historic incidents, one with historic deployments, one with station locations, and one with the resources available at each station. After providing this information, a simulation is performed in just a single line of code.

>>> from fdsim.simulation import Simulator
>>> sim = Simulator(incidents, deployments, stations, resource_allocation)
>>> sim.simulate_n_incidents(10000)
>>> # save the simulated incidents and deployments
>>> sim.save_log("simulation_results.csv")
>>> # Continue simulating where you left of:
>>> sim.simulate_n_incidents(10000, restart=False)

You can save the simulor object after initializing, so that next time you can skip the initialization.

>>> sim.save_simulator_object()
>>> from fdsim.helpers import quick_load_simulator
>>> sim = quick_load_simulator('simulator.pickle')
activate_backup_protocol(station_name, vehicle_types=None)[source]

Let the part time crew at a station come to the station when the full time crew is dispatched in order to minimize response times for a second incident.

Parameters:
  • station_name (str) – The name of the station for which to use the backup protocol in capitalized letters (e.g., “VICTOR”, “AMSTELVEEN”, …).
  • vehicle_types (array-like of str or None, optional, default: None) – The vehicle types for which to apply the backup protocol. Available types are [“TS”, “HV”, “RV”, “WO”]. If None, applies it to all types.
add_station(station_name, location, **resources)[source]

Add a new fire station at a specified location without changing existing stations.

Parameters:
  • station_name (str) – The name of the new station.
  • location (str) – The identifier of the demand location to put the new station in.
  • **resources (key-value pairs) – Resources to assign to the station. Keys must match the columns of ‘resource_allocation’ and values must be integers.
fast_relocate_vehicle(vehicle_type, origin, destination)[source]

Relocate a vehicle form one station to another. The vehicle must be available and will remain available, but just from a different location.

In contrast to the relocate_vehicle method, this method completely ignores the availability of crews and does not udpate the crews either. This makes it faster, but means it is only correct when every vehicle has its own dedicated full time crew.

Parameters:
  • vehicle_type (str, one of ['TS', 'RV', 'HV', 'WO']) – The type of vehicle that should be relocated.
  • origin (str) – The name of the station from which a vehicle should be moved.
  • destination (str) – The name of the station the vehicle should be moved to.
fast_simulate_big_incident(forced_num_ts=None)[source]

Simulate a big incident at a random time in a random place. This method is mostly useful to create a low-coverage starting point for further simulation.

This method differs from self.simulate_big_incident in that it completely ignores the availability of crews. Essentially it assumes that every vehicles has its own dedicated full time crew. It also does not initialize a simulation log, but stores the major incident information in a dictionary self.major_incident_info.

Parameters:forced_num_ts (int, default=None) – A number of TS responses to force to the incident. Useful to manipulate the available vehicles to a specific number.
get_relocation_time(origin, destination)[source]

Get the travel time between two stations (useful for relocations).

This is a convenience method that links the input directly to self.dispatcher.get_relocation_time().

Parameters:destination (origin,) – The names of the stations.
Returns:time – The travel time betweent the two stations in seconds.
Return type:float
move_station(station_name, new_location, keep_name=True, new_name=None)[source]

Move an existing station to a new location.

Parameters:
  • station_name (str) – The name of the station to move.
  • new_location (str) – The identifier of the demand location to move the station to or the decimal longitude and latitude coordinates to move the station to.
  • keep_name (boolean, optional, default=True) – Whether to keep the current name of the station or not.
  • new_name (str, required if keep_name=False) – New name of the station. Ignored if keep_name=True.
relocate_vehicle(vehicle_type, origin, destination)[source]

Relocate a vehicle form one station to another. The vehicle must be available and will remain available, but just from a different location.

Parameters:
  • vehicle_type (str, one of ['TS', 'RV', 'HV', 'WO']) – The type of vehicle that should be relocated.
  • origin (str) – The name of the station from which a vehicle should be moved.
  • destination (str) – The name of the station the vehicle should be moved to.
remove_backup_protocol(station_name)[source]

Remove any backup protocols from a given station.

Parameters:station_name (str,) – The name of the station in all capital letters.
remove_station(station_name)[source]

Remove a fire station from the current set of stations.

Parameters:station_name (str) – The name of the station to remove.
reset_all_backup_protocols()[source]

Remove all backup protocols from all stations.

reset_simulation_period()[source]

Reset the start and end dates and times of the simulation period to the full range of the forecast.

reset_stations()[source]

Reset station locations and names to the original stations from the data.

save_log(file_name='simulation_results.csv')[source]

Save the current log file to disk.

Parameters:file_name (str, optional) – How to name the csv of the log. Default: ‘simulation_results.csv’.

Notes

File gets saved in the folder ‘data_dir’ that is specified on initialization of the Simulator.

save_simulator_object(path=None)[source]

Save the Simulator instance as a pickle for quick loading.

Saves the entire Simulator object as a pickle, so that it can be quickly loaded with all preprocessed attributes. Note: generator objects are not supported by pickle, so they have to be removed before dumping and re-initialized after loading. Therefore, always load the simulator with fdsim.helpers.quick_load_simulator.

Parameters:path (str, optional, default=None) – Where to save the file. If None, saves it in self.data_dir with the name simulator.pickle.

Notes

Requires the pickle package to be installed.

set_crews(station_name, vehicle_type, number, appointment='ft')[source]

Set the number of vehicles for a specific station and vehicle_type.

Parameters:
  • station_name (str) – The name of the station to change the vehicles for.
  • vehicle_type (str) – The type of vehicle to change the number of vehicles for.
  • number (int) – The new number of vehicles of vehicle_type to assign to the station.
  • appointment (str) – One of [‘ft’, “pt”] for full time or part time crew respectively.
set_custom_forecast(forecast, start_time=None, end_time=None)[source]

Manually provide a forecast to use during simulation.

Parameters:
  • forecast (pd.DataFrame) – Must have the same shape and columns as the output of self.isampler.predictor.get_forecast(). No assertions are made on this input.
  • end_time (start_time,) – The start and end time of the new sampling dictionary that will be created from the provided forecast. If None, uses the entire forecast.
set_daily_station_status(station_name, start_hour, end_hour, days_of_week=[0, 1, 2, 3, 4, 5, 6], status='closed', remove_previous=False)[source]

Close or operate a station in part time specified hours every week.

Parameters:
  • station_name (str) – The name of the station to close.
  • start_hour (int) – The hour of the day from which the station is closed.
  • end_hour (int) – The hour of the day from which the station is open.
  • days_of_week (array-like, optional, default=[0, 1, 2, 3, 4, 5, 6]) – The days of the week for which the status adjustment applies in zero-based integers (i.e., Monday = 0, Tuesday = 1, …, Sunday = 6).
  • status (str, one of ['closed', 'parttime'], optional, default='closed') – Whether the station should be completely closed or operating as a part time station during the specified hours.
  • remove_previous (boolean, optional, default=False) – Whether to reset previously set any closing times.

Notes

To set a certain status for the whole day(s), set start_hour and end_hour to the same value. It does not matter what value this is.

set_end_time(end_time)[source]

Set the end date and time of the simulation period.

Parameters:end_time (str or datetime object) – The new end time of the simulation. If providing a string, please make sure it is in a non-ambiguous format, such as “YYYY-MM-DD HH:mm:ss”.
set_location_incident_rates(loc, equal_to=None, value_dict=None, types=None)[source]

Set the incident rates of a location equal to that of one or more other locations.

Updating the incident rates works by changing the spatial distributions of incident types. The probabilities are first set to the given values, then they are normalized again to form a proper probability distribution. The forecast is updated accordingly, so that incident rates in other areas remain the same. This can be done using a dictionary of probabilities for each incident type or by setting the incident rate equal to that of one or more other locations.

Parameters:
  • loc (str) – The location to set the probabilities for.
  • equal_to (str or list(str)) – The location(s) from which to copy the incident rates. ignored if value_dict is provided.
  • value_dict (dict) – Dictionary specifying the incident types to change and the specific probability to set them to like {‘type’ -> prob}.
  • types (list(str)) – The incident types to change the probabilities of. If None, uses all. Ignored if a value_dict is provided.
set_max_target(target)[source]

Overwrite the default maximum response time target. The maximum target is used for all incident types that are not in ‘self.target_incident_types’.

By default, this value is set to 18 minutes as defined by Dutch Law.

Parameters:target (int) – The new response time target in minutes.
set_resource_allocation(resource_allocation)[source]

Assign custom allocation of vehicles to stations.

Parameters:resource_allocation (pd.DataFrame) – The allocation of vehicles and crews to stations. column names are vehicle types and row names (index) are station names. Alternatively, there is a column called ‘kazerne’ that specifies the station names. In the latter case, the index is ignored.
set_simulation_period(start_time, end_time)[source]

Change the start and end times of the simulation period.

Parameters:end_time (start_time,) – The new start and end times of the simulation. If providing a string, please make sure it is in a non-ambiguous format, such as “YYYY-MM-DD HH:mm:ss”.
set_start_time(start_time)[source]

Set the start date and time of the simulation period.

Parameters:start_time (str or datetime object) – The new start time of the simulation. If providing a string, please make sure it is in a non-ambiguous format, such as “YYYY-MM-DD HH:mm:ss”.
set_station_locations(station_locations, resource_allocation, station_names=None)[source]

Assign custom locations of fire stations.

Parameters:
  • station_locations (array-like of strings) – The demand locations that should get a fire station.
  • resource_allocation (pd.DataFrame) – The vehicles and crews to assign to each station. Every row corresponds to a station in the same order as station_locations and station_names.
  • station_names (array-like of strings, optional) – The custom names of the stations. If None, will use ‘STATION 1’, ‘STATION 2’, etc.
set_target_incident_types(types)[source]

Overwrite the default incident types for which object-dependent response time targets are computed.

By default, the simulator does this for inside fires and automatic fire alarms: [“Binnenbrand”, “OMS / automatische melding”].

Parameters:types (array-like of strings) – The incident types for which targets should be computed (if it is a priority 1 incident).
set_vehicles(station_name, vehicle_type, number)[source]

Set the number of vehicles for a specific station and vehicle_type.

Parameters:
  • station_name (str) – The name of the station to change the vehicles for.
  • vehicle_type (str) – The type of vehicle to change the number of vehicles for.
  • number (int) – The new number of vehicles of vehicle_type to assign to the station.
simulate_big_incident(forced_num_ts=None)[source]

Simulate a big incident at a random time in a random place. This method is mostly useful to create a low-coverage starting point for further simulation.

This method resets simulation logs and simulation time. The moment of the incident is considered t=0 and all vehicles are available at the time of the incident.

Parameters:forced_num_ts (int, default=None) – A number of TS responses to force to the incident. Useful to manipulate the available vehicles to a specific number.
simulate_n_incidents(N, restart=True)[source]

Simulate N incidents and their reponses.

Parameters:
  • N (int) – The number of incidents to simulate.
  • restart (boolean, optional, default=True) – Whether to empty the log and reset time before simulation (True) or to continue where stopped (False). Optional, defaults to True.
simulate_period(start_time=None, end_time=None, n=1, restart=True)[source]

Simulate a specific time period.

Parameters:
  • start_time (Timestamp or str, opional, default=None) – The start time of the simulation. Must be somewhere in the interval with which the simulator is initialized. If None, uses the start time with which the Simulator is initialized.
  • end)time (Timestamp or str, opional, default=None) – The end time of the simulation. Must be somewhere in the interval with which the simulator is initialized. If None, uses the end time with which the Simulator is initialized.
  • n (int, optional, default=1) – The number of runs, i.e., how many times to simulate the period.

Notes

-The simulation is started from a “base” state for all n simulation runs. This means all vehicles are available and at their base stations. -An additional column (run) is added to the log/results, denoting the number of the run/experiment.

simulate_single_incident()[source]

Simulate a random incident and its corresponding deployments.

Requires the Simulator to be initialized with initialize_without_simulating. Simulates a single incidents and all deployments that correspond to it.