SCML2020World

class scml.scml2020.SCML2020World(process_inputs, process_outputs, catalog_prices, profiles, agent_types, agent_params=None, exogenous_contracts=(), initial_balance=1000, allow_buying_output=False, allow_selling_input=False, catalog_quantities=50, buy_missing_products=True, borrow_on_breach=True, bankruptcy_limit=0.0, liquidation_rate=1.0, spot_market_global_loss=0.3, interest_rate=0.05, financial_report_period=5, compensation_fraction=1.0, compensate_immediately=False, compensate_before_past_debt=True, exogenous_horizon=None, exogenous_force_max=False, production_confirm=False, production_buy_missing=False, production_no_borrow=True, production_no_bankruptcy=False, production_penalty=0.15, compact=False, no_logs=False, n_steps=1000, time_limit=5400, neg_n_steps=20, neg_time_limit=120, neg_step_time_limit=60, negotiation_speed=21, negotiation_quota_per_step=None, negotiation_quota_per_simulation=inf, n_concurrent_negs_between_partners=inf, avoid_ultimatum=True, end_negotiation_on_refusal_to_propose=True, trading_price_discount=0.9, spot_discount=0.9, spot_multiplier=0.05, signing_delay=0, force_signing=False, batch_signing=True, name=None, publish_exogenous_summary=True, publish_trading_prices=True, agent_name_reveals_position=True, agent_name_reveals_type=True, inventory_valuation_trading=0.5, inventory_valuation_catalog=0.0, **kwargs)

Bases: negmas.situated.situated.TimeInAgreementMixin, negmas.situated.situated.World

A Supply Chain SCML2020World simulation as described for the SCML league of ANAC @ IJCAI 2020.

