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=False, shuffle_negotiations=False, 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.mixins.TimeInAgreementMixin
,negmas.situated.world.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 productsprofiles (
list
[FactoryProfile
]) – An n_agents list ofFactoryProfile
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 agentagent_params (
Optional
[list
[dict
[str
,Any
]]]) – An n_agents dictionaries giving the parameters of each agentinitial_balance (
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 (
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 pricespot_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 contractsexogenous_force_max (
bool
) – If true, exogenous contracts are forced to be signed independent of the setting offorce_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
**kwargs – Other parameters that are passed directly to
SCML2020World
constructor.
Attributes Summary
Fraction of negotiations ending in agreement and leading to signed contracts
Fraction of negotiations ending in agreement and leading to signed contracts
The fraction of factories that went bankrupt
Fraction of signed contracts that led to breaches
The average breach level per contract
Fraction of signed contracts that led to breaches
The total business size defined as the total money transferred within the system
Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.
Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.
Fraction of signed contracts that were never executed because they were signed to late to be executable
Fraction of signed contracts that caused exception during their execution
Fraction of signed contracts successfully executed with no breaches, or errors
Fraction of signed contracts were nullified by the system (e.g.
Returns a pandas data frame with the contracts
The unique ID of this entity
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
Average number of rounds in a successful negotiation
Average number of rounds in a successful negotiation
Returns a mapping from agent ID to the total number of exceptions its negotiators have raised
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
Returns the total number of exceptions per step that are not directly raised by agents or their negotiators.
A convenient name of the entity (intended primarily for printing/logging/debugging).
Returns names of all agents except system agents
Returns names of all agents except system agents
Returns all agents except system agents
The fraction of factories that went bankrupt
Fraction of production lines occupied during the simulation
Productivity relative to the expected value.
Returns a number between
0
and1
indicating elapsed relative time or steps.Returns the remaining number of steps until the end of the mechanism run.
Returns remaining time in seconds.
- rtype
Returns a pandas data frame with the stats
Returns the names two system agents
Returns the names two system agents
Returns the two system agents
Elapsed time since world started in seconds.
Returns total simulation time (till now) in mx
- rtype
The unique ID of this entity
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
announce
(event)Raises an event and informs all event sinks that are registered for notifications on this event type
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
can_negotiate
(a1, a2)checkpoint
(path[, file_name, info, ...])Saves a checkpoint of the current object at the given path.
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
Should be called on every step to save checkpoints as needed.
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.
create
(*args, **kwargs)Creates an object and returns a proxy to it.
current_balance
(agent_id)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
Called at every time-step to get the contracts that are
executable
at this point of the simulationexecute_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
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
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])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
negs_between
(a1, a2)nullify_contract
(contract, new_quantity)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
Called at the end of the simulation step to update all 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
record_bankrupt
(factory)Records agent bankruptcy
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.
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
scores
([assets_multiplier_trading, ...])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
()A single simulation step
trading_prices_for
([discount, condition])Calculates the prices at which all products traded using an optional discount factor
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
- agreement_rate¶
Fraction of negotiations ending in agreement and leading to signed contracts
- Return type
- business_size¶
The total business size defined as the total money transferred within the system
- Return type
- cancellation_fraction¶
Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.
- Return type
- cancellation_rate¶
Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.
- Return type
- contract_dropping_fraction¶
Fraction of signed contracts that were never executed because they were signed to late to be executable
- Return type
- contract_err_fraction¶
Fraction of signed contracts that caused exception during their execution
- Return type
- contract_execution_fraction¶
Fraction of signed contracts successfully executed with no breaches, or errors
- Return type
- contract_nullification_fraction¶
Fraction of signed contracts were nullified by the system (e.g. due to bankruptcy)
- Return type
- contracts_df¶
Returns a pandas data frame with the contracts
- Return type
DataFrame
- current_step¶
- 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_successful¶
Average number of rounds in a successful negotiation
- Return type
- 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.
- Remarks:
This property sums the totals of
n_simulation_exceptions
,n_contract_exceptions
, andn_mechanism_exceptions
- name¶
A convenient name of the entity (intended primarily for printing/logging/debugging).
- non_system_agents¶
Returns all agents except system agents
- Return type
- relative_productivity¶
Productivity relative to the expected value. Will return None if self.info does not have the expected productivity
- relative_time¶
Returns a number between
0
and1
indicating elapsed relative time or steps.- Return type
- remaining_steps¶
Returns the remaining number of steps until the end of the mechanism run. None if unlimited
- remaining_time¶
Returns remaining time in seconds. None if no time limit is given.
- stats_df¶
Returns a pandas data frame with the stats
- Return type
DataFrame
- system_agents¶
Returns the two system agents
- Return type
- time¶
Elapsed time since world started in seconds. 0.0 if the world did not start running
- Return type
- total_time¶
Returns total simulation time (till now) in mx
- trading_prices¶
- 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, 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 agentfactory (
Factory
) – Its factoryreports_agent – A dictionary of financial reports indexed by agent id
reports_time – A dictionary of financial reports indexed by time
Returns:
- Return type
- 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
- can_negotiate(a1, a2)¶
- 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 checkpointfile_name (
Optional
[str
]) – Name of the file to dump into. If not given, a unique name is createdinfo (
Optional
[dict
[str
,Any
]]) – Information to save with the checkpoint (must be json serializable)exist_ok (
bool
) – If true, override existing dumpsingle_checkpoint (
bool
) – If true, keep a single checkpoint for the last stepstep_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
- 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.
- classmethod checkpoint_info(file_name)¶
Returns the information associated with a dump of the object saved in the given file
Returns:
- 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 conceptevery (
int
) – Number of steps per checkpoint. If < 1 no checkpoints will be savedfolder (
Optional
[PathLike
]) – The directory to store checkpoints underfilename (
Optional
[str
]) – Name of the file to save the checkpoint under. If None, a unique name will be chosen. Ifsingle_checkpoint
was False, then multiple files will be used prefixed with the step numberinfo (
Optional
[dict
[str
,Any
]]) – Any extra information to save in the json file associated with each checkpointexist_ok (
bool
) – Override existing files if anysingle (
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
- 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
- compensate(available, factory)¶
Called by a factory when it is going bankrupt after liquidation
- 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
- 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. Higher is better :type contract:
Contract
:param contract:Returns:
- Return type
- 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
- 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 accomulatedwhat (
Collection
[str
]) – The edges to have on the graph. Options are: negotiations, concluded, signed, executedwho (
Optional
[Callable
[[Agent
],bool
]]) – Either a callable that receives an agent and returns True if it is to be shown or None for allwhere (
Optional
[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 (
Optional
[Collection
[Axis
]]) – The axes used for drawing. If together is true, it should be a singleAxis
object otherwise it should be a list ofAxis
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
- 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
- classmethod from_checkpoint(file_name, return_info=False)¶
Creates an object from a saved checkpoint
- Parameters
- Return type
- 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
section (
Optional
[str
]) – A section in the file or a key in the dictionary to use for loading paramsignore_children (
bool
) – If true then children will be ignored and there will be a single returntry_parsing_children (
bool
) – If true the children will first be parsed asConfigReader
classes if they are notint (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, 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
] |str
]) – All agent typesagent_params (
Optional
[list
[dict
[str
,Any
]]]) – Agent parameters used to initialize themn_steps (
tuple
[int
,int
] |int
) – Number of simulation stepsn_processes (
tuple
[int
,int
] |int
) – Number of processes in the production chainn_lines (
ndarray
|tuple
[int
,int
] |int
) – Number of lines per factoryprocess_inputs (
ndarray
|tuple
[int
,int
] |int
) – Number of input units per processprocess_outputs (
ndarray
|tuple
[int
,int
] |int
) – Number of output units per processproduction_costs (
ndarray
|tuple
[int
,int
] |int
) – Production cost per factoryprofit_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).inventory_valuation_catalog (
ndarray
|tuple
[float
,float
] |float
) – The fraction of catalog price to value items at the end.inventory_valuation_trading (
ndarray
|tuple
[float
,float
] |float
) – The fraction of trading price to value items at the end.max_productivity (
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 agentsn_agents_per_process (
ndarray
|tuple
[int
,int
] |int
) – Number of agents per processcost_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 (
tuple
[float
,float
] |float
) – The horizon used for revealing external supply/sales as a fraction of n_stepsequal_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 randomexogenous_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 randomcash_availability (
tuple
[float
,float
] |float
) – The fraction of the total money needs of the agent to work at maximum capacity that is available asinitial_balance
. This is only effective ifinitial_balance
is set toNone
.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 Truerandom_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 generationmethod – The method used for world generation. Available methods are “profitable” and “guaranteed_profit”
exogenous_supply_surplus (
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 (
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
- 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 lengthn_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
- 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
- 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
]
- 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 (
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 accumulatedwhat (
Collection
[str
]) – The edges to have on the graph. Options are: negotiations, concluded, signed, executedwho (
Optional
[Callable
[[Agent
],bool
]]) – Either a callable that receives an agent and returns True if it is to be shown or None for alltogether (
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')¶
- is_valid_agreement(negotiation, agreement, mechanism)¶
Confirms that the agreement is valid given the world rules.
- Parameters
negotiation (
NegotiationInfo
) – TheNegotiationInfo
that led to the agreementagreement (
tuple
) – The agreementmechanism (
Mechanism
) – The mechanism that led to the agreement
- Return type
- 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_contract(contract)¶
Confirms that the agreement is valid given the world rules.
- Parameters
contract (
Contract
) – The contract being tested- Return type
- 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
Returns:
- logdebug(s, event=None)¶
logs debug-level information
- logdebug_agent(aid, s, event=None)¶
logs debug to the agent individual log
- logerror(s, event=None)¶
logs error-level information
- logerror_agent(aid, s, event=None)¶
logs information to the agent individual log
- loginfo(s, event=None)¶
logs info-level information
- loginfo_agent(aid, s, event=None)¶
logs information to the agent individual log
- logwarning(s, event=None)¶
logs warning-level information
- logwarning_agent(aid, s, event=None)¶
logs warning to the agent individual log
- n_saved_contracts(ignore_no_issue=True)¶
Number of saved contracts
- negs_between(a1, a2)¶
- nullify_contract(contract, new_quantity)¶
- 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 addto_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
- 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
- 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.
- 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
- Return type
- 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 registeredsimulation_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.
- 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
- 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 callercaller (
Agent
) – The agent requesting the negotiationpartners (
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 ifroles
was passed as None.issues (
list
[Issue
]) – Negotiation issuesannotation (
Optional
[dict
[str
,Any
]]) – Extra information to be passed to thepartners
when asking them to join the negotiationpartners – 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 Nonemechanism_name (
Optional
[str
]) – Name of the mechanism to use. It must be one of the mechanism_names that are supported by theNone (must also be) –
my_role (then roles and) –
None –
mechanism_params (
Optional
[dict
[str
,Any
]]) – A dict of parameters used to initialize the mechanism objectgroup (
Optional
[str
]) – An identifier for the group to which the negotiation belongs. This is not not used by the system.
- Return type
- Returns
None. The caller will be informed by a callback function
on_neg_request_accepted
oron_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 negotiationpartners (
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 ifroles
was passed as None.negotiator (
Negotiator
) – The negotiator to be used in the negotiationpreferences (
Optional
[Preferences
]) – The utility function. Only needed if the negotiator does not already know itcaller_role (
Optional
[str
]) – The role of the caller in the negotiationissues (
list
[Issue
]) – Negotiation issuesannotation (
Optional
[dict
[str
,Any
]]) – Extra information to be passed to thepartners
when asking them to join the negotiationpartners – 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 Nonemechanism_name (
Optional
[str
]) – Name of the mechanism to use. It must be one of the mechanism_names that are supported by theNone (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
- 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 negotiationpartners (
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 ifroles
was passed as None.issues (
list
[Issue
] |list
[list
[Issue
]]) – Negotiation issuesnegotiators (
list
[Negotiator
]) – The negotiator to be used in the negotiationufuns – 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 negotiationannotations (
Optional
[list
[dict
[str
,Any
] |None
]]) – Extra information to be passed to thepartners
when asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles (
Optional
[list
[list
[str
] |None
]]) – The roles of different partners. If None then each role for each partner will be Nonemechanism_names (
Union
[str
,list
[str
],None
]) – Name of the mechanism to use. It must be one of the mechanism_names that are supported by theNone (must also be) –
my_role (then roles and) –
None –
mechanism_params (
Union
[dict
[str
,Any
],list
[dict
[str
,Any
]],None
]) – A dict of parameters used to initialize the mechanism objectall_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
- 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
- scores(assets_multiplier_trading=None, assets_multiplier_catalog=None, assets_multiplier=None)¶
scores of all agents given the asset multiplier.
- 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).
- trading_prices_for(discount=1.0, condition='executed')¶
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
- 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.