scml

class scml.ANACContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, non_competitors: tuple[str | type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, n_agents_per_process: ~numpy.ndarray | list[int] | tuple[int, int] | int = (4, 8), production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True, year: int = 2024)[source]

Generates a oneshot world with no constraints except compatibility with a specific ANAC competition year.

class scml.ANACOneShotContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, non_competitors: tuple[str | type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, n_agents_per_process: ~numpy.ndarray | list[int] | tuple[int, int] | int = (4, 8), production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True, year: int = 2024)[source]

Generates a oneshot world with no constraints except compatibility with a specific ANAC competition year.

class scml.AWI(world: World, agent: Agent)[source]

The Agent SCML2020World Interface for SCML2020 world.

This class contains all the methods needed to access the simulation to extract information which are divided into 5 groups:

Static World Information:

Information about the world and the agent that does not change over time. These include:

  1. Market Information:

  • n_products: Number of products in the production chain.

  • n_processes: Number of processes in the production chain.

  • n_competitors: Number of other factories on the same production level.

  • all_suppliers: A list of all suppliers by product.

  • all_consumers: A list of all consumers by product.

  • catalog_prices: A list of the catalog prices (by product).

  • inputs: Inputs to every manufacturing process.

  • outputs: Outputs to every manufacturing process.

  • is_system: Is the given system ID corresponding to a system agent?

  • is_bankrupt: Is the given agent bankrupt (None asks about self)?

  • current_step: Current simulation step (inherited from negmas.situated.AgentWorldInterface ).

  • n_steps: Number of simulation steps (inherited from negmas.situated.AgentWorldInterface ).

  • relative_time: fraction of the simulation completed (inherited from negmas.situated.AgentWorldInterface).

  • settings: The system settings (inherited from negmas.situated.AgentWorldInterface ).

  1. Agent Information:

  • profile: Gives the agent profile including its production cost, number of production lines, input product index, mean of its delivery penalties, mean of its disposal costs, standard deviation of its shortfall penalties and standard deviation of its disposal costs. See OneShotProfile for full description. This information is private information and no other agent knows it.

  • n_lines: the number of production lines in the factory (private information).

  • is_first_level: Is the agent in the first production level (i.e. it is an input agent that buys the raw material).

  • is_last_level: Is the agent in the last production level (i.e. it is an output agent that sells the final product).

  • is_middle_level: Is the agent neither a first level nor a last level agent

  • my_input_product: The input product to the factory controlled by the agent.

  • my_output_product: The output product from the factory controlled by the agent.

  • my_input_products: All input products of a factory controlled by the agent. Currently, it is always a list of one item. For future compatibility.

  • my_output_products: All output products of a factory controlled by the agent. Currently, it is always a list of one item. For future compatibility.

  • available_for_production: Returns the line-step slots available for production.

  • level: The production level which is numerically the same as the input product.

  • my_suppliers: A list of IDs for all suppliers to the agent (i.e. agents that can sell the input product of the agent).

  • my_consumers: A list of IDs for all consumers to the agent (i.e. agents that can buy the output product of the agent).

  • penalties_scale: The scale at which to calculate disposal cost/delivery penalties. “trading” and “catalog” mean trading and catalog prices. “unit” means the contract’s unit price while “none” means that disposal cost/shortfall penalty are absolute.

  • n_input_negotiations: Number of negotiations with suppliers.

  • n_output_negotiations: Number of negotiations with consumers.

  • state: The full state of the agent ( FactoryState ).

  • current_balance: The current balance of the agent

  • current_inventory: The current inventory of the agent (quantity per product)

Dynamic World Information:

Information about the world and the agent that changes over time.

  1. Market Information:

  • trading_prices: The trading prices of all products. This information is only available if publish_trading_prices is set in the world.

  • exogenous_contract_summary: A list of n_products tuples each giving the total quantity and average price of exogenous contracts for a product. This information is only available if publish_exogenous_summary is set in the world.

  1. Other Agents’ Information:

  • reports_of_agent: Gives all past financial reports of a given agent. See FinancialReport for details.

  • reports_at_step: Gives all reports of all agents at a given step. See FinancialReport for details.

  1. Current Negotiations Information:

  • current_input_issues: The current issues for all negotiations to buy the input product of the agent. If the agent is at level zero, this will be empty.

  • current_output_issues: The current issues for all negotiations to buy the output product of the agent. If the agent is at level n_products - 1, this will be empty.

  1. Agent Information:

  • spot_market_quantity: The quantity the agent bought from the spot market at

    a given step

  • spot_market_loss: The spot market loss for the agent.

Actions:
  1. Negotiation Control:

  • request_negotiations: Requests a set of negotiations controlled by a single controller.

  • request_negotiation: Requests a negotiation controlled by a single negotiator.

  1. Production Control:

  • schedule_production: Schedules production using one of the predefined scheduling strategies.

  • order_production: Orders production directly for the current step.

  • set_commands: Sets production commands directly on the factory.

  • cancel_production: Cancels a scheduled production command.

Services (All inherited from negmas.situated.AgentWorldInterface):
  • logdebug/loginfo/logwarning/logerror: Logs to the world log at the given log level.

  • logdebug_agent/loginf_agnet/…: Logs to the agent specific log at the given log level.

  • bb_query: Queries the bulletin-board.

  • bb_read: Read a section of the bulletin-board.

property all_consumers: List[List[str]]

Returns a list of agent IDs for all consumers for every product

property all_suppliers: List[List[str]]

Returns a list of agent IDs for all suppliers for every product

property allow_zero_quantity: bool

Does negotiations allow zero quantity?

available_for_production(repeats: int, step: int | Tuple[int, int] = -1, line: int = -1, override: bool = True, method: str = 'latest') Tuple[ndarray, ndarray][source]

Finds available times and lines for scheduling production.

Parameters:
  • repeats – How many times to repeat the process

  • step – The simulation step or a range of steps. The special value ANY_STEP gives the factory the freedom to schedule production at any step in the present or future.

  • line – The production line. The special value ANY_LINE gives the factory the freedom to use any line

  • override – Whether to override any existing commands at that line at that time.

  • method – When to schedule the command if step was set to a range. Options are latest, earliest, all

Returns:

Tuple[np.ndarray, np.ndarray] The steps and lines at which production is scheduled.

Remarks:

  • You cannot order production in the past or in the current step

  • Ordering production, will automatically update inventory and balance for all simulation steps assuming that this production will be carried out. At the indicated step if production was not possible (due to insufficient funds or insufficient inventory of the input product), the predictions for the future will be corrected.

cancel_production(step: int, line: int) bool[source]

Cancels any production commands on that line at this step

Parameters:
  • step – The step to cancel production at (must be in the future).

  • line – The production line

Returns:

success/failure

Remarks:

  • The step cannot be in the past or the current step. Cancellation can only be ordered for future steps

property catalog_prices: ndarray

Returns the catalog prices of all products

property current_balance

Current balance of the agent

property current_inventory

Current inventory of the agent

property exogenous_contract_summary: List[Tuple[int, int]]

The exogenous contracts in the current step for all products

Returns:

A list of tuples giving the total quantity and total price of all revealed exogenous contracts of all products at the current step.

property inputs: ndarray

Returns the number of inputs to every production process

is_bankrupt(aid: str | None = None) bool[source]

Checks whether the agent is bankrupt

Parameters:

aid – Agent ID (None means self)

property is_first_level

Whether this agent is in the first production level

property is_last_level

Whether this agent is in the last production level

property is_middle_level

Whether this agent is in neither in the first nor in the last level

is_system(aid: str) bool[source]

Checks whether an agent is a system agent or not

Parameters:

aid – Agent ID

property level

The production level which is the index of the process for this factory (or the index of its input product)

property my_consumers: List[str]

Returns a list of IDs for all the agent’s consumers (agents that can consume at least one product it may produce).

Remarks:

  • If the agent have multiple output products, consumers of a specific product $p$ can be found using: self.all_consumers[p].

property my_input_product: int

Returns a list of products that are inputs to at least one process the agent can run

property my_input_products: ndarray

Returns a list of products that are inputs to at least one process the agent can run

property my_output_product: int

Returns a list of products that are outputs to at least one process the agent can run

property my_output_products: ndarray

Returns a list of products that are outputs to at least one process the agent can run

property my_suppliers: List[str]

Returns a list of IDs for all of the agent’s suppliers (agents that can supply at least one product it may need).

Remarks:

  • If the agent have multiple input products, suppliers of a specific product $p$ can be found using: self.all_suppliers[p].

property n_competitors: int

Returns the number of factories/agents in the same production level

property n_lines: int

The number of lines in the corresponding factory. You can read state to get this among other information

property n_processes: int

Returns the number of processes in the system

property n_products: int

Number of products in the world

order_production(process: int, steps: ndarray, lines: ndarray) None[source]

Orders production of the given process

Parameters:
  • process – The process to run

  • steps – The time steps to run the process at as an np.ndarray

  • lines – The corresponding lines to run the process at

Remarks:

  • len(steps) must equal len(lines)

  • No checks are done in this function. It is expected to be used after calling available_for_production

property outputs: ndarray

Returns the number of outputs to every production process

property profile: FactoryProfile

Gets the profile (static private information) associated with the agent

reports_at_step(step: int) Dict[str, FinancialReport][source]

Returns a dictionary mapping agent ID to its financial report for the given time-step

reports_of_agent(aid: str) Dict[int, FinancialReport][source]

Returns a dictionary mapping time-steps to financial reports of the given agent

request_negotiation(is_buy: bool, product: int, quantity: int | Tuple[int, int], unit_price: int | Tuple[int, int], time: int | Tuple[int, int], partner: str, negotiator: SAONegotiator, extra: Dict[str, Any] = None) bool[source]

Requests a negotiation

Parameters:
  • is_buy – If True the negotiation is about buying otherwise selling.

  • 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

Returns:

True if the partner accepted and the negotiation is ready to start

Remarks:

  • All negotiations will use the following issues in order: quantity, time, unit_price

  • Negotiations with bankrupt agents or on invalid products (see next point) will be automatically rejected

  • Valid products for a factory are the following (any other products are not valid):
    1. Buying an input product (i.e. product $in$ my_input_products ) and an output product if the world settings allows it (see allow_buying_output)

    1. Selling an output product (i.e. product $in$ my_output_products ) and an input product if the world settings allows it (see allow_selling_input)

request_negotiations(is_buy: bool, product: int, quantity: int | Tuple[int, int], unit_price: int | Tuple[int, int], time: int | Tuple[int, int], controller: SAOController | None = None, negotiators: List[Negotiator] = None, partners: List[str] = None, extra: Dict[str, Any] = None, copy_partner_id=True) bool[source]

Requests a negotiation

Parameters:
  • is_buy – If True the negotiation is about buying otherwise selling.

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

  • partners – ID of all the partners to negotiate with.

  • extra – Extra information accessible through the negotiation annotation to the caller

  • copy_partner_id – If true, the partner ID will be copied to the negotiator ID

Returns:

True if the partner accepted and the negotiation is ready to start

Remarks:

  • You can either use controller or negotiators. One of them must be None.

  • All negotiations will use the following issues in order: quantity, time, unit_price

  • Negotiations with bankrupt agents or on invalid products (see next point) will be automatically rejected

  • Valid products for a factory are the following (any other products are not valid):
    1. Buying an input product (i.e. product $in$ my_input_products ) and an output product if the world settings allows it (see allow_buying_output)

    1. Selling an output product (i.e. product $in$ my_output_products ) and an input product if the world settings allows it (see allow_selling_input)

schedule_production(process: int, repeats: int, step: int | Tuple[int, int] = -1, line: int = -1, override: bool = True, method: str = 'latest', partial_ok: bool = False) Tuple[ndarray, ndarray][source]

Orders the factory to run the given process at the given line at the given step

Parameters:
  • process – The process to run

  • repeats – How many times to repeat the process

  • step – The simulation step or a range of steps. The special value ANY_STEP gives the factory the freedom to schedule production at any step in the present or future.

  • line – The production line. The special value ANY_LINE gives the factory the freedom to use any line

  • override – Whether to override existing production commands or not

  • method – When to schedule the command if step was set to a range. Options are latest, earliest

  • partial_ok – If true, allows partial scheduling

Returns:

Tuple[int, int] giving the steps and lines at which production is scheduled.

Remarks:

  • The step cannot be in the past. Production can only be ordered for current and future steps

  • ordering production of process -1 is equivalent of cancel_production only if both step and line are given

set_commands(commands: ndarray, step: int = -1) None[source]

Sets the production commands for all lines in the given step

Parameters:
  • commands – n_lines vector of commands. A command is either a process number to run or NO_COMMAND to keep the line idle

  • step – The step to set the commands at. If < 0, it means current step

spot_market_loss(step: int | None) int[source]

The spot market loss of the agent at the given step.

Parameters:

step – The simulation step (day)

Remarks:

If step is None, the current step will be used

spot_market_quantity(step: int | None) int[source]

The quantity bought by the agent from the spot market at the given step.

Parameters:

step – The simulation step (day)

Remarks:

If step is None, the current step will be used

property state: FactoryState

Receives the factory state

property trading_prices: ndarray

Returns the current trading prices of all products

class scml.ActionManager(context: BaseContext, continuous: bool = False)[source]

Manges actions of an agent in an RL environment.

abstract decode(awi: OneShotAWI, action: ndarray) dict[str, SAOResponse][source]

Decodes an action from an array to a PurchaseOrder and a CounterMessage.

encode(awi: OneShotAWI, responses: dict[str, SAOResponse]) ndarray[source]

Encodes an action as an array. This is only used for testing so it is optional

abstract make_space() Space[source]

Creates the action space

class scml.BalancedConsumerContext(*args, **kwargs)[source]

A consumer with almost same number of suppliers as competitors

class scml.BalancedSupplierContext(*args, **kwargs)[source]

A supplier with almost same number of consumers as competitors

class scml.BuyCheapSellExpensiveAgent(*args, **kwargs)[source]

An agent that tries to buy cheap and sell expensive but does not care about production scheduling.

create_ufun(is_seller: bool, issues=None, outcomes=None)[source]

Creates a utility function

class scml.ConsumerContext(*args, **kwargs)[source]

A world context that can generate any world compatible with the observation manager

class scml.Context[source]

A context used for generating worlds satisfying predefined conditions and testing for them

abstract contains_context(context: Context) bool[source]

Checks that the any world generated from the given context could have been generated from this context

abstract generate(types: tuple[type[OneShotAgent], ...] | None = None, params: tuple[dict[str, Any], ...] | None = None, name: str | None = None) tuple[SCMLBaseWorld, tuple[OneShotAgent]][source]

Generates a world with one or more agents to be controlled externally and returns both

Parameters:
  • agent_types – The types of a list of agents to be guaranteed to exist in the world

  • agent_params – The parameters to pass to the constructors of these agents. None means no parameters for any agents

  • name – The name of the worlds to generate. Uses a random name if not given

Returns:

The constructed world and a tuple of the agents created corresponding (in order) to the given agent types/params

abstract is_valid_awi(awi: OneShotAWI) bool[source]

Checks that the given AWI is connected to a world that could have been generated from this context

abstract is_valid_world(world: SCMLBaseWorld) bool[source]

Checks that the given world could have been generated from this context

class scml.ContextParams(perishable: bool, nlines: int, nsuppliers: int, nconsumers: int)[source]

Basic Parameters you can assume about a context. Returned by extract_context_params

class scml.DecentralizingAgent(*args, negotiator_type: ~negmas.sao.negotiators.base.SAONegotiator | str = <class 'negmas.gb.negotiators.timebased.AspirationNegotiator'>, negotiator_params: ~typing.Dict[str, ~typing.Any] | None = None, **kwargs)[source]
class scml.DecentralizingAgentWithLogging(*args, **kwargs)[source]
scml.DefaultActionManager[source]

alias of FlexibleActionManager

scml.DefaultObservationManager[source]

alias of FlexibleObservationManager

class scml.DefaultRewardFunction[source]

The default reward function of SCML

Remarks:
  • The reward is the difference between the balance before the action and after it.

before_action(awi: OneShotAWI) float[source]

Called before executing the action from the RL agent to save any required information for calculating the reward in its return

Remarks:

The returned value will be passed as info to __call__() when it is time to calculate the reward.

class scml.DemandDrivenProductionStrategy(*args, **kwargs)[source]

A production strategy that produces ONLY when a contract is secured

Hooks Into:
  • on_contract_finalized

Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.DoNothingAgent(name: str | None = None, type_postfix: str = '', preferences: Preferences | None = None, ufun: UtilityFunction | None = None)[source]

An agent that does nothing for the whole length of the simulation

init()[source]

Called to initialize the agent after the world is initialized. the AWI is accessible at this point.

on_agent_bankrupt(agent: str, contracts: List[Contract], quantities: List[int], compensation_money: int) None[source]

Called whenever a contract is nullified (because the partner is bankrupt)

Parameters:
  • agent – The ID of the agent that went bankrupt.

  • contracts – All future contracts between this agent and the bankrupt agent.

  • quantities – The actual quantities that these contracts will be executed at.

  • compensation_money – The compensation money that is already added to the agent’s wallet (if ANY).

Remarks:

  • compensation_money will be nonzero iff immediate_compensation is enabled for this world

on_contract_breached(contract: Contract, breaches: List[Breach], resolution: Contract | None) None[source]

Called after complete processing of a contract that involved a breach.

Parameters:
  • contract – The contract

  • breaches – All breaches committed (even if they were resolved)

  • resolution – The resolution contract if re-negotiation was successful. None if not.

on_contract_cancelled(contract: Contract, rejectors: List[str]) None[source]

Called whenever at least a partner did not sign the contract

on_contract_executed(contract: Contract) None[source]

Called after successful contract execution for which the agent is one of the partners.

on_contracts_finalized(signed: List[Contract], cancelled: List[Contract], rejectors: List[List[str]]) None[source]

Called for all contracts in a single step to inform the agent about which were finally signed and which were rejected by any agents (including itself)

Parameters:
  • signed – A list of signed contracts. These are binding

  • cancelled – A list of cancelled contracts. These are not binding

  • rejectors – A list of lists where each of the internal lists gives the rejectors of one of the cancelled contracts. Notice that it is possible that this list is empty which means that the contract other than being rejected by any agents (if that was possible in the specific world).

Remarks:

The default implementation is to call on_contract_signed for singed contracts and on_contract_cancelled for cancelled contracts

on_failures(failures: List[Failure]) None[source]

Called whenever there are failures either in production or in execution of guaranteed transactions

Parameters:

failures – A list of Failure s.

on_negotiation_failure(partners: List[str], annotation: Dict[str, Any], mechanism: NegotiatorMechanismInterface, state: MechanismState) None[source]

Called whenever a negotiation ends without agreement

on_negotiation_success(contract: Contract, mechanism: NegotiatorMechanismInterface) None[source]

Called whenever a negotiation ends with agreement

respond_to_negotiation_request(initiator: str, issues: List[Issue], annotation: Dict[str, Any], mechanism: NegotiatorMechanismInterface) Negotiator | None[source]

Called whenever another agent requests a negotiation with this agent.

Parameters:
  • initiator – The ID of the agent that requested this negotiation

  • issues – Negotiation issues

  • annotation – Annotation attached with this negotiation

  • mechanism – The NegotiatorMechanismInterface interface to the mechanism to be used for this negotiation.

Returns:

None to reject the negotiation, otherwise a negotiator

sign_all_contracts(contracts: List[Contract]) List[str | None][source]

Signs all contracts

step()[source]

Called by the simulator at every simulation step

