agentlib.utils package
Module containing all util functions for the agentlib.
Most notably, the custom injection enabling dynamic loading of custom models and modules.
- agentlib.utils.custom_injection(config: dict, module_name: str | None = None)[source]
Function to dynamically load new python files into the agentlib. Using this, users may use custom modules oder custom models together with the existing agentlib objects.
- Parameters:
config (dict) – Config dict containing the following items: file (str): Filepath to a python file (.py) class_name (str): Name of the class to be imported
module_name (str, optional) – Name of the imported module in the sys.modules list. Carefully check if duplicate module keys raise unexpected behaviour. If so, use randomly generated strings or similar in classes calling this function. Default is None. In that case, the path is converted to a matching string.
- Returns:
The class object specified by class_name
- Return type:
class (object)
Subpackages
Submodules
agentlib.utils.broker module
Module containing a basic Broker which may be inherited by specialized classes.
agentlib.utils.fuzzy_matching module
agentlib.utils.load_config module
agentlib.utils.local_broadcast_broker module
Module containing a LocalBroadcastBroker that enables local broadcast communication.
agentlib.utils.local_broker module
Module containing a LocalBroker that enables local communication with subscriptions.
- class agentlib.utils.local_broker.LocalBroker(*args, **kwargs)[source]
Bases:
Broker
Local broker class which sends messages
- send(agent_id: str, message: bytes | AgentVariable)[source]
Send the given message to all clients if the source matches. :param agent_id: Source to match :param message: The message to send
Returns:
agentlib.utils.multi_agent_system module
Module containing a local agency to test any LocalMASAgency system without the need of cloneMAP.
- pydantic model agentlib.utils.multi_agent_system.LocalCloneMAPAgency[source]
Bases:
LocalMASAgency
Local LocalMASAgency agency class which tries to mimic cloneMAP behaviour for the local execution.
- Config:
arbitrary_types_allowed: bool = True
- Fields:
- Validators:
- model_post_init(context: Any, /) None
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self – The BaseModel instance.
context – The context.
- pydantic model agentlib.utils.multi_agent_system.LocalMASAgency[source]
Bases:
MAS
Local LocalMASAgency agency class which holds the agents in a common environment, executes and terminates them.
- Config:
arbitrary_types_allowed: bool = True
- Fields:
- Validators:
setup_env
»env
- add_agent(config: AgentConfig)[source]
Also setup the agent directly
- get_results(cleanup: bool = True) Dict[str, DataFrame] [source]
Get all results of the agentLogger :param cleanup: If true, read files are deleted.
- Returns:
key is the agent_id, value the dataframe
- Return type:
Dict[str, pd.DataFrame]
- model_post_init(context: Any, /) None
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self – The BaseModel instance.
context – The context.
- pydantic model agentlib.utils.multi_agent_system.MAS[source]
Bases:
BaseModel
Parent class for all MAS
- Config:
arbitrary_types_allowed: bool = True
- Fields:
- Validators:
- field agent_configs: List[dict | Path | str] [Required]
- Validated by:
- field env: Environment | dict | Path [Optional]
The environment for the agents.
- field variable_logging: bool = False
Enable variable logging in all agents with sampling rate of environment.
- add_agent(config: AgentConfig)[source]
Add an agent to the local agency with the given agent config.
- Parameters:
Dict (config) – agent config
- static add_agent_logger(config: AgentConfig, sampling=60) AgentConfig [source]
Adds the AgentLogger to the list of configs.
- Parameters:
dict (config) – The config to be updated
sampling= –
- model_post_init(context: Any, /) None
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self – The BaseModel instance.
context – The context.
- abstract run(until)[source]
Run the MAS. :param until: The time until which the simulation should run.
Returns:
- validator setup_agents » agent_configs[source]
Load agent configs and add them.
- pydantic model agentlib.utils.multi_agent_system.MultiProcessingMAS[source]
Bases:
MAS
Helper class to conveniently run multi-agent-systems in separate processes.
- Config:
arbitrary_types_allowed: bool = True
- Fields:
- Validators:
- field agent_configs: List[dict | FilePath | str] [Required]
- Validated by:
- field cleanup: bool = False
Whether agents should clean the results files after running.
- field log_level: int = 40
Loglevel to set for the processes.
- field variable_logging: bool = False
Enable variable logging in all agents with sampling rate of environment.
- get_results() Dict[str, DataFrame] [source]
Get all results of the agentLogger :returns: key is the agent_id, value the dataframe :rtype: Dict[str, pd.DataFrame]
- model_post_init(context: Any, /) None
This function is meant to behave like a BaseModel method to initialise private attributes.
It takes context as an argument since that’s what pydantic-core passes when calling it.
- Parameters:
self – The BaseModel instance.
context – The context.
- agentlib.utils.multi_agent_system.agent_process(agent_config: dict | Path, until: float, env: dict | Path, results_dict: dict, cleanup=True, log_level=40)[source]
Function to initialize and start an agent in its own process. Collects results from the agent and stores them in the passed results_dict. :param cleanup: :param agent_config: Config for an agent. :param until: Simulation runtime :param env: config for an environment :param results_dict: dict from process manager :param log_level: the log level for this process
Returns:
agentlib.utils.multi_processing_broker module
Module containing a MultiProcessingBroker that enables communication across different processes.
- class agentlib.utils.multi_processing_broker.BrokerManager(address=None, authkey=None, serializer='pickle', ctx=None)[source]
Bases:
SyncManager
- get_queue(*args, **kwds)
- class agentlib.utils.multi_processing_broker.MPClient(agent_id, read, write)
Bases:
tuple
- agent_id
Alias for field number 0
- read
Alias for field number 1
- write
Alias for field number 2
- class agentlib.utils.multi_processing_broker.Message(agent_id, payload)
Bases:
tuple
- agent_id
Alias for field number 0
- payload
Alias for field number 1
- class agentlib.utils.multi_processing_broker.MultiProcessingBroker(*args, **kwargs)[source]
Bases:
Broker
Singleton which acts as a broker for distributed simulations among multiple local processes. Establishes a connection to a multiprocessing.Manager object, which defines a queue. This queue is used to receive connection requests from local clients. The clients send a Conn object (from multiprocessing.Pipe()) object through which the connection is established. For each connected client, a thread waits for incoming objects.
- property config: MultiProcessingBrokerConfig
Return the config of the environment
- pydantic model agentlib.utils.multi_processing_broker.MultiProcessingBrokerConfig[source]
Bases:
BaseModel
Class describing the configuration options for the MultiProcessingBroker.
- field authkey: bytes = b'useTheAgentlib'
Authorization key for the connection with the broker.
- field ipv4: IPv4Address = '127.0.0.1'
IP Address for the communication server. Defaults to localhost.
- field port: int = 50000
Port for setting up the connection with the server.
agentlib.utils.plugin_import module
Module containing all function to import new plugins
- pydantic model agentlib.utils.plugin_import.ModuleImport[source]
Bases:
BaseModel
Data-Class to import a given python file from
import_path
and load the givenclass_name
- Fields:
- field class_name: str [Required]
- field import_path: str [Required]
- class agentlib.utils.plugin_import.SaveUpdateDict[source]
Bases:
dict
Custom object to safely update the dictionary. Duplicate entries will raise an error.
- agentlib.utils.plugin_import.load_plugin(name: str, loaded_classes: SaveUpdateDict, plugin_types_name: str)[source]
Loads the plugin based on the given name.
- Parameters:
str (plugin_types_name) – Name of the plugin
SaveUpdateDict (loaded_classes) – SaveUpdateDict instance with already loaded classes (modules or models)
str – Name of the dictionary in the plugin. Typical values are “MODULE_TYPES” or “MODEL_TYPES”.
agentlib.utils.validators module
Module with validator function used in multiple parts of the agentlib
- agentlib.utils.validators.convert_to_list(obj)[source]
Function to convert an object to a list. Either is is already a list. Or it is None, then [] is returned, or it is a scalar object and thus converted to a list.
- agentlib.utils.validators.include_defaults_in_root(variables: ~typing.List[~typing.Dict], field: ~pydantic.fields.FieldInfo, make_shared: bool, agent_id: str, field_name: str, type_: ~typing.Type[~agentlib.core.datamodels.AgentVariable] = <class 'agentlib.core.datamodels.AgentVariable'>) List[AgentVariable] [source]
Validator building block to merge default variables with config variables in the root validator. Updates default variables when a variable with the same name is present in the config. Then returns the union of the default variables and the external config variables.
- agentlib.utils.validators.is_valid_agent_var_config(data: dict, field_name: str, type_: ~agentlib.core.datamodels.AgentVariable = <class 'agentlib.core.datamodels.AgentVariable'>)[source]
- agentlib.utils.validators.update_default_agent_variable(default_var: AgentVariable, user_data: dict, make_shared: bool, agent_id: str, field_name: str)[source]
Update a variable based on it’s default