scml.oneshot.world
Module Contents
Classes
Implements the a generalized form of SCML-OneShot game which supports both oneshot and standard simulations |
|
Basic oneshot simulation |
|
Oneshot simulation as used in SCML 2020 competition |
|
Oneshot simulation as used in SCML 2021 competition |
|
Oneshot simulation as used in SCML 2022 competition |
|
Oneshot simulation as used in SCML 2023 competition |
|
Oneshot simulation as used in SCML 2024 competition |
Attributes
- class scml.oneshot.world.SCMLBaseWorld(catalog_prices: numpy.ndarray, profiles: list[scml.oneshot.common.OneShotProfile], agent_types: list[type[scml.oneshot.agent.OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | numpy.ndarray = 50, financial_report_period=5, bankruptcy_limit=0.0, penalize_bankrupt_for_future_contracts=True, penalties_scale: Literal[trading, catalog, unit, none] = 'trading', exogenous_contracts: Collection[scml.oneshot.common.OneShotExogenousContract] = tuple(), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: numpy.ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=60 * 15, sync_calls=False, neg_n_steps=20, neg_time_limit=None, neg_hidden_time_limit=60, neg_step_time_limit=20, negotiation_speed=None, shuffle_negotiations=False, one_offer_per_step=False, publish_exogenous_summary=True, publish_trading_prices=True, publish_assets=False, publish_production_capacity=True, price_multiplier=0.0, price_range_fraction=0.0, wide_price_range=False, allow_zero_quantity: bool = False, trading_price_discount=0.9, signing_delay=0, force_signing=False, batch_signing=True, name: str | None = None, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_catalog=0, inventory_valuation_trading=0, perishable=True, horizon=0, one_time_per_negotiation=True, quantity_multiplier: float = 1.0, nullify_bankrupt_contracts: bool = False, debug: bool = False, verbose: bool = False, **kwargs)[source]
Bases:
negmas.TimeInAgreementMixin
,negmas.World
[scml.oneshot.awi.OneShotAWI
,scml.oneshot.sysagents.DefaultOneShotAdapter
]Implements the a generalized form of SCML-OneShot game which supports both oneshot and standard simulations
- Parameters:
catalog_prices – An n_products vector (i.e. n_processes+1 vector) giving the catalog price of all products
profiles – An n_agents list of
OneShotFactoryProfile
objects specifying the private profile of the factory associated with each agent.agent_types – An n_agents list of strings/
OneShotAgent
classes specifying the type of each agentagent_params – An n_agents dictionaries giving the parameters of each agent
catalog_quantities – 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
financial_report_period – The number of steps between financial reports. If < 1, it is a fraction of n_steps
exogenous_force_max – If true, exogenous contracts are forced to be signed independent of the setting of
force_signing
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 – The name of the simulations
**kwargs – Other parameters that are passed directly to
SCML2020World
constructor.
- property system_agents: list[scml.oneshot.sysagents._StdSystemAgent][source]
Returns the two system agents
- property non_system_agents: list[scml.oneshot.sysagents.DefaultOneShotAdapter][source]
Returns all agents except system agents
- property non_system_agent_names: list[str][source]
Returns names of all agents except system agents
- property agreement_fraction: float[source]
Fraction of negotiations ending in agreement and leading to signed contracts
- classmethod replace_agents(config: dict, old_types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | list[str | type[scml.oneshot.agent.OneShotAgent]], types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | list[str | type[scml.oneshot.agent.OneShotAgent]], params: list[dict[str, Any]] | tuple[dict[str, Any], Ellipsis] | None = None)[source]
Replaces all agents of a given type by agents of a new type
- classmethod generate(agent_types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | list[str | type[scml.oneshot.agent.OneShotAgent]] | type[scml.oneshot.agent.OneShotAgent] | str, agent_params: list[dict[str, Any]] | tuple[dict[str, Any], Ellipsis] | None = None, agent_processes: list[int] | None = None, n_steps: tuple[int, int] | int = (50, 200), n_processes: tuple[int, int] | int = 2, n_lines: numpy.ndarray | tuple[int, int] | int = 10, n_agents_per_process: numpy.ndarray | tuple[int, int] | int = (4, 8), process_inputs: numpy.ndarray | tuple[int, int] | int = 1, process_outputs: numpy.ndarray | tuple[int, int] | int = 1, production_costs: numpy.ndarray | tuple[int, int] | int = (1, 4), profit_means: numpy.ndarray | tuple[float, float] | float = (0.1, 0.2), profit_stddevs: numpy.ndarray | tuple[float, float] | float = 0.05, max_productivity: numpy.ndarray | tuple[float, float] | float = (0.8, 1.0), initial_balance: numpy.ndarray | tuple[int, int] | int | None = None, exogenous_supply_predictability: tuple[float, float] | float = (0.6, 0.9), exogenous_sales_predictability: tuple[float, float] | float = (0.6, 0.9), exogenous_control: tuple[float, float] | float = -1, cash_availability: tuple[float, float] | float = (1.5, 2.5), shortfall_penalty: tuple[float, float] | float = (0.2, 1.0), shortfall_penalty_dev: tuple[float, float] | float = (0.0, 0.1), disposal_cost: tuple[float, float] | float = (0.0, 0.2), disposal_cost_dev: tuple[float, float] | float = (0.0, 0.02), storage_cost: tuple[float, float] | float = (0.0, 0.02), storage_cost_dev: tuple[float, float] | float = 0, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), price_multiplier: numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), cost_increases_with_level=True, equal_exogenous_supply=False, equal_exogenous_sales=False, force_signing=True, profit_basis=np.max, random_agent_types: bool = False, penalties_scale: str | list[str] = 'trading', cap_exogenous_quantities: bool = True, exogenous_generation_method='profitable', perishable: bool | None = True, max_supply: numpy.ndarray | tuple[float, float] | float = (0.8, 1.0), **kwargs) dict[str, Any] [source]
Generates the configuration for a world
- Parameters:
agent_types – All agent types
agent_params – Agent parameters used to initialize them
n_steps – Number of simulation steps
n_processes – Number of processes in the production chain
n_lines – Number of lines per factory
process_inputs – Number of input units per process
process_outputs – Number of output units per process
production_costs – Production cost per factory
profit_means – Mean profitability per production level (i.e. process).
profit_stddevs – Std. Dev. of the profitability of every level (i.e. process).
max_productivity – Maximum possible productivity per level (i.e. process).
max_supply – Maximum possible supply level to the market,
initial_balance – The initial balance of all agents
n_agents_per_process – Number of agents per process
agent_processes – The process for each agent. If not
None
, it will overriden_agents_per_process
and must be a list/tuple of the same length asagent_types
. Morevoer,random_agent_types
must be False in this casecost_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 – 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 – 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 – 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 – If True, all exogenous quantities in all contracts are capped to be no more than the number of lines
cash_availability – 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 ifinitial_balance
is set toNone
.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 – A range to sample mean-disposal costs for all factories from (only used if perishable is True)
shortfall_penalty – A range to sample mean-shortfall penalty for all factories from
storage_cost – A range to sample mean-storage costs fro all factories from (only used if perishable is False)
disposal_cost_dev – A range to sample std. dev of disposal costs for all factories from
shortfall_penalty_dev – A range to sample std. dev of shortfall penalty for all factories from
storage_cost_dev – The standard deviation of storage cost relative to the mean price
exogenous_price_dev – The standard deviation of exogenous contract prices relative to the mean price
price_multiplier – A value to multiply with trading/catalog price to get the upper limit on prices for all negotiations
random_agent_types – If True, the final agent types used by the generator will always be sampled from the given types. If False, this random sampling will only happen if len(agent_types) != n_agents.
penalties_scale – What are
disposal_cost
andshortfall_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 andnone
means thestorage-cost
andshortfall_penalty
are absolute values (in money unit). If not given will be read through the AWIexogenous_generation_method – the generation method. This is only for compatibility with SCML2020World and is not used.
perishable – If True, storage_cost is set to zero as there is no storage and if False, disposal_cost is set to zero as there is no disposal. If None, neither is overridden.
**kwargs –
- Returns:
world configuration as a Dict[str, Any]. A world can be generated from this dict by calling OneShotWorld(**d)
Remarks:
- There are two general ways to use this generator:
Pass
random_agent_types = False
, and passagent_types
,agent_processes
to control placement of each agent in each level of the production graph.Pass
random_agent_types = True
and passagent_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 lengthn_processes
, it is used as it is otherwise, it is used to sample values for each process.
- add_financial_report(agent: scml.oneshot.sysagents.DefaultOneShotAdapter, reports_agent, reports_time) None [source]
Records a financial report for the given agent in the agent indexed reports and time indexed reports
- Parameters:
agent – The agent
reports_agent – A dictionary of financial reports indexed by agent id
reports_time – A dictionary of financial reports indexed by time
Returns:
- step_with(actions: dict[str, dict[str, negmas.SAOResponse]], init=False) bool [source]
Runs a simulation step for the agents given in keys passing the corresponding values as counter offers.
- 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 thatinit()
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 asTrue
(default isFalse
).
- simulation_step(stage=0)[source]
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.
- on_contract_signed(contract: negmas.Contract) bool [source]
Called to add a contract to the existing set of contract after it is signed
- Parameters:
contract – The contract to add
- 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.
- contract_record(contract: negmas.Contract) dict[str, Any] [source]
Converts a contract to a record suitable for permanent storage
- breach_record(breach: negmas.Breach) dict[str, Any] [source]
Converts a breach to a record suitable for storage during the simulation
- execute_action(action, agent, callback: Callable | None = None) bool [source]
Executes the given action by the given agent
- contract_size(contract: negmas.Contract) float [source]
Returns an estimation of the activity level associated with this contract. Higher is better :param contract:
Returns:
- post_step_stats()[source]
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()[source]
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
- relative_welfare(include_bankrupt: bool = False) float | None [source]
Total welfare relative to expected value. Returns None if no expectation is found in self.info
- is_valid_contact(contract: negmas.Contract) bool [source]
Checks whether a signed contract is valid
- scores(assets_multiplier: float = 0.0) dict[str, float] [source]
Scores of all agents given the asset multiplier.
- Parameters:
assets_multiplier – A multiplier to multiply the assets with.
- trading_prices_for(discount: float = 1.0, condition='executed') numpy.ndarray [source]
Calculates the prices at which all products traded using an optional discount factor
- Parameters:
discount – 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
- Returns:
an n_products vector of trading prices
- draw(steps: tuple[int, int] | int | None = None, what: Collection[str] = DEFAULT_EDGE_TYPES, who: Callable[[negmas.Agent], bool] | None = None, where: Callable[[negmas.Agent], int | tuple[float, float]] | None = None, together: bool = True, axs: Collection[matplotlib.axis.Axis] | None = None, ncols: int = 4, figsize: tuple[int, int] = (15, 15), **kwargs) tuple[matplotlib.axis.Axis, networkx.Graph] | tuple[list[matplotlib.axis.Axis], list[networkx.Graph]] [source]
- _request_negotiations(agent_id: str, controller: negmas.sao.SAOController | None = None, negotiators: list[negmas.sao.SAONegotiator] | None = None, extra: dict[str, Any] | None = None) bool [source]
Requests negotiations (used internally)
- Parameters:
agent_id – the agent requesting
product – The product to negotiate about
quantity – The minimum and maximum quantities. Passing a single value q is equivalent to passing (q,q)
unit_price – The minimum and maximum unit prices. Passing a single value u is equivalent to passing (u,u)
time – The minimum and maximum delivery step. Passing a single value t is equivalent to passing (t,t)
controller – The controller to manage the complete set of negotiations
negotiators – An optional list of negotiators to use for negotiating with the given partners (in the same order).
extra – Extra information accessible through the negotiation annotation to the caller
consumer_starts (#) – Whether the consumer or supplier sends the first offer in the negotiation
- Returns:
True
if the partner accepted and the negotiation is ready to start
- _request_negotiation(agent_id: str, product: int, partner: str, negotiator: negmas.sao.SAONegotiator, extra: dict[str, Any] | None = None, is_buy: bool = True) negmas.situated.NegotiationInfo | None [source]
Requests a negotiation
- Parameters:
product – The product to negotiate about
quantity – The minimum and maximum quantities. Passing a single value q is equivalent to passing (q,q)
unit_price – The minimum and maximum unit prices. Passing a single value u is equivalent to passing (u,u)
time – The minimum and maximum delivery step. Passing a single value t is equivalent to passing (t,t)
partner – ID of the partner to negotiate with.
negotiator – The negotiator to use for this negotiation (if the partner accepted to negotiate)
extra – Extra information accessible through the negotiation annotation to the caller
is_buy – whether the consumer starts the negotiation
- Returns:
True
if the partner accepted and the negotiation is ready to start
- _make_issues(product) tuple[tuple[int, int], tuple[int, int], tuple[int, int]] [source]
Creates the negotiation agendas
- Parameters:
product (int) – The product to be negotiated about
- Returns:
A tuple of minimum and maximum values for unit-price, time, and quantity in that order
- order_contracts_for_execution(contracts: Collection[negmas.Contract]) Collection[negmas.Contract] [source]
Orders the contracts in a specific time-step that are about to be executed
- start_contract_execution(contract: negmas.Contract) set[negmas.Breach] | None [source]
Tries to execute the contract
- Parameters:
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).
- complete_contract_execution(contract: negmas.Contract, breaches: list[negmas.Breach], resolution: negmas.Contract) None [source]
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:
- classmethod plot_combined_stats(worlds: tuple[SCMLBaseWorld, Ellipsis] | SCMLBaseWorld, stats: str | tuple[str, Ellipsis] | None = None, pertype=False, makefig=False, title=True, ylabel=False, xlabel=False, legend=True, figsize=None, perishable: bool = False, **kwargs)[source]
Plots combined statistics of multiple worlds in a single plot
- Parameters:
stats – The statistics to plot. If
None
, some selected stats will be displayedpertype – combine agent-statistics per type
use_sum – plot sum for type statistics instead of mean
title – If given a title will be added to each subplot
ylabel – If given, the ylabel will be added to each subplot
xlabel – If given The xlabel will be added (Simulation Step)
legend – If given, a legend will be displayed
makefig – If given a new figure will be started
figsize – Size of the figure to host the plot
ylegend – y-axis of legend for cases with large number of labels
legend_n_cols – number of columns in the legend
- plot_stats(stats: str | tuple[str, Ellipsis] | None = None, pertype=False, use_sum=False, makefig=False, title=True, ylabel=False, xlabel=False, legend=True, figsize=None, ylegend=2.0, legend_ncols=8)[source]
Plots statistics of the world in a single plot
- Parameters:
stats – The statistics to plot. If
None
, some selected stats will be displayedpertype – combine agent-statistics per type
use_sum – plot sum for type statistics instead of mean
title – If given a title will be added to each subplot
ylabel – If given, the ylabel will be added to each subplot
xlabel – If given The xlabel will be added (Simulation Step)
legend – If given, a legend will be displayed
makefig – If given a new figure will be started
figsize – Size of the figure to host the plot
ylegend – y-axis of legend for cases with large number of labels
- class scml.oneshot.world.OneShotWorld(catalog_prices: numpy.ndarray, profiles: list[scml.oneshot.common.OneShotProfile], agent_types: list[type[scml.oneshot.agent.OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | numpy.ndarray = 50, financial_report_period=5, bankruptcy_limit=0.0, penalize_bankrupt_for_future_contracts=True, penalties_scale: Literal[trading, catalog, unit, none] = 'trading', exogenous_contracts: Collection[scml.oneshot.common.OneShotExogenousContract] = tuple(), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: numpy.ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=60 * 15, sync_calls=False, neg_n_steps=20, neg_time_limit=None, neg_hidden_time_limit=60, neg_step_time_limit=20, negotiation_speed=None, shuffle_negotiations=False, one_offer_per_step=False, publish_exogenous_summary=True, publish_trading_prices=True, publish_assets=False, publish_production_capacity=True, price_multiplier=0.0, price_range_fraction=0.0, wide_price_range=False, allow_zero_quantity: bool = False, trading_price_discount=0.9, signing_delay=0, force_signing=False, batch_signing=True, name: str | None = None, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_catalog=0, inventory_valuation_trading=0, perishable=True, horizon=0, one_time_per_negotiation=True, quantity_multiplier: float = 1.0, nullify_bankrupt_contracts: bool = False, debug: bool = False, verbose: bool = False, **kwargs)[source]
Bases:
SCMLBaseWorld
Basic oneshot simulation
- class scml.oneshot.world.SCML2020OneShotWorld(catalog_prices: numpy.ndarray, profiles: list[scml.oneshot.common.OneShotProfile], agent_types: list[type[scml.oneshot.agent.OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | numpy.ndarray = 50, financial_report_period=5, bankruptcy_limit=0.0, penalize_bankrupt_for_future_contracts=True, penalties_scale: Literal[trading, catalog, unit, none] = 'trading', exogenous_contracts: Collection[scml.oneshot.common.OneShotExogenousContract] = tuple(), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: numpy.ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=60 * 15, sync_calls=False, neg_n_steps=20, neg_time_limit=None, neg_hidden_time_limit=60, neg_step_time_limit=20, negotiation_speed=None, shuffle_negotiations=False, one_offer_per_step=False, publish_exogenous_summary=True, publish_trading_prices=True, publish_assets=False, publish_production_capacity=True, price_multiplier=0.0, price_range_fraction=0.0, wide_price_range=False, allow_zero_quantity: bool = False, trading_price_discount=0.9, signing_delay=0, force_signing=False, batch_signing=True, name: str | None = None, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_catalog=0, inventory_valuation_trading=0, perishable=True, horizon=0, one_time_per_negotiation=True, quantity_multiplier: float = 1.0, nullify_bankrupt_contracts: bool = False, debug: bool = False, verbose: bool = False, **kwargs)[source]
Bases:
OneShotWorld
Oneshot simulation as used in SCML 2020 competition
- class scml.oneshot.world.SCML2021OneShotWorld(*args, **kwargs)[source]
Bases:
SCML2020OneShotWorld
Oneshot simulation as used in SCML 2021 competition
- class scml.oneshot.world.SCML2022OneShotWorld(*args, **kwargs)[source]
Bases:
SCML2021OneShotWorld
Oneshot simulation as used in SCML 2022 competition
- class scml.oneshot.world.SCML2023OneShotWorld(*args, **kwargs)[source]
Bases:
SCML2020OneShotWorld
Oneshot simulation as used in SCML 2023 competition
- class scml.oneshot.world.SCML2024OneShotWorld(*args, **kwargs)[source]
Bases:
SCML2023OneShotWorld
Oneshot simulation as used in SCML 2024 competition