class scml.EndingNegotiator(preferences: Preferences | None = None, ufun: BaseUtilityFunction | None = None, name: str | None = None, parent: Controller | None = None, owner: Agent | None = None, id: str | None = None, type_name: str | None = None, can_propose: bool = True, **kwargs)[source]
propose(state)[source]

Propose an offer or None to refuse.

Parameters:

stateGBState giving current state of the negotiation.

Returns:

The outcome being proposed or None to refuse to propose

Remarks:
  • This function guarantees that no agents can propose something with a utility value

respond(state, source=None)[source]

Called to respond to an offer. This is the method that should be overriden to provide an acceptance strategy.

Parameters:
  • state – a SAOState giving current state of the negotiation.

  • source – The ID of the negotiator that gave this offer

Returns:

The response to the offer

Return type:

ResponseType

Remarks:
  • The default implementation never ends the negotiation

  • The default implementation asks the negotiator to propose`() and accepts the `offer if its utility was at least as good as the offer that it would have proposed (and above the reserved value).

  • The current offer to respond to can be accessed through state.current_offer

class scml.EqualDistOneShotAgent(*args, **kwargs)[source]

Same as RandDistOneShotAgent but defaulting to equal distribution of needs

Parameters:
  • equal – If given, it tries to equally distribute its needs over as many of its suppliers/consumers as possible

  • overordering_max – Maximum fraction of needs to over-order. For example, it the agent needs 5 items and this is 0.2, it will order 6 in the first negotiation step.

  • overordering_min – Minimum fraction of needs to over-order. Used in the last negotiation step.

  • overordering_exp – Controls how fast does the over-ordering quantity go from max to min.

  • concession_exp – Controls how fast does the agent concedes on matching its needs exactly.

  • mismatch_max – Maximum mismtach in quantity allowed between needs and accepted offers. If a fraction, it is will be this fraction of the production capacity (n_lines).

class scml.EutopiaConsumerContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True, buying_strength: ~scml.oneshot.context.Strength | None = None, selling_strength: ~scml.oneshot.context.Strength | None = None, n_competitors: tuple[int, int] = (0, 0), n_agents_per_process=(1, 8), non_competitors=(<class 'scml.oneshot.agents.rand.NiceAgent'>,), level=-1, n_consumers: tuple[int, int] = (0, 0), n_suppliers: tuple[int, int] = (4, 8))[source]

An unrealistic context in which the agent is the only consumer and all suppliers are nice.

class scml.EutopiaContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True, level: int = 0, n_consumers: tuple[int, int] = (4, 8), n_suppliers: tuple[int, int] = (0, 0), buying_strength: ~scml.oneshot.context.Strength | None = None, selling_strength: ~scml.oneshot.context.Strength | None = None, n_competitors: tuple[int, int] = (0, 0), n_agents_per_process=(1, 8), non_competitors=(<class 'scml.oneshot.agents.rand.NiceAgent'>,))[source]

An unrealistic context in which the agent is the only one in its level and all other agents are nice.

class scml.EutopiaSupplierContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True, buying_strength: ~scml.oneshot.context.Strength | None = None, selling_strength: ~scml.oneshot.context.Strength | None = None, n_competitors: tuple[int, int] = (0, 0), n_agents_per_process=(1, 8), non_competitors=(<class 'scml.oneshot.agents.rand.NiceAgent'>,), level=0, n_consumers: tuple[int, int] = (4, 8), n_suppliers: tuple[int, int] = (0, 0))[source]

An unrealistic context in which the agent is the only supplier and all consumers are nice.

class scml.ExecutionRatePredictionStrategy[source]

A prediction strategy for expected inputs and outputs at every step

Provides:
  • predict_quantity : A method for predicting the quantity that will actually be executed from a contract

Abstract:
  • predict_quantity : A method for predicting the quantity that will actually be executed from a contract

Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.ExogenousContract(product: int, quantity: int, unit_price: int, time: int, revelation_time: int, seller: int = -1, buyer: int = -1)[source]

Represents a contract to be revealed at revelation_time to buyer and seller between them that is not agreed upon through negotiation but is endogenously given

buyer: int = -1

Buyer index in the agents array (-1 means “system”)

product: int

Product

quantity: int

Quantity

revelation_time: int

Time at which to reveal the contract to both buyer and seller

seller: int = -1

Seller index in the agents array (-1 means “system”)

time: int

Delivery time

unit_price: int

Unit price

class scml.Factory(profile: FactoryProfile, initial_balance: int, inputs: ndarray, outputs: ndarray, catalog_prices: ndarray, world: SCML2020World, compensate_before_past_debt: bool, buy_missing_products: bool, production_buy_missing: bool, production_penalty: float, production_no_bankruptcy: bool, production_no_borrow: bool, agent_id: str, agent_name: str | None = None, confirm_production: bool = True, initial_inventory: ndarray | None = None, disallow_concurrent_negs_with_same_partners=False)[source]

A simulated factory

agent_id

A unique ID for the agent owning the factory

agent_name

SCML2020Agent names used for logging purposes

available_for_production(repeats: int, step: int | Tuple[int, int] = -1, line: int = -1, override: bool = True, method: str = 'latest') Tuple[ndarray, ndarray]

Finds available times and lines for scheduling production.

Parameters:
  • repeats – How many times to repeat the process

  • step – The simulation step or a range of steps. The special value ANY_STEP gives the factory the freedom to schedule production at any step in the present or future.

  • line – The production line. The special value ANY_LINE gives the factory the freedom to use any line

  • override – Whether to override any existing commands at that line at that time.

  • method – When to schedule the command if step was set to a range. Options are latest, earliest, all

Returns:

Tuple[np.ndarray, np.ndarray] The steps and lines at which production is scheduled.

Remarks:

  • You cannot order production in the past or in the current step

  • Ordering production, will automatically update inventory and balance for all simulation steps assuming that this production will be carried out. At the indicated step if production was not possible (due to insufficient funds or insufficient inventory of the input product), the predictions for the future will be corrected.

balance_change

Change in the balance in the last step

bankrupt(required: int) int

Bankruptcy processing for the given agent

Parameters:

required – The money required after the bankruptcy is processed

Returns:

The amount of money to pay back to the entity that should have been paid money

buy(product: int, quantity: int, unit_price: int, buy_missing: bool, penalty: float, no_bankruptcy: bool = False, no_borrowing: bool = False) Tuple[int, int][source]

Executes a transaction to buy/sell involving adding quantity and paying price (both are signed)

Parameters:
  • product – The product transacted on

  • quantity – The quantity (added)

  • unit_price – The unit price (paid)

  • buy_missing – If true, attempt buying missing products from the spot market

  • penalty – The penalty as a fraction to be paid for breaches

  • no_bankruptcy – If true, this transaction can never lead to bankruptcy

  • no_borrowing – If true, this transaction can never lead to borrowing

Returns:

Tuple[int, int] The actual quantities bought and the total cost

cancel_production(step: int, line: int) bool

Cancels pre-ordered production given that it did not start yet.

Parameters:
  • step – Step to cancel at

  • line – Line to cancel at

Returns:

True if step >= self.current_step

Remarks:

  • Cannot cancel a process in the past or present.

commands

An n_steps * n_lines array giving the process scheduled for each line at every step. -1 indicates an empty line.

contracts: List[List[ContractInfo]]

A list of lists of contracts per time-step (len == n_steps)

property current_balance: int

Current wallet balance

property current_inventory: ndarray

Current inventory contents

inputs

An n_process array giving the number of inputs needed for each process (of the product with the same index)

inventory_changes

Changes in the inventory in the last step

is_bankrupt

Will be true when the factory is bankrupt

min_balance

The minimum balance possible

order_production(process: int, steps: ndarray, lines: ndarray) None

Orders production of the given process

Parameters:
  • process – The process to run

  • steps – The time steps to run the process at as an np.ndarray

  • lines – The corresponding lines to run the process at

Remarks:

  • len(steps) must equal len(lines)

  • No checks are done in this function. It is expected to be used after calling available_for_production

outputs

An n_process array giving the number of outputs produced by each process (of the product with the next index)

pay(money: int, no_bankruptcy: bool = False, no_borrowing: bool = False, unit: int = 0) int[source]

Pays money

Parameters:
  • money – amount to pay

  • no_bankruptcy – If true, this transaction can never lead to bankruptcy

  • no_borrowing – If true, this transaction can never lead to borrowing

  • unit – If nonzero then an integer multiple of unit will be paid

Returns:

The amount actually paid

schedule_production(process: int, repeats: int, step: int | Tuple[int, int] = -1, line: int = -1, override: bool = True, method: str = 'latest', partial_ok: bool = False) Tuple[ndarray, ndarray]

Orders production of the given process on the given step and line.

Parameters:
  • process – The process index

  • repeats – How many times to repeat the process

  • step – The simulation step or a range of steps. The special value ANY_STEP gives the factory the freedom to schedule production at any step in the present or future.

  • line – The production line. The special value ANY_LINE gives the factory the freedom to use any line

  • override – Whether to override any existing commands at that line at that time.

  • method – When to schedule the command if step was set to a range. Options are latest, earliest, all

  • partial_ok – If true, it is OK to produce only a subset of repeats

Returns:

Tuple[np.ndarray, np.ndarray] The steps and lines at which production is scheduled.

Remarks:

  • You cannot order production in the past or in the current step

  • Ordering production, will automatically update inventory and balance for all simulation steps assuming that this production will be carried out. At the indicated step if production was not possible (due to insufficient funds or insufficient inventory of the input product), the predictions for the future will be corrected.

spot_price(product: int, spot_loss: float) int

Get the current spot price for buying the given product on the spot market

Parameters:
  • product – Product

  • spot_loss – Spot loss specific to that agent

Returns:

The unit price

step() List[Failure][source]

Override this method to modify stepping logic.

store(product: int, quantity: int, buy_missing: bool, spot_price: float, no_bankruptcy: bool = False, no_borrowing: bool = False) int

Stores the given amount of product (signed) to the factory.

Parameters:
  • product – Product

  • quantity – quantity to store/take out (-ve means take out)

  • buy_missing – If the quantity is negative and not enough product exists in the market, it buys the product from the spot-market at an increased price of penalty

  • spot_price – The fraction of unit_price added because we are buying from the spot market. Only effective if quantity is negative and not enough of the product exists in the inventory

  • no_bankruptcy – Never bankrupt the agent on this transaction

  • no_borrowing – Never borrow for this transaction

Returns:

The quantity actually stored or taken out (always positive)

class scml.FactoryProfile(costs: ndarray)[source]

Defines all private information of a factory

costs: ndarray

An n_lines * n_processes array giving the cost of executing any process (INVALID_COST indicates infinity)

property input_products: ndarray

The input products to all processes runnable (See processes )

property output_products: ndarray

The output products to all processes runnable (See processes )

property processes: ndarray

The processes that have valid costs

class scml.FactoryState(inventory: numpy.ndarray, balance: int, commands: numpy.ndarray, inventory_changes: numpy.ndarray, balance_change: int, contracts: list[list[scml.scml2020.common.ContractInfo]])[source]
balance: int

Current balance in the wallet

balance_change: int

Change in the balance in the last step

commands: ndarray

n_steps * n_lines array giving the process scheduled on each line at every step for the whole simulation

contracts: list[list[ContractInfo]]

The An n_steps list of lists containing the contracts of this agent by time-step

inventory: ndarray

An n_products vector giving current quantity of every product in storage

inventory_changes: ndarray

Changes in the inventory in the last step

class scml.Failure(is_inventory: bool, line: int, step: int, process: int)[source]

A production failure

is_inventory: bool

True if the cause of failure was insufficient inventory. If False, the cause was insufficient funds. Note that if both conditions were true, only insufficient funds (is_inventory=False) will be reported.

line: int

The line at which the failure happened

process: int

The process that failed to execute

step: int

The step at which the failure happened

class scml.FinancialReport(agent_id: str, step: int, cash: int, assets: int, breach_prob: float, breach_level: float, is_bankrupt: bool, agent_name: str)[source]

A report published periodically by the system showing the financial standing of an agent

agent_id: str

Agent ID

agent_name: str

Agent name for printing purposes

assets: int

Value of the products in the agent’s inventory @ catalog prices.

breach_level: float

Sum of the agent’s breach levels so far divided by the number of contracts it signed.

breach_prob: float

Number of times the agent breached a contract over the total number of contracts it signed.

cash: int

Cash in the agent’s wallet. Negative numbers indicate liabilities.

is_bankrupt: bool

Whether the agent is already bankrupt (i.e. incapable of doing any more transactions).

step: int

Simulation step at the beginning of which the report was published.

class scml.FixedERPStrategy(*args, execution_fraction=0.95, **kwargs)[source]

Predicts that the there is a fixed execution rate that does not change for all partners

Parameters:

execution_fraction – The expected fraction of any contract’s quantity to be executed

Provides:
  • predict_quantity : A method for predicting the quantity that will actually be executed from a contract

Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.FixedPartnerNumbersContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, non_competitors: tuple[str | type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, n_agents_per_process: ~numpy.ndarray | list[int] | tuple[int, int] | int = (4, 8), production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True, buying_strength: ~scml.oneshot.context.Strength | None = None, selling_strength: ~scml.oneshot.context.Strength | None = None, level: int = 0, n_consumers: int = 4, n_suppliers: int = 0, n_competitors: int = 3)[source]

Generates a world limiting the range of the agent level, production capacity and the number of suppliers, consumers, and optionally same-level competitors.

class scml.FixedPartnerNumbersOneShotContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, non_competitors: tuple[str | type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, n_agents_per_process: ~numpy.ndarray | list[int] | tuple[int, int] | int = (4, 8), production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True, buying_strength: ~scml.oneshot.context.Strength | None = None, selling_strength: ~scml.oneshot.context.Strength | None = None, level: int = 0, n_consumers: int = 4, n_suppliers: int = 0, n_competitors: int = 3)[source]
class scml.FixedTradePredictionStrategy(*args, add_trade=True, **kwargs)[source]

Predicts a fixed amount of trade both for the input and output products.

Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

trade_prediction_init()[source]

Will be called to update expected_outputs, expected_inputs, input_cost, output_cost during init()

class scml.FlexibleActionManager(context: BaseContext, continuous: bool = False, capacity_multiplier: int = 1, n_prices: int = 2, max_group_size: int = 2, reduce_space_size: bool = True, extra_checks: bool = False)[source]

An action manager that matches any context.

Parameters:
  • n_prices – Number of distinct prices allowed in the action.

  • max_quantity – Maximum allowed quantity to offer in any negotiation. The number of quantities is one plus that because zero is allowed to model ending negotiation.

  • n_partners – Maximum of partners allowed in the action.

Remarks:
  • This action manager will always generate offers that are within the price and quantity limits given in its parameters. Wen decoding them, it will scale them up so that the maximum corresponds to the actual value in the world it finds itself. For example, if n_prices is 10 and the world has only two prices currently in the price issue, it will use any value less than 5 as the minimum price and any value above 5 as the maximum price. If on the other hand the current price issue has 20 values, then it will scale by multiplying the number given in the encoded action (ranging from 0 to 9) by 19/9 which makes it range from 0 to 19 which is what is expected by the world.

  • This action manager will adjust offers for different number of partners as follows: - If the true number of partners is larger than n_partners used by this action manager,

    it will simply use n_partners of them and always end negotiations with the rest of them.

    • If the true number of partners is smaller than n_partners, it will use the first n_partners values in the encoded action and increase the quantities of any counter offers (i.e. ones in which the response is REJECT_OFFER) by the amount missing from the ignored partners in the encoded action up to the maximum quantities allowed by the current negotiation context. For example, if n_partneers is 4 and we have only 2 partners in reality, and the received quantities from partners were [4, 3] while the maximum quantity allowed is 10 and the encoded action was [2, *, 3, *, 2, *, 1, *] (where we ignored prices), then the encoded action will be converted to [(Reject, 5, *), (Accept, 3, *)] where the 3 extra units that were supposed to be offered to the last two partners are moved to the first partner. If the maximum quantity allowed was 4 in that example, the result will be [(Reject, 4, *), (Accept, 3, *)].

decode(awi: OneShotAWI, action: ndarray) dict[str, SAOResponse][source]

Generates offers to all partners from an encoded action. Default is to return the action as it is assuming it is a dict[str, SAOResponse]

encode(awi: OneShotAWI, responses: dict[str, SAOResponse]) ndarray[source]

Receives offers for all partners and generates the corresponding action. Used mostly for debugging and testing.

make_space() MultiDiscrete | Box[source]

Creates the action space

class scml.FlexibleObservationManager(context: BaseContext, continuous: bool = False, capacity_multiplier: int = 1, n_prices: int = 2, max_group_size: int = 2, reduce_space_size: bool = True, n_past_received_offers: int = 1, extra_checks: bool = False, n_bins: int = 40, n_sigmas: int = 2, max_production_cost: int = 10, exogenous_multiplier: int = 1)[source]

An observation manager that can be used with any SCML world.

Parameters:
  • capacity_multiplier – A factor to multiply by the number of lines to give the maximum quantity allowed in offers

  • exogenous_multiplier – A factor to multiply maximum production capacity with when encoding exogenous quantities

  • continuous – If given the observation space will be a Box otherwise it will be a MultiDiscrete

  • n_prices – The number of prices to use for encoding the unit price (if not continuous)

  • max_production_cost – The limit for production cost. Anything above that will be mapped to this max

  • max_group_size – Maximum size used for grouping observations from multiple partners. This will be used in the number of partners in the simulation is larger than the number used for training.

  • n_past_received_offers – Number of past received offers to add to the observation.

  • n_bins

    1. bins to use for discretization (if not continuous)

  • n_sigmas – The number of sigmas used for limiting the range of randomly distributed variables

  • extra_checks – If given, extra checks are applied to make sure encoding and decoding make sense

Remarks:

encode(awi: OneShotAWI) ndarray[source]

Encodes the awi as an array

extra_obs(awi: OneShotAWI) list[tuple[float, int] | float][source]

The observation values other than offers and previous offers.

Returns:

A list of tuples. Each is some observation variable as a real number between zero and one and a number of bins to use for discrediting this variable. If a single value, the number of bins will be self.n_bin

get_dims() list[int][source]

Get the sizes of all dimensions in the observation space. Used if not continuous.

get_offers(awi: OneShotAWI, encoded: ndarray) dict[str, tuple | None][source]

Gets offers from an encoded awi.

make_first_observation(awi: OneShotAWI) ndarray[source]

Creates the initial observation (returned from gym’s reset())

make_space() MultiDiscrete | Box[source]

Creates the action space

class scml.GeneralContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, non_competitors: tuple[str | type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, n_agents_per_process: ~numpy.ndarray | list[int] | tuple[int, int] | int = (4, 8), production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True)[source]

A context that generates oneshot worlds with agents of a given types with predetermined structure and settings

contains_context(context: Context, raise_on_failure: bool = False, warn_on_failure: bool = False, n_tests: int = 20) bool[source]

Checks that the any world generated from the given context could have been generated from this context

contains_general_context(context: GeneralContext) bool[source]

Checks that the any world generated from the given context could have been generated from this context

is_valid_world(world: SCMLBaseWorld, raise_on_failure: bool = False, warn_on_failure: bool = False, types: tuple[str | type[OneShotAgent], ...] | None = None) bool[source]

Checks that the given world could have been generated from this context

make_config() dict[str, Any][source]

Generates a config for a world

make_predefined_config(agent_types: list[type[OneShotAgent]], agent_processes: list[int], agent_params: list[dict[str, Any]], n_agents_per_process: list[int]) dict[str, Any][source]

