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, 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, 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 Objects Layer 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, 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, 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, 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 Objects Layer 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 Objects Layer 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, 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, 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 Objects Layer 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, 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 Objects Layer 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 Objects Layer 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, 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, 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 Objects Layer 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 Objects Layer 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, 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 Objects Layer 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 Objects Layer 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 Objects Layer 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 Objects Layer 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