Parameters
  • process_inputs (ndarray) – An n_processes vector specifying the number of inputs from each product needed to execute each process.

  • process_outputs (ndarray) – An n_processes vector specifying the number of inputs from each product generated by executing each process.

  • catalog_prices (ndarray) – An n_products vector (i.e. n_processes+1 vector) giving the catalog price of all products

  • profiles (List[FactoryProfile]) – An n_agents list of FactoryProfile objects specifying the private profile of the factory associated with each agent.

  • agent_types (List[Type[SCML2020Agent]]) – An n_agents list of strings/ SCML2020Agent classes specifying the type of each agent

  • agent_params (Optional[List[Dict[str, Any]]]) – An n_agents dictionaries giving the parameters of each agent

  • initial_balance (Union[ndarray, Tuple[int, int], int]) – The initial balance in each agent’s wallet. All agents will start with this same value.

  • allow_selling_input – Allows agents to sell their input product(s) through negotiation

  • allow_buying_output – Allows agents to buy their output product(s) through negotiation

  • catalog_quantities (Union[int, ndarray]) – The quantities in the past for which catalog_prices are the average unit prices. This is used when updating the trading prices. If set to zero then the trading price will follow the market price and will not use the catalog_price (except for products that are never sold in the market for which the trading price will take the default value of the catalog price). If set to a large value (e.g. 10000), the price at which a product is sold will not affect the trading price

  • spot_market_global_loss – Buying from the spot market will cost trading-price * (1+`spot_market_global_loss) and selling to it will cost trading-price / (1+ spot_market_global_loss) for agents with unit spot-market-loss-multiplier

  • financial_report_period – The number of steps between financial reports. If < 1, it is a fraction of n_steps

  • borrow_on_breach – If true, agents will be forced to borrow money on breach as much as possible to honor the contract

  • interest_rate – The interest at which loans grow over time (it only affect a factory when its balance is negative)

  • bankruptcy_limit – The maximum amount that be be borrowed (including interest). The balance of any factory cannot go lower than - borrow_limit or the agent will go bankrupt immediately

  • liquidation_rate – The rate at which future contracts get liquidated when an agent gets bankrupt. It should be between zero and one.

  • compensation_fraction – Fraction of a contract to be compensated (at most) if a partner goes bankrupt. Notice that this fraction is not guaranteed because the bankrupt agent may not have enough assets to pay all of its standing contracts to this level of compensation. In such cases, a smaller fraction will be used.

  • compensate_immediately – If true, compensation will happen immediately when an agent goes bankrupt and in in money. This means that agents with contracts involving the bankrupt agent will just have these contracts be nullified and receive monetary compensation immediately . If false, compensation will not happen immediately but at the contract execution time. In this case, agents with contracts involving the bankrupt agent will be informed of the compensation fraction (instead of the compensation money) at the time of bankruptcy and will receive the compensation in kind (money if they are sellers and products if they are buyers) at the normal execution time of the contract. In the special case of no-compensation (i.e. compensation_fraction is zero or the bankrupt agent has no assets), the two options will behave similarity.

  • compensate_before_past_debt – If true, then compensations will be paid before past debt is considered, otherwise, the money from liquidating bankrupt agents will first be used to pay past debt then whatever remains will be used for compensation. Notice that in all cases, the trigger of bankruptcy will be paid before compensation and past debts.

  • exogenous_horizon (Optional[int]) – The horizon for revealing external contracts

  • exogenous_force_max (bool) – If true, exogenous contracts are forced to be signed independent of the setting of force_signing

  • production_no_borrow – If true, agents will not borrow if they fail to satisfy its production need to execute a scheduled production command

  • production_no_bankruptcy – If true, agents will not go bankrupt because of an production related transaction.

  • production_penalty – The penalty paid when buying from spot-market to satisfy production needs

  • production_confirm – If true, the factory will confirm running processes at every time-step just before running them by calling confirm_production on the agent controlling it.

  • compact – If True, no logs will be kept and the whole simulation will use a smaller memory footprint

  • n_steps – Number of simulation steps (can be considered as days).

  • time_limit – Total time allowed for the complete simulation in seconds.

  • neg_n_steps – Number of negotiation steps allowed for all negotiations.

  • neg_time_limit – Total time allowed for a complete negotiation in seconds.

  • neg_step_time_limit – Total time allowed for a single step of a negotiation. in seconds.

  • negotiation_speed – The number of negotiation steps that pass in every simulation step. If 0, negotiations will be guaranteed to finish within a single simulation step

  • signing_delay – The number of simulation steps to pass between a contract is concluded and signed

  • name (Optional[str]) – The name of the simulations

  • **kwargs – Other parameters that are passed directly to SCML2020World constructor.

Attributes Summary

agreement_fraction

Fraction of negotiations ending in agreement and leading to signed contracts

bankruptcy_rate

The fraction of factories that went bankrupt

contracts_df

Returns a pandas data frame with the contracts

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

num_bankrupt

The fraction of factories that went bankrupt

productivity

Fraction of production lines occupied during the simulation

relative_productivity

Productivity relative to the expected value.

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

trading_prices

winners

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

Methods Summary

add_financial_report(agent, factory, …)

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

breach_record(breach)

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

can_negotiate(a1, a2)

compensate(available, factory)

Called by a factory when it is going bankrupt after liquidation

complete_contract_execution(contract, …)

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.

current_balance(agent_id)

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

Generates a graph showing some aspect of the simulation

execute_action(action, agent[, callback])

Executes the given action by the given agent

generate(agent_types[, agent_params, …])

Generates the configuration for a world

generate_guaranteed_profit(n_steps, n_lines, …)

Generates prices, contracts and profiles ensuring that all agents can profit and returning a set of explict contracts that can achieve this profit

generate_profitable(n_steps, n_lines, …[, …])

Generates the prices, contracts and profiles ensuring there is some possibility of profit in the market

get_private_state(agent)

Reads the private state of the given agent

is_valid_contact(contract)

Checks whether a signed contract is valid

negs_between(a1, a2)

nullify_contract(contract, new_quantity)

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_signed(contract)

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

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

record_bankrupt(factory)

Records agent bankruptcy

relative_welfare([include_bankrupt])

Total welfare relative to expected value.

scores([assets_multiplier_trading, …])

scores of all agents given the asset multiplier.

simulation_step(stage)

A single step of the simulation.

start_contract_execution(contract)

Tries to execute the contract

trading_prices_for([discount, condition])

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

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

bankruptcy_rate

The fraction of factories that went bankrupt

Return type

float

contracts_df

Returns a pandas data frame with the contracts

Return type

DataFrame

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[SCML2020Agent]

num_bankrupt

The fraction of factories that went bankrupt

Return type

float

productivity

Fraction of production lines occupied during the simulation

Return type

float

relative_productivity

Productivity relative to the expected value. Will return None if self.info does not have the expected productivity

Return type

Optional[float]

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[SCML2020Agent]

trading_prices
winners

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

Methods Documentation

add_financial_report(agent, factory, reports_agent, reports_time)

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

Parameters
  • agent (SCML2020Agent) – The agent

  • factory (Factory) – Its factory

  • 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

breach_record(breach)

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

Return type

Dict[str, Any]

can_negotiate(a1, a2)
compensate(available, factory)

Called by a factory when it is going bankrupt after liquidation

Parameters
  • available (int) – The amount available from liquidation

  • factory (Factory) – The factory being bankrupted

Return type

Dict[str, List[Tuple[Contract, int, int]]]

Returns

A mapping from agent ID to nullified contracts, the new quantity for them and compensation_money

complete_contract_execution(contract, breaches, resolution)

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

Parameters
  • contract (Contract) – The contract considered.

  • breaches (List[Breach]) – The list of potential breaches that was generated by _execute_contract.

  • resolution (Contract) – The agreed upon resolution

Returns:

Return type

None

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

current_balance(agent_id)
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 (Union[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 (Optional[Callable[[Agent], bool]]) – Either a callable that receives an agent and returns True if it is to be shown or None for all

  • where (Optional[Callable[[Agent], Union[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 (Optional[Collection[Axis]]) – The axes used for drawing. If together is true, it should be a single Axis object otherwise it should be a list of Axis 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

Union[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

execute_action(action, agent, callback=None)

Executes the given action by the given agent

Return type

bool

classmethod generate(agent_types, agent_params=None, n_steps=(50, 200), n_processes=(2, 4), n_lines=10, n_agents_per_process=(2, 4), process_inputs=1, process_outputs=1, production_costs=(1, 4), profit_means=(0.15, 0.2), profit_stddevs=0.001, max_productivity=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=(0.2, 0.8), cash_availability=(1.5, 2.5), force_signing=False, profit_basis=<function amax>, horizon=(0.2, 0.5), inventory_valuation_trading=0.5, inventory_valuation_catalog=0.0, random_agent_types=False, cost_relativity=1.0, method='profitable', exogenous_supply_surplus=0.0, exogenous_sales_surplus=0.0, run_extra_checks=True, **kwargs)

Generates the configuration for a world

Parameters
  • agent_types (List[Type[SCML2020Agent]]) – All agent types

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

  • n_steps (Union[Tuple[int, int], int]) – Number of simulation steps

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

  • n_lines (Union[ndarray, Tuple[int, int], int]) – Number of lines per factory

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

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

  • production_costs (Union[ndarray, Tuple[int, int], int]) – Production cost per factory

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

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

  • inventory_valuation_catalog (Union[ndarray, Tuple[float, float], float]) – The fraction of catalog price to value items at the end.

  • inventory_valuation_trading (Union[ndarray, Tuple[float, float], float]) – The fraction of trading price to value items at the end.

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

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

  • n_agents_per_process (Union[ndarray, Tuple[int, int], int]) – Number of agents per process

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

  • horizon (Union[Tuple[float, float], float]) – The horizon used for revealing external supply/sales as a fraction of n_steps

  • 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 (Union[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 (Union[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

  • cash_availability (Union[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 .

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

  • exogenous_control (Union[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

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

  • cost_relativity (float) – The exponent of production cost used to distribute contracts during generation

  • method – The method used for world generation. Available methods are “profitable” and “guaranteed_profit”

  • exogenous_supply_surplus (Union[Tuple[float, float], float]) – The surpolus exogenous supply contract quantity to add to the system as a fraction of the a fraction of the contracts generated by the given method.

  • exogenous_sales_surplus (Union[Tuple[float, float], float]) – The surpolus exogenous sales contract quantity to add to the system as a fraction of the a fraction of the contracts generated by the given method.

  • run_extra_checks (bool) – If given, the world generation method will check whether the genrated world “makes sense” given its internal criteria. May slow down world generation

  • **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:

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

classmethod generate_guaranteed_profit(n_steps, n_lines, n_agents_per_process, process_of_agent, first_agent, last_agent, production_costs, exogenous_control, cash_availability, force_signing, horizon, exogenous_supplies, max_productivity_process, max_productivity_agent, equal_exogenous_sales, process_inputs, process_outputs, exogenous_sales_predictability, costs, profit_stddevs_agent=typing.List[float], profit_means_agent=typing.List[float], initial_balance=None, cost_relativity=1.0, profit_basis=<function amax>, inventory_valuation_trading=0.5, inventory_valuation_catalog=0.0, run_extra_checks=True)

Generates prices, contracts and profiles ensuring that all agents can profit and returning a set of explict contracts that can achieve this profit

Return type

Tuple[List[ExogenousContract], List[int], List[FactoryProfile], List[float], Dict[str, Any]]

classmethod generate_profitable(n_steps, n_lines, n_agents_per_process, process_of_agent, first_agent, last_agent, production_costs, exogenous_control, cash_availability, force_signing, horizon, exogenous_supplies, max_productivity_process, max_productivity_agent, equal_exogenous_sales, process_inputs, process_outputs, exogenous_sales_predictability, costs, profit_stddevs_agent=typing.List[float], profit_means_agent=typing.List[float], initial_balance=None, cost_relativity=1.0, profit_basis=<function amax>, inventory_valuation_trading=0.5, inventory_valuation_catalog=0.0, run_extra_checks=True)

Generates the prices, contracts and profiles ensuring there is some possibility of profit in the market

Return type

Tuple[List[ExogenousContract], List[int], List[FactoryProfile], List[float], Dict[str, Any]]

get_private_state(agent)

Reads the private state of the given agent

Return type

dict

is_valid_contact(contract)

Checks whether a signed contract is valid

Return type

bool

negs_between(a1, a2)
nullify_contract(contract, new_quantity)
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_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.

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

record_bankrupt(factory)

Records agent bankruptcy

Return type

None

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]

scores(assets_multiplier_trading=None, assets_multiplier_catalog=None, assets_multiplier=None)

scores of all agents given the asset multiplier.

Parameters

assets_multiplier (Optional[float]) – a multiplier to multiply the assets with.

Return type

Dict[str, float]

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.

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

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

welfare(include_bankrupt=False)

Total welfare of all agents

Return type

float