Generates a config for a world

class scml.GreedyOneShotAgent(*args, concession_exponent=None, acc_price_slack=inf, step_price_slack=None, opp_price_slack=None, opp_acc_price_slack=None, range_slack=None, **kwargs)[source]

A greedy agent based on OneShotAgent

Parameters:
  • concession_exponent – A real number controlling how fast does the agent concede on price.

  • acc_price_slack – The allowed slack in price limits compared with best prices I got so far

  • step_price_slack – The allowed slack in price limits compared with best prices I got this step

  • opp_price_slack – The allowed slack in price limits compared with best prices I got so far from a given opponent in this step

  • opp_acc_price_slack – The allowed slack in price limits compared with best prices I got so far from a given opponent so far

  • range_slack – Always consider prices above (1-range_slack) of the best possible prices good enough.

Remarks:
  • A concession_exponent greater than one makes the agent concede super linearly and vice versa

before_step()[source]

Initialize the quantities and best prices received for next step

init()[source]

Initialize the quantities and best prices received so far

on_negotiation_success(contract, mechanism)[source]

Record sales/supplies secured

propose(negotiator_id: str, state, source=None) tuple | None[source]

Proposes an offer to one of the partners.

Parameters:
  • negotiator_id – ID of the negotiator (and partner)

  • state – Mechanism state including current step

Returns:

an outcome to offer.

respond(negotiator_id, state, source=None) ResponseType[source]

Responds to an offer from one of the partners.

Parameters:
  • negotiator_id – ID of the negotiator (and partner)

  • state – Mechanism state including current step

Returns:

A response type which can either be reject, accept, or end negotiation.

Remarks:

default behavior is to accept only if the current offer is the same or has a higher utility compared with what the agent would have proposed in the given state and reject otherwise

class scml.GreedySingleAgreementAgent(*args, **kwargs)[source]

A greedy agent based on OneShotSingleAgreementAgent

before_step()[source]

Called at the beginning of every step.

Remarks:
  • Use this for any proactive code that needs to be done every simulation step.

best_offer(offers)[source]

Return the ID of the negotiator with the best offer

Parameters:

offers – A mapping from negotiator ID to the offer it received

Returns:

The ID of the negotiator with best offer. Ties should be broken. Return None only if there is no way to calculate the best offer.

is_acceptable(offer, source, state) bool[source]

Should decide if the given offer is acceptable

Parameters:
  • offer – The offer being tested

  • source – The ID of the negotiator that received this offer

  • state – The state of the negotiation handled by that negotiator

Remarks:
  • If True is returned, this offer will be accepted and all other negotiations will be ended.

is_better(a, b, negotiator, state)[source]

Compares two outcomes of the same negotiation

Parameters:
  • a – “Outcome”

  • b – “Outcome”

  • negotiator – The negotiator for which the comparison is to be made

  • state – Current state of the negotiation

Returns:

True if utility(a) > utility(b)

class scml.GreedySyncAgent(*args, threshold=None, **kwargs)[source]

A greedy agent based on OneShotSyncAgent

before_step()[source]

Called at the beginning of every step.

Remarks:
  • Use this for any proactive code that needs to be done every simulation step.

counter_all(offers, states) dict[source]

Respond to a set of offers given the negotiation state of each.

first_proposals()[source]

Decide a first proposal on every negotiation. Returning None for a negotiation means ending it.

propose(negotiator_id, state)[source]

Proposes an offer to one of the partners.

Parameters:
  • negotiator_id – ID of the negotiator (and partner)

  • state – Mechanism state including current step

Returns:

an outcome to offer.

respond(negotiator_id, state, source='')[source]

Responds to an offer from one of the partners.

Parameters:
  • negotiator_id – ID of the negotiator (and partner)

  • state – Mechanism state including current step

Returns:

A response type which can either be reject, accept, or end negotiation.

Remarks:

default behavior is to accept only if the current offer is the same or has a higher utility compared with what the agent would have proposed in the given state and reject otherwise

class scml.IndDecentralizingAgent(*args, negotiator_type: ~negmas.sao.negotiators.base.SAONegotiator | str = <class 'negmas.gb.negotiators.timebased.AspirationNegotiator'>, negotiator_params: ~typing.Dict[str, ~typing.Any] | None = None, **kwargs)[source]
create_ufun(is_seller: bool, issues=None, outcomes=None)[source]

Creates a utility function

class scml.IndependentNegotiationsAgent(*args, **kwargs)[source]

Implements the base class for agents that negotiate independently with different partners.

These agents do not take production capacity, availability of materials or any other aspects of the simulation into account. They are to serve only as baselines.

