SCML2021OneShotWorld

class scml.oneshot.SCML2021OneShotWorld(*args, **kwargs)

Bases: SCML2020OneShotWorld

Attributes Summary

agreement_fraction

Fraction of negotiations ending in agreement and leading to signed contracts

agreement_rate

Fraction of negotiations ending in agreement and leading to signed contracts

breach_fraction

Fraction of signed contracts that led to breaches

breach_level

The average breach level per contract

breach_rate

Fraction of signed contracts that led to breaches

business_size

The total business size defined as the total money transferred within the system

cancellation_fraction

Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.

cancellation_rate

Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.

cancelled_contracts

rtype:

list[dict[str, Any]]

contract_dropping_fraction

Fraction of signed contracts that were never executed because they were signed to late to be executable

contract_err_fraction

Fraction of signed contracts that caused exception during their execution

contract_execution_fraction

Fraction of signed contracts successfully executed with no breaches, or errors

contract_nullification_fraction

Fraction of signed contracts were nullified by the system (e.g.

contracts_df

Returns a pandas data frame with the contracts

current_step

erred_contracts

rtype:

list[dict[str, Any]]

executed_contracts

rtype:

list[dict[str, Any]]

id

The unique ID of this entity

log_folder

n_agent_exceptions

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

n_contract_exceptions

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

n_mechanism_exceptions

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

n_negotiation_rounds_failed

Average number of rounds in a successful negotiation

n_negotiation_rounds_successful

Average number of rounds in a successful negotiation

n_negotiator_exceptions

Returns a mapping from agent ID to the total number of exceptions its negotiators have raised

n_simulation_exceptions

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

n_total_agent_exceptions

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

n_total_simulation_exceptions

Returns the total number of exceptions per step that are not directly raised by agents or their negotiators.

name

A convenient name of the entity (intended primarily for printing/logging/debugging).

non_system_agent_ids

Returns names of all agents except system agents

non_system_agent_names

Returns names of all agents except system agents

non_system_agents

Returns all agents except system agents

nullified_contracts

rtype:

list[dict[str, Any]]

relative_time

Returns a number between 0 and 1 indicating elapsed relative time or steps.

remaining_steps

Returns the remaining number of steps until the end of the mechanism run.

remaining_time

Returns remaining time in seconds.

resolved_breaches

rtype:

list[dict[str, Any]]

saved_breaches

rtype:

list[dict[str, Any]]

saved_contracts

rtype:

list[dict[str, Any]]

saved_negotiations

rtype:

list[dict[str, Any]]

short_type_name

rtype:

str

signed_contracts

rtype:

list[dict[str, Any]]

stats

rtype:

dict[str, Any]

stats_df

Returns a pandas data frame with the stats

system_agent_ids

Returns the names two system agents

system_agent_names

Returns the names two system agents

system_agents

Returns the two system agents

time

Elapsed time since world started in seconds.

total_time

Returns total simulation time (till now) in mx

trading_prices

type_name

rtype:

str

unresolved_breaches

rtype:

list[dict[str, Any]]

uuid

The unique ID of this entity

winners

The winners of this world (factory managers with maximum wallet balance

Methods Summary

add_financial_report(agent, reports_agent, ...)

Records a financial report for the given agent in the agent indexed reports and time indexed reports

announce(event)

Raises an event and informs all event sinks that are registered for notifications on this event type

append_stats()

breach_record(breach)

Converts a breach to a record suitable for storage during the simulation

call(agent, method, *args, **kwargs)

Calls a method on an agent updating exeption count

checkpoint(path[, file_name, info, ...])

Saves a checkpoint of the current object at the given path.

checkpoint_final_step()

Should be called at the end of the simulation to save the final state

checkpoint_info(file_name)

Returns the information associated with a dump of the object saved in the given file

checkpoint_init([step_attrib, every, ...])

Initializes the object to automatically save a checkpoint

checkpoint_on_step_started()

Should be called on every step to save checkpoints as needed.

complete_contract_execution(*args, **kwargs)

Called after breach resolution is completed for contracts for which some potential breaches occurred.

contract_record(contract)

Converts a contract to a record suitable for permanent storage

contract_size(contract)

Returns an estimation of the activity level associated with this contract.

create(*args, **kwargs)

Creates an object and returns a proxy to it.

current_balance(agent_id)

delete_executed_contracts()

Called after processing executable contracts at every simulation step to delete processed contracts

draw([steps, what, who, where, together, ...])

Generates a graph showing some aspect of the simulation

executable_contracts()

Called at every time-step to get the contracts that are executable at this point of the simulation

execute_action(action, agent[, callback])

Executes the given action by the given agent

from_checkpoint(file_name[, return_info])

Creates an object from a saved checkpoint

from_config(config[, section, ...])

Creates an object of this class given the configuration info.

generate(agent_types[, agent_params, ...])

Generates the configuration for a world

get_dropped_contracts()

Called at the end of every time-step to get a list of the contracts that are signed but will never be executed

get_private_state(agent)

Reads the private state of the given agent

graph([steps, what, who, together])

Generates a graph showing some aspect of the simulation

ignore_contract(contract[, as_dropped])

Ignores the contract as if it was never agreed upon or as if was dropped

init([time_field])

is_basic_stat(s)

Checks whether a given statistic is agent specific.

is_valid_agreement(negotiation, agreement, ...)

Confirms that the agreement is valid given the world rules.

is_valid_contact(contract)

Checks whether a signed contract is valid

is_valid_contract(contract)

Confirms that the agreement is valid given the world rules.

join(x[, simulation_priority])

Add an agent to the world.

logdebug(s[, event])

logs debug-level information

logdebug_agent(aid, s[, event])

logs debug to the agent individual log

logerror(s[, event])

logs error-level information

logerror_agent(aid, s[, event])

logs information to the agent individual log

loginfo(s[, event])

logs info-level information

loginfo_agent(aid, s[, event])

logs information to the agent individual log

logwarning(s[, event])

logs warning-level information

logwarning_agent(aid, s[, event])

logs warning to the agent individual log

n_saved_contracts([ignore_no_issue])

Number of saved contracts

on_contract_cancelled(contract)

Called whenever a concluded contract is not signed (cancelled)

on_contract_concluded(contract, to_be_signed_at)

Called to add a contract to the existing set of unsigned contract after it is concluded

on_contract_processed(contract)

Called whenever a contract finished processing to be removed from unsigned contracts

on_contract_signed(contract)

Called to add a contract to the existing set of contract after it is signed

on_event(event, sender)

Received when an event is raised

on_exception(entity, e)

Called when an exception happens.

order_contracts_for_execution(contracts)

Orders the contracts in a specific time-step that are about to be executed

post_step_stats()

Called at the end of the simulation step to update all stats

pre_step_stats()

Called at the beginning of the simulation step to prepare stats or update them

read_config(config[, section])

Reads the configuration from a file or a dict and prepares it for parsing.

register(x[, simulation_priority])

Registers an entity in the world so it can be looked up by name.

register_listener(event_type, listener)

Registers a listener for the given event_type.

register_stats_monitor(m)

register_world_monitor(m)

relative_welfare([include_bankrupt])

Total welfare relative to expected value.

request_negotiation_about(req_id, caller, ...)

Requests to start a negotiation with some other agents

run()

Runs the simulation until it ends

run_negotiation(caller, issues, partners, ...)

Runs a negotiation until completion

run_negotiations(caller, issues, partners, ...)

Requests to run a set of negotiations simultaneously.

run_with_progress([callback])

Runs the simulation showing progress, with optional callback

save_config(file_name)

Saves the config of the world as a yaml file

save_gif([path, what, who, together, ...])

rtype:

None

scores([assets_multiplier])

Scores of all agents given the asset multiplier.

set_bulletin_board(bulletin_board)

simulation_step(stage)

A single step of the simulation.

spawn([spawn_as, spawn_params])

spawn_object(*args, **kwargs)

start_contract_execution(contract)

Tries to execute the contract

step([n_neg_steps, n_mechanisms, actions, ...])

A single simulation step.

step_with(actions[, init])

Runs a simulation step for the agents given in keys passing the corresponding values as counter offers.

trading_prices_for([discount, condition])

Calculates the prices at which all products traded using an optional discount factor

unregister_stats_monitor(m)

unregister_world_monitor(m)

update_stats(stage)

Called to update any custom stats that the world designer wants to keep

welfare([include_bankrupt])

Total welfare of all agents

Attributes Documentation

agreement_fraction

Fraction of negotiations ending in agreement and leading to signed contracts

Return type:

float

agreement_rate

Fraction of negotiations ending in agreement and leading to signed contracts

Return type:

float

breach_fraction

Fraction of signed contracts that led to breaches

Return type:

float

breach_level

The average breach level per contract

Return type:

float

breach_rate

Fraction of signed contracts that led to breaches

Return type:

float

business_size

The total business size defined as the total money transferred within the system

Return type:

float

cancellation_fraction

Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.

Return type:

float

cancellation_rate

Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.

Return type:

float

cancelled_contracts
Return type:

list[dict[str, Any]]

contract_dropping_fraction

Fraction of signed contracts that were never executed because they were signed to late to be executable

Return type:

float

contract_err_fraction

Fraction of signed contracts that caused exception during their execution

Return type:

float

contract_execution_fraction

Fraction of signed contracts successfully executed with no breaches, or errors

Return type:

float

contract_nullification_fraction

Fraction of signed contracts were nullified by the system (e.g. due to bankruptcy)

Return type:

float

contracts_df

Returns a pandas data frame with the contracts

Return type:

DataFrame

current_step
erred_contracts
Return type:

list[dict[str, Any]]

executed_contracts
Return type:

list[dict[str, Any]]

id

The unique ID of this entity

log_folder
n_agent_exceptions

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

Return type:

dict[str, int]

n_contract_exceptions

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

Return type:

dict[int, int]

n_mechanism_exceptions

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

Return type:

dict[int, int]

n_negotiation_rounds_failed

Average number of rounds in a successful negotiation

Return type:

float

n_negotiation_rounds_successful

Average number of rounds in a successful negotiation

Return type:

float

n_negotiator_exceptions

Returns a mapping from agent ID to the total number of exceptions its negotiators have raised

Return type:

dict[str, int]

n_simulation_exceptions

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

Return type:

dict[int, int]

n_total_agent_exceptions

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

Return type:

dict[str, int]

n_total_simulation_exceptions

Returns the total number of exceptions per step that are not directly raised by agents or their negotiators.

Remarks:
Return type:

dict[int, int]

name

A convenient name of the entity (intended primarily for printing/logging/debugging).

non_system_agent_ids

Returns names of all agents except system agents

Return type:

list[str]

non_system_agent_names

Returns names of all agents except system agents

Return type:

list[str]

non_system_agents

Returns all agents except system agents

Return type:

list[DefaultOneShotAdapter]

nullified_contracts
Return type:

list[dict[str, Any]]

relative_time

Returns a number between 0 and 1 indicating elapsed relative time or steps.

Return type:

float

remaining_steps

Returns the remaining number of steps until the end of the mechanism run. None if unlimited

Return type:

Optional[int]

remaining_time

Returns remaining time in seconds. None if no time limit is given.

Return type:

Optional[float]

resolved_breaches
Return type:

list[dict[str, Any]]

saved_breaches
Return type:

list[dict[str, Any]]

saved_contracts
Return type:

list[dict[str, Any]]

saved_negotiations
Return type:

list[dict[str, Any]]

short_type_name
Return type:

str

signed_contracts
Return type:

list[dict[str, Any]]

stats
Return type:

dict[str, Any]

stats_df

Returns a pandas data frame with the stats

Return type:

DataFrame

system_agent_ids

Returns the names two system agents

Return type:

list[str]

system_agent_names

Returns the names two system agents

Return type:

list[str]

system_agents

Returns the two system agents

Return type:

list[_SystemAgent]

time

Elapsed time since world started in seconds. 0.0 if the world did not start running

Return type:

float

total_time

Returns total simulation time (till now) in mx

trading_prices
type_name
Return type:

str

unresolved_breaches
Return type:

list[dict[str, Any]]

uuid

The unique ID of this entity

winners

The winners of this world (factory managers with maximum wallet balance

Methods Documentation

add_financial_report(agent, reports_agent, reports_time)

Records a financial report for the given agent in the agent indexed reports and time indexed reports

Parameters:
  • agent (DefaultOneShotAdapter) – The agent

  • reports_agent – A dictionary of financial reports indexed by agent id

  • reports_time – A dictionary of financial reports indexed by time

Returns:

Return type:

None

announce(event)

Raises an event and informs all event sinks that are registered for notifications on this event type

append_stats()
breach_record(breach)

Converts a breach to a record suitable for storage during the simulation

Return type:

dict[str, Any]

call(agent, method, *args, **kwargs)

Calls a method on an agent updating exeption count

Parameters:
  • agent (Agent) – The agent on which the method is to be called

  • method (Callable) – The bound method (bound to the agent)

  • *args – position arguments

  • **kwargs – keyword arguments

Return type:

Any

Returns:

whatever method returns

checkpoint(path, file_name=None, info=None, exist_ok=False, single_checkpoint=True, step_attribs=('current_step', '_current_step', '_Entity__current_step', '_step'))

Saves a checkpoint of the current object at the given path.

Parameters:
  • path (PathLike) – Full path to a directory to store the checkpoint

  • file_name (Optional[str]) – Name of the file to dump into. If not given, a unique name is created

  • info (Optional[dict[str, Any]]) – Information to save with the checkpoint (must be json serializable)

  • exist_ok (bool) – If true, override existing dump

  • single_checkpoint (bool) – If true, keep a single checkpoint for the last step

  • step_attribs (tuple[str, ...]) – Attributes to represent the time-step of the object. Any of the given attributes will be used in the file name generated if single_checkpoint is False. If single_checkpoint is True, the filename will not contain time-step information

Return type:

Path

Returns:

full path to the file used to save the checkpoint

checkpoint_final_step()

Should be called at the end of the simulation to save the final state

Remarks:
  • Should be called after all processing of the final step is conducted.

Return type:

Optional[Path]

classmethod checkpoint_info(file_name)

Returns the information associated with a dump of the object saved in the given file

Parameters:

file_name (Path | str) – Name of the object

Returns:

Return type:

dict[str, Any]

checkpoint_init(step_attrib='current_step', every=1, folder=None, filename=None, info=None, exist_ok=True, single=True)

Initializes the object to automatically save a checkpoint

Parameters:
  • step_attrib (str) – The attribute that defines the current step. If None, there is no step concept

  • every (int) – Number of steps per checkpoint. If < 1 no checkpoints will be saved

  • folder (Optional[PathLike]) – The directory to store checkpoints under

  • filename (Optional[str]) – Name of the file to save the checkpoint under. If None, a unique name will be chosen. If single_checkpoint was False, then multiple files will be used prefixed with the step number

  • info (Optional[dict[str, Any]]) – Any extra information to save in the json file associated with each checkpoint

  • exist_ok (bool) – Override existing files if any

  • single (bool) – If True, only the most recent checkpoint will be kept

Remarks:

  • single_checkpoint implies exist_ok

checkpoint_on_step_started()

Should be called on every step to save checkpoints as needed.

Return type:

Optional[Path]

Returns:

The path on which the checkpoint is stored if one is stored. None otherwise.

Remarks:

  • Should be called at the BEGINNING of every step before any processing takes place

complete_contract_execution(*args, **kwargs)

Called after breach resolution is completed for contracts for which some potential breaches occurred.

Parameters:
  • contract – The contract considered.

  • breaches – The list of potential breaches that was generated by _execute_contract.

  • resolution – The agreed upon resolution

Returns:

contract_record(contract)

Converts a contract to a record suitable for permanent storage

Return type:

dict[str, Any]

contract_size(contract)

Returns an estimation of the activity level associated with this contract. Higher is better :type contract: Contract :param contract:

Returns:

Return type:

float

classmethod create(*args, **kwargs)

Creates an object and returns a proxy to it.

current_balance(agent_id)
delete_executed_contracts()

Called after processing executable contracts at every simulation step to delete processed contracts

Return type:

None

draw(steps=None, what=['negotiation-requests-rejected', 'negotiation-requests-accepted', 'negotiations-rejected', 'negotiations-started', 'negotiations-failed', 'contracts-concluded', 'contracts-cancelled', 'contracts-signed', 'contracts-breached', 'contracts-executed'], who=None, where=None, together=True, axs=None, ncols=4, figsize=(15, 15), **kwargs)

Generates a graph showing some aspect of the simulation

Parameters:
  • steps (UnionType[tuple[int, int], int, None]) – The step/steps to generate the graphs for. If a tuple is given all edges within the given range (inclusive beginning, exclusive end) will be accomulated

  • what (Collection[str]) – The edges to have on the graph. Options are: negotiations, concluded, signed, executed

  • who (Callable[[Agent], bool]) – Either a callable that receives an agent and returns True if it is to be shown or None for all

  • where (Callable[[Agent], int | tuple[float, float]]) – A callable that returns for each agent the position it showed by drawn at either as an integer specifying the column in which to draw the column or a tuple of two floats specifying the position within the drawing area of the agent. If None, the default Networkx layout will be used.

  • together (bool) – IF specified all edge types are put in the same graph.

  • axs (Collection[Axis]) – The axes used for drawing. If together is true, it should be a single Axes object otherwise it should be a list of Axes objects with the same length as what.

  • show_node_labels – show node labels!

  • show_edge_labels – show edge labels!

  • kwargs – passed to networx.draw_networkx

Return type:

tuple[Axis, Graph] | tuple[list[Axis], list[Graph]]

Returns:

A networkx graph representing the world if together==True else a list of graphs one for each item in what

executable_contracts()

Called at every time-step to get the contracts that are executable at this point of the simulation

Return type:

Collection[Contract]

execute_action(action, agent, callback=None)

Executes the given action by the given agent

Return type:

bool

classmethod from_checkpoint(file_name, return_info=False)

Creates an object from a saved checkpoint

Parameters:
  • file_name (Path | str) –

  • return_info (bool) – If True, tbe information saved when the file was dumped are returned

Return type:

NamedObject | tuple[NamedObject, dict[str, Any]]

Returns:

Either the object or the object and dump-info as a dict (if return_info was true)

Remarks:

  • If info is returned, it is guaranteed to have the following members:
    • time: Dump time

    • type: Type of the dumped object

    • id: ID

    • name: name

classmethod from_config(config, section=None, ignore_children=True, try_parsing_children=True, scope=None)

Creates an object of this class given the configuration info.

Parameters:
  • config (str | dict) – Either a file name or a dictionary

  • section (Optional[str]) – A section in the file or a key in the dictionary to use for loading params

  • ignore_children (bool) – If true then children will be ignored and there will be a single return

  • try_parsing_children (bool) – If true the children will first be parsed as ConfigReader classes if they are not

  • int (simple types (e.g.) –

  • str

  • float

  • Iterable[int|str|float]

  • scope – The scope at which to evaluate any child classes. This MUST be passed as scope=globals() if you are

  • parsed. (having any children that are to be) –

Returns:

An object of cls if ignore_children is True or a tuple with an object of cls and a dictionary with children that were not parsed.

Remarks:

  • This function will return an object of its class after passing the key-value pairs found in the config to the init function.

  • Requiring passing scope=globals() to this function is to get around the fact that in python eval() will be called with a globals dictionary based on the module in which the function is defined not called. This means that in general when eval() is called to create the children, it will not have access to the class definitions of these children (except if they happen to be imported in this file). To avoid this problem causing an undefined_name exception, the caller must pass her globals() as the scope.

classmethod generate(agent_types, agent_params=None, agent_processes=None, n_steps=(50, 200), n_processes=2, n_lines=10, n_agents_per_process=(4, 8), process_inputs=1, process_outputs=1, production_costs=(1, 4), profit_means=(0.1, 0.2), profit_stddevs=0.05, max_productivity=(0.8, 1.0), initial_balance=None, cost_increases_with_level=True, equal_exogenous_supply=False, equal_exogenous_sales=False, exogenous_supply_predictability=(0.6, 0.9), exogenous_sales_predictability=(0.6, 0.9), exogenous_control=-1, cash_availability=(1.5, 2.5), force_signing=True, profit_basis=<function amax>, disposal_cost=(0.0, 0.2), shortfall_penalty=(0.2, 1.0), disposal_cost_dev=(0.0, 0.02), shortfall_penalty_dev=(0.0, 0.1), exogenous_price_dev=(0.1, 0.2), price_multiplier=(1.5, 2.0), random_agent_types=False, penalties_scale='trading', cap_exogenous_quantities=True, method='profitable', **kwargs)

Generates the configuration for a world

Parameters:
  • agent_types (list[str | type[OneShotAgent]]) – All agent types

  • agent_params (Optional[list[dict[str, Any]]]) – Agent parameters used to initialize them

  • n_steps (tuple[int, int] | int) – Number of simulation steps

  • n_processes (tuple[int, int] | int) – Number of processes in the production chain

  • n_lines (ndarray | tuple[int, int] | int) – Number of lines per factory

  • process_inputs (ndarray | tuple[int, int] | int) – Number of input units per process

  • process_outputs (ndarray | tuple[int, int] | int) – Number of output units per process

  • production_costs (ndarray | tuple[int, int] | int) – Production cost per factory

  • profit_means (ndarray | tuple[float, float] | float) – Mean profitability per production level (i.e. process).

  • profit_stddevs (ndarray | tuple[float, float] | float) – Std. Dev. of the profitability of every level (i.e. process).

  • max_productivity (ndarray | tuple[float, float] | float) – Maximum possible productivity per level (i.e. process).

  • initial_balance (UnionType[ndarray, tuple[int, int], int, None]) – The initial balance of all agents

  • n_agents_per_process (ndarray | tuple[int, int] | int) – Number of agents per process

  • agent_processes (Optional[list[int]]) – The process for each agent. If not None , it will override n_agents_per_process and must be a list/tuple of the same length as agent_types . Morevoer, random_agent_types must be False in this case

  • cost_increases_with_level – If true, production cost will be higher for processes nearer to the final product.

  • profit_basis – The statistic used when controlling catalog prices by profit arguments. It can be np.mean, np.median, np.min, np.max or any Callable[[list[float]], float] and is used to summarize production costs at every level.

  • equal_exogenous_supply – If true, external supply will be distributed equally among all agents in the first layer

  • equal_exogenous_sales – If true, external sales will be distributed equally among all agents in the last layer

  • exogenous_supply_predictability (tuple[float, float] | float) – How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random

  • exogenous_sales_predictability (tuple[float, float] | float) – How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random

  • force_signing – Whether to force contract signatures (exogenous contracts are treated in the same way).

  • exogenous_control (tuple[float, float] | float) – How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True

  • cap_exogenous_quantities (bool) – If True, all exogenous quantities in all contracts are capped to be no more than the number of lines

  • cash_availability (tuple[float, float] | float) – The fraction of the total money needs of the agent to work at maximum capacity that is available as initial_balance . This is only effective if initial_balance is set to None .

  • exogenous_control – How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True

  • disposal_cost (ndarray | tuple[float, float] | float) – A range to sample mean-disposal costs for all factories from

  • shortfall_penalty (ndarray | tuple[float, float] | float) – A range to sample mean-shortfall penalty for all factories from

  • disposal_cost_dev (ndarray | tuple[float, float] | float) – A range to sample std. dev of disposal costs for all factories from

  • shortfall_penalty_dev (ndarray | tuple[float, float] | float) – A range to sample std. dev of shortfall penalty for all factories from

  • exogenous_price_dev (ndarray | tuple[float, float] | float) – The standard deviation of exogenous contract prices relative to the mean price

  • price_multiplier (ndarray | tuple[float, float] | float) – A value to multiply with trading/catalog price to get the upper limit on prices for all negotiations

  • random_agent_types (bool) – If True, the final agent types used by the generato wil always be sampled from the given types. If False, this random sampling will only happin if len(agent_types) != n_agents.

  • penalties_scale (str | list[str]) – What are disposal_cost and shortfall_penalty relative to. There are four options: trading, catalog mean trading and catalog prices of the product. unit means the unit price in the contract and none means the storage-cost and shortfall_penalty are absolute values (in money unit). If not given will be read through the AWI

  • method – the generation method. This is only for compatibility with SCML2020World and is not used.

  • **kwargs

Return type:

dict[str, Any]

Returns:

world configuration as a Dict[str, Any]. A world can be generated from this dict by calling SCML2020World(**d)

Remarks:

  • There are two general ways to use this generator:
    1. Pass random_agent_types = False, and pass agent_types, agent_processes to control placement of each agent in each level of the production graph.

    2. Pass random_agent_types = True and pass agent_types, n_agents_per_process to make the system randomly place the specified number of agents in each production level

  • Most parameters (i.e. process_inputs , process_outputs , n_agents_per_process , costs ) can take a single value, a tuple of two values, or a list of values. If it has a single value, it is repeated for all processes/factories as appropriate. If it is a tuple of two numbers $(i, j)$, each process will take a number sampled from a uniform distribution supported on $[i, j]$ inclusive. If it is a list of values, of the length n_processes , it is used as it is otherwise, it is used to sample values for each process.

get_dropped_contracts()

Called at the end of every time-step to get a list of the contracts that are signed but will never be executed

Return type:

Collection[Contract]

get_private_state(agent)

Reads the private state of the given agent

Return type:

dict

graph(steps=None, what=['negotiation-requests-rejected', 'negotiation-requests-accepted', 'negotiations-rejected', 'negotiations-started', 'negotiations-failed', 'negotiations-succeeded', 'contracts-concluded', 'contracts-cancelled', 'contracts-signed', 'contracts-nullified', 'contracts-erred', 'contracts-breached', 'contracts-executed'], who=None, together=True)

Generates a graph showing some aspect of the simulation

Parameters:
  • steps (UnionType[tuple[int, int], int, None]) – The step/steps to generate the graphs for. If a tuple is given all edges within the given range (inclusive beginning, exclusive end) will be accumulated

  • what (Collection[str]) – The edges to have on the graph. Options are: negotiations, concluded, signed, executed

  • who (Optional[Callable[[Agent], bool]]) – Either a callable that receives an agent and returns True if it is to be shown or None for all

  • together (bool) – IF specified all edge types are put in the same graph.

Return type:

Graph | list[Graph]

Returns:

A networkx graph representing the world if together==True else a list of graphs one for each item in what

ignore_contract(contract, as_dropped=False)

Ignores the contract as if it was never agreed upon or as if was dropped

Parameters:
  • contract – The contract to ignore

  • as_dropped – If true, the contract is treated as a dropped invalid contract, otherwise it is treated as if it never happened.

init(time_field='time')
classmethod is_basic_stat(s)

Checks whether a given statistic is agent specific.

Return type:

bool

is_valid_agreement(negotiation, agreement, mechanism)

Confirms that the agreement is valid given the world rules.

Parameters:
  • negotiation (NegotiationInfo) – The NegotiationInfo that led to the agreement

  • agreement (tuple) – The agreement

  • mechanism (Mechanism) – The mechanism that led to the agreement

Return type:

bool

Returns:

Returns True for valid agreements and False for invalid agreements

Remarks:

  • This test is conducted before the agents are asked to sign the corresponding contract

  • Invalid agreements will be treated as never happened and agents will not be asked to sign it

is_valid_contact(contract)

Checks whether a signed contract is valid

Return type:

bool

is_valid_contract(contract)

Confirms that the agreement is valid given the world rules.

Parameters:

contract (Contract) – The contract being tested

Return type:

bool

Returns:

Returns True for valid contracts and False for invalid contracts

Remarks:

  • This test will be conducted after agents are asked to sign the contract and only for signed contracts.

  • If False is returned, the contract will considered unsigned and will be recorded as a concluded but not signed contract with no rejectors

join(x, simulation_priority=0, **kwargs)

Add an agent to the world.

Parameters:
  • x (Agent) – The agent to be registered

  • simulation_priority (int) – The simulation priority. Entities with lower pprioritieswill be stepped first during

  • kwargs – Any key-value pairs specifying attributes of the agent. NegMAS internally uses the attribute ‘color’ when drawing the agent in draw

Returns:

logdebug(s, event=None)

logs debug-level information

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

Return type:

None

logdebug_agent(aid, s, event=None)

logs debug to the agent individual log

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

Return type:

None

logerror(s, event=None)

logs error-level information

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

Return type:

None

logerror_agent(aid, s, event=None)

logs information to the agent individual log

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

Return type:

None

loginfo(s, event=None)

logs info-level information

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

Return type:

None

loginfo_agent(aid, s, event=None)

logs information to the agent individual log

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

Return type:

None

logwarning(s, event=None)

logs warning-level information

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

Return type:

None

logwarning_agent(aid, s, event=None)

logs warning to the agent individual log

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

Return type:

None

n_saved_contracts(ignore_no_issue=True)

Number of saved contracts

Parameters:

ignore_no_issue (bool) – If true, only contracts resulting from negotiation (has some issues) will be counted

Return type:

int

on_contract_cancelled(contract)

Called whenever a concluded contract is not signed (cancelled)

Parameters:

contract – The contract to add

Remarks:

  • By default this function just adds the contract to the set of contracts maintaned by the world.

  • You should ALWAYS call this function when overriding it.

on_contract_concluded(contract, to_be_signed_at)

Called to add a contract to the existing set of unsigned contract after it is concluded

Parameters:
  • contract (Contract) – The contract to add

  • to_be_signed_at (int) – The timestep at which the contract is to be signed

Remarks:

  • By default this function just adds the contract to the set of contracts maintaned by the world.

  • You should ALWAYS call this function when overriding it.

Return type:

None

on_contract_processed(contract)

Called whenever a contract finished processing to be removed from unsigned contracts

Parameters:

contract – Contract

Remarks:

  • called by on_contract_cancelled and on_contract_signed

on_contract_signed(contract)

Called to add a contract to the existing set of contract after it is signed

Parameters:

contract (Contract) – The contract to add

Return type:

bool

Returns:

True if everything went OK and False otherwise

Remarks:

  • By default this function just adds the contract to the set of contracts maintaned by the world.

  • You should ALWAYS call this function when overriding it.

on_event(event, sender)

Received when an event is raised

on_exception(entity, e)

Called when an exception happens.

Parameters:
  • entity (Entity) – The entity that caused the exception

  • e (Exception) – The exception

Return type:

None

order_contracts_for_execution(contracts)

Orders the contracts in a specific time-step that are about to be executed

Return type:

Collection[Contract]

post_step_stats()

Called at the end of the simulation step to update all stats

Kept for backward compatibility and will be dropped. Override update_stats ins

pre_step_stats()

Called at the beginning of the simulation step to prepare stats or update them

Kept for backward compatibility and will be dropped. Override update_stats instead

classmethod read_config(config, section=None)

Reads the configuration from a file or a dict and prepares it for parsing.

Parameters:
  • config (str | dict) – Either a file name or a dictionary

  • section (Optional[str]) – A section in the file or a key in the dictionary to use for loading params

Return type:

dict[str, Any]

Returns:

A dict ready to be parsed by from_config

Remarks:

register(x, simulation_priority=0)

Registers an entity in the world so it can be looked up by name. Should not be called directly

Parameters:
  • x (Entity) – The entity to be registered

  • simulation_priority (int) – The simulation periority. Entities with lower periorities will be stepped first during

Returns:

register_listener(event_type, listener)

Registers a listener for the given event_type.

Parameters:
  • event_type (Optional[str]) – The type to register. If None, the listener will be registered for all types

  • listener (EventSink) – The listening agent (must have an on_event method that receives an event: Event and a sender: EventSource)

register_stats_monitor(m)
register_world_monitor(m)
relative_welfare(include_bankrupt=False)

Total welfare relative to expected value. Returns None if no expectation is found in self.info

Return type:

Optional[float]

request_negotiation_about(req_id, caller, issues, partners, roles=None, annotation=None, mechanism_name=None, mechanism_params=None, group=None)

Requests to start a negotiation with some other agents

Parameters:
  • req_id (str) – An ID For the request that is unique to the caller

  • caller (Agent) – The agent requesting the negotiation

  • partners (list[Agent | str]) – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/Agent or as a list containing a single string/Agent, then he caller will be added at the beginning of the list. This will only be done if roles was passed as None.

  • issues (list[Issue]) – Negotiation issues

  • annotation (Optional[dict[str, Any]]) – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation

  • roles (Optional[list[str]]) – The roles of different partners. If None then each role for each partner will be None

  • mechanism_name (Optional[str]) – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be) –

  • my_role (then roles and) –

  • None

  • mechanism_params (Optional[dict[str, Any]]) – A dict of parameters used to initialize the mechanism object

  • group (Optional[str]) – An identifier for the group to which the negotiation belongs. This is not not used by the system.

Return type:

NegotiationInfo

Returns:

None. The caller will be informed by a callback function on_neg_request_accepted or on_neg_request_rejected about the status of the negotiation.

run()

Runs the simulation until it ends

run_negotiation(caller, issues, partners, negotiator, preferences=None, caller_role=None, roles=None, annotation=None, mechanism_name=None, mechanism_params=None)

Runs a negotiation until completion

Parameters:
  • caller (Agent) – The agent requesting the negotiation

  • partners (list[str | Agent]) – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/Agent or as a list containing a single string/Agent, then he caller will be added at the beginning of the list. This will only be done if roles was passed as None.

  • negotiator (Negotiator) – The negotiator to be used in the negotiation

  • preferences (Optional[Preferences]) – The utility function. Only needed if the negotiator does not already know it

  • caller_role (Optional[str]) – The role of the caller in the negotiation

  • issues (list[Issue]) – Negotiation issues

  • annotation (Optional[dict[str, Any]]) – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation

  • roles (Optional[list[str]]) – The roles of different partners. If None then each role for each partner will be None

  • mechanism_name (Optional[str]) – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be) –

  • my_role (then roles and) –

  • None

  • mechanism_params (Optional[dict[str, Any]]) – A dict of parameters used to initialize the mechanism object

Return type:

tuple[Optional[Contract], Optional[NegotiatorMechanismInterface]]

Returns:

A Tuple of a contract and the nmi of the mechanism used to get it in case of success. None otherwise

run_negotiations(caller, issues, partners, negotiators, preferences=None, caller_roles=None, roles=None, annotations=None, mechanism_names=None, mechanism_params=None, all_or_none=False)

Requests to run a set of negotiations simultaneously. Returns after all negotiations are run to completion

Parameters:
  • caller (Agent) – The agent requesting the negotiation

  • partners (list[list[str | Agent]]) – A list of list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners[i] is passed as a single string/Agent or as a list containing a single string/Agent, then he caller will be added at the beginning of the list. This will only be done if roles was passed as None.

  • issues (list[Issue] | list[list[Issue]]) – Negotiation issues

  • negotiators (list[Negotiator]) – The negotiator to be used in the negotiation

  • ufuns – The utility function. Only needed if the negotiator does not already know it

  • caller_roles (Optional[list[str]]) – The role of the caller in the negotiation

  • annotations (Optional[list[Optional[dict[str, Any]]]]) – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation

  • roles (Optional[list[Optional[list[str]]]]) – The roles of different partners. If None then each role for each partner will be None

  • mechanism_names (UnionType[str, list[str], None]) – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be) –

  • my_role (then roles and) –

  • None

  • mechanism_params (UnionType[dict[str, Any], list[dict[str, Any]], None]) – A dict of parameters used to initialize the mechanism object

  • all_of_none – If True, ALL partners must agree to negotiate to go through.

Returns:

contract (None for failure) and nmi (The mechanism info [None if the partner refused the negotiation])

Return type:

A list of tuples each with two values

run_with_progress(callback=None)

Runs the simulation showing progress, with optional callback

Return type:

None

save_config(file_name)

Saves the config of the world as a yaml file

Parameters:

file_name (str) – Name of file to save the config to

Returns:

save_gif(path=None, what=['negotiation-requests-rejected', 'negotiation-requests-accepted', 'negotiations-rejected', 'negotiations-started', 'negotiations-failed', 'negotiations-succeeded', 'contracts-concluded', 'contracts-cancelled', 'contracts-signed', 'contracts-nullified', 'contracts-erred', 'contracts-breached', 'contracts-executed'], who=None, together=True, draw_every=1, fps=5)
Return type:

None

scores(assets_multiplier=0.0)

Scores of all agents given the asset multiplier.

Parameters:

assets_multiplier (float) – A multiplier to multiply the assets with.

Return type:

dict[str, float]

set_bulletin_board(bulletin_board)
simulation_step(stage)

A single step of the simulation.

Parameters:

stage – How many times so far was this method called within the current simulation step

Remarks:

  • Using the stage parameter, it is possible to have Operations . SimulationStep several times with the list of operations while differentiating between these calls.

classmethod spawn(spawn_as='object', spawn_params=None, *args, **kwargs)
classmethod spawn_object(*args, **kwargs)
start_contract_execution(contract)

Tries to execute the contract

Parameters:

contract (Contract) –

Returns:

The set of breaches committed if any. If there are no breaches return an empty set

Return type:

Set[Breach]

Remarks:

  • You must call super() implementation of this method before doing anything

  • It is possible to return None which indicates that the contract was nullified (i.e. not executed due to a reason other than an execution exeception).

step(n_neg_steps=None, n_mechanisms=None, actions=None, neg_actions=None)

A single simulation step.

Parameters:
  • n_mechanisms (Optional[int]) – Number of mechanisms to step (None for all)

  • n_neg_steps (Optional[int]) – Number of steps for every mechanism (None to complete one simulation step)

  • actions (Optional[dict[str, Any]]) – Mapping of agent IDs to their actions. The agent will be asked to act only if this is not given

  • neg_actions (Optional[dict[str, Optional[Any]]]) – Mapping of negotiator IDs to corresponding negotiation action (e.g. offer in SAO) for every mechanism. Negotiators will be called upon to act only if no action is passed here.

Remarks:

  • We have two modes of operation depending on n_neg_steps

    1. n_neg_steps is None will run a single complete simulation step every call

      including all negotiations and everything before and after them.

    2. n_neg_steps is an integer will step the simulation so that the given number

      of simulation steps are executed every call. The simulator will run operations before and after negotiations appropriately.

  • We have two modes of operation depending on n_mechanisms

    1. n_mechanisms is None will step all negotiations according to n_neg_steps

    2. n_mechanisms is an integer and n_neg_steps will step this number of

      mechanisms in parallel every call to step.

  • We have a total of four modes:

    1. n_neg_steps and n_mechanisms are both None: Each call to step corresponds

      to one simulation step from start to end.

    2. n_neg_steps and n_mechanisms are both integers: Each call to step steps n_mechanisms mechanisms by n_neg_steps steps.

    3. n_neg_steps is None and n_mechanisms is an integer: Each call to step runs n_mechanisms according to negotiation_speed

    4. n_neg_steps is an integer and n_mechanisms is None: Each call to step steps all mechanisms n_neg_steps steps.

  • Never mix calls with n_neg_steps equaling None and an integer.

  • Never call this method again on a world if it ever returned False on that world.

  • TODO Implement actions. Currently they are just ignored

Return type:

bool

step_with(actions, init=False)

Runs a simulation step for the agents given in keys passing the corresponding values as counter offers.

Return type:

bool

Returns:

False if this is the last negotiation.

Remarks:
  • You must call this with init=True once at the beginning of every simulation to make sure that init() and other initialization code is called correctly.

  • Every step advances all negotiations one step.

  • Negotiators belonging to the given agents are never called as long as a corresponding action (response) is given in the agents dict.

  • The world MUST be created with one_offer_per_step passed as True (default is False).

trading_prices_for(discount=1.0, condition='executed')

Calculates the prices at which all products traded using an optional discount factor

Parameters:
  • discount (float) – A discount factor to treat older prices less importantly (exponential discounting).

  • condition – The condition for contracts to consider. Possible values are executed, signed, concluded, nullified

Return type:

ndarray

Returns:

an n_products vector of trading prices

unregister_stats_monitor(m)
unregister_world_monitor(m)
update_stats(stage)

Called to update any custom stats that the world designer wants to keep

Parameters:

stage (int) – How many times was this method called during this stage

Remarks:

  • Default behavior is: - If Operations . StatsUpdate appears once in operations, it calls post_step_stats once - Otherwise: it calls pre_step_stats for stage 0, and post_step_stats for any other stage.

welfare(include_bankrupt=False)

Total welfare of all agents

Return type:

float