title | description | keywords |
---|---|---|
bptk |
BPTK API Documentation for the bptk class |
agent-based modeling, system dynamics, bptk, bptk-py, python, business prototyping |
The bptk
class provides high level functions that let you interact with your simulation models and scenarios.
You will typically start the framework by instantiating the bptk
class within a Jupyer notebook, as follows:
import BPTK_PY
bptk=bptk()
This automatically starts a background process that scans your scenario
directory and imports all scenarios.
bptk(loglevel='WARN', configuration=None)
The Main entry point for managing simulation scenarios for Agent-based models, hybrid models, SD-DSL models and XMILE models.
Upon instantiation, the class automatically reads all scenario files located in the scenarios folder and instantiates the scenarios defined there. The location of the scenarios folder can be set via the configuration passed to the initializer, default is “./scenarios”.
The class also provides methods to register new scenario managers and scenarios dynamically.
Once all scenarios are set up, you can run them and plot the results.
-
Parameters
-
loglevel – String. Configures the loglevel, which can be either ERROR, WARN (Default) or INFO. Logfile is stored in the root directory under bptk_py.log
-
configuration – Conf. Defaults to None. Containts settings for loglevels, maplotlib and colors.
-
begin_session(scenarios, scenario_managers, agents=[], agent_states=[], agent_properties=[], agent_property_types=[], individual_agent_properties=[], equations=[], starttime=0.0, dt=1.0)
Begins a session to allow stepwise simulation.
This resets the internal session cache, there can only be one session at any time.
It also resets the scenario cache for all scenarios that are passed to the session.
The start time is set to be the max of start and the start time of all the scenarios.
The stop time is set internally to be the minimum of all the scenario stop times.
-
Parameters
-
scenarios – List. Names of scenarios to plot
-
scenario_managers – List. Names of scenario managers to plot
-
agents – List. List of agents to plot (Agent based modelling)
-
agent_states – List. List of agent states to plot, REQUIRES “AGENTS” param
-
agent_properties – List. List of agent properties to plot, REQUIRES “AGENTS” param
-
equations – list. Names of equations to plot (System Dynamics).
-
starttime – Float (Default=0.0) Timestep at which to start.
-
dt – Dt (Default=1.0) Deltatime.
-
destroy()
Destroy the BPTK object without stopping the Python Kernel.
Kills all the file monitors and makes sure the Python process can die happily.
end_session()
Ends a session, resets the cache of all relevant scenarios and deletes the session state.
export_scenarios(scenario_manager, scenarios=None, equations=None, interactive_scenario=None, interactive_equations=None, interactive_settings=None, time_column_name='time', scenario_df_name='scenario', scenario_column_name='scenario', indicator_df_name='indicator', interactive_df_name='interactive', filename=None)
Export scenario data into a spreadsheet.
Export data for the given scenarios in a structure that is amenable to analysis in BI tools. By default, the data is returned in a dictionary of dataframes. The first dataframe named scenario_df_name will contain all the data for all the scenarios, indexed by the scenario name. The second dataframe named interactive_df_name will contain all the data for the interactive scenarios. The interactive scenarios are generated by the export function according to the interactive settings. If you provide a filename, the data will not be returned in a dictionary but will be writen directly to an Excel (.xlsx) file. The data will be split into two tabs, one named <scenario_df_name> for the scenario data and one named <interactive_df_name> for the interactive data. Currently the export function only works for System Dynamics models (both XMILE and SD DSL).
-
Parameters
-
scenario_manager – string. Name of the scenario manager
-
scenarios – list, default None. List of scenarios to export
-
equations – list, default None. List of equations to export.
-
-
Returns
If passed a filename, then the data is exported to the file and nothing is returned. Else the method returns a dictionary of dataframes.
get_scenario(scenario_manager, scenario)
Get a scenario object for a particular scenario manager - this can be a SimulationScenario (for SD DSL and XMILE models) instance or a Model instance (for ABM and Hybrid models).
-
Parameters
-
scenario_manager – String. Name of the scenario manager
-
scenario – String. Name of the scenario.
-
-
Returns
For models built using the Model class (ABM, SD DSL, hybrid) this returns the model. For XMILE-models, this returns a SimulationScenario object.
get_scenario_names(scenario_managers=[], format='list')
Returns a concatenated list of all the scenario names from a list of scenario managers
-
Parameters
-
scenario_managers – List. List of scenario manager names. Default is an empty list.
-
format – String. Either “list” (=Default) or “dict”
-
-
Returns
List of scenario names or a dictionary.
get_scenarios(scenario_managers=[], scenarios=[], scenario_manager_type='')
Get a dictionary of scenario objects - this can be a SimulationScenario (for SD DSL and XMILE models) instance or a Model instance (for ABM and Hybrid models).
The keys of the dictionary are the scenario names, unless more than one scenario manager is passed, in which case the name of the scenario manager is used to prefixes the scenario name (i.e. <scenario_manager>_).
-
Parameters
-
scenario_managers – List. List of scenario managers to get the scenarios from.
-
scenarios – List. Names of the scenarios to get.
-
scenario_manager_type – String. Type of the scenario manager, (“sd”|”abm”|””). Default is “”.
-
-
Returns
Dictionary of scenario objects.
list_equations(scenario_managers=[], scenarios=[])
Prints all available equations for the given scenario manager(s) and scenario(s)
-
Parameters
-
scenario_managers – List. List of scenario managers to pull the scenarios’ equations for. If empty, list for all scenario managers (default)
-
scenarios – List. List of scenarios to pull the equations for. If empty, list for all scenarios of the given scenario managers(s) (default)
-
-
Returns
This method prints the equation(s) and doesn’t return anything.
list_scenarios(scenario_managers=[], scenario_manager_type='')
List scenarios for selected scenario managers.
List all scenarios or scenarios from selected scenario managers
-
Parameters
-
scenario_managers – List. The list of scenario managers whose scenarios you want to list. Default is an empty list.
-
scenario_manager_type – String. The type of scenario manager you want to list your scenarios for (“abm”|”sd”|””), default is an empty string, which returns scenario managers of both types.
-
plot_lookup(scenarios, scenario_managers, lookup_names, return_df=False, visualize_from_period=0, visualize_to_period=0, stacked=None, title='', alpha=None, x_label='', y_label='', start_date='', freq='D', series_names={}, kind=None)
Plot lookup functions.
If they come with very different indices, do not be surprised that the plot looks weird as I greedily try to plot everything
-
Parameters
-
scenarios – List. names of scenarios to plot.
-
scenario_managers – List. Names of scenario managers to plot.
-
lookup_names – List. List of lookups to plot.
-
kind – String. Type of graph to plot (“line” or “area”).
-
alpha – Float (0 < x <=1). Set transparency of plot.
-
stacked – Boolean. If True, use stacked (only with kind=”bar”).
-
freq – String. Frequency of time series. Uses the pandas offset aliases.
-
start_date – String. Start date for time series (e.g. 1/11/2017)
-
title – String. Title of plot.
-
visualize_from_period – Integer. Visualize from specific period onwards.
-
visualize_to_period – Integer. Visualize until a specific period.
-
x_label – String Label for x axis.
-
y_label – String Label for y axis.
-
series_names – Dict. Names of series to rename to, using a dict: {equation_name : rename_to}
-
return_df – Boolean. Set to True if you want to receive a dataFrame instead of the plot
-
-
Returns
Dataframe with simulation results if return_df=True, else it plots the lookup function.
plot_scenarios(scenarios, scenario_managers, agents=[], agent_states=[], agent_properties=[], agent_property_types=[], equations=[], kind=None, alpha=None, stacked=None, freq='D', start_date='', title='', visualize_from_period=0, visualize_to_period=0, x_label='', y_label='', series_names={}, progress_bar=False, return_df=False)
Plot scenarios for SD, ABM and hybrid models.
-
Parameters
-
scenarios – List Names of scenarios to plot.
-
scenario_managers – List Names of scenario managers to plot.
-
agents – List. List of agents to plot (Agent based modeling).
-
agent_states – List: List of agent states to plot, REQUIRES “AGENTS” param
-
agent_properties – List. List of agent properties to plot, REQUIRES “AGENTS” param
-
agent_property_types – List. List of agent property types to plot, REQUIRES “AGENTS” param
-
equations – List. Names of equations to plot (System Dynamics, SD).
-
kind – String. Type of graph to plot (“line” or “area”).
-
alpha – Float. Transparency 0 < x <= 1.
-
stacked – Boolean If trues, use stacked charts (only relevant for kind=”bar”).
-
freq – String. Frequency of time series. Uses the pandas offset aliases.
-
start_date – String. Start date for time series.
-
title – String. Title of plot
-
visualize_from_period – Integer Visualize from specific period onwards.
-
visualize_to_period – Integer Visualize until a specific period.
-
x_label – String. Label for x axis.
-
y_label – String. Label for y axis.
-
series_names – Dict. Names of series to rename to, using the following format {<equation_name> : <rename_to>}.
-
progress_bar – Boolean. Set True if you want to show a progress bar (useful for ABM simulations).
-
return_df – Boolean. Set True if you want to receive a dataFrame instead of the plot
-
-
Returns
Dataframe with simulation results if return_df=True.
progress()
Returns the progress of a simulation as float.
register_model(model, scenario_manager=None, scenario=None)
Registers the given model with bptk.
Automatically creates both a scenario manager and an initial scenario. If no scenario manager or scenario is passed, a scenario manager is created whose name is “sm<Model.name>” along with a scenario named “base”. Internally, this method calls register_scenario_manager and then register_scenarios.
-
Parameters
-
model – Model. The model that is registered, of type bptk.Model.
-
scenario_manager – String. The name of the scenario manager
-
scenario – Dict. A scenario in the dictionary format (see the examples in the InDepth section)
-
register_scenario_manager(scenario_manager)
Manually register a scenario manager.
Register a manually defined Scenario manager using the common dictionary notation. Keep in mind that it HAS TO contain a reference to a live model instance.
-
Parameters
scenario_manager – Dict. Dictionary notation as used in the scenarios definitions. The scenario manager definition does not necessarily need to contain scenarios, but it can.
register_scenarios(scenarios, scenario_manager)
Register a new scenario with an existing scenario manage.
Uses the usual dictionary format to configure the scenario.
-
Parameters
-
scenarios – Dict. Dictionary containing the scenario settings.
-
scenario_manager – String. Name of scenario manager to add the scenario to.
-
reset_all_scenarios()
Reload all scenarios
Reload all scenarios from the scenario definition files. If scenarios where not created via a scenario definition file but dynamically, these are lost and must be reconfigured.
reset_scenario(scenario_manager, scenario)
Reset a scenario
Reload a scenario from its file. All scenarios for the relevant file are reloaded. NOTE: If the scenario wasn’t defined via a file, this removes the scenario from the scenario manager. If you just want to reset the scenario memory, call reset_senario_cache.
-
Parameters
-
scenario_manager – String. Name of scenario manager
-
scenario – String. Name of the scenario that should be reset.
-
reset_scenario_cache(scenario_manager='', scenario='')
Resets only the interal cache (equation results) of a scenario, does not re-read from storage
-
Parameters
-
scenario_manager – String Name of scenario manager for lookup.
-
scenario – String. Name of scenario.
-
run_scenarios(scenarios, scenario_managers, agents=[], agent_states=[], agent_properties=[], agent_property_types=[], equations=[], series_names={}, progress_bar=False, return_format='df')
Run a set of scenarios.
Return the results either as dictionaries or as a dataframe.
-
Parameters
-
scenarios – List. Names of scenarios to plot
-
scenario_managers – List. Names of scenario managers to plot
-
agents – List. List of agents to plot (Agent based modelling)
-
agent_states – List. List of agent states to plot, REQUIRES “AGENTS” param
-
agent_properties – List. List of agent properties to plot, REQUIRES “AGENTS” param
-
equations – list. Names of equations to plot (System Dynamics).
-
series_names – Dict. Names of series to rename to, using a dict: {equation_name : rename_to}
-
progress_bar – Boolean. Set True if you want to show a progress bar (useful for ABM simulations)
-
return_format – String. The data type of the return, which can either be ‘df’ for dataframe, ‘dict’ for a dictionary of dataframes or ‘json’ for a JSON string.
-
-
Returns
Based on the return_format value, results are returned as df, dict, or a json string
run_step(settings=None, flat=False)
Run the next step of a session.
-
Parameters
settings – Dictionary (Default=None) The settings to apply to this step.
session_results(index_by_time=True, flat=False)
Return the results collected so far within a session
-
Parameters
index_by_time – Boolean. Indey by time (default) or else by scenario manager,scenario and equation.
-
Returns
By default this returns a dictionary of the results indexed by timestep – this is essentially just a collection of the results created by run_step. If index_by_time==False, a dictionary is returned that is structure by scenario managers, scenarios and the equations - this resembles the data structure returend by run_scenarios.
train_scenarios(scenarios, scenario_managers, episodes=1, agents=[], agent_states=[], agent_properties=[], agent_property_types=[], series_names={}, return_df=False, progress_bar=False)
Used to run a scenario repeatedly in episodes.
Ensures that the begin_epsiode and end_epsisode methods are called on the underlying model.
The method plots the agent states and properties that are passed to the method … this will typically be data used to evaluate whether training was successful.
Once the scenario has been trained, it can be used in plot_scenarios like any other scenario.
This method only works for agent-based and hybrid models.
Please check the notebook Training AI to Play the Beergame and associated models to see this in action.
-
Parameters
-
scenarios – List. The scenarios to run.
-
scenario_managers – List. The scenario managers to select the scenarios from
-
episodes – Integer (Default=1). The number of episodes to run
-
agents – List (Default=[]). The agents containing the results we want to measure.
-
agent_states – List (Default=[]). The agent state information we are interested in.
-
agent_properties – List (Default=[]). The agent property information we are interested in.
-
agent_property_types – List (Default=[]). The agent property type we are interested in.
-
series_names – Dictionary (Default={}). Allows renaming of variables in the plots
-
return_df – Boolean (Default=False). Defines whether to plot the results (default) or return results as a dataframe.
-
progress_bar – Boolean (Default=False). If true, display a progress bar that tracks the epsiode number.
-
-
Returns
If return_df is true it returns a dataframe of the results, otherwise the results are plotted directly.
-
Return type
dataframe
classmethod update()
Update BPTK to latest version - useful if you are working in a notebook environment and don't want to switch to the commandline and do a pip install
.
This method updates BPTK to the newest version that’s available on PyPi.