Remarks:

  • IndependentNegotiationsAgent agents assume that each production process has one input type with the same

    index as itself and one output type with one added to the index (i.e. process $i$ takes product $i$ as input and creates product $i+1$ as output.

  • It does not assume that all lines have the same production cost (it uses the average cost though).

  • It does not assume that the agent has a single production process.

acceptable_unit_price(step: int, sell: bool) int[source]

Returns the maximum/minimum acceptable unit price for buying/selling at the given time-step

Parameters:
  • step – Simulation step

  • sell – Sell or buy

target_quantity(step: int, sell: bool) int[source]

Returns the target quantity to sell/buy at a given time-step

Parameters:
  • step – Simulation step

  • sell – Sell or buy

class scml.IndependentNegotiationsManager(*args, negotiator_type: ~negmas.sao.negotiators.base.SAONegotiator | str = <class 'negmas.gb.negotiators.timebased.AspirationNegotiator'>, negotiator_params: ~typing.Dict[str, ~typing.Any] | None = None, **kwargs)[source]

A negotiation manager that manages independent negotiators that do not share any information once created

Parameters:
  • negotiator_type – The negotiator type to use to manage all negotiations

  • negotiator_params – Parameters of the negotiator

Requires:
Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

create_ufun(is_seller: bool, issues=None, outcomes=None) UtilityFunction[source]

Creates a utility function

negotiator(is_seller: bool, issues=None, outcomes=None, partner=None) SAONegotiator[source]

Creates a negotiator

class scml.KeepOnlyGoodPrices(*args, buying_margin=0.5, selling_margin=0.5, **kwargs)[source]

Signs all contracts that have good prices

Overrides:
- buying_margin

The margin from the catalog price to allow for buying. The agent will never buy at a price higher than the catalog price by more than this margin (relative to catalog price).

- selling_margin

The margin from the catalog price to allow for selling. The agent will never sell at a price lower than the catalog price by more than this margin (relative to catalog price).

Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.LimitedPartnerNumbersContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, non_competitors: tuple[str | type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, n_agents_per_process: ~numpy.ndarray | list[int] | tuple[int, int] | int = (4, 8), production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True, level: int = 0, n_consumers: tuple[int, int] = (4, 8), n_suppliers: tuple[int, int] = (0, 0), n_competitors: tuple[int, int] = (3, 7), buying_strength: ~scml.oneshot.context.Strength | None = None, selling_strength: ~scml.oneshot.context.Strength | None = None)[source]

Generates a world limiting the range of the agent level, production capacity and the number of suppliers, consumers, and optionally same-level competitors.

contains_context(context: Context, raise_on_failure: bool = False, warn_on_failure: bool = False, n_tests: int = 20) bool[source]

Checks that the any world generated from the given context could have been generated from this context

is_valid_world(world: SCMLBaseWorld, types: tuple[type[OneShotAgent], ...] | None = None, raise_on_failure: bool = False, warn_on_failure: bool = False) bool[source]

Checks that the given world could have been generated from this context

make_config() dict[str, Any][source]

Generates a config

class scml.LimitedPartnerNumbersOneShotContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, non_competitors: tuple[str | type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, n_agents_per_process: ~numpy.ndarray | list[int] | tuple[int, int] | int = (4, 8), production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True, level: int = 0, n_consumers: tuple[int, int] = (4, 8), n_suppliers: tuple[int, int] = (0, 0), n_competitors: tuple[int, int] = (3, 7), buying_strength: ~scml.oneshot.context.Strength | None = None, selling_strength: ~scml.oneshot.context.Strength | None = None, year: int = 2024)[source]

Generates a oneshot world limiting the range of the agent level, production capacity and the number of suppliers, consumers, and optionally same-level competitors.

class scml.MarketAwareBuyCheapSellExpensiveAgent(*args, buying_margin=None, selling_margin=None, min_price_margin=0.5, max_price_margin=0.5, **kwargs)[source]

An agent that tries to buy cheap and sell expensive but does not care about production scheduling.

class scml.MarketAwareDecentralizingAgent(*args, buying_margin=None, selling_margin=None, min_price_margin=0.5, max_price_margin=0.5, **kwargs)[source]
class scml.MarketAwareIndDecentralizingAgent(*args, buying_margin=None, selling_margin=None, min_price_margin=0.5, max_price_margin=0.5, **kwargs)[source]
class scml.MarketAwareIndependentNegotiationsAgent(*args, buying_margin=None, selling_margin=None, min_price_margin=0.5, max_price_margin=0.5, **kwargs)[source]

Implements the base class for agents that negotiate independently with different partners using trading/catalog prices to control signing

These agents do not take production capacity, availability of materials or any other aspects of the simulation into account. They are to serve only as baselines.

Remarks:

  • IndependentNegotiationsAgent agents assume that each production process has one input type with the same

    index as itself and one output type with one added to the index (i.e. process $i$ takes product $i$ as input and creates product $i+1$ as output.

  • It does not assume that all lines have the same production cost (it uses the average cost though).

  • It does not assume that the agent has a single production process.

class scml.MarketAwareMovingRangeAgent(*args, min_price_margin=0.5, max_price_margin=0.5, **kwargs)[source]
class scml.MarketAwarePredictionBasedTradingStrategy(*args, add_trade=True, **kwargs)[source]
class scml.MarketAwareReactiveAgent(*args, buying_margin=None, selling_margin=None, min_price_margin=0.5, max_price_margin=0.5, **kwargs)[source]
class scml.MarketAwareTradePredictionStrategy(*args, predicted_outputs: int | ndarray = None, predicted_inputs: int | ndarray = None, add_trade=False, **kwargs)[source]

Predicts an amount based on publicly available market information. Falls back to fixed prediction if no information is available

Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

trade_prediction_before_step()[source]

Will be called at the beginning of every step to update the prediction

trade_prediction_init()[source]

Will be called to update expected_outputs, expected_inputs, input_cost, output_cost during init()

trade_prediction_step()[source]

Will be called at the end of every step to update the prediction

class scml.MeanERPStrategy(*args, execution_fraction=0.95, **kwargs)[source]

Predicts the mean execution fraction for each partner

Parameters:

execution_fraction – The expected fraction of any contract’s quantity to be executed

Provides:
  • predict_quantity : A method for predicting the quantity that will actually be executed from a contract

Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.MonopolicContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, non_competitors: tuple[str | type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True, level: int = 0, n_consumers: tuple[int, int] = (4, 8), n_suppliers: tuple[int, int] = (0, 0), buying_strength: ~scml.oneshot.context.Strength | None = None, selling_strength: ~scml.oneshot.context.Strength | None = None, n_competitors: tuple[int, int] = (0, 0), n_agents_per_process=(1, 8))[source]

An agent that has no competitors in the same level as themselves

class scml.MovingRangeAgent(*args, price_weight=0.7, utility_threshold=0.9, time_threshold=0.9, time_horizon=0.1, min_price_margin=0.5, max_price_margin=0.5, **kwargs)[source]
class scml.MovingRangeNegotiationManager(*args, price_weight=0.7, utility_threshold=0.9, time_threshold=0.9, time_horizon=0.1, min_price_margin=0.5, max_price_margin=0.5, **kwargs)[source]

My negotiation strategy

Parameters:
  • price_weight – The relative importance of price in the utility calculation.

  • utility_threshold – The fraction of maximum utility above which all offers will be accepted.

  • time_threshold – The fraction of the negotiation time after which any valid offers will be accepted.

  • time_range – The time-range for each controller as a fraction of the number of simulation steps

Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.NegotiationManager(*args, horizon=5, negotiate_on_signing=True, logdebug=False, use_trading_prices=True, min_price_margin=0.5, max_price_margin=0.5, **kwargs)[source]

A negotiation manager is a component that provides negotiation control functionality to an agent

Parameters:

horizon – The number of steps in the future to consider for selling outputs.

Provides:
Requires:
Abstract:
Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

abstract acceptable_unit_price(step: int, sell: bool) int[source]

Returns the maximum/minimum acceptable unit price for buying/selling at the given time-step

Parameters:
  • step – Simulation step

  • sell – Sell or buy

start_negotiations(product: int, quantity: int, unit_price: int, step: int, partners: List[str] = None) None[source]

Starts a set of negotiations to buy/sell the product with the given limits

Parameters:
  • product – product type. If it is an input product, negotiations to buy it will be started otherweise to sell.

  • quantity – The maximum quantity to negotiate about

  • unit_price – The maximum/minimum unit price for buy/sell

  • step – The maximum/minimum time for buy/sell

  • partners – A list of partners to negotiate with

Remarks:

  • This method assumes that product is either my_input_product or my_output_product

step()[source]

Generates buy and sell negotiations as needed

target_quantities(steps: Tuple[int, int], sell: bool) ndarray[source]

Returns the target quantity to negotiate about for each step in the range given (beginning included and ending excluded) for buying/selling

Parameters:
  • steps – Simulation step

  • sell – Sell or buy

abstract target_quantity(step: int, sell: bool) int[source]

Returns the target quantity to sell/buy at a given time-step

Parameters:
  • step – Simulation step

  • sell – Sell or buy

class scml.ObservationManager(*args, **kwargs)[source]

Manages the observations of an agent in an RL environment

encode(awi: OneShotAWI) ndarray[source]

Encodes an observation from the agent’s awi

get_offers(awi: OneShotAWI, encoded: ndarray) dict[str, tuple | None][source]

Gets the offers from an encoded awi

make_first_observation(awi: OneShotAWI) ndarray[source]

Creates the initial observation (returned from gym’s reset())

make_space() Space[source]

Creates the observation space

class scml.OneShotAWI(world: SCMLBaseWorld, agent: OneShotAgent)[source]

The agent world interface for the one-shot game.

This class contains all the methods needed to access the simulation to extract information which are divided into 4 groups:

Static World Information:

Information about the world and the agent that does not change over time. These include:

  1. Market Information:

  • n_products: Number of products in the production chain.

  • n_processes: Number of processes in the production chain.

  • n_competitors: Number of other factories on the same production level.

  • all_suppliers: A list of all suppliers by product.

  • all_consumers: A list of all consumers by product.

  • proudction_capacities: The total production capacity (i.e. number of lines)

    for each production level (i.e. manufacturing process).

  • is_system: Is the given system ID corresponding to a system agent?

  • is_bankrupt: Is the given agent bankrupt? None asks about self

  • catalog_prices: A list of the catalog prices (by product).

  • price_multiplier: The multiplier multiplied by the trading/catalog price when the negotiation agendas are created to decide the maximum and lower quantities.

  • is_exogenous_forced: Are exogenous contracts always forced or can the agent decide not to sign them.

  • current_step: Current simulation step (inherited from negmas.situated.AgentWorldInterface ).

  • n_steps: Number of simulation steps (inherited from negmas.situated.AgentWorldInterface ).

  • relative_time: fraction of the simulation completed (inherited from negmas.situated.AgentWorldInterface).

  • state: The full state of the agent ( OneShotState ).

  • **settings* The system settings (inherited from negmas.situated.AgentWorldInterface ).

  • **quantity_range* The maximum quantity in all negotiation agendas (new in 0.6.1)

  • **price_range* The maximum number of different prices in any negotiation agenda (new in 0.6.1)

  1. Agent Information:

  • profile: Gives the agent profile including its production cost, number of production lines, input product index, mean of its delivery penalties, mean of its disposal costs, standard deviation of its shortfall penalties and standard deviation of its disposal costs. See OneShotProfile for full description. This information is private information and no other agent knows it.

  • n_lines: the number of production lines in the factory (private information).

  • is_first_level: Is the agent in the first production level (i.e. it is an input agent that buys the raw material).

  • is_last_level: Is the agent in the last production level (i.e. it is an output agent that sells the final product).

  • is_middle_level: Is the agent neither a first level nor a last level agent

  • my_input_product: The input product to the factory controlled by the agent.

  • my_output_product: The output product from the factory controlled by the agent.

  • level: The production level which is numerically the same as the input product.

  • my_suppliers: A list of IDs for all suppliers to the agent (i.e. agents that can sell the input product of the agent).

  • my_consumers: A list of IDs for all consumers to the agent (i.e. agents that can buy the output product of the agent).

  • penalties_scale: The scale at which to calculate disposal cost/delivery penalties. “trading” and “catalog” mean trading and catalog prices. “unit” means the contract’s unit price while “none” means that disposal cost/shortfall penalty are absolute.

  • n_input_negotiations: Number of negotiations with suppliers.

  • n_output_negotiations: Number of negotiations with consumers.

Dynamic World Information:

Information about the world and the agent that changes over time.

  1. Market Information:

  • trading_prices: The trading prices of all products. This information is only available if publish_trading_prices is set in the world.

  • exogenous_contract_summary: A list of n_products tuples each giving the total quantity and average price of exogenous contracts for a product. This information is only available if publish_exogenous_summary is set in the world.

  • is_perishable: Are all products perishable?

  1. Other Agents’ Information:

  • reports_of_agent: Gives all past financial reports of a given agent. See FinancialReport for details.

  • reports_at_step: Gives all reports of all agents at a given step. See FinancialReport for details.

  1. Current Negotiations Information:

  • current_input_outcome_space: The current outcome-space for all negotiations to buy the input product of the agent. If the agent is at level zero, this will have no issues.

  • current_output_outcome_space: The current outcome-space for all negotiations to buy the output product of the agent. If the agent is at level n_products - 1, this will have no issues.

  • current_negotiation_details: Details on all current negotiations separated into “buy” and “sell” dictionaries.

Useful helpers about current negotiations:

  • current_input_issues: The current issues for all negotiations to buy the input product of the agent. If the agent is at level zero, this will be empty. This is exactly the same as current_input_outcome_space.issues

  • current_output_issues: The current issues for all negotiations to buy the output product of the agent. If the agent is at level n_products - 1, this will be empty. This is exactly the same as current_output_outcome_space.issues

  • current_buy_nmis: All NMIs for current buy negotiations.

  • current_sell_nmis: All NMIs for current sell negotiations.

  • current_nmis: All states for current negotiations.

  • current_buy_states: All states for current buy negotiations.

  • current_sell_states: All states for current sell negotiations.

  • current_states: All states for current negotiations.

  • current_buy_offers: All offers for current buy negotiations.

  • current_sell_offers: All offers for current sell negotiations.

  • current_offers: All offers for current negotiations.

  • running_buy_nmis: All NMIs for running buy negotiations.

  • running_sell_nmis: All NMIs for running sell negotiations.

  • running_nmis: All states for running negotiations.

  • running_buy_states: All states for running buy negotiations.

  • running_sell_states: All states for running sell negotiations.

  • running_states: All states for running negotiations.

  1. Agent Information:

  • current_exogenous_input_quantity: The total quantity the agent have in its input exogenous contract.

  • current_exogenous_input_price: The total price of the agent’s input exogenous contract.

  • current_exogenous_output_quantity: The total quantity the agent have in its output exogenous contract.

  • current_exogenous_output_price: The total price of the agent’s output exogenous contract

  • current_disposal_cost: The disposal cost per unit item in the current step.

  • current_shortfall_penalty: The shortfall penalty per unit item in the current step.

  • current_balance: The current balance of the agent

  • current_score: The current score (balance / initial balance) of the agent

  • current_inventory_input: The total quantity remaining in the inventory of the input product

  • current_inventory_output: The total quantity remaining in the inventory of the output product

  • current_inventory: The total quantity remaining in the inventory of the input and output product

  1. Sales and Supplies (quantities) for today:

  • sales: Today’s sales per customer so far.

  • supplies: Today’s supplies per supplier so far.

  • total_sales: Today’s total sales so far.

  • total_supplies: Today’s total supplies so far.

  • needed_sales: Today’s needed sales as of now (exogenous input + total supplies - exogenous output - total sales so far).

  • needed_supplies: Today’s needed supplies as of now (exogenous output + total sales - exogenous input - total supplies so far).

Services (All inherited from negmas.situated.AgentWorldInterface):
  • logdebug/loginfo/logwarning/logerror: Logs to the world log at the given log level.

  • logdebug_agent/loginf_agnet/…: Logs to the agent specific log at the given log level.

  • bb_query: Queries the bulletin-board.

  • bb_read: Read a section of the bulletin-board.

property all_consumers: list[list[str]]

Returns a list of agent IDs for all consumers for every product

property all_suppliers: list[list[str]]

Returns a list of agent IDs for all suppliers for every product

property allow_zero_quantity: bool

Does negotiations allow zero quantity?

property catalog_prices: ndarray

Returns the catalog prices of all products

property current_buy_nmis: dict[str, SAONMI]

All running buy negotiations as a mapping from partner ID to current negotiation nmi

property current_buy_offers: dict[str, tuple]

All current buy negotiations as a mapping from partner ID to current offer

property current_buy_states: dict[str, SAOState]

All running buy negotiations as a mapping from partner ID to current negotiation state

property current_disposal_cost: float

Cost of storing one unit (penalizes buying too much/ selling too little)

property current_exogenous_input_price: int

The exogenous contracts for the input (this step)

property current_exogenous_input_quantity: int

The exogenous contracts for the input (this step)

property current_exogenous_output_price: int

The exogenous contracts for the input (this step)

property current_exogenous_output_quantity: int

The exogenous contracts for the input (this step)

property current_inventory: tuple[int, int]

Current input and output inventory quantity

property current_inventory_input: int

Current input inventory quantity

property current_inventory_output: int

Current output inventory quantity

property current_negotiation_details: dict[str, dict[str, NegotiationDetails]]

Details of current negotiations separated as two dicts for buying and selling.

Remarks:
  • current_negotiation_details[“buy”] gives details on all negotiations for buying

  • current_negotiation_details[“sell”] gives details on all negotiations for selling

property current_nmis: dict[str, SAONMI]

All running negotiations as a mapping from partner ID to current negotiation nmi

property current_offers: dict[str, tuple]

All current negotiations as a mapping from partner ID to current offer

property current_score: float

Returns the current score (profit) of the agent

property current_sell_nmis: dict[str, SAONMI]

All running negotiations as a mapping from partner ID to current negotiation state

property current_sell_offers: dict[str, tuple]

All current sell negotiations as a mapping from partner ID to current offer

property current_sell_states: dict[str, SAOState]

All running sell negotiations as a mapping from partner ID to current negotiation state

property current_shortfall_penalty: float

Cost of failure to deliver one unit (penalizes buying too little / selling too much)

property current_states: dict[str, SAOState]

All running negotiations as a mapping from partner ID to current negotiation state

property current_storage_cost: float

Cost of storing one unit (penalizes buying too much/ selling too little)

property exogenous_contract_summary: list[tuple[int, int]]

The exogenous contracts in the current step for all products

Returns:

A list of tuples giving the total quantity and total price of all revealed exogenous contracts of all products at the current step. Will be empty if the world has “publish_exogenous_summary==False”

property future_sales: dict[int, dict[str, int]]

Future sales (quantity) per customer so far (excluding this day)

property future_sales_cost: dict[int, dict[str, int]]

Future sales (total price) per customer so far (excluding this day)

property future_supplies: dict[int, dict[str, int]]

Future supplies (quantity) per supplier so far (excluding this day)

property future_supplies_cost: dict[int, dict[str, int]]

Future supplies (total price) per supplier so far (excluding this day)

property horizon: int

Horizon for negotiations

is_bankrupt(aid: str | None = None) bool[source]

Checks whether an agent is a system agent or not

Parameters:

aid – Agent ID

property is_exogenous_forced: bool

Are exogenous contracts forced in the sense that the agent cannot decide not to sign them?

property is_first_level

Whether this agent is in the first production level

property is_last_level

Whether this agent is in the last production level

property is_middle_level

Whether this agent is in neither in the first nor in the last level

property is_perishable: bool

Are all products perishable (original design of OneShot)

is_system(aid: str) bool[source]

Checks whether an agent is a system agent or not

Parameters:

aid – Agent ID

property level

The production level which is the index of the process for this factory (or the index of its input product)

property max_n_lines: int

Maximum number of lines in the whole system

property my_competitors: list[str]

Returns the names of all factories in the same level as me

property my_consumers: list[str]

Returns a list of IDs for all the agent’s consumers (agents that can consume at least one product it may produce).

property my_input_product: int

the product I need to buy

property my_output_product: int

the product I need to sell

property my_partners: list[str]

Returns a list of IDs for all of the agent’s partners starting with suppliers

property my_suppliers: list[str]

Returns a list of IDs for all of the agent’s suppliers (agents that can supply the product I need).

property n_competitors: int

Returns the number of factories/agents in the same production level

property n_input_negotiations: int

Number of negotiations with suppliers at every step

property n_lines: int

The number of lines in the corresponding factory. You can read state to get this among other information

property n_output_negotiations: int

Number of negotiations with consumers at every step

property n_processes: int

Returns the number of processes in the system

property n_products: int

Returns the number of products in the system

property needed_sales: int

Sales that need to be secured (exogenous input + total supplies - exogenous output - total sales so far)

property needed_supplies: int

Supplies that need to be secured (exogenous output + total sales - exogenous input - total supplies so far)

penalty_multiplier(is_input: bool, unit_price: float | None) float[source]

Returns the penalty multiplier for a contract with the give unit price.

Remarks:
  • The unit price is only needed if the penalties_scale is unit. For all other options (trading, catalog, none), the penalty scale does not depend on the unit price.

property price_multiplier: float

Controls the minimum and maximum prices in the negotiation agendas

Remarks:
  • The base price is either the catalog price if trading price information is not public or the trading price.

  • The minimum unit price in any negotiation agenda is the base price of the previous product in the chain **divided by the multiplier. If that is less than 1, the minimum unit price becomes 1.

  • The maximum unit price in any negotiation agenda is the base price of the previous product in the chain **multiplied by the multiplier. If that is less than 1, the minimum unit price becomes 1.

property price_range: int

The maximum cardinality of the quantity issue in all negotiations

property production_capacities: list[int]

Returns the total production capacity in the market for each process

property profile: OneShotProfile

Gets the profile (static private information) associated with the agent

property quantity_range: int

The maximum cardinality of the quantity issue in all negotiations

reports_at_step(step: int) dict[str, FinancialReport][source]

Returns a dictionary mapping agent ID to its financial report for the given time-step

reports_of_agent(aid: str) dict[int, FinancialReport][source]

Returns a dictionary mapping time-steps to financial reports of the given agent

property running_buy_nmis: dict[str, SAONMI]

All running buy negotiations as a mapping from partner ID to current negotiation nmi

property running_buy_states: dict[str, SAOState]

All running buy negotiations as a mapping from partner ID to current negotiation state

property running_nmis: dict[str, SAONMI]

All running negotiations as a mapping from partner ID to current negotiation nmi

property running_sell_nmis: dict[str, SAONMI]

All running sell negotiations as a mapping from partner ID to current negotiation nmi

property running_sell_states: dict[str, SAOState]

All running sell negotiations as a mapping from partner ID to current negotiation state

property running_states: dict[str, SAOState]

All running negotiations as a mapping from partner ID to current negotiation state

property sales: dict[str, int]

Sales (quantity) per customer so far (this day)

property sales_cost: dict[str, int]

Sales (total price) per customer so far (this day)

property state: OneShotState

Returns the private state of the agent in that world

property supplies: dict[str, int]

Supplies (quantity) per supplier so far (this day)

property supplies_cost: dict[str, int]

Supplies (total price) per supplier so far (this day)

property total_future_sales: int

Total sales so far (this day)

property total_future_supplies: int

Total supplies so far (this day)

property total_sales: int

Total sales so far (this day)

total_sales_at(step: int) int[source]

Total sales already signed at a future step

total_sales_between(start: int, end: int) int[source]

Total sales starting at start and ending at end (inclusive). Past days are ignored

total_sales_from(start: int) int[source]

Total sales starting at start and ending at end (inclusive). Past days are ignored

total_sales_until(step: int) int[source]

Total sales starting today until the given step (inclusive). Past days are ignored

property total_supplies: int

Total supplies so far (this day)

total_supplies_at(step: int) int[source]

Total supplies already signed at a future step

total_supplies_between(start: int, end: int) int[source]

Total supplies starting at start and ending at end (inclusive). Past days are ignored

total_supplies_from(start: int) int[source]

Total supplies starting at start and ending at end (inclusive). Past days are ignored

total_supplies_until(step: int) int[source]

Total supplies starting today until the given step (inclusive). Past days are ignored

property trading_prices: ndarray

Returns the current trading prices of all products

class scml.OneShotAdapter(oneshot_type: str | OneShotAgent, oneshot_params: Dict[str, Any], obj: OneShotAgent | None = None, name=None, type_postfix='', ufun=None)[source]

An adapter allowing agents developed for SCML-OneShot to run in SCML2020World simulations.

property allow_zero_quantity: bool

Does negotiations allow zero quantity?

property current_disposal_cost: float

Cost of storing one unit (penalizes buying too much/ selling too little)

property current_shortfall_penalty: float

Cost of failure to deliver one unit (penalizes buying too little / selling too much)

property current_storage_cost: float

Cost of storing one unit (penalizes buying too much/ selling too little)

init()[source]

Override this method to modify initialization logic

property is_perishable: bool

Are all products perishable (original design of OneShot)

respond_to_negotiation_request(initiator, issues, annotation, mechanism)[source]

Called whenever another agent requests a negotiation with this agent.

Parameters:
  • initiator – The ID of the agent that requested this negotiation

  • issues – Negotiation issues

  • annotation – Annotation attached with this negotiation

  • mechanism – The NegotiatorMechanismInterface interface to the mechanism to be used for this negotiation.

Returns:

None to reject the negotiation, otherwise a negotiator

step()[source]

Override this method to modify stepping logic

class scml.OneShotAgent(owner=None, ufun: OneShotUFun | None = None, name=None)[source]

Base class for all agents in the One-Shot game.

Remarks:
  • You can access all of the negotiators associated with the agent using self.negotiators which is a dictionary mapping the negotiator_id to a tuple of two values: The SAONegotiator object and a key-value context dictionary. In 2021, the context will always be empty.

  • The negotiator_id associated with a negotiation with some partner will be the same as the agent ID of that partner. This means that all negotiators engaged with some partner over all simulation steps will have the same ID which is useful if you are keeping information about past negotiations and partner behavior.

property awi: OneShotAWI

Returns a OneShotAWI object for accessing the simulation.

before_step()[source]

Called at the beginning of every step.

Remarks:
  • Use this for any proactive code that needs to be done every simulation step.

connect_to_2021_adapter(owner)[source]

Connects the agent to its adapter (used internally)

connect_to_oneshot_adapter(owner)[source]

Connects the agent to its adapter (used internally)

get_ami(partner_id: str) SAONMI[source]

Returns the SAONMI (Agent Mechanism Interface) connecting the agent to the negotiation mechanism for the given partner.

get_negotiator(partner_id: str) SAONegotiator[source]

Returns the negotiator corresponding to the given partner ID.

Remarks:
  • Note that the negotiator ID and the partner ID are always the same.

get_nmi(partner_id: str) SAONMI[source]

Returns the SAONMI (Agent Mechanism Interface) connecting the agent to the negotiation mechanism for the given partner.

init()[source]

Called once after the AWI is set.

Remarks:
  • Use this for any proactive initialization code.

property internal_state: dict[str, Any]

Returns the internal state of the agent for debugging purposes.

Remarks:
  • In your agent, you can add any key-value pair to this dict and then use agent_log_* methods to log this information at any point.

make_ufun(add_exogenous=False)[source]

Creates a utility function for the agent.

Parameters:

add_exogenous – If True then the exogenous contracts of the agent will be automatically added whenever the ufun is evaluated for any set of contracts, offers or otherwise.

Remarks:
  • You can always as assume that self.ufun returns the ufun for your. You will not need to directly use this method in most cases.

on_negotiation_failure(partners: list[str], annotation: dict[str, Any], mechanism: SAONMI, state: SAOState) None[source]

Called whenever a negotiation ends without agreement.

Parameters:
  • partners – List of the partner IDs consisting from self and the opponent.

  • annotation – The annotation of the negotiation including the seller ID, buyer ID, and the product.

  • mechanism – The NegotiatorMechanismInterface instance containing all information about the negotiation.

  • state – The final state of the negotiation of the type SAOState including the agreement if any.

on_negotiation_success(contract: Contract, mechanism: SAONMI) None[source]

Called whenever a negotiation ends with agreement.

Parameters:
  • contract – The Contract agreed upon.

  • mechanism – The NegotiatorMechanismInterface instance containing all information about the negotiation that led to the Contract if any.

abstract propose(negotiator_id: str, state: SAOState) tuple | None[source]

Proposes an offer to one of the partners.

Parameters:
  • negotiator_id – ID of the negotiator (and partner)

  • state – Mechanism state including current step

Returns:

an outcome to offer.

respond(negotiator_id: str, state: SAOState, source=None) ResponseType[source]

Responds to an offer from one of the partners.

Parameters:
  • negotiator_id – ID of the negotiator (and partner)

  • state – Mechanism state including current step

Returns:

A response type which can either be reject, accept, or end negotiation.

Remarks:

default behavior is to accept only if the current offer is the same or has a higher utility compared with what the agent would have proposed in the given state and reject otherwise

property running_negotiations: list[RunningNegotiationInfo]

The negotiations currently requested by the agent.

Returns:

A list of negotiation information objects (RunningNegotiationInfo)

sign_all_contracts(contracts: list[Contract]) list[str | None][source]

Signs all contracts (used internally)

step()[source]

Called at the end of every step.

Remarks:
  • Use this for any proactive code that needs to be done every simulation step.

property unsigned_contracts: list[Contract]

All contracts that are not yet signed.

class scml.OneShotEnv(action_manager: ~scml.oneshot.rl.action.ActionManager, observation_manager: ~scml.oneshot.rl.observation.ObservationManager, reward_function: ~scml.oneshot.rl.reward.RewardFunction = <scml.oneshot.rl.reward.DefaultRewardFunction object>, context: ~scml.oneshot.context.BaseContext = FixedPartnerNumbersOneShotContext(name=None, world_type=<class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params={}, non_competitors=(<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types=(<class 'scml.oneshot.agents.nothing.Placeholder'>, ), placeholder_params=None, placeholder_levels=None, perishable=True, price_multiplier=(1.5, 2.0), n_steps=(20, 200), n_processes=2, n_lines=10, n_agents_per_process=(4, 8), production_costs=(1, 4), cash_availability=(1.5, 2.5), shortfall_penalty=(0.2, 1.0), shortfall_penalty_dev=(0.0, 0.1), disposal_cost=(0.0, 0.2), disposal_cost_dev=(0.0, 0.02), storage_cost=(0.0, 0.02), storage_cost_dev=0, penalties_scale='trading', process_inputs=1, process_outputs=1, profit_means=(0.1, 0.2), profit_stddevs=0.05, max_productivity=(0.8, 1.0), initial_balance=None, exogenous_supply_predictability=(0.6, 0.9), exogenous_sales_predictability=(0.6, 0.9), exogenous_control=-1, exogenous_price_dev=(0.1, 0.2), cap_exogenous_quantities=True, buying_strength=None, selling_strength=None, level=0, n_consumers=4, n_suppliers=0, n_competitors=3), agent_type: type[~scml.oneshot.agent.OneShotAgent] = <class 'scml.oneshot.agents.nothing.Placeholder'>, agent_params: dict[str, ~typing.Any] | None = None, extra_checks: bool = True, skip_after_negotiations: bool = True, render_mode=None, debug=False)[source]
calc_info()[source]

Calculates info to be returned from step().

close()[source]

After the user has finished using the environment, close contains the code necessary to “clean up” the environment.

This is critical for closing rendering windows, database or HTTP connections. Calling close on an already closed environment has no effect and won’t raise an error.

render()[source]

Compute the render frames as specified by render_mode during the initialization of the environment.

The environment’s metadata render modes (env.metadata["render_modes"]) should contain the possible ways to implement the render modes. In addition, list versions for most render modes is achieved through gymnasium.make which automatically applies a wrapper to collect rendered frames.

Note

As the render_mode is known during __init__, the objects used to render the environment state should be initialised in __init__.

By convention, if the render_mode is:

  • None (default): no render is computed.

  • “human”: The environment is continuously rendered in the current display or terminal, usually for human consumption. This rendering should occur during step() and render() doesn’t need to be called. Returns None.

  • “rgb_array”: Return a single frame representing the current state of the environment. A frame is a np.ndarray with shape (x, y, 3) representing RGB values for an x-by-y pixel image.

  • “ansi”: Return a strings (str) or StringIO.StringIO containing a terminal-style text representation for each time step. The text can include newlines and ANSI escape sequences (e.g. for colors).

  • “rgb_array_list” and “ansi_list”: List based version of render modes are possible (except Human) through the wrapper, gymnasium.wrappers.RenderCollection that is automatically applied during gymnasium.make(..., render_mode="rgb_array_list"). The frames collected are popped after render() is called or reset().

Note

Make sure that your class’s metadata "render_modes" key includes the list of supported modes.

Changed in version 0.25.0: The render function was changed to no longer accept parameters, rather these parameters should be specified in the environment initialised, i.e., gymnasium.make("CartPole-v1", render_mode="human")

reset(*, seed: int | None = None, options: dict[str, Any] | None = None) tuple[Any, dict[str, Any]][source]

Resets the environment to an initial internal state, returning an initial observation and info.

This method generates a new starting state often with some randomness to ensure that the agent explores the state space and learns a generalised policy about the environment. This randomness can be controlled with the seed parameter otherwise if the environment already has a random number generator and reset() is called with seed=None, the RNG is not reset.

Therefore, reset() should (in the typical use case) be called with a seed right after initialization and then never again.

For Custom environments, the first line of reset() should be super().reset(seed=seed) which implements the seeding correctly.

Changed in version v0.25: The return_info parameter was removed and now info is expected to be returned.

Parameters:
  • seed (optional int) – The seed that is used to initialize the environment’s PRNG (np_random). If the environment does not already have a PRNG and seed=None (the default option) is passed, a seed will be chosen from some source of entropy (e.g. timestamp or /dev/urandom). However, if the environment already has a PRNG and seed=None is passed, the PRNG will not be reset. If you pass an integer, the PRNG will be reset even if it already exists. Usually, you want to pass an integer right after the environment has been initialized and then never again. Please refer to the minimal example above to see this paradigm in action.

  • options (optional dict) – Additional information to specify how the environment is reset (optional, depending on the specific environment)

Returns:

Observation of the initial state. This will be an element of observation_space

(typically a numpy array) and is analogous to the observation returned by step().

info (dictionary): This dictionary contains auxiliary information complementing observation. It should be analogous to

the info returned by step().

Return type:

observation (ObsType)

step(action)[source]

Run one timestep of the environment’s dynamics using the agent actions.

When the end of an episode is reached (terminated or truncated), it is necessary to call reset() to reset this environment’s state for the next episode.

Changed in version 0.26: The Step API was changed removing done in favor of terminated and truncated to make it clearer to users when the environment had terminated or truncated which is critical for reinforcement learning bootstrapping algorithms.

Parameters:

action (ActType) – an action provided by the agent to update the environment state.

Returns:

An element of the environment’s observation_space as the next observation due to the agent actions.

An example is a numpy array containing the positions and velocities of the pole in CartPole.

reward (SupportsFloat): The reward as a result of taking the action. terminated (bool): Whether the agent reaches the terminal state (as defined under the MDP of the task)

which can be positive or negative. An example is reaching the goal state or moving into the lava from the Sutton and Barton, Gridworld. If true, the user needs to call reset().

truncated (bool): Whether the truncation condition outside the scope of the MDP is satisfied.

Typically, this is a timelimit, but could also be used to indicate an agent physically going out of bounds. Can be used to end the episode prematurely before a terminal state is reached. If true, the user needs to call reset().

info (dict): Contains auxiliary diagnostic information (helpful for debugging, learning, and logging).

This might, for instance, contain: metrics that describe the agent’s performance state, variables that are hidden from observations, or individual reward terms that are combined to produce the total reward. In OpenAI Gym <v26, it contains “TimeLimit.truncated” to distinguish truncation and termination, however this is deprecated in favour of returning terminated and truncated variables.

done (bool): (Deprecated) A boolean value for if the episode has ended, in which case further step() calls will

return undefined results. This was removed in OpenAI Gym v26 in favor of terminated and truncated attributes. A done signal may be emitted for different reasons: Maybe the task underlying the environment was solved successfully, a certain timelimit was exceeded, or the physics simulation has entered an invalid state.

Return type:

observation (ObsType)

class scml.OneShotExogenousContract(quantity: int, unit_price: int, product: int, seller: str, buyer: str, time: int, revelation_time: int)[source]

Exogenous contract information

buyer: str

Buyer ID (when passing contrtacts to the constructor of SCML2020OneShotWorld, you can also pass an interged index referring to the agent’s index in the agent_types list)

product: int

Product index

quantity: int

Contract quantity

revelation_time: int

Simulation step at which the contract is revealed to its owner. Should not exceed time and the default generate() method sets it to time

seller: str

Seller ID (when passing contrtacts to the constructor of SCML2020OneShotWorld, you can also pass an interged index referring to the agent’s index in the agent_types list)

time: int

Simulation step at which the contract is exceucted

unit_price: int

Contract unit price

class scml.OneShotIndNegotiatorsAgent(*args, default_negotiator_type='negmas.sao.AspirationNegotiator', default_negotiator_params=None, normalize_ufuns=False, set_reservation=False, **kwargs)[source]

A one-shot agent that deligates all of its decisions to a set of independent negotiators (one per partner per day).

Parameters:
  • default_negotiator_type – An SAONegotiator descendent to be used for creating all negotiators. It can be passed either as a class object or a string with the full class name (e.g. “negmas.sao.AspirationNegotiator”).

  • default_negotiator_type – A dict specifying the paratmers used to create negotiators.

  • normalize_ufuns – If true, all utility functions will be normalized to have a maximum of 1.0 (the minimum value may be negative).

  • set_reservation – If given, the reserved value of all ufuns will be guaranteed to be between the minimum and maximum of the ufun. This is needed to avoid failures of some GeniusNegotiators.

Remarks:

  • To use this class, you need to override generate_ufuns. If you want to change the negotiator type used depending on the partner, you can also override generate_negotiator.

  • If you are using a GeniusNegotiator you must guarantee the following:
    • All ufuns are of the type LinearAdditiveUtilityFunction.

    • All ufuns are normalized with a maximum value of 1.0. You can use normalize_ufuns=True to gruarantee that.

    • All ufuns have a finite reserved value and at least one outcome is

    above it. You can guarantee that by using set_reservation=True.

    • All weights of the LinearAdditiveUtilityFunction must be between zero and one and the weights must sum to one.

generate_negotiator(partner_id: str) SAONegotiator[source]

Returns a negotiator to be used with some partner.

Remarks:

The default implementation will use the default_negotiator_type and default_negotiator_params.

abstract generate_ufuns() dict[str, UtilityFunction][source]

Returns a utility function for each partner. All ufuns MUST be of type LinearAdditiveUtilityFunction if a genius negotiator is used.

init()[source]

Called once after the AWI is set.

Remarks:
  • Use this for any proactive initialization code.

make_negotiator(negotiator_type=None, name: str | None = None, **kwargs) ControlledSAONegotiator[source]

Creates a negotiator but does not add it to the controller. Call add_negotiator to add it.

Parameters:
  • negotiator_type – Type of the negotiator to be created.

  • name – negotiator name

  • **kwargs – any key-value pairs to be passed to the negotiator constructor

Returns:

The negotiator to be controlled. None for failure

Remarks:

If you would like not to negotiate, just return EndingNegotiator() instead of None. The value None should only be returned if an exception is to be thrown.

propose(negotiator_id, state)[source]

Proposes an offer to one of the partners.

Parameters:
  • negotiator_id – ID of the negotiator (and partner)

  • state – Mechanism state including current step

Returns:

an outcome to offer.

step()[source]

Called at the end of every step.

Remarks:
  • Use this for any proactive code that needs to be done every simulation step.

class scml.OneShotPolicy(*args, **kwargs)[source]

A oneshot agent structured in three components, state encoder, policy (action) and action decoder.

The agent is divided into three components:

  1. State encoder (encode_state()) which takes the current state of all negotiation mechanisms, access the awi as needed, and generates a state which can be of any type to be passed to the next component.

  2. Policy (act()) which takes the state generated from the state encoder and returns an action which may be encoded as any type to be passed to the next component. The policy (i.e. `act` () method) is not supposed to access the AWI or any other members of the class. It is preferred to be a pure function. This makes it easy to test the policy at predefined conditions (i.e. states) without having to construct a simulation.

  3. Action decoder (decode_action()) which takes the action generated from the policy and generates the appropriate set of responses to all partners.

Remarks:
  • The simplest form of state encoder which is implemented by default is to return the state member of the AWI.

  • The simplest form of action encoding is to simply return the responses as a dict[str, SAOResponse] from act which is then passed as it is by decode_action . This is the default implementation of decode_action

abstract act(state: Any) Any[source]

The main policy. Generates an action given a state

counter_all(offers: dict[str, tuple | None], states: dict[str, SAOState]) dict[str, SAOResponse][source]

Calculate a response to all offers from all negotiators (negotiator ID is the key).

Parameters:
  • offers – Maps negotiator IDs to offers

  • states – Maps negotiator IDs to offers AT the time the offers were made.

Returns:

A dictionary mapping negotiator ID to an SAOResponse. The response per agent consist of a tuple. In case of acceptance or ending the negotiation the second item of the tuple should be None. In case of rejection, the second item should be the counter offer.

Remarks:
  • The response type CANNOT be WAIT.

  • If the system determines that a loop is formed, the agent may

receive this call for a subset of negotiations not all of them.

decode_action(action: Any) dict[str, SAOResponse][source]

Generates offers to all partners from an encoded action. Default is to return the action as it is assuming it is a dict[str, SAOResponse]

encode_action(responses: dict[str, SAOResponse]) dict[str, SAOResponse][source]

Receives offers for all partners and generates the corresponding action. Used mostly for debugging and testing.

encode_state(mechanism_states: dict[str, SAOState]) Any[source]

Called to generate a state to be passed to the act() method. The default is all of awi of type OneShotState

first_proposals() dict[str, tuple | None][source]

Gets a set of proposals to use for initializing the negotiation.

Returns:

A dictionary mapping each negotiator (in self.negotiators dict) to an outcome to be used as the first proposal if the agent is to start a negotiation.

class scml.OneShotProfile(cost: float, input_product: int, n_lines: int, shortfall_penalty_mean: float, disposal_cost_mean: float, shortfall_penalty_dev: float, disposal_cost_dev: float, storage_cost_mean: float, storage_cost_dev: float)[source]

Defines all private information of a factory

cost: float

The cost of production

disposal_cost_dev: float

A positive number specifying the std. dev. penalty buying too much.

disposal_cost_mean: float

A positive number specifying the average penalty buying too much.

input_product: int

The index of the input product (x for $L_x$ factories)

n_lines: int

Number of lines for this factory

shortfall_penalty_dev: float

A positive number specifying the std. dev. of penalty for selling too much.

shortfall_penalty_mean: float

A positive number specifying the average penalty for selling too much.

storage_cost_dev: float

A positive number specifying the std. dev. cost for keeping inventory for one step. This is only used if the products are not perishable.

storage_cost_mean: float

A positive number specifying the average cost for keeping inventory for one step. This is only used if the products are not perishable.

class scml.OneShotRLAgent(*args, models: list[~typing.Callable[[~numpy.ndarray], ~numpy.ndarray]] | tuple[~typing.Callable[[~numpy.ndarray], ~numpy.ndarray], ...] = (), observation_managers: list[~scml.oneshot.rl.observation.ObservationManager] | tuple[~scml.oneshot.rl.observation.ObservationManager, ...] = (), action_managers: list[~scml.oneshot.rl.action.ActionManager] | tuple[~scml.oneshot.rl.action.ActionManager, ...] | None = None, fallback_type: type[~scml.oneshot.agent.OneShotAgent] | None = <class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, fallback_params: dict[str, ~typing.Any] | None = None, dynamic_context_switching: bool = False, randomize_test_order: bool = False, **kwargs)[source]

A oneshot agent that can execute trained RL models in appropriate worlds. It falls back to the given agent type otherwise

Parameters:
  • models – List of models to choose from.

  • observation_managers – List of observation managers. Must be the same length as models

  • action_managers – List of action managers of the same length as models or None to use the default action manager.

  • fallback_type – A OneShotAgent type to use as a fall-back if the current world is not compatible with any observation/action managers

  • fallback_params – Parameters of the fallback_type

  • dynamic_context_switching – If True, the world is tested each step (instead of only at init) to find the appropriate model

  • randomize_test_order – If True, the order at which the observation/action managers are checked for compatibility with the current world is randomized.

  • **kwargs – Any other OneShotPolicy parameters

act(state: ndarray) ndarray[source]

The main policy. Generates an action given a state

before_step()[source]

Called at at the BEGINNING of every production step (day)

decode_action(action: ndarray) dict[str, SAOResponse][source]

Generates offers to all partners from an encoded action. Default is to return the action as it is assuming it is a dict[str, SAOResponse]

encode_state(mechanism_states: dict[str, SAOState]) ndarray[source]

Called to generate a state to be passed to the act() method. The default is all of awi of type OneShotState

init()[source]

Called once after the AWI is set.

Remarks:
  • Use this for any proactive initialization code.

on_negotiation_failure(*args, **kwargs) None[source]

Called when a negotiation the agent is a party of ends without agreement

on_negotiation_success(*args, **kwargs) None[source]

Called when a negotiation the agent is a party of ends with agreement

propose(*args, **kwargs) tuple | None[source]

Called when the agent is asking to propose in one negotiation

respond(*args, **kwargs) ResponseType[source]

Called when the agent is asked to respond to an offer

step()[source]

Called at at the END of every production step (day)

class scml.OneShotSingleAgreementAgent(*args, strict: bool = False, **kwargs)[source]

A synchronized agent that tries to get no more than one agreement.

This controller manages a set of negotiations from which only a single one – at most – is likely to result in an agreement. To guarantee a single agreement, pass strict=True

The general algorithm for this controller is something like this:

  • Receive offers from all partners.

  • Find the best offer among them by calling the abstract best_offer method.

  • Check if this best offer is acceptable using the abstract is_acceptable method.

    • If the best offer is acceptable, accept it and end all other negotiations.

    • If the best offer is still not acceptable, then all offers are rejected and with the partner who sent it receiving the result of best_outcome while the rest of the partners receive the result of make_outcome.

  • The default behavior of best_outcome is to return the outcome with maximum utility.

  • The default behavior of make_outcome is to return the best offer received in this round if it is valid for the respective negotiation and the result of best_outcome otherwise.

Parameters:

strict – If True the controller is guaranteed to get a single agreement but it will have to send no-response repeatedly so there is a higher chance of never getting an agreement when two of those controllers negotiate with each other

abstract best_offer(offers: dict[str, tuple]) str | None[source]

Return the ID of the negotiator with the best offer

Parameters:

offers – A mapping from negotiator ID to the offer it received

Returns:

The ID of the negotiator with best offer. Ties should be broken. Return None only if there is no way to calculate the best offer.

abstract is_acceptable(offer: tuple, source: str, state: SAOState) bool[source]

Should decide if the given offer is acceptable

Parameters:
  • offer – The offer being tested

  • source – The ID of the negotiator that received this offer

  • state – The state of the negotiation handled by that negotiator

Remarks:
  • If True is returned, this offer will be accepted and all other negotiations will be ended.

abstract is_better(a: tuple | None, b: tuple | None, negotiator: str, state: SAOState) bool[source]

Compares two outcomes of the same negotiation

Parameters:
  • a – “Outcome”

  • b – “Outcome”

  • negotiator – The negotiator for which the comparison is to be made

  • state – Current state of the negotiation

Returns:

True if utility(a) > utility(b)

class scml.OneShotState(exogenous_input_quantity: int, exogenous_input_price: int, exogenous_output_quantity: int, exogenous_output_price: int, disposal_cost: float, shortfall_penalty: float, current_balance: int, total_sales: int, total_supplies: int, total_future_sales: int, total_future_supplies: int, n_products: int, n_processes: int, n_competitors: int, all_suppliers: list[list[str]], all_consumers: list[list[str]], production_capacities: list[int], bankrupt_agents: list[str], catalog_prices: list[float], price_multiplier: float, is_exogenous_forced: bool, current_step: int, n_steps: int, relative_simulation_time: float, profile: OneShotProfile, n_lines: int, is_first_level: bool, is_last_level: bool, is_middle_level: bool, my_input_product: int, my_output_product: int, level: int, my_suppliers: list[str], my_consumers: list[str], my_partners: list[str], penalties_scale: Literal['trading', 'catalog', 'unit', 'none'], n_input_negotiations: int, n_output_negotiations: int, trading_prices: list[float], exogenous_contract_summary: list[tuple[int, int]], reports_of_agents: dict[str, dict[int, FinancialReport]], current_input_outcome_space: DiscreteCartesianOutcomeSpace, current_output_outcome_space: DiscreteCartesianOutcomeSpace, current_negotiation_details: dict[str, dict[str, NegotiationDetails]], sales: dict[str, int], supplies: dict[str, int], needed_sales: int, needed_supplies: int, perishable: bool = True, allow_zero_quantity: bool = False, storage_cost: float = 0.0)[source]

State of a one-shot agent

all_consumers: list[list[str]]

A list of all consumers by product.

all_suppliers: list[list[str]]

A list of all suppliers by product.

allow_zero_quantity: bool

Does this world allow zero quantity in negotiated offers

bankrupt_agents: list[str]

list of bankrupt agents

catalog_prices: list[float]

A list of the catalog prices (by product).

current_balance: int

Current balance of the agent.

property current_buy_nmis: dict[str, SAONMI]

All running buy negotiations as a mapping from partner ID to current negotiation nmi

property current_buy_offers: dict[str, tuple]

All current buy negotiations as a mapping from partner ID to current offer

current_input_outcome_space: DiscreteCartesianOutcomeSpace

The current issues for all negotiations to buy the input product of the agent. If the agent is at level zero, this will be empty. This is exactly the same as current_input_outcome_space.issues

current_negotiation_details: dict[str, dict[str, NegotiationDetails]]

Details on all current negotiations separated into “buy” and “sell” dictionaries.

property current_nmis: dict[str, SAONMI]

All running negotiations as a mapping from partner ID to current negotiation state

property current_offers: dict[str, tuple]

All current negotiations as a mapping from partner ID to current offer

current_output_outcome_space: DiscreteCartesianOutcomeSpace

The current issues for all negotiations to buy the output product of the agent. If the agent is at level n_products - 1, this will be empty. This is exactly the same as current_output_outcome_space.issues

property current_sell_nmis: dict[str, SAONMI]

All running sell negotiations as a mapping from partner ID to current negotiation nmi

property current_sell_offers: dict[str, tuple]

All current sell negotiations as a mapping from partner ID to current offer

property current_sell_states: dict[str, SAOState]

All running sell negotiations as a mapping from partner ID to current negotiation state

property current_states: dict[str, SAOState]

All running negotiations as a mapping from partner ID to current negotiation state

current_step: int

Current simulation step (inherited from negmas.situated.AgentWorldInterface ).

disposal_cost: float

Current unit disposal cost

exogenous_contract_summary: list[tuple[int, int]]

A list of n_products lists each giving the total quantity and average price of exogenous contracts for a product. This information is only available if publish_exogenous_summary is set in the world.

exogenous_input_price: int

Exogenous input unit price for the current step

exogenous_input_quantity: int

Exogenous input quantity for the current step

exogenous_output_price: int

Exogenous output unit price for the current step

exogenous_output_quantity: int

Exogenous output quantity for the current step

is_exogenous_forced: bool

exogenous contracts always forced or can the agent decide not to sign them.

is_first_level: bool

Is the agent in the first production level (i.e. it is an input agent that buys the raw material).

is_last_level: bool

Is the agent in the last production level (i.e. it is an output agent that sells the final product).

is_middle_level: bool

Is the agent neither a first level nor a last level agent

level: int

The production level which is numerically the same as the input product.

my_consumers: list[str]

A list of IDs for all consumers to the agent (i.e. agents that can buy the output product of the agent).

my_input_product: int

The input product to the factory controlled by the agent.

my_output_product: int

The output product from the factory controlled by the agent.

my_partners: list[str]

A list of IDs for all negotiation partners of the agent (in the order suppliers then consumers).

my_suppliers: list[str]

A list of IDs for all suppliers to the agent (i.e. agents that can sell the input product of the agent).

n_competitors: int

Number of other factories on the same production level.

n_input_negotiations: int

Number of negotiations with suppliers.

n_lines: int

The number of production lines in the factory (private information).

n_output_negotiations: int

Number of negotiations with consumers.

n_processes: int

Number of processes in the production chain.

n_products: int

Number of products in the production chain.

n_steps: int

Number of simulation steps (inherited from negmas.situated.AgentWorldInterface ).

needed_sales: int

Today’s needed sales as of now (exogenous input - exogenous output - total sales so far).

needed_supplies: int

Today needed supplies as of now (exogenous output - exogenous input - total supplies).

penalties_scale: Literal['trading', 'catalog', 'unit', 'none']

The scale at which to calculate disposal cost/delivery penalties. “trading” and “catalog” mean trading and catalog prices. “unit” means the contract’s unit price while “none” means that disposal cost/shortfall penalty are absolute.

perishable: bool

Is this a perishable domain (oneshot) of not (std)

price_multiplier: float

The multiplier multiplied by the trading/catalog price when the negotiation agendas are created to decide the maximum and lower quantities.

production_capacities: list[int]

A list of total production capacity per production level.

profile: OneShotProfile

Gives the agent profile including its production cost, number of production lines, input product index, mean of its delivery penalties, mean of its disposal costs, standard deviation of its shortfall penalties and standard deviation of its disposal costs. See OneShotProfile for full description. This information is private information and no other agent knows it.

relative_simulation_time: float

Fraction of the simulation completed (inherited from negmas.situated.AgentWorldInterface).

reports_of_agents: dict[str, dict[int, FinancialReport]]

Gives all past financial reports of a given agent. See FinancialReport for details.

property running_buy_states: dict[str, SAOState]

All running buy negotiations as a mapping from partner ID to current negotiation state

sales: dict[str, int]

Today’s sales per customer so far.

shortfall_penalty: float

Current unit shortfall penalty

storage_cost: float

Current unit storage cost. Only used in standard worlds where products are not perishable

supplies: dict[str, int]

Today supplies per supplier so far.

total_future_sales: int

Total quantity registered as sales in the future using awi.register_sale.

total_future_supplies: int

Total quantity registered as supplies in the future using awi.register_supply.

total_sales: int

Total quantity registered as sales today using awi.register_sale.

total_supplies: int

Total quantity registered as supplies today using awi.register_supply.

trading_prices: list[float]

The trading prices of all products. This information is only available if publish_trading_prices is set in the world.

class scml.OneShotSyncAgent(*args, **kwargs)[source]

An agent that automatically accumulate offers from opponents and allows you to control all negotiations centrally in the counter_all method.

abstract counter_all(offers: dict[str, tuple | None], states: dict[str, SAOState]) dict[str, SAOResponse][source]

Calculate a response to all offers from all negotiators (negotiator ID is the key).

Parameters:
  • offers – Maps negotiator IDs to offers

  • states – Maps negotiator IDs to offers AT the time the offers were made.

Returns:

A dictionary mapping negotiator ID to an SAOResponse. The response per agent consist of a tuple. In case of acceptance or ending the negotiation the second item of the tuple should be None. In case of rejection, the second item should be the counter offer.

Remarks:
  • The response type CANNOT be WAIT.

  • If the system determines that a loop is formed, the agent may

receive this call for a subset of negotiations not all of them.

abstract first_proposals() dict[str, tuple | None][source]

Gets a set of proposals to use for initializing the negotiation.

Returns:

A dictionary mapping each negotiator (in self.negotiators dict) to an outcome to be used as the first proposal if the agent is to start a negotiation.

sign_all_contracts(contracts: list[Contract]) list[str | None][source]

Signs all contracts (used internally)

class scml.OneShotUFun(ex_pin: int, ex_qin: int, ex_pout: int, ex_qout: int, input_product: int, input_agent: bool, output_agent: bool, production_cost: float, disposal_cost: float, storage_cost: float, shortfall_penalty: float, input_penalty_scale: float | None, output_penalty_scale: float | None, storage_penalty_scale: float | None, n_input_negs: int, n_output_negs: int, current_step: int, agent_id: str | None, time_range: tuple[int, int], inventory_in: int = 0, inventory_out: int = 0, input_qrange: tuple[int, int] = (0, 0), input_prange: tuple[int, int] = (0, 0), output_qrange: tuple[int, int] = (0, 0), output_prange: tuple[int, int] = (0, 0), force_exogenous: bool = True, n_lines: int = 10, normalized: bool = False, current_balance: int | float = inf, suppliers: set[str] = {}, consumers: set[str] = {}, perishable=True, **kwargs)[source]

Calculates the utility function of a list of contracts or offers.

Parameters:
  • force_exogenous – Is the agent forced to accept exogenous contracts given through ex_* arguments?

  • ex_pin – total price of exogenous inputs for this agent

  • ex_qin – total quantity of exogenous inputs for this agent

  • ex_pout – total price of exogenous outputs for this agent

  • ex_qout – total quantity of exogenous outputs for this agent.

  • cost – production cost of the agent.

  • disposal_cost – disposal cost per unit of input/output.

  • shortfall_penalty – penalty for failure to deliver one unit of output.

  • input_agent – Is the agent an input agent which means that its input product is the raw material

  • output_agent – Is the agent an output agent which means that its output product is the final product

  • n_lines – Number of production lines. If None, will be read through the AWI.

  • input_product – Index of the input product. If None, will be read through the AWI

  • input_qrange – A 2-int tuple giving the range of input quantities negotiated. If not given will be read through the AWI

  • input_prange – A 2-int tuple giving the range of input unit prices negotiated. If not given will be read through the AWI

  • output_qrange – A 2-int tuple giving the range of output quantities negotiated. If not given will be read through the AWI

  • output_prange – A 2-int tuple giving the range of output unit prices negotiated. If not given will be read through the AWI

  • n_input_negs – How many input negotiations are allowed. If not given, it will be the number of suppliers as given by the AWI

  • n_output_negs – How many output negotiations are allowed. If not given, it will be the number of consumers as given by the AWI

  • current_step – Current simulation step. Needed only for ufun_range when returning best outcomes

  • normalized – If given the values returned by from_*, utility_range and __call__ will all be normalized between zero and one.

Remarks:
  • The utility function assumes that the agent will have to pay for all its input products but will receive money only for the output products it could generate and sell.

  • The utility function respects production capacity (n. lines). The agent cannot produce more than the number of lines it has.

  • disposal cost is paid for items bought but not produced only. Items consumed in production (i.e. sold) are not counted.

property best_option: UFunLimit

Best possible options

breach_level(qin: int = 0, qout: int = 0)[source]

Calculates the breach level that would result from a given quantities

eval(offer: tuple[int, int, int] | None) float[source]

Calculates the utility function given a single contract.

Remarks:
  • This method calculates the utility value of a single offer assuming all other negotiations end in failure.

  • It can only be called for agents that exist in the first or last layer of the production graph.

find_limit(best: bool, n_input_negs=None, n_output_negs=None, secured_input_quantity=0, secured_input_unit_price=0.0, secured_output_quantity=0, secured_output_unit_price=0.0, ignore_signed_contracts: bool = True) UFunLimit[source]

Finds either the maximum or the minimum of the ufun.

Parameters:
  • best – Best(max) or worst (min) ufun value?

  • n_input_negs – How many input negs are we to consider? None means all

  • n_output_negs – How many output negs are we to consider? None means all

  • secured_input_quantity – A quantity that MUST be bought

  • secured_input_unit_price – The (average) unit price of the quantity that MUST be bought.

  • secured_output_quantity – A quantity that MUST be sold.

  • secured_output_unit_price – The (average) unit price of the quantity that MUST be sold.

  • ignore_signed_contracts – If True all signed contracts will be ignored. Use secured_* to pass this information if you need to in this case.

Remarks:
  • You can use the secured_* arguments and control over the number of negotiations to consider to find the utility limits given some already concluded and signed contracts

find_limit_brute_force(best, n_input_negs=None, n_output_negs=None, secured_input_quantity=0, secured_input_unit_price=0.0, secured_output_quantity=0, secured_output_unit_price=0.0, ignore_signed_contracts=True) UFunLimit[source]

Finds either the maximum and the minimum of the ufun.

Parameters:
  • best – Best(max) or worst (min) ufun value?

  • n_input_negs – How many input negs are we to consider? None means all

  • n_output_negs – How many output negs are we to consider? None means all

  • secured_input_quantity – A quantity that MUST be bought

  • secured_input_unit_price – The (average) unit price of the quantity that MUST be bought.

  • secured_output_quantity – A quantity that MUST be sold.

  • secured_output_unit_price – The (average) unit price of the quantity that MUST be sold.

Remarks:
  • You can use the secured_* arguments and control over the number of negotiations to consider to find the utility limits given some already concluded and signed contracts

  • Note that this function CANNOT take into account the sales or supplies already signed (and registered via register_sale and/or register_supply). You MUST pass the quantities and prices for signed contracts through the secured_* parameters.

Returns:

worst and best outcome information in the form of UFunLimit tuple.

from_aggregates(qin: int, qout_signed: int, qout_sold: int, pin: int, pout: int, input_penalty: float, output_penalty: float, storage_penalty: float) float[source]

Calculates the utility from aggregates of input/output quantity/prices

Parameters:
  • qin – Input quantity (total including all exogenous contracts).

  • qout_signed – Output quantity (total including all exogenous contracts) that the agent agreed to sell.

  • qout_sold – Output quantity (total including all exogenous contracts) that the agent will actually sell.

  • pin – Input total price (i.e. unit price * qin).

  • pout – Output total price (i.e. unit price * qin).

  • input_penalty – total disposal cost

  • output_penalty – total shortfall penalty

  • storage_penalty – total storage penalty

Remarks:
  • Most likely, you do not need to directly call this method. Consider from_offers and from_contracts that take current balance and exogenous contract information (passed during ufun construction) into account.

  • The method respects production capacity (n. lines). The agent cannot produce more than the number of lines it has.

  • This method does not take exogenous contracts or current balance into account.

  • The method assumes that the agent CAN pay for all input and production.

from_contracts(contracts: Iterable[Contract], return_info: Literal[False] = False, ignore_exogenous=True) float[source]
from_contracts(contracts: Iterable[Contract], return_info: Literal[True], ignore_exogenous=True) UtilityInfo

Calculates the utility function given a list of contracts

Parameters:
  • contracts – A list/tuple of contracts

  • ignore_exogenous – If given, any contracts with a system agent will be ignored.

Remarks:
  • This method ignores any unsigned contracts passed to it.

  • We do not consider time at all so it is implicitly assumed that all contracts have the same delivery time value.

  • The reason for having the ignore_exogenous parameter is to avoid double counting exogenous contracts if their information is passed during construction of the ufun and they also exist in the list of contracts passed here.

from_offers(offers: tuple[tuple[int, int, int | float] | None, ...] | dict[str, tuple[int, int, int] | None], outputs: tuple[bool, ...] | None = None, return_info: Literal[False] = False, ignore_signed_contracts: bool = True) float[source]
from_offers(offers: tuple[tuple[int, int, int | float] | None, ...] | dict[str, tuple[int, int, int] | None], outputs: tuple[bool, ...] | None, return_info: Literal[True], ignore_signed_contracts: bool = True) UtilityInfo

Calculates the utility value given a list of offers and whether each offer is for output or not (= input).

Parameters:
  • offers – An iterable (e.g. list) of tuples each with three values: (quantity, time, unit price) IN THAT ORDER. Time is ignored and can be set to any value.

  • outputs – An iterable of the same length as offers of booleans specifying for each offer whether it is an offer for buying the agent’s output product.

  • return_info – If true, detailed utility information is returned as Utility Info

  • ignore_signed_contracts – If true, ignores the registered signed contracts. This means that only exogenous contracts and offers will be used in evaluating the utility.

Remarks:
  • This method takes into account the exogenous contract information passed when constructing the ufun.

  • You can pass a dictionary mapping partner ID to an offer and the system will use the correct value for the corresponding outputs array.

is_breach(qin: int = 0, qout: int = 0)[source]

Whether the given quantities would lead to a breach.

property max_utility

The maximum possible utility value

property min_utility

The minimum possible utility value

minmax(*args, **kwargs) tuple[float, float][source]

Finds the range of the given utility function for the given outcomes

Parameters:
  • self – The utility function

  • issues – List of issues (optional)

  • outcomes – A collection of outcomes (optional)

  • max_cardinality – the maximum number of outcomes to try sampling (if sampling is used and outcomes are not given)

  • above_reserve – If given, the minimum and maximum will be set to reserved value if they were less than it.

Returns:

(lowest, highest) utilities in that order

ok_to_buy_at(unit_price: float) bool[source]

Checks if the unit price can – even in principle – be acceptable for buying

Remarks:
  • This method is very optimistic. If it returns False, an agent should never buy at this price. If it returns True, it may still be a bad idea to buy at this price.

  • If we buy at this price, the best case scenario is that we pay it and pay production cost then receive the unit price of one output.

  • If we do not buy at this price, the worst case scenario is that we will pay shortfall penalty for one item

  • We should NOT buy if the best case scenario when buying is worse than the worst case scenario when not buying.

  • If called for agents not at the end of the production chain, it will always return True because in these cases we do not know what the the unit price for the output so there is nothing to compare with.

ok_to_sell_at(unit_price: float) bool[source]

Checks if the unit price can – even in principle – be acceptable for selling

Remarks:
  • This method is very optimistic. If it returns False, an agent should never sell at this price. If it returns True, it may still be a bad idea to sell at this price.

  • Sales decisions does not affect in any way the amount we pay for input materials. It only affects the amount we produce, the amout we get paid in sales and the amount we pay as disposal cost and shortfall penalty.

  • If we agree to sell an item at this price, the best case scenario is that we can actually produce this item and sell it. We pay production cost and receive the given unit price.

  • If we do not sell at this price, the worst case scenario is that we really needed that sale. In this case, we will pay disposal cost for one item.

  • We should NOT sell if the best case scenario when selling is worse than the worst case scenario when not selling.

  • If called for agents not at the beginning of the production chain, it will always return True because in these cases we do not know what the the unit price for the input so there is nothing to compare with.

register_sale(q: int, p: int, t: int)[source]

Registers a sale to be considered when calculating utilities

register_supply(q: int, p: int, t: int)[source]

Registers a supply to be considered when calculating utilities

utility_range(outcome_space: OutcomeSpace | None = None, issues: list[Issue] | None = None, outcomes: list[tuple] | None = None, return_outcomes=False, max_n_outcomes=1000) tuple[float, float] | tuple[float, float, tuple, tuple][source]

Finds the utility range and optionally returns the corresponding outcomes from a given issue space or in a single negotiation.

Parameters:
  • issues – The set of issues of the negotiation. If not given it will be read from the AWI. Note that you cannot specify these issues except for agent in the first or last layer of the production graph (because otherwise, the agent cannot know whether this negotiation is for buying of selling).

  • outcomes – A list of outcomes to consider. Using outcomes is much slower than using issues and you should never pass both.

  • infeasible_cutoff – A utility value under which we consider the outcome infeasible.

  • return_outcomes – If given the worst and best outcomes (in that order) will be returned.

  • max_n_outcomes – Maximum number of outcomes to try. Not used.

Returns:

A tuple of worst and best utility values if return_outcomes is False. otherwise, the worst and best outcomes are appended to the returned utilities leading to a 4-items tuple instead of two.

Remarks:
  • You will get a warning if you use a list of outcomes here because it is too slow.

  • You should only pass issues if you know that the agent is either an input agent or an output agent. Agents in the middle of the production graph cannot know whether these issues are for buying of for selling. To find the utility range for these agents, you can use worst and best that allow specifying input and output issues separately.

  • It is always assumed that the range required is for a single negotiation not a set of negotiations and under the assumption that all other negotiations if any will end in failure

property worst_option: UFunLimit

Best possible options

class scml.OneShotWorld(catalog_prices: ndarray, profiles: list[OneShotProfile], agent_types: list[type[OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | 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[OneShotExogenousContract] = (), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=900, 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]

Basic oneshot simulation

class scml.OneshotDoNothingAgent(owner=None, ufun: OneShotUFun | None = None, name=None)[source]

An agent that does nothing.

Remarks:

Note that this agent will lose money whenever it is at the edges (i.e. it is an input or an output agent trading in raw material or final product).

propose(negotiator_id, state)[source]

Proposes an offer to one of the partners.

Parameters:
  • negotiator_id – ID of the negotiator (and partner)

  • state – Mechanism state including current step

Returns:

an outcome to offer.

respond(negotiator_id, state, source=None)[source]

Responds to an offer from one of the partners.

Parameters:
  • negotiator_id – ID of the negotiator (and partner)

  • state – Mechanism state including current step

Returns:

A response type which can either be reject, accept, or end negotiation.

Remarks:

default behavior is to accept only if the current offer is the same or has a higher utility compared with what the agent would have proposed in the given state and reject otherwise

class scml.Placeholder(*args, **kwargs)[source]

An agent that always raises an exception if called to negotiate. It is useful as a placeholder (for example for RL and MARL exposition)

act(state)[source]

The main policy. Generates an action given a state

class scml.PredictionBasedTradingStrategy(*args, add_trade=True, **kwargs)[source]

A trading strategy that uses prediction strategies to manage inputs/outputs needed

Hooks Into:
Requires:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.ProductionStrategy(*args, **kwargs)[source]

Represents a strategy for controlling production.

Provides:
  • schedule_range : A mapping from contract ID to a tuple of the first and last steps at which some lines are occupied to produce the quantity specified by the contract and whether it is a sell contract

  • can_be_produced : Given a contract, it returns whether or not it is possible to produce the quantity entailed by it (which means that there is enough vacant production line slots before/after the contracts delivery time for sell/buy contracts).

Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

can_be_produced(contract_id: str)[source]

Returns True if the SELL contract given can be honored in principle given the production capacity of the agent (n. lines). It does not check for the availability of inputs or enough money to run the production process.

Remarks:

  • Cannot be called before calling on_contracts_finalized

schedule_range: dict[str, tuple[int, int, bool]]

Gives the range of steps at which the production needed for a given contract are scheduled

scml.RLAction[source]

alias of ndarray

scml.RLState[source]

alias of ndarray

class scml.RandDistOneShotAgent(*args, **kwargs)[source]

An agent that distributes its needs over its partners randomly.

Parameters:
  • equal – If given, it tries to equally distribute its needs over as many of its suppliers/consumers as possible

  • overordering_max – Maximum fraction of needs to over-order. For example, it the agent needs 5 items and this is 0.2, it will order 6 in the first negotiation step.

  • overordering_min – Minimum fraction of needs to over-order. Used in the last negotiation step.

  • overordering_exp – Controls how fast does the over-ordering quantity go from max to min.

  • concession_exp – Controls how fast does the agent concedes on matching its needs exactly.

  • mismatch_max – Maximum mismtach in quantity allowed between needs and accepted offers. If a fraction, it is will be this fraction of the production capacity (n_lines).

class scml.RandomAgent(*args, **kwargs)[source]

An agent that negotiates randomly.

create_ufun(is_seller: bool, issues=None, outcomes=None)[source]

Creates a utility function

class scml.RandomOneShotAgent(*args, p_accept=0.1, p_end=0.005, **kwargs)[source]

An agent that randomly leaves the negotiation, accepts or counters with random outcomes

propose(negotiator_id, state) tuple | None[source]

Proposes an offer to one of the partners.

Parameters:
  • negotiator_id – ID of the negotiator (and partner)

  • state – Mechanism state including current step

Returns:

an outcome to offer.

respond(negotiator_id, state, source=None) ResponseType[source]

Responds to an offer from one of the partners.

Parameters:
  • negotiator_id – ID of the negotiator (and partner)

  • state – Mechanism state including current step

Returns:

A response type which can either be reject, accept, or end negotiation.

Remarks:

default behavior is to accept only if the current offer is the same or has a higher utility compared with what the agent would have proposed in the given state and reject otherwise

class scml.ReactiveAgent(*args, negotiator_type: ~negmas.sao.negotiators.base.SAONegotiator | str = <class 'negmas.gb.negotiators.timebased.AspirationNegotiator'>, negotiator_params: ~typing.Dict[str, ~typing.Any] | None = None, **kwargs)[source]
acceptable_unit_price(step: int, sell: bool) int[source]

Returns the maximum/minimum acceptable unit price for buying/selling at the given time-step

Parameters:
  • step – Simulation step

  • sell – Sell or buy

target_quantities(steps: Tuple[int, int], sell: bool) ndarray[source]

Implemented for speed but not really required

target_quantity(step: int, sell: bool) int[source]

Returns the target quantity to sell/buy at a given time-step

Parameters:
  • step – Simulation step

  • sell – Sell or buy

class scml.ReactiveTradingStrategy(*args, **kwargs)[source]

The agent reactively responds to contracts for selling by buying and vice versa.

Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.RepeatingContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, non_competitors: tuple[str | type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, configs: tuple[dict[str, ~typing.Any], ...] = _Nothing.NOTHING, randomize: bool = True, rename: bool = True)[source]

Encapsulates one or more configs and switches between them when asked to generate or make something.

contains_context(context: Context, raise_on_failure: bool = False, warn_on_failure: bool = False, n_tests: int = 20) bool[source]

Checks that the any world generated from the given context could have been generated from this context

is_valid_world(world: SCMLBaseWorld, raise_on_failure=False, warn_on_failure=True, types: tuple[str | type[OneShotAgent], ...] | None = None) bool[source]

Checks that the given world could have been generated from this context

make_config(types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), params: tuple[dict[str, ~typing.Any], ...] | None = None) dict[str, Any][source]

Generates a config for a world

class scml.RewardFunction(*args, **kwargs)[source]

Represents a reward function.

Remarks:
  • before_action is called before the action is executed for initialization and should return info to be passed to the call

  • __call__ is called with the awi (to get the state), action and info and should return the reward

before_action(awi: OneShotAWI) Any[source]

Called before executing the action from the RL agent to save any required information for calculating the reward in its return

Remarks:

The returned value will be passed as info to __call__() when it is time to calculate the reward.

class scml.SCML2020Agent(name: str | None = None, type_postfix: str = '', preferences: Preferences | None = None, ufun: UtilityFunction | None = None)[source]

Base class for all SCML2020 agents (factory managers)

confirm_production(commands: ndarray, balance: int, inventory) ndarray[source]

Called just before production starts at every time-step allowing the agent to change what is to be produced in its factory

Parameters:
  • commands – an n_lines vector giving the process to be run at every line (NO_COMMAND indicates nothing to be processed

  • balance – The current balance of the factory

  • inventory – an n_products vector giving the number of items available in the inventory of every product type.

Returns:

an n_lines vector giving the process to be run at every line (NO_COMMAND indicates nothing to be processed

Remarks:

  • Not called in SCML2020 competition.

  • The inventory will contain zero items of all products that the factory does not buy or sell

  • The default behavior is to just retrun commands confirming production of everything.

init()[source]

Called to initialize the agent after the world is initialized. the AWI is accessible at this point.

property internal_state: Dict[str, Any]

Returns the internal state of the agent for debugging purposes

on_agent_bankrupt(agent: str, contracts: List[Contract], quantities: List[int], compensation_money: int) None[source]

Called whenever a contract is nullified (because the partner is bankrupt)

Parameters:
  • agent – The ID of the agent that went bankrupt.

  • contracts – All future contracts between this agent and the bankrupt agent.

  • quantities – The actual quantities that these contracts will be executed at.

  • compensation_money – The compensation money that is already added to the agent’s wallet (if ANY).

Remarks:

  • compensation_money will be nonzero iff immediate_compensation is enabled for this world

on_contract_breached(contract: Contract, breaches: List[Breach], resolution: Contract | None) None[source]

Called after complete processing of a contract that involved a breach.

Parameters:
  • contract – The contract

  • breaches – All breaches committed (even if they were resolved)

  • resolution – The resolution contract if re-negotiation was successful. None if not.

on_contract_executed(contract: Contract) None[source]

Called after successful contract execution for which the agent is one of the partners.

on_failures(failures: List[Failure]) None[source]

Called whenever there are failures either in production or in execution of guaranteed transactions

Parameters:

failures – A list of Failure s.

on_neg_request_accepted(req_id: str, mechanism: NegotiatorMechanismInterface)[source]

Called when a requested negotiation is accepted

on_neg_request_rejected(req_id: str, by: List[str] | None)[source]

Called when a requested negotiation is rejected

Parameters:
  • req_id – The request ID passed to _request_negotiation

  • by – A list of agents that refused to participate or None if the failure was for another reason

on_negotiation_failure(partners: List[str], annotation: Dict[str, Any], mechanism: NegotiatorMechanismInterface, state: MechanismState) None[source]

Called whenever a negotiation ends without agreement

on_negotiation_success(contract: Contract, mechanism: NegotiatorMechanismInterface) None[source]

Called whenever a negotiation ends with agreement

respond_to_negotiation_request(initiator: str, issues: List[Issue], annotation: Dict[str, Any], mechanism: NegotiatorMechanismInterface) Negotiator | None[source]

Called whenever another agent requests a negotiation with this agent.

Parameters:
  • initiator – The ID of the agent that requested this negotiation

  • issues – Negotiation issues

  • annotation – Annotation attached with this negotiation

  • mechanism – The NegotiatorMechanismInterface interface to the mechanism to be used for this negotiation.

Returns:

None to reject the negotiation, otherwise a negotiator

respond_to_renegotiation_request(contract: Contract, breaches: List[Breach], agenda: RenegotiationRequest) Negotiator | None[source]

Called to respond to a renegotiation request

Parameters:
  • agenda

  • contract

  • breaches

Returns:

set_renegotiation_agenda(contract: Contract, breaches: List[Breach]) RenegotiationRequest | None[source]

Received by partners in ascending order of their total breach levels in order to set the renegotiation agenda when contract execution fails

Parameters:
  • contract – The contract being breached

  • breaches – All breaches on contract

Returns:

Renegotiation agenda (issues to negotiate about to avoid reporting the breaches).

sign_all_contracts(contracts: List[Contract]) List[str | None][source]

Signs all contracts

step()[source]

Called by the simulator at every simulation step

step_()[source]

Called at every time-step. This function is called directly by the world.

class scml.SCML2020OneShotWorld(catalog_prices: ndarray, profiles: list[OneShotProfile], agent_types: list[type[OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | 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[OneShotExogenousContract] = (), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=900, 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]

Oneshot simulation as used in SCML 2020 competition

class scml.SCML2020World(process_inputs: ndarray, process_outputs: ndarray, catalog_prices: ndarray, profiles: list[FactoryProfile], agent_types: list[type[SCML2020Agent]], agent_params: list[dict[str, Any]] | None = None, exogenous_contracts: Collection[ExogenousContract] = (), initial_balance: ndarray | tuple[int, int] | int = 1000, allow_buying_output=False, allow_selling_input=False, catalog_quantities: int | ndarray = 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: int = 5, compensation_fraction: float = 1.0, compensate_immediately=False, compensate_before_past_debt=True, exogenous_horizon: int | None = None, exogenous_force_max: bool = 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, 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: str = None, publish_exogenous_summary=True, publish_trading_prices=True, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_trading: float = 0.5, inventory_valuation_catalog: float = 0.0, **kwargs)[source]

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

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

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

  • 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 FactoryProfile objects specifying the private profile of the factory associated with each agent.

  • agent_types – An n_agents list of strings/ SCML2020Agent classes specifying the type of each agent

  • agent_params – An n_agents dictionaries giving the parameters of each agent

  • initial_balance – 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 – 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 – The horizon for revealing external contracts

  • exogenous_force_max – 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 – The name of the simulations

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

add_financial_report(agent: SCML2020Agent, factory: Factory, 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

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

property agreement_fraction: float

Fraction of negotiations ending in agreement and leading to signed contracts

property bankruptcy_rate: float

The fraction of factories that went bankrupt

breach_record(breach: Breach) dict[str, Any][source]

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

compensate(available: int, factory: Factory) dict[str, list[tuple[Contract, int, int]]][source]

Called by a factory when it is going bankrupt after liquidation

Parameters:
  • available – The amount available from liquidation

  • factory – The factory being bankrupted

Returns:

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

complete_contract_execution(contract: Contract, breaches: list[Breach], resolution: 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:

contract_record(contract: Contract) dict[str, Any][source]

Converts a contract to a record suitable for permanent storage

contract_size(contract: Contract) float[source]

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

Returns:

property contracts_df: DataFrame

Returns a pandas data frame with the contracts

draw(steps: tuple[int, int] | int | None = None, what: Collection[str] = ['negotiation-requests-rejected', 'negotiation-requests-accepted', 'negotiations-rejected', 'negotiations-started', 'negotiations-failed', 'contracts-concluded', 'contracts-cancelled', 'contracts-signed', 'contracts-breached', 'contracts-executed'], who: Callable[[Agent], bool] = None, where: Callable[[Agent], int | tuple[float, float]] = None, together: bool = True, axs: Collection[Axis] = None, ncols: int = 4, figsize: tuple[int, int] = (15, 15), **kwargs) tuple[Axis, Graph] | tuple[list[Axis], list[Graph]][source]

Generates a graph showing some aspect of the simulation

Parameters:
  • steps – 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 – The edges to have on the graph. Options are: negotiations, concluded, signed, executed

  • who – Either a callable that receives an agent and returns True if it is to be shown or None for all

  • where – 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 – IF specified all edge types are put in the same graph.

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

  • show_node_labels – show node labels!

  • show_edge_labels – show edge labels!

  • kwargs – passed to networx.draw_networkx

Returns:

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

execute_action(action: Action, agent: SCML2020Agent, callback: Callable = None) bool[source]

Executes the given action by the given agent

classmethod generate(agent_types: list[type[~scml.scml2020.agent.SCML2020Agent] | str], agent_params: list[dict[str, ~typing.Any]] | None = None, agent_processes: list[int] | None = None, n_steps: tuple[int, int] | int = (50, 200), n_processes: tuple[int, int] | int = (2, 4), n_lines: ~numpy.ndarray | tuple[int, int] | int = 10, n_agents_per_process: ~numpy.ndarray | tuple[int, int] | int = (2, 4), 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.15, 0.2), profit_stddevs: ~numpy.ndarray | tuple[float, float] | float = 0.001, max_productivity: ~numpy.ndarray | tuple[float, float] | float = 1.0, initial_balance: ~numpy.ndarray | tuple[int, int] | int | None = None, cost_increases_with_level=True, equal_exogenous_supply=False, equal_exogenous_sales=False, 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 = (0.2, 0.8), cash_availability: tuple[float, float] | float = (1.5, 2.5), force_signing=False, profit_basis=<function max>, horizon: tuple[float, float] | float = (0.2, 0.5), inventory_valuation_trading: ~numpy.ndarray | tuple[float, float] | float = 0.5, inventory_valuation_catalog: ~numpy.ndarray | tuple[float, float] | float = 0.0, random_agent_types: bool = False, cost_relativity: float = 1.0, exogenous_generation_method='profitable', exogenous_supply_surplus: tuple[float, float] | float = 0.0, exogenous_sales_surplus: tuple[float, float] | float = 0.0, run_extra_checks: bool = True, **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).

  • inventory_valuation_catalog – The fraction of catalog price to value items at the end.

  • inventory_valuation_trading – The fraction of trading price to value items at the end.

  • max_productivity – Maximum possible productivity per level (i.e. process).

  • 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 override n_agents_per_process and must be a list/tuple of the same length as agent_types . Morevoer, random_agent_types must be False in this case

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

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

  • horizon – 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 – 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

  • 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 if initial_balance is set to None .

  • 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

  • random_agent_types – 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 – 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 – 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 – 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 – If given, the world generation method will check whether the genrated world “makes sense” given its internal criteria. May slow down world generation

  • **kwargs

Returns:

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

Remarks:

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

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

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

classmethod generate_guaranteed_profit(n_steps: int, n_lines: int, n_agents_per_process: int, process_of_agent: list[int], first_agent: list[int], last_agent: list[int], production_costs: list[int], exogenous_control: float, cash_availability: float, force_signing: bool, horizon: int, exogenous_supplies: list[int], max_productivity_process: list[float], max_productivity_agent: list[float], equal_exogenous_sales: bool, process_inputs: list[int], process_outputs: list[int], exogenous_sales_predictability: float, costs: ~numpy.ndarray, profit_stddevs_agent=list[float], profit_means_agent=list[float], initial_balance: ~numpy.ndarray | tuple[int, int] | int | None = None, cost_relativity: float = 1.0, profit_basis=<function max>, inventory_valuation_trading: float = 0.5, inventory_valuation_catalog: float = 0.0, run_extra_checks=True) tuple[list[ExogenousContract], list[int], list[FactoryProfile], list[float], dict[str, Any]][source]

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: int, n_lines: int, n_agents_per_process: int, process_of_agent: list[int], first_agent: list[int], last_agent: list[int], production_costs: list[int], exogenous_control: float, cash_availability: float, force_signing: bool, horizon: int, exogenous_supplies: list[int], max_productivity_process: list[float], max_productivity_agent: list[float], equal_exogenous_sales: bool, process_inputs: list[int], process_outputs: list[int], exogenous_sales_predictability: float, costs: ~numpy.ndarray, profit_stddevs_agent=list[float], profit_means_agent=list[float], initial_balance: ~numpy.ndarray | tuple[int, int] | int | None = None, cost_relativity: float = 1.0, profit_basis=<function max>, inventory_valuation_trading: float = 0.5, inventory_valuation_catalog: float = 0.0, run_extra_checks: bool = True) tuple[list[ExogenousContract], list[int], list[FactoryProfile], list[float], dict[str, Any]][source]

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

get_private_state(agent: SCML2020Agent) dict[source]

Reads the private state of the given agent

is_valid_contact(contract: Contract) bool[source]

Checks whether a signed contract is valid

property non_system_agent_ids: list[str]

Returns names of all agents except system agents

property non_system_agent_names: list[str]

Returns names of all agents except system agents

property non_system_agents: list[SCML2020Agent]

Returns all agents except system agents

property num_bankrupt: float

The fraction of factories that went bankrupt

on_contract_concluded(contract: Contract, to_be_signed_at: int) None[source]

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

Parameters:
  • contract – The contract to add

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

on_contract_signed(contract: 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.

order_contracts_for_execution(contracts: Collection[Contract]) Collection[Contract][source]

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

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

property productivity: float

Fraction of production lines occupied during the simulation

record_bankrupt(factory: Factory) None[source]

Records agent bankruptcy

property relative_productivity: float | None

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

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

scores(assets_multiplier_trading: float | None = None, assets_multiplier_catalog: float | None = None, assets_multiplier: float | None = None) dict[str, float][source]

scores of all agents given the asset multiplier.

Parameters:

assets_multiplier – a multiplier to multiply the assets with.

simulation_step(stage)[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.

start_contract_execution(contract: Contract) set[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).

property stats_df: DataFrame

Returns a pandas data frame with the stats

property system_agent_ids: list[str]

Returns the names two system agents

property system_agent_names: list[str]

Returns the names two system agents

property system_agents: list[SCML2020Agent]

Returns the two system agents

trading_prices_for(discount: float = 1.0, condition='executed') 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

welfare(include_bankrupt: bool = False) float[source]

Total welfare of all agents

property winners

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

class scml.SCML2021OneShotWorld(*args, **kwargs)[source]

Oneshot simulation as used in SCML 2021 competition

class scml.SCML2021World(*args, **kwargs)[source]
classmethod generate(*args, inventory_valuation_trading: ndarray | tuple[float, float] | float = (0.0, 0.5), horizon: tuple[float, float] | float = (0.2, 0.5), **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).

  • inventory_valuation_catalog – The fraction of catalog price to value items at the end.

  • inventory_valuation_trading – The fraction of trading price to value items at the end.

  • max_productivity – Maximum possible productivity per level (i.e. process).

  • 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 override n_agents_per_process and must be a list/tuple of the same length as agent_types . Morevoer, random_agent_types must be False in this case

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

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

  • horizon – 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 – 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

  • 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 if initial_balance is set to None .

  • 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

  • random_agent_types – 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 – 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 – 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 – 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 – If given, the world generation method will check whether the genrated world “makes sense” given its internal criteria. May slow down world generation

  • **kwargs

Returns:

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

Remarks:

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

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

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

class scml.SCML2022OneShotWorld(*args, **kwargs)[source]

Oneshot simulation as used in SCML 2022 competition

class scml.SCML2022World(*args, **kwargs)[source]
class scml.SCML2023OneShotWorld(*args, **kwargs)[source]

Oneshot simulation as used in SCML 2023 competition

class scml.SCML2023World(*args, **kwargs)[source]
class scml.SCML2024OneShotWorld(*args, **kwargs)[source]

Oneshot simulation as used in SCML 2024 competition

class scml.SCML2024World(*args, **kwargs)[source]
class scml.SCMLBaseWorld(catalog_prices: ndarray, profiles: list[OneShotProfile], agent_types: list[type[OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | 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[OneShotExogenousContract] = (), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=900, 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]

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 agent

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

add_financial_report(agent: 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:

property agreement_fraction: float

Fraction of negotiations ending in agreement and leading to signed contracts

breach_record(breach: Breach) dict[str, Any][source]

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

complete_contract_execution(contract: Contract, breaches: list[Breach], resolution: 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:

contract_record(contract: Contract) dict[str, Any][source]

Converts a contract to a record suitable for permanent storage

contract_size(contract: Contract) float[source]

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

Returns:

property contracts_df: DataFrame

Returns a pandas data frame with the contracts

draw(steps: tuple[int, int] | int | None = None, what: Collection[str] = ['negotiation-requests-rejected', 'negotiation-requests-accepted', 'negotiations-rejected', 'negotiations-started', 'negotiations-failed', 'contracts-concluded', 'contracts-cancelled', 'contracts-signed', 'contracts-breached', 'contracts-executed'], who: Callable[[Agent], bool] | None = None, where: Callable[[Agent], int | tuple[float, float]] | None = None, together: bool = True, axs: Collection[Axis] | None = None, ncols: int = 4, figsize: tuple[int, int] = (15, 15), **kwargs) tuple[Axis, Graph] | tuple[list[Axis], list[Graph]][source]

Generates a graph showing some aspect of the simulation

Parameters:
  • steps – 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 – The edges to have on the graph. Options are: negotiations, concluded, signed, executed

  • who – Either a callable that receives an agent and returns True if it is to be shown or None for all

  • where – 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 – IF specified all edge types are put in the same graph.

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

  • show_node_labels – show node labels!

  • show_edge_labels – show edge labels!

  • kwargs – passed to networx.draw_networkx

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: Callable | None = None) bool[source]

Executes the given action by the given agent

classmethod generate(agent_types: tuple[str | type[~scml.oneshot.agent.OneShotAgent], ...] | list[str | type[~scml.oneshot.agent.OneShotAgent]] | type[~scml.oneshot.agent.OneShotAgent] | str, agent_params: list[dict[str, ~typing.Any]] | tuple[dict[str, ~typing.Any], ...] | 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=<function 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 override n_agents_per_process and must be a list/tuple of the same length as agent_types . Morevoer, random_agent_types must be False in this case

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

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

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

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

  • exogenous_supply_predictability – 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 if initial_balance is set to None .

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

  • disposal_cost – 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 and shortfall_penalty relative to. There are four options: trading, catalog mean trading and catalog prices of the product. unit means the unit price in the contract and none means the storage-cost and shortfall_penalty are absolute values (in money unit). If not given will be read through the AWI

  • exogenous_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:
    1. Pass random_agent_types = False, and pass agent_types, agent_processes to control placement of each agent in each level of the production graph.

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

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

get_private_state(agent: Agent) dict[source]

Reads the private state of the given agent

is_valid_contact(contract: Contract) bool[source]

Checks whether a signed contract is valid

property non_system_agent_ids: list[str]

Returns names of all agents except system agents

property non_system_agent_names: list[str]

Returns names of all agents except system agents

property non_system_agents: list[DefaultOneShotAdapter]

Returns all agents except system agents

on_contract_signed(contract: 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.

order_contracts_for_execution(contracts: Collection[Contract]) Collection[Contract][source]

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

classmethod plot_combined_stats(worlds: tuple[SCMLBaseWorld, ...] | SCMLBaseWorld, stats: str | tuple[str, ...] | 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 displayed

  • pertype – 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, ...] | 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 displayed

  • pertype – 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

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

classmethod replace_agents(config: dict, old_types: tuple[str | type[OneShotAgent], ...] | list[str | type[OneShotAgent]], types: tuple[str | type[OneShotAgent], ...] | list[str | type[OneShotAgent]], params: list[dict[str, Any]] | tuple[dict[str, Any], ...] | None = None)[source]

Replaces all agents of a given type by agents of a new type

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.

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.

start_contract_execution(contract: Contract) set[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).

property stats_df: DataFrame

Returns a pandas data frame with the stats

step_with(actions: dict[str, dict[str, 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 that init() and other initialization code is called correctly.

  • Every step advances all negotiations one step.

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

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

property system_agent_ids: list[str]

Returns the names two system agents

property system_agent_names: list[str]

Returns the names two system agents

property system_agents: list[_StdSystemAgent]

Returns the two system agents

trading_prices_for(discount: float = 1.0, condition='executed') 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

welfare(include_bankrupt: bool = False) float[source]

Total welfare of all agents

property winners

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

class scml.SatisficerAgent(*args, target_productivity=1.0, satisfying_profit=0.15, acceptable_loss=0.02, price_range=0.4, concession_rate_price=1.0, concession_rate_quantity=1.0, concession_rate_time=1.0, market_share=1, horizon=5, **kwargs)[source]

A simple monolithic agent that tries to carefully make small profit every step.

Parameters:
  • target_productivity – The productivity level targeted by the agent defined as the fraction of its lines to be active per step.

  • satisfying_profit – A profit amount considered satisfactory. Used when deciding negotiation agenda and signing to decide if a price is a good price (see _good_price()). A fraction of the trading price.

  • acceptable_loss – A fraction of trading price that the seller/buyer is willing to go under/over the current trading price during negotiation.

  • price_range – The total range around the trading price for negotiation agendas.

  • concession_rate_price – The exponent of the consession curve for price.

  • concession_rate_quantity – The exponent of the consession curve for quantity.

  • concession_rate_time – The exponent of the consession curve for time.

  • market_share – An integer specifying the expected share of the agent in the market. The agent will assume that it can get up to (market_share / (n_competitors + market_share -1)) of all sales and supplies where n_competitors is the number of agents at the same production level. Setting it to 1 means that the agent assumes it will get the same amount of trade as all other agents. Setting it to infinity means that the agent will assume it will take all the trade in the market

  • horizon – Time horizon for negotiations. If None, the exogenous_contracts_revelation horizon will be used

before_step()[source]

Called at at the BEGINNING of every production step (day)

init()[source]

Called once

on_contracts_finalized(signed, cancelled, rejectors)[source]

Called for all contracts in a single step to inform the agent about which were finally signed and which were rejected by any agents (including itself)

Parameters:
  • signed – A list of signed contracts. These are binding

  • cancelled – A list of cancelled contracts. These are not binding

  • rejectors – A list of lists where each of the internal lists gives the rejectors of one of the cancelled contracts. Notice that it is possible that this list is empty which means that the contract other than being rejected by any agents (if that was possible in the specific world).

Remarks:

The default implementation is to call on_contract_signed for singed contracts and on_contract_cancelled for cancelled contracts

on_negotiation_failure(partners, annotation, mechanism, state)[source]

Called when a negotiation fails

on_negotiation_success(contract, mechanism)[source]

Called when a negotiation fails

propose(state: SAOState, ami: SAONMI, is_selling: bool, is_requested: bool)[source]

Used to propose to the opponent

Parameters:
  • state – mechanism state including current round

  • ami – Agent-mechanism-interface for accessing the negotiation mechanism

  • offer – The offer proposed by the partner

  • is_selling – Whether the agent is selling to this partner

  • is_requested – Whether the agent requested this negotiation

respond(state, ami, is_selling, is_requested)[source]

Responds to an offer from one partner.

Parameters:
  • state – mechanism state including current round

  • ami – Agent-mechanism-interface for accessing the negotiation mechanism

  • offer – The offer proposed by the partner

  • is_selling – Whether the agent is selling to this partner

  • is_requested – Whether the agent requested this negotiation

Remarks:

  • The main idea is to accept offers that are within the quantity limits for the delivery day if its price is good enough for the current stage of the negotiation.

  • During negotiation, the agent starts accepting highest/lowest prices for selling/buying and gradually conceeds to the minimally acceptable price (good_price) defined as being acceptable_loss above/below the trading price for buying/selling.

respond_to_negotiation_request(initiator, issues, annotation, mechanism)[source]

Called whenever another agent requests a negotiation with this agent.

Parameters:
  • initiator – The ID of the agent that requested this negotiation

  • issues – Negotiation issues

  • annotation – Annotation attached with this negotiation

  • mechanism – The NegotiatorMechanismInterface interface to the mechanism to be used for this negotiation.

Returns:

None to reject the negotiation, otherwise a negotiator

sign_all_contracts(contracts)[source]

Signs all contracts

step()[source]

Called at the end of the day. Will request all negotiations

class scml.SignAll[source]

Signs all contracts no matter what.

Overrides:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.SignAllPossible[source]

Signs all contracts that can in principle be honored. The only check made by this strategy is that for sell contracts there is enough production capacity

Overrides:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.Simulation(*args, **kwargs)[source]

Provides a simulator to the agent.

Provides:
  • simulator (FactorySimulator): A simulator that can be used to simulate the effect of contracts on the future of the factory

Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.SingleAgentPerLevelSupplierContext(name: str | None = None, world_type: type[~scml.oneshot.world.SCMLBaseWorld] = <class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params: dict[str, ~typing.Any] = _Nothing.NOTHING, non_competitors: tuple[str | type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types: tuple[type[~scml.oneshot.agent.OneShotAgent], ...] = (<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params: tuple[dict, ...] | None = None, placeholder_levels: tuple[int, ...] | None = None, perishable: bool = True, price_multiplier: ~numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), n_steps: tuple[int, int] | int = (20, 200), n_processes: tuple[int, int] | int = 2, n_lines: tuple[int, int] | int = 10, production_costs: ~numpy.ndarray | tuple[int, int] | int = (1, 4), 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, penalties_scale: str | list[str] = 'trading', process_inputs: tuple[int, int] | int = 1, process_outputs: ~numpy.ndarray | tuple[int, int] | int = 1, 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, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), cap_exogenous_quantities: bool = True, buying_strength: ~scml.oneshot.context.Strength | None = None, selling_strength: ~scml.oneshot.context.Strength | None = None, n_competitors: tuple[int, int] = (0, 0), level: int = 0, n_consumers: tuple[int, int] = (1, 1), n_suppliers: tuple[int, int] = (0, 0), n_agents_per_process=1)[source]

A world in which every level has exactly one factory and the agent is a supplier

class scml.SingleAgreementAspirationAgent(*args, **kwargs)[source]

Uses a time-based strategy to accept a single agreement from the set it is considering.

before_step()[source]

Called at the beginning of every step.

Remarks:
  • Use this for any proactive code that needs to be done every simulation step.

choose_agents(offers, outcome)[source]

Selects an appropriate way to distribute this outcome to agents with given IDs.

counter_all(offers, states)[source]

Calculate a response to all offers from all negotiators (negotiator ID is the key).

Parameters:
  • offers – Maps negotiator IDs to offers

  • states – Maps negotiator IDs to offers AT the time the offers were made.

Returns:

A dictionary mapping negotiator ID to an SAOResponse. The response per agent consist of a tuple. In case of acceptance or ending the negotiation the second item of the tuple should be None. In case of rejection, the second item should be the counter offer.

Remarks:
  • The response type CANNOT be WAIT.

  • If the system determines that a loop is formed, the agent may

receive this call for a subset of negotiations not all of them.

first_proposals() Dict[str, tuple | None][source]

Gets a set of proposals to use for initializing the negotiation.

Returns:

A dictionary mapping each negotiator (in self.negotiators dict) to an outcome to be used as the first proposal if the agent is to start a negotiation.

class scml.SingleAgreementRandomAgent(*args, p_accept: float = 0.1, **kwargs)[source]

A controller that agrees randomly to one offer

best_offer(offers: dict[str, tuple]) str | None[source]

Return the ID of the negotiator with the best offer

Parameters:

offers – A mapping from negotiator ID to the offer it received

Returns:

The ID of the negotiator with best offer. Ties should be broken. Return None only if there is no way to calculate the best offer.

is_acceptable(offer: tuple, source: str, state: SAOState) bool[source]

Should decide if the given offer is acceptable

Parameters:
  • offer – The offer being tested

  • source – The ID of the negotiator that received this offer

  • state – The state of the negotiation handled by that negotiator

Remarks:
  • If True is returned, this offer will be accepted and all other negotiations will be ended.

is_better(a: tuple | None, b: tuple | None, negotiator: str, state: SAOState) bool[source]

Compares two outcomes of the same negotiation

Parameters:
  • a – “Outcome”

  • b – “Outcome”

  • negotiator – The negotiator for which the comparison is to be made

  • state – Current state of the negotiation

Returns:

True if utility(a) > utility(b)

class scml.StepNegotiationManager(*args, negotiator_type: ~negmas.sao.negotiators.base.SAONegotiator | str = <class 'negmas.gb.negotiators.timebased.AspirationNegotiator'>, negotiator_params: ~typing.Dict[str, ~typing.Any] | None = None, **kwargs)[source]

A negotiation manager that controls a controller and another for selling for every timestep

Parameters:
  • negotiator_type – The negotiator type to use to manage all negotiations

  • negotiator_params – Paramters of the negotiator

Provides:
Requires:
Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

all_negotiations_concluded(controller_index: int, is_seller: bool) None[source]

Called by the StepController to affirm that it is done negotiating for some time-step

buyers

Buyer controllers and seller controllers. Each of them is responsible of covering the needs for one step (either buying or selling).

class scml.StrongConsumerContext(*args, **kwargs)[source]

A consumer with almost many suppliers relative to competitors

class scml.StrongSupplierContext(*args, **kwargs)[source]

A supplier with almost many consumers relative to competitors

class scml.SupplierContext(*args, **kwargs)[source]

A world context that can generate any world compatible with the observation manager

class scml.SupplyDrivenProductionStrategy(*args, **kwargs)[source]

A production strategy that converts all inputs to outputs

Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.SyncRandomOneShotAgent(*args, equal: bool = False, overordering_max: float = 0.2, overordering_min: float = 0.0, overordering_exp: float = 0.4, mismatch_exp: float = 4.0, mismatch_max: float = 0.3, **kwargs)[source]

An agent that distributes its needs over its partners randomly.

Parameters:
  • equal – If given, it tries to equally distribute its needs over as many of its suppliers/consumers as possible

  • overordering_max – Maximum fraction of needs to over-order. For example, it the agent needs 5 items and this is 0.2, it will order 6 in the first negotiation step.

  • overordering_min – Minimum fraction of needs to over-order. Used in the last negotiation step.

  • overordering_exp – Controls how fast does the over-ordering quantity go from max to min.

  • concession_exp – Controls how fast does the agent concedes on matching its needs exactly.

  • mismatch_max – Maximum mismtach in quantity allowed between needs and accepted offers. If a fraction, it is will be this fraction of the production capacity (n_lines).

counter_all(offers, states)[source]

Calculate a response to all offers from all negotiators (negotiator ID is the key).

Parameters:
  • offers – Maps negotiator IDs to offers

  • states – Maps negotiator IDs to offers AT the time the offers were made.

Returns:

A dictionary mapping negotiator ID to an SAOResponse. The response per agent consist of a tuple. In case of acceptance or ending the negotiation the second item of the tuple should be None. In case of rejection, the second item should be the counter offer.

Remarks:
  • The response type CANNOT be WAIT.

  • If the system determines that a loop is formed, the agent may

receive this call for a subset of negotiations not all of them.

distribute_needs(t: float) dict[str, int][source]

Distributes my needs randomly over all my partners

first_proposals()[source]

Gets a set of proposals to use for initializing the negotiation.

Returns:

A dictionary mapping each negotiator (in self.negotiators dict) to an outcome to be used as the first proposal if the agent is to start a negotiation.

init()[source]

Called once after the AWI is set.

Remarks:
  • Use this for any proactive initialization code.

class scml.TradeDrivenProductionStrategy(*args, **kwargs)[source]

A production strategy that produces ONLY for contracts that the agent did not initiate.

Hooks Into:
  • on_contract_finalized

Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

class scml.TradePredictionStrategy(*args, predicted_outputs: int | ndarray = None, predicted_inputs: int | ndarray = None, add_trade=False, **kwargs)[source]

A prediction strategy for expected inputs and outputs at every step

Parameters:
  • predicted_inputs (-) – None for default, a number of an n_steps numbers giving predicted inputs

  • predicted_outputs (-) – None for default, a number of an n_steps numbers giving predicted outputs

Provides:
  • expected_inputs : n_steps vector giving the predicted inputs at every time-step. It defaults to the number of lines.

  • expected_outputs : n_steps vector giving the predicted outputs at every time-step. It defaults to the number of lines.

  • input_cost : n_steps vector giving the predicted input cost at every time-step. It defaults to catalog price.

  • output_price : n_steps vector giving the predicted output price at every time-step. It defaults to catalog price.

Hooks Into:
Abstract:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

expected_inputs

Expected input quantity every step

expected_outputs

Expected output quantity every step

input_cost: ndarray

Expected unit price of the input

output_price: ndarray

Expected unit price of the output

trade_prediction_before_step() None[source]

Will be called at the beginning of every step to update the prediction

abstract trade_prediction_init() None[source]

Will be called to update expected_outputs, expected_inputs, input_cost, output_cost during init()

trade_prediction_step() None[source]

Will be called at the end of every step to update the prediction

class scml.TradingStrategy(*args, **kwargs)[source]

Base class for all trading strategies.

Provides:
  • inputs_needed (np.ndarray): How many items of the input product do I need to buy at every time step (n_steps vector). This should be read but not updated by the NegotiationManager.

  • outputs_needed (np.ndarray): How many items of the output product do I need to sell at every time step (n_steps vector). This should be read but not updated by the NegotiationManager.

  • inputs_secured (np.ndarray): How many items of the input product I already contracted to buy (n_steps vector) [out of input_needed]. This can be read but not updated by the NegotiationManager.

  • outputs_secured (np.ndarray): How many units of the output product I already contracted to sell (n_steps vector) [out of outputs_secured] This can be read but not updated by the NegotiationManager.

Hooks Into:
Remarks:
  • Attributes section describes the attributes that can be used to construct the component (passed to its __init__ method).

  • Provides section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the Bases section above for all the bases of this component).

  • Requires section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component

  • Abstract section describes abstract methods that MUST be implemented by any descendant of this component.

  • Hooks Into section describes the methods this component overrides calling super () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with on_ are hooked into this way.

  • Overrides section describes the methods this component overrides without calling super effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with on_) are overridden this way.

inputs_needed: ndarray

How many items of the input product do I need at every time step

inputs_secured: ndarray

How many units of the input product I have already secured per step

outputs_needed: ndarray

How many items of the output product do I need at every time step

outputs_secured: ndarray

How many units of the output product I have already secured per step

class scml.UFunLimit(utility, input_quantity, input_price, output_quantity, output_price, exogenous_input_quantity, exogenous_input_price, exogenous_output_quantity, exogenous_output_price, inventory_input, inventory_output, producible)[source]

Information about one utility limit (either highest or lowest). See OnShotUFun.find_limit for details.

exogenous_input_price

Alias for field number 6

exogenous_input_quantity

Alias for field number 5

exogenous_output_price

Alias for field number 8

exogenous_output_quantity

Alias for field number 7

input_price

Alias for field number 2

input_quantity

Alias for field number 1

inventory_input

Alias for field number 9

inventory_output

Alias for field number 10

output_price

Alias for field number 4

output_quantity

Alias for field number 3

producible

Alias for field number 11

utility

Alias for field number 0

class scml.WeakConsumerContext(*args, **kwargs)[source]

A consumer with few suppliers relative to competitors

class scml.WeakSupplierContext(*args, **kwargs)[source]

A supplier with few consumers relative to competitors

scml.builtin_agent_types(as_str=False)[source]

Returns all built-in agents.

Parameters:

as_str – If true, the full type name will be returned otherwise the type object itself.

scml.greedy_policy(obs: ~numpy.ndarray, awi: ~scml.oneshot.awi.OneShotAWI, obs_manager: ~scml.oneshot.rl.observation.ObservationManager, action_manager: ~scml.oneshot.rl.action.ActionManager = FlexibleActionManager(context=ANACOneShotContext(name=None, world_type=<class 'scml.oneshot.world.SCML2024OneShotWorld'>, world_params={}, non_competitors=(<class 'scml.oneshot.agents.greedy.GreedyOneShotAgent'>, <class 'scml.oneshot.agents.rand.RandDistOneShotAgent'>, <class 'scml.oneshot.agents.rand.EqualDistOneShotAgent'>), placeholder_types=(<class 'scml.oneshot.agents.nothing.Placeholder'>,), placeholder_params=None, placeholder_levels=None, perishable=True, price_multiplier=(1.5, 2.0), n_steps=(20, 200), n_processes=2, n_lines=10, n_agents_per_process=(4, 8), production_costs=(1, 4), cash_availability=(1.5, 2.5), shortfall_penalty=(0.2, 1.0), shortfall_penalty_dev=(0.0, 0.1), disposal_cost=(0.0, 0.2), disposal_cost_dev=(0.0, 0.02), storage_cost=(0.0, 0.02), storage_cost_dev=0, penalties_scale='trading', process_inputs=1, process_outputs=1, profit_means=(0.1, 0.2), profit_stddevs=0.05, max_productivity=(0.8, 1.0), initial_balance=None, exogenous_supply_predictability=(0.6, 0.9), exogenous_sales_predictability=(0.6, 0.9), exogenous_control=-1, exogenous_price_dev=(0.1, 0.2), cap_exogenous_quantities=True, year=2024), continuous=False, n_suppliers=4, n_consumers=4, n_partners=8, capacity_multiplier=1, n_prices=2, max_group_size=2, reduce_space_size=True, extra_checks=False, max_quantity=10), debug=False, distributor: ~typing.Callable[[int, int], list[int]] = <function all_but_concentrated>) ndarray[source]

A simple greedy policy.

Parameters:
  • obs – The current observation

  • awi – The AWI of the agent running the policy

  • obs_manager – The observation manager used to encode the observation

  • action_manager – The action manager to be used to encode the action

  • debug – If True, extra assertions are tested

  • distributor – A callable that receives a total quantity to be distributed over n partners and returns a list of n values that sum to this total quantity

Remarks:
  • Accepts the subset of offers with maximum total quantity under current needs.

  • The remaining quantity is distributed over the remaining partners using the distributor function

  • Prices are set to the worst for the agent if the price range is small else they are set randomly

scml.is_system_agent(aid: str) bool[source]

Checks whether an agent is a system agent or not

Parameters:

aid – Agent ID

Returns:

True if the ID is for a system agent.

scml.model_wrapper(model, deterministic: bool = False) Callable[[ndarray], ndarray][source]

Wraps a stable_baselines3 model as an RL model

scml.random_action(obs: ndarray, env: OneShotEnv) ndarray[source]

Samples a random action from the action space of the

scml.random_policy(obs: ndarray, env: OneShotEnv, pend: float = 0.05, paccept: float = 0.15) ndarray[source]

Ends the negotiation or accepts with a predefined probability or samples a random response.