scml

class scml.AWI(world, 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

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

Return type

List[List[str]]

property all_suppliers

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

Return type

List[List[str]]

available_for_production(repeats, step=- 1, line=- 1, override=True, method='latest')[source]

Finds available times and lines for scheduling production.

Parameters
  • repeats (int) – How many times to repeat the process

  • step (Union[int, Tuple[int, int]]) – 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 (int) – The production line. The special value ANY_LINE gives the factory the freedom to use any line

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

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

Return type

Tuple[ndarray, ndarray]

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, line)[source]

Cancels any production commands on that line at this step

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

  • line (int) – The production line

Return type

bool

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

Returns the catalog prices of all products

Return type

ndarray

property current_balance

Current balance of the agent

property current_inventory

Current inventory of the agent

property exogenous_contract_summary

The exogenous contracts in the current step for all products

Return type

List[Tuple[int, int]]

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

Returns the number of inputs to every production process

Return type

ndarray

is_bankrupt(aid=None)[source]

Checks whether the agent is bankrupt

Parameters

aid (Optional[str]) – Agent ID (None means self)

Return type

bool

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)[source]

Checks whether an agent is a system agent or not

Parameters

aid (str) – Agent ID

Return type

bool

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

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

Return type

List[str]

property my_input_product

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

Return type

int

property my_input_products

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

Return type

ndarray

property my_output_product

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

Return type

int

property my_output_products

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

Return type

ndarray

property my_suppliers

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

Return type

List[str]

property n_competitors

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

Return type

int

property n_lines

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

Return type

int

property n_processes

Number of processes in the world

Return type

int

property n_products

Number of products in the world

Return type

int

order_production(process, steps, lines)[source]

Orders production of the given process

Parameters
  • process (int) – The process to run

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

  • lines (ndarray) – 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

Return type

None

property outputs

Returns the number of outputs to every production process

Return type

ndarray

property profile

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

Return type

FactoryProfile

reports_at_step(step)[source]

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

Return type

Dict[str, FinancialReport]

reports_of_agent(aid)[source]

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

Return type

Dict[int, FinancialReport]

request_negotiation(is_buy, product, quantity, unit_price, time, partner, negotiator, extra=None)[source]

Requests a negotiation

Parameters
  • is_buy (bool) – If True the negotiation is about buying otherwise selling.

  • product (int) – The product to negotiate about

  • quantity (Union[int, Tuple[int, int]]) – The minimum and maximum quantities. Passing a single value q is equivalent to passing (q,q)

  • unit_price (Union[int, Tuple[int, int]]) – The minimum and maximum unit prices. Passing a single value u is equivalent to passing (u,u)

  • time (Union[int, Tuple[int, int]]) – The minimum and maximum delivery step. Passing a single value t is equivalent to passing (t,t)

  • partner (str) – ID of the partner to negotiate with.

  • negotiator (SAONegotiator) – The negotiator to use for this negotiation (if the partner accepted to negotiate)

  • extra (Optional[Dict[str, Any]]) – Extra information accessible through the negotiation annotation to the caller

Return type

bool

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, product, quantity, unit_price, time, controller=None, negotiators=None, partners=None, extra=None, copy_partner_id=True)[source]

Requests a negotiation

Parameters
  • is_buy (bool) – If True the negotiation is about buying otherwise selling.

  • product (int) – The product to negotiate about

  • quantity (Union[int, Tuple[int, int]]) – The minimum and maximum quantities. Passing a single value q is equivalent to passing (q,q)

  • unit_price (Union[int, Tuple[int, int]]) – The minimum and maximum unit prices. Passing a single value u is equivalent to passing (u,u)

  • time (Union[int, Tuple[int, int]]) – The minimum and maximum delivery step. Passing a single value t is equivalent to passing (t,t)

  • controller (Optional[SAOController]) – The controller to manage the complete set of negotiations

  • negotiators (Optional[List[Negotiator]]) – An optional list of negotiators to use for negotiating with the given partners (in the same order).

  • partners (Optional[List[str]]) – ID of all the partners to negotiate with.

  • extra (Optional[Dict[str, Any]]) – 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

Return type

bool

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, repeats, step=- 1, line=- 1, override=True, method='latest', partial_ok=False)[source]

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

Parameters
  • process (int) – The process to run

  • repeats (int) – How many times to repeat the process

  • step (Union[int, Tuple[int, int]]) – 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 (int) – The production line. The special value ANY_LINE gives the factory the freedom to use any line

  • override (bool) – Whether to override existing production commands or not

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

  • partial_ok (bool) – If true, allows partial scheduling

Return type

Tuple[ndarray, ndarray]

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, step=- 1)[source]

Sets the production commands for all lines in the given step

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

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

Return type

None

spot_market_loss(step)[source]

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

Parameters

step (Optional[int]) – The simulation step (day)

Remarks:

If step is None, the current step will be used

Return type

int

spot_market_quantity(step)[source]

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

Parameters

step (Optional[int]) – The simulation step (day)

Remarks:

If step is None, the current step will be used

Return type

int

property state

Receives the factory state

Return type

FactoryState

property trading_prices

Returns the current trading prices of all products

Return type

ndarray

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, issues=None, outcomes=None)[source]

Creates a utility function

class scml.DecentralizingAgent(*args, negotiator_type=<class 'negmas.sao.negotiators.AspirationNegotiator'>, negotiator_params=None, **kwargs)[source]
class scml.DecentralizingAgentWithLogging(*args, **kwargs)[source]
class scml.DemandDrivenProductionStrategy(*args, **kwargs)[source]

A production strategy that produces ONLY when a contract is secured

Hooks Into:
  • on_contract_finalized

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

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

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

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

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

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

class scml.DoNothingAgent(name=None, type_postfix='', ufun=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, contracts, quantities, compensation_money)[source]

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

Parameters
  • agent (str) – The ID of the agent that went bankrupt.

  • contracts (List[Contract]) – All future contracts between this agent and the bankrupt agent.

  • quantities (List[int]) – The actual quantities that these contracts will be executed at.

  • compensation_money (int) – 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

Return type

None

on_contract_breached(contract, breaches, resolution)[source]

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

Parameters
  • contract (Contract) – The contract

  • breaches (List[Breach]) – All breaches committed (even if they were resolved)

  • resolution (Optional[Contract]) – The resolution contract if re-negotiation was successful. None if not.

Return type

None

on_contract_cancelled(contract, rejectors)[source]

Called whenever at least a partner did not sign the contract

Return type

None

on_contract_executed(contract)[source]

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

Return type

None

on_contracts_finalized(signed, cancelled, rejectors)[source]

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

Parameters
  • signed (List[Contract]) – A list of signed contracts. These are binding

  • cancelled (List[Contract]) – A list of cancelled contracts. These are not binding

  • rejectors (List[List[str]]) – 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

Return type

None

on_failures(failures)[source]

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

Parameters

failures (List[Failure]) – A list of Failure s.

Return type

None

on_negotiation_failure(partners, annotation, mechanism, state)[source]

Called whenever a negotiation ends without agreement

Return type

None

on_negotiation_success(contract, mechanism)[source]

Called whenever a negotiation ends with agreement

Return type

None

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

Called whenever another agent requests a negotiation with this agent.

Parameters
  • initiator (str) – The ID of the agent that requested this negotiation

  • issues (List[Issue]) – Negotiation issues

  • annotation (Dict[str, Any]) – Annotation attached with this negotiation

  • mechanism (AgentMechanismInterface) – The AgentMechanismInterface interface to the mechanism to be used for this negotiation.

Return type

Optional[Negotiator]

Returns

None to reject the negotiation, otherwise a negotiator

sign_all_contracts(contracts)[source]

Signs all contracts

Return type

List[Optional[str]]

step()[source]

Called by the simulator at every simulation step

class scml.EndingNegotiator(assume_normalized=True, ufun=None, name=None, parent=None, owner=None, id=None, rational_proposal=True)[source]
propose(state)[source]

Propose an offer or None to refuse.

Parameters

stateMechanismState 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, offer)[source]

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

Parameters
  • state – a MechanismState giving current state of the negotiation.

  • offer – offer being tested

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

class scml.ExecutionRatePredictionStrategy[source]

A prediction strategy for expected inputs and outputs at every step

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

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

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

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

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

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

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

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

class scml.ExogenousContract(product, quantity, unit_price, time, revelation_time, seller=- 1, buyer=- 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, initial_balance, inputs, outputs, catalog_prices, world, compensate_before_past_debt, buy_missing_products, production_buy_missing, production_penalty, production_no_bankruptcy, production_no_borrow, agent_id, agent_name=None, confirm_production=True, initial_inventory=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, step=- 1, line=- 1, override=True, method='latest')[source]

Finds available times and lines for scheduling production.

Parameters
  • repeats (int) – How many times to repeat the process

  • step (Union[int, Tuple[int, int]]) – 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 (int) – The production line. The special value ANY_LINE gives the factory the freedom to use any line

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

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

Return type

Tuple[ndarray, ndarray]

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)[source]

Bankruptcy processing for the given agent

Parameters

required (int) – The money required after the bankruptcy is processed

Return type

int

Returns

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

buy(product, quantity, unit_price, buy_missing, penalty, no_bankruptcy=False, no_borrowing=False)[source]

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

Parameters
  • product (int) – The product transacted on

  • quantity (int) – The quantity (added)

  • unit_price (int) – The unit price (paid)

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

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

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

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

Return type

Tuple[int, int]

Returns

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

cancel_production(step, line)[source]

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

Parameters
  • step (int) – Step to cancel at

  • line (int) – Line to cancel at

Return type

bool

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[scml.scml2020.common.ContractInfo]]

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

property current_balance

Current wallet balance

Return type

int

property current_inventory

Current inventory contents

Return type

ndarray

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, steps, lines)[source]

Orders production of the given process

Parameters
  • process (int) – The process to run

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

  • lines (ndarray) – 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

Return type

None

outputs

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

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

Pays money

Parameters
  • money (int) – amount to pay

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

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

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

Return type

int

Returns

The amount actually paid

schedule_production(process, repeats, step=- 1, line=- 1, override=True, method='latest', partial_ok=False)[source]

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

Parameters
  • process (int) – The process index

  • repeats (int) – How many times to repeat the process

  • step (Union[int, Tuple[int, int]]) – 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 (int) – The production line. The special value ANY_LINE gives the factory the freedom to use any line

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

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

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

Return type

Tuple[ndarray, ndarray]

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, spot_loss)[source]

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

Parameters
  • product (int) – Product

  • spot_loss (float) – Spot loss specific to that agent

Return type

int

Returns

The unit price

step()[source]

Override this method to modify stepping logic.

Return type

List[Failure]

store(product, quantity, buy_missing, spot_price, no_bankruptcy=False, no_borrowing=False)[source]

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

Parameters
  • product (int) – Product

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

  • buy_missing (bool) – 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 (float) – 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 (bool) – Never bankrupt the agent on this transaction

  • no_borrowing (bool) – Never borrow for this transaction

Return type

int

Returns

The quantity actually stored or taken out (always positive)

class scml.FactoryProfile(costs)[source]

Defines all private information of a factory

costs

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

property input_products

The input products to all processes runnable (See processes )

Return type

ndarray

property output_products

The output products to all processes runnable (See processes )

Return type

ndarray

property processes

The processes that have valid costs

Return type

ndarray

class scml.FactoryState(inventory, balance, commands, inventory_changes, balance_change, contracts)[source]
balance: int

Current balance in the wallet

balance_change: int

Change in the balance in the last step

commands: numpy.ndarray

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

contracts: List[List[scml.scml2020.common.ContractInfo]]

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

inventory: numpy.ndarray

An n_products vector giving current quantity of every product in storage

inventory_changes: numpy.ndarray

Changes in the inventory in the last step

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

A production failure

is_inventory

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

The line at which the failure happened

process

The process that failed to execute

step

The step at which the failure happened

class scml.FinancialReport(agent_id, step, cash, assets, breach_prob, breach_level, is_bankrupt, agent_name)[source]

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

agent_id

Agent ID

agent_name

Agent name for printing purposes

assets

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

breach_level

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

breach_prob

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

cash

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

is_bankrupt

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

step

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

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

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

Parameters

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

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

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

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

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

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

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

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

class scml.FixedTradePredictionStrategy(*args, add_trade=True, **kwargs)[source]

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

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

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

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

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

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

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

trade_prediction_init()[source]

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

class scml.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, state)[source]

Proposes an offer to one of the partners.

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

  • state – Mechanism state including current step

Returns

an outcome to offer.

respond(negotiator_id, state, offer)[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

  • offer – The offer received.

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

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

Return type

bool

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]

Initialize the quantities and best prices received for next step

counter_all(offers, states)[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.

class scml.IndDecentralizingAgent(*args, negotiator_type=<class 'negmas.sao.negotiators.AspirationNegotiator'>, negotiator_params=None, **kwargs)[source]
create_ufun(is_seller, 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, sell)[source]

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

Parameters
  • step (int) – Simulation step

  • sell (bool) – Sell or buy

Return type

int

target_quantity(step, sell)[source]

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

Parameters
  • step (int) – Simulation step

  • sell (bool) – Sell or buy

Return type

int

class scml.IndependentNegotiationsManager(*args, negotiator_type=<class 'negmas.sao.negotiators.AspirationNegotiator'>, negotiator_params=None, **kwargs)[source]

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

Parameters
  • negotiator_type (Union[SAONegotiator, str]) – The negotiator type to use to manage all negotiations

  • negotiator_params (Optional[Dict[str, Any]]) – Parameters of the negotiator

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

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

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

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

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

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

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

Creates a utility function

Return type

UtilityFunction

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

Creates a negotiator

Return type

SAONegotiator

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

Signs all contracts that have good prices

Overrides:
- buying_margin

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

- selling_margin

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

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

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

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

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

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

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

class scml.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=None, predicted_inputs=None, add_trade=False, **kwargs)[source]

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

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

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

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

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

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

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

trade_prediction_before_step()[source]

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

trade_prediction_init()[source]

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

trade_prediction_step()[source]

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

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

Predicts the mean execution fraction for each partner

Parameters

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

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

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

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

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

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

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

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

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

My negotiation strategy

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

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

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

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

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

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

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

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

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

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

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

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

Parameters

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

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

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

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

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

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

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

abstract acceptable_unit_price(step, sell)[source]

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

Parameters
  • step (int) – Simulation step

  • sell (bool) – Sell or buy

Return type

int

start_negotiations(product, quantity, unit_price, step, partners=None)[source]

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

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

  • quantity (int) – The maximum quantity to negotiate about

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

  • step (int) – The maximum/minimum time for buy/sell

  • partners (Optional[List[str]]) – A list of partners to negotiate with

Remarks:

  • This method assumes that product is either my_input_product or my_output_product

Return type

None

step()[source]

Generates buy and sell negotiations as needed

target_quantities(steps, sell)[source]

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

Parameters
Return type

ndarray

abstract target_quantity(step, sell)[source]

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

Parameters
  • step (int) – Simulation step

  • sell (bool) – Sell or buy

Return type

int

class scml.OneShotAWI(world, agent)[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.

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

  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.

  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:

  • 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

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

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

Return type

List[List[str]]

property all_suppliers

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

Return type

List[List[str]]

property catalog_prices

Returns the catalog prices of all products

Return type

ndarray

property current_disposal_cost

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

Return type

float

property current_exogenous_input_price

The exogenous contracts for the input (this step)

Return type

int

property current_exogenous_input_quantity

The exogenous contracts for the input (this step)

Return type

int

property current_exogenous_output_price

The exogenous contracts for the input (this step)

Return type

int

property current_exogenous_output_quantity

The exogenous contracts for the input (this step)

Return type

int

property current_shortfall_penalty

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

Return type

float

property exogenous_contract_summary

The exogenous contracts in the current step for all products

Return type

List[Tuple[int, int]]

Returns

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

is_bankrupt(aid=None)[source]

Checks whether an agent is a system agent or not

Parameters

aid (Optional[str]) – Agent ID

Return type

bool

property is_exogenous_forced

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

is_system(aid)[source]

Checks whether an agent is a system agent or not

Parameters

aid (str) – Agent ID

Return type

bool

property level

The production level of the agent

Return type

int

property my_consumers

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

Return type

List[str]

property my_input_product

the product I need to buy

Return type

int

property my_output_product

the product I need to sell

Return type

int

property my_suppliers

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

Return type

List[str]

property n_competitors

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

Return type

int

property n_input_negotiations

Number of negotiations with suppliers at every step

Return type

int

property n_lines

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

Return type

int

property n_output_negotiations

Number of negotiations with consumers at every step

Return type

int

property n_processes

Returns the number of processes in the system

Return type

int

property n_products

Returns the number of products in the system

Return type

int

penalty_multiplier(is_input, unit_price)[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.

Return type

float

property price_multiplier

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 profile

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

Return type

OneShotProfile

reports_at_step(step)[source]

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

Return type

Dict[str, FinancialReport]

reports_of_agent(aid)[source]

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

Return type

Dict[int, FinancialReport]

state()[source]

Returns the private state of the agent in that world

Return type

Any

property trading_prices

Returns the current trading prices of all products

Return type

ndarray

class scml.OneShotAdapter(oneshot_type, oneshot_params, obj=None, name=None, type_postfix='', ufun=None)[source]

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

init()[source]

Override this method to modify initialization logic

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 AgentMechanismInterface 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=None, name=None)[source]

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

Parameters
  • owner – The adapter owning the agent. You do not need to directly deal with this.

  • ufun – An optional OneShotUFun to set for the agent.

  • name – Agent name.

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

Returns a OneShotAWI object for accessing the simulation.

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)[source]

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

Return type

SAOAMI

get_negotiator(partner_id)[source]

Returns the negotiator corresponding to the given partner ID.

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

Return type

SAONegotiator

init()[source]

Called once after the AWI is set.

Remarks:
  • Use this for any proactive initialization code.

property internal_state

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.

Return type

Dict[str, Any]

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, annotation, mechanism, state)[source]

Called whenever a negotiation ends without agreement.

Parameters
  • partners (List[str]) – List of the partner IDs consisting from self and the opponent.

  • annotation (Dict[str, Any]) – The annotation of the negotiation including the seller ID, buyer ID, and the product.

  • mechanism (AgentMechanismInterface) – The AgentMechanismInterface instance containing all information about the negotiation.

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

Return type

None

on_negotiation_success(contract, mechanism)[source]

Called whenever a negotiation ends with agreement.

Parameters
  • contract (Contract) – The Contract agreed upon.

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

Return type

None

abstract propose(negotiator_id, state)[source]

Proposes an offer to one of the partners.

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

  • state (MechanismState) – Mechanism state including current step

Return type

Union[OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]

Returns

an outcome to offer.

respond(negotiator_id, state, offer)[source]

Responds to an offer from one of the partners.

Parameters
Return type

ResponseType

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

The negotiations currently requested by the agent.

Return type

List[RunningNegotiationInfo]

Returns

A list of negotiation information objects (RunningNegotiationInfo)

sign_all_contracts(contracts)[source]

Signs all contracts (used internally)

Return type

List[Optional[str]]

step()[source]

Called every step.

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

property unsigned_contracts

All contracts that are not yet signed.

Return type

List[Contract]

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

Exogenous contract information

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

    • 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 ufuns are created with outcome_type=tuple. See test_ind_negotiators_genius() at tests/test_scml2021oneshot.py for an example.

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

generate_negotiator(partner_id)[source]

Returns a negotiator to be used with some partner.

Remarks:

The default implementation will use the default_negotiator_type and default_negotiator_params.

Return type

SAONegotiator

abstract generate_ufuns()[source]

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

Return type

Dict[str, UtilityFunction]

init()[source]

Called once after the AWI is set.

Remarks:
  • Use this for any proactive initialization code.

make_negotiator(negotiator_type=None, name=None, **kwargs)[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 (Optional[str]) – 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 every step.

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

class scml.OneShotProfile(cost, input_product, n_lines, shortfall_penalty_mean, disposal_cost_mean, shortfall_penalty_dev, disposal_cost_dev)[source]

Defines all private information of a factory

cost

The cost of production

disposal_cost_dev

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

disposal_cost_mean

A positive number specifying the average penalty buying too much.

input_product

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

n_lines

Number of lines for this factory

shortfall_penalty_dev

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

shortfall_penalty_mean

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

class scml.OneShotSingleAgreementAgent(*args, strict=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 (bool) – 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)[source]

Return the ID of the negotiator with the best offer

Parameters

offers (Dict[str, Union[OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]) – A mapping from negotiator ID to the offer it received

Return type

Optional[str]

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, source, state)[source]

Should decide if the given offer is acceptable

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

Return type

bool

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

Compares two outcomes of the same negotiation

Parameters
Returns

True if utility(a) > utility(b)

class scml.OneShotState(exogenous_input_quantity, exogenous_input_price, exogenous_output_quantity, exogenous_output_price, disposal_cost, shortfall_penalty, current_balance)[source]

State of a one-shot agent

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.

Parameters
  • owner – The adapter owning the agent. You do not need to directly deal with this.

  • ufun – An optional OneShotUFun to set for the agent.

  • name – Agent name.

abstract counter_all(offers, states)[source]

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

Parameters
Return type

Dict[str, SAOResponse]

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()[source]

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

Return type

Dict[str, Union[OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]

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)[source]

Signs all contracts (used internally)

Return type

List[Optional[str]]

class scml.OneShotUFun(ex_pin, ex_qin, ex_pout, ex_qout, input_product, input_agent, output_agent, production_cost, disposal_cost, shortfall_penalty, input_penalty_scale, output_penalty_scale, n_input_negs, n_output_negs, current_step, input_qrange=(0, 0), input_prange=(0, 0), output_qrange=(0, 0), output_prange=(0, 0), force_exogenous=True, n_lines=10, normalized=False, current_balance=inf, **kwargs)[source]

Calculates the utility function of a list of contracts or offers.

Parameters
  • force_exogenous (bool) – Is the agent forced to accept exogenous contracts given through ex_* arguments?

  • ex_pin (int) – total price of exogenous inputs for this agent

  • ex_qin (int) – total quantity of exogenous inputs for this agent

  • ex_pout (int) – total price of exogenous outputs for this agent

  • ex_qout (int) – total quantity of exogenous outputs for this agent.

  • cost – production cost of the agent.

  • disposal_cost (float) – disposal cost per unit of input/output.

  • shortfall_penalty (float) – penalty for failure to deliver one unit of output.

  • input_agent (bool) – Is the agent an input agent which means that its input product is the raw material

  • output_agent (bool) – Is the agent an output agent which means that its output product is the final product

  • n_lines (int) – Number of production lines. If None, will be read through the AWI.

  • input_product (int) – Index of the input product. If None, will be read through the AWI

  • input_qrange (Tuple[int, int]) – A 2-int tuple giving the range of input quantities negotiated. If not given will be read through the AWI

  • input_prange (Tuple[int, int]) – A 2-int tuple giving the range of input unit prices negotiated. If not given will be read through the AWI

  • output_qrange (Tuple[int, int]) – A 2-int tuple giving the range of output quantities negotiated. If not given will be read through the AWI

  • output_prange (Tuple[int, int]) – A 2-int tuple giving the range of output unit prices negotiated. If not given will be read through the AWI

  • n_input_negs (int) – How many input negotiations are allowed. If not given, it will be the number of suppliers as given by the AWI

  • n_output_negs (int) – How many output negotiations are allowed. If not given, it will be the number of consumers as given by the AWI

  • current_step (int) – Current simulation step. Needed only for ufun_range when returning best outcomes

  • normalized (bool) – 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.

breach_level(qin=0, qout=0)[source]

Calculates the breach level that would result from a given quantities

find_limit(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)[source]

Finds either the maximum or the minimum of the ufun.

Parameters
  • best (bool) – 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

Return type

UFunLimit

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

Return type

UFunLimit

Returns

worst and best outcome information in the form of UFunLimit tuple.

from_aggregates(qin, qout_signed, qout_sold, pin, pout, input_penalty, output_penalty)[source]

Calculates the utility from aggregates of input/output quantity/prices

Parameters
  • qin (int) – Input quantity (total including all exogenous contracts).

  • qout_signed (int) – Output quantity (total including all exogenous contracts) that the agent agreed to sell.

  • qout_sold (int) – Output quantity (total including all exogenous contracts) that the agent will actually sell.

  • pin (int) – Input total price (i.e. unit price * qin).

  • pout (int) – Output total price (i.e. unit price * qin).

  • input_penalty – total disposal cost

  • output_penalty – total shortfall 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.

Return type

float

from_contracts(contracts, ignore_exogenous=True)[source]

Calculates the utility function given a list of contracts

Parameters
  • contracts (Iterable[Contract]) – 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.

Return type

float

from_offers(offers, outputs, return_producible=False)[source]

Calculates the utility value given a list of offers and whether each offer is for output or not (= input).

Parameters
  • offers (Iterable[Tuple]) – 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 (Iterable[bool]) – 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_producible – If true, the producible quantity will be returned

Remarks:
  • This method takes into account the exogenous contract information passed when constructing the ufun.

Return type

Union[float, Tuple[float, int]]

is_breach(qin=0, qout=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

ok_to_buy_at(unit_price)[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.

Return type

bool

ok_to_sell_at(unit_price)[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.

Return type

bool

utility_range(issues=None, outcomes=None, infeasible_cutoff=None, return_outcomes=False, max_n_outcomes=1000, ami=None)[source]

Finds the utility range and optionally returns the corresponding outcomes from a given issue space or in a single negotiation.

Parameters
  • issues (Optional[List[Issue]]) – 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 (Optional[Collection[Union[OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]]) – A list of outcomes to consider. Using outcomes is much slower than using issues and you should never pass both.

  • infeasible_cutoff (Optional[float]) – 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.

Return type

Union[Tuple[Union[Distribution, float], Union[Distribution, float]], Tuple[Union[Distribution, float], Union[Distribution, float], Union[OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]], Union[OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]]

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

xml(issues)[source]

Converts the function into a well formed XML string preferrably in GENIUS format.

If the output has with </objective> then discount factor and reserved value should also be included If the output has </utility_space> it will not be appended in to_xml_str

Return type

str

class scml.OneshotDoNothingAgent(owner=None, ufun=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, offer)[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

  • offer – The offer received.

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.PredictionBasedTradingStrategy(*args, add_trade=True, **kwargs)[source]

A trading strategy that uses prediction strategies to manage inputs/outputs needed

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

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

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

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

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

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

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

Represents a strategy for controlling production.

Provides:
  • schedule_range : A mapping from contract ID to a tuple of the first and last steps at which some lines are occupied to produce the quantity specified by the contract and whether it is a sell contract

  • can_be_produced : Given a contract, it returns whether or not it is possible to produce the quantity entailed by it (which means that there is enough vacant production line slots before/after the contracts delivery time for sell/buy contracts).

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

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

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

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

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

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

can_be_produced(contract_id)[source]

Returns True if the SELL contract given can be honored in principle given the production capacity of the agent (n. lines). It does not check for the availability of inputs or enough money to run the production process.

Remarks:

  • Cannot be called before calling on_contracts_finalized

schedule_range: Dict[str, Tuple[int, int, bool]]

Gives the range of steps at which the production needed for a given contract are scheduled

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

An agent that negotiates randomly.

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

Creates a utility function

class scml.RandomOneShotAgent(owner=None, ufun=None, name=None)[source]
propose(negotiator_id, state)[source]

Proposes an offer to one of the partners.

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

  • state (MechanismState) – Mechanism state including current step

Return type

Union[OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]

Returns

an outcome to offer.

respond(negotiator_id, state, offer)[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

  • offer – The offer received.

Returns

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

Remarks:

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

class scml.ReactiveAgent(*args, negotiator_type=<class 'negmas.sao.negotiators.AspirationNegotiator'>, negotiator_params=None, **kwargs)[source]
acceptable_unit_price(step, sell)[source]

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

Parameters
  • step (int) – Simulation step

  • sell (bool) – Sell or buy

Return type

int

target_quantities(steps, sell)[source]

Implemented for speed but not really required

Return type

ndarray

target_quantity(step, sell)[source]

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

Parameters
  • step (int) – Simulation step

  • sell (bool) – Sell or buy

Return type

int

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

The agent reactively responds to contracts for selling by buying and vice versa.

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

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

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

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

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

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

class scml.SCML2020Agent(name=None, type_postfix='', ufun=None)[source]

Base class for all SCML2020 agents (factory managers)

confirm_production(commands, balance, inventory)[source]

Called just before production starts at every time-step allowing the agent to change what is to be produced in its factory

Parameters
  • commands (ndarray) – an n_lines vector giving the process to be run at every line (NO_COMMAND indicates nothing to be processed

  • balance (int) – The current balance of the factory

  • inventory – an n_products vector giving the number of items available in the inventory of every product type.

Return type

ndarray

Returns

an n_lines vector giving the process to be run at every line (NO_COMMAND indicates nothing to be processed

Remarks:

  • Not called in SCML2020 competition.

  • The inventory will contain zero items of all products that the factory does not buy or sell

  • The default behavior is to just retrun commands confirming production of everything.

init()[source]

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

property internal_state

Returns the internal state of the agent for debugging purposes

Return type

Dict[str, Any]

on_agent_bankrupt(agent, contracts, quantities, compensation_money)[source]

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

Parameters
  • agent (str) – The ID of the agent that went bankrupt.

  • contracts (List[Contract]) – All future contracts between this agent and the bankrupt agent.

  • quantities (List[int]) – The actual quantities that these contracts will be executed at.

  • compensation_money (int) – 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

Return type

None

on_contract_breached(contract, breaches, resolution)[source]

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

Parameters
  • contract (Contract) – The contract

  • breaches (List[Breach]) – All breaches committed (even if they were resolved)

  • resolution (Optional[Contract]) – The resolution contract if re-negotiation was successful. None if not.

Return type

None

on_contract_executed(contract)[source]

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

Return type

None

on_failures(failures)[source]

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

Parameters

failures (List[ForwardRef]) – A list of Failure s.

Return type

None

on_neg_request_accepted(req_id, mechanism)[source]

Called when a requested negotiation is accepted

on_neg_request_rejected(req_id, by)[source]

Called when a requested negotiation is rejected

Parameters
  • req_id (str) – The request ID passed to _request_negotiation

  • by (Optional[List[str]]) – A list of agents that refused to participate or None if the failure was for another reason

on_negotiation_failure(partners, annotation, mechanism, state)[source]

Called whenever a negotiation ends without agreement

Return type

None

on_negotiation_success(contract, mechanism)[source]

Called whenever a negotiation ends with agreement

Return type

None

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

Called whenever another agent requests a negotiation with this agent.

Parameters
  • initiator (str) – The ID of the agent that requested this negotiation

  • issues (List[Issue]) – Negotiation issues

  • annotation (Dict[str, Any]) – Annotation attached with this negotiation

  • mechanism (AgentMechanismInterface) – The AgentMechanismInterface interface to the mechanism to be used for this negotiation.

Return type

Optional[Negotiator]

Returns

None to reject the negotiation, otherwise a negotiator

respond_to_renegotiation_request(contract, breaches, agenda)[source]

Called to respond to a renegotiation request

Parameters
  • agenda (RenegotiationRequest) –

  • contract (Contract) –

  • breaches (List[Breach]) –

Returns:

Return type

Optional[Negotiator]

set_renegotiation_agenda(contract, breaches)[source]

Received by partners in ascending order of their total breach levels in order to set the renegotiation agenda when contract execution fails

Parameters
  • contract (Contract) – The contract being breached

  • breaches (List[Breach]) – All breaches on contract

Return type

Optional[RenegotiationRequest]

Returns

Renegotiation agenda (issues to negotiate about to avoid reporting the breaches).

sign_all_contracts(contracts)[source]

Signs all contracts

Return type

List[Optional[str]]

step()[source]

Called by the simulator at every simulation step

step_()[source]

Called at every time-step. This function is called directly by the world.

class scml.SCML2020OneShotWorld(catalog_prices, profiles, agent_types, agent_params=None, catalog_quantities=50, financial_report_period=5, bankruptcy_limit=0.0, penalize_bankrupt_for_future_contracts=True, penalties_scale='trading', exogenous_contracts=(), exogenous_dynamic=False, exogenous_force_max=False, initial_balance=1000, compact=False, no_logs=False, n_steps=1000, time_limit=5400, neg_n_steps=20, neg_time_limit=120, neg_step_time_limit=60, negotiation_speed=0, avoid_ultimatum=True, publish_exogenous_summary=True, publish_trading_prices=True, price_multiplier=2.0, trading_price_discount=0.9, signing_delay=0, force_signing=False, batch_signing=True, name=None, agent_name_reveals_position=True, agent_name_reveals_type=True, inventory_valuation_catalog=0, inventory_valuation_trading=0, **kwargs)

Implements the SCML-OneShot variant of the SCM world.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

add_financial_report(agent, reports_agent, reports_time)

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

Parameters
  • agent (DefaultOneShotAdapter) – The agent

  • reports_agent – A dictionary of financial reports indexed by agent id

  • reports_time – A dictionary of financial reports indexed by time

Returns:

Return type

None

property agreement_fraction

Fraction of negotiations ending in agreement and leading to signed contracts

Return type

float

breach_record(breach)

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

Return type

Dict[str, Any]

complete_contract_execution(*args, **kwargs)

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

Parameters
  • contract – The contract considered.

  • breaches – The list of potential breaches that was generated by _execute_contract.

  • resolution – The agreed upon resolution

Returns:

contract_record(contract)

Converts a contract to a record suitable for permanent storage

Return type

Dict[str, Any]

contract_size(contract)

Returns an estimation of the activity level associated with this contract. Higher is better :type contract: Contract :param contract:

Returns:

Return type

float

property contracts_df

Returns a pandas data frame with the contracts

Return type

DataFrame

draw(steps=None, what=['negotiation-requests-rejected', 'negotiation-requests-accepted', 'negotiations-rejected', 'negotiations-started', 'negotiations-failed', 'contracts-concluded', 'contracts-cancelled', 'contracts-signed', 'contracts-breached', 'contracts-executed'], who=None, where=None, together=True, axs=None, ncols=4, figsize=(15, 15), **kwargs)

Generates a graph showing some aspect of the simulation

Parameters
  • steps (Union[Tuple[int, int], int, None]) – The step/steps to generate the graphs for. If a tuple is given all edges within the given range (inclusive beginning, exclusive end) will be accomulated

  • what (Collection[str]) – The edges to have on the graph. Options are: negotiations, concluded, signed, executed

  • who (Optional[Callable[[Agent], bool]]) – Either a callable that receives an agent and returns True if it is to be shown or None for all

  • where (Optional[Callable[[Agent], Union[int, Tuple[float, float]]]]) – A callable that returns for each agent the position it showed by drawn at either as an integer specifying the column in which to draw the column or a tuple of two floats specifying the position within the drawing area of the agent. If None, the default Networkx layout will be used.

  • together (bool) – IF specified all edge types are put in the same graph.

  • axs (Optional[Collection[Axis]]) – The axes used for drawing. If together is true, it should be a single Axis object otherwise it should be a list of Axis objects with the same length as what.

  • show_node_labels – show node labels!

  • show_edge_labels – show edge labels!

  • kwargs – passed to networx.draw_networkx

Return type

Union[Tuple[Axis, Graph], Tuple[List[Axis], List[Graph]]]

Returns

A networkx graph representing the world if together==True else a list of graphs one for each item in what

execute_action(action, agent, callback=None)

Executes the given action by the given agent

Return type

bool

classmethod generate(agent_types, agent_params=None, n_steps=(50, 200), n_processes=2, n_lines=10, n_agents_per_process=(4, 8), process_inputs=1, process_outputs=1, production_costs=(1, 4), profit_means=(0.1, 0.2), profit_stddevs=0.05, max_productivity=(0.8, 1.0), initial_balance=None, cost_increases_with_level=True, equal_exogenous_supply=False, equal_exogenous_sales=False, exogenous_supply_predictability=(0.6, 0.9), exogenous_sales_predictability=(0.6, 0.9), exogenous_control=-1, cash_availability=(1.5, 2.5), force_signing=True, profit_basis=<function amax>, disposal_cost=(0.0, 0.2), shortfall_penalty=(0.2, 1.0), disposal_cost_dev=(0.0, 0.02), shortfall_penalty_dev=(0.0, 0.1), exogenous_price_dev=(0.1, 0.2), price_multiplier=(1.5, 2.0), random_agent_types=False, penalties_scale='trading', cap_exogenous_quantities=True, method='profitable', **kwargs)

Generates the configuration for a world

Parameters
  • agent_types (List[Union[str, Type[OneShotAgent]]]) – All agent types

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

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

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

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

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

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

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

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

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

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

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

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

  • cost_increases_with_level – If true, production cost will be higher for processes nearer to the final product.

  • profit_basis – The statistic used when controlling catalog prices by profit arguments. It can be np.mean, np.median, np.min, np.max or any Callable[[list[float]], float] and is used to summarize production costs at every level.

  • horizon – The horizon used for revealing external supply/sales as a fraction of n_steps

  • equal_exogenous_supply – If true, external supply will be distributed equally among all agents in the first layer

  • equal_exogenous_sales – If true, external sales will be distributed equally among all agents in the last layer

  • exogenous_supply_predictability (Union[Tuple[float, float], float]) – How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random

  • exogenous_sales_predictability (Union[Tuple[float, float], float]) – How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random

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

  • exogenous_control (Union[Tuple[float, float], float]) – How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True

  • cap_exogenous_quantities (bool) – If True, all exogenous quantities in all contracts are capped to be no more than the number of lines

  • cash_availability (Union[Tuple[float, float], float]) – The fraction of the total money needs of the agent to work at maximum capacity that is available as initial_balance . This is only effective if initial_balance is set to None .

  • exogenous_control – How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True

  • disposal_cost (Union[ndarray, Tuple[float, float], float]) – A range to sample mean-disposal costs for all factories from

  • shortfall_penalty (Union[ndarray, Tuple[float, float], float]) – A range to sample mean-shortfall penalty for all factories from

  • disposal_cost_dev (Union[ndarray, Tuple[float, float], float]) – A range to sample std. dev of disposal costs for all factories from

  • shortfall_penalty_dev (Union[ndarray, Tuple[float, float], float]) – A range to sample std. dev of shortfall penalty for all factories from

  • exogenous_price_dev (Union[ndarray, Tuple[float, float], float]) – The standard deviation of exogenous contract prices relative to the mean price

  • price_multiplier (Union[ndarray, Tuple[float, float], float]) – A value to multiply with trading/catalog price to get the upper limit on prices for all negotiations

  • random_agent_types (bool) – If True, the final agent types used by the generato wil always be sampled from the given types. If False, this random sampling will only happin if len(agent_types) != n_agents.

  • penalties_scale (Union[str, List[str]]) – What are disposal_cost and shortfall_penalty relative to. There are four options: trading, catalog mean trading and catalog prices of the product. unit means the unit price in the contract and non means the storage-cost and shortfall_penalty are absolute values (in money unit). If not given will be read through the AWI

  • **kwargs

Return type

Dict[str, Any]

Returns

world configuration as a Dict[str, Any]. A world can be generated from this dict by calling SCML2020World(**d)

Remarks:

  • Most parameters (i.e. process_inputs , process_outputs , n_agents_per_process , costs ) can take a single value, a tuple of two values, or a list of values. If it has a single value, it is repeated for all processes/factories as appropriate. If it is a tuple of two numbers $(i, j)$, each process will take a number sampled from a uniform distribution supported on $[i, j]$ inclusive. If it is a list of values, of the length n_processes , it is used as it is otherwise, it is used to sample values for each process.

get_private_state(agent)

Reads the private state of the given agent

Return type

dict

is_valid_contact(contract)

Checks whether a signed contract is valid

Return type

bool

property non_system_agent_ids

Returns names of all agents except system agents

Return type

List[str]

property non_system_agent_names

Returns names of all agents except system agents

Return type

List[str]

property non_system_agents

Returns all agents except system agents

Return type

List[DefaultOneShotAdapter]

on_contract_signed(contract)

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

Parameters

contract (Contract) – The contract to add

Return type

bool

Returns

True if everything went OK and False otherwise

Remarks:

  • By default this function just adds the contract to the set of contracts maintaned by the world.

  • You should ALWAYS call this function when overriding it.

order_contracts_for_execution(contracts)

Orders the contracts in a specific time-step that are about to be executed

Return type

Collection[Contract]

post_step_stats()

Called at the end of the simulation step to update all stats

Kept for backward compatibility and will be dropped. Override update_stats ins

pre_step_stats()

Called at the beginning of the simulation step to prepare stats or update them

Kept for backward compatibility and will be dropped. Override update_stats instead

relative_welfare(include_bankrupt=False)

Total welfare relative to expected value. Returns None if no expectation is found in self.info

Return type

Optional[float]

scores(assets_multiplier=0.5)

Scores of all agents given the asset multiplier.

Parameters

assets_multiplier (float) – A multiplier to multiply the assets with.

Return type

Dict[str, float]

simulation_step(stage)

A single step of the simulation.

Parameters

stage – How many times so far was this method called within the current simulation step

Remarks:

  • Using the stage parameter, it is possible to have Operations . SimulationStep several times with the list of operations while differentiating between these calls.

start_contract_execution(contract)

Tries to execute the contract

Parameters

contract (Contract) –

Returns

The set of breaches committed if any. If there are no breaches return an empty set

Return type

Set[Breach]

Remarks:

  • You must call super() implementation of this method before doing anything

  • It is possible to return None which indicates that the contract was nullified (i.e. not executed due to a reason other than an execution exeception).

property stats_df

Returns a pandas data frame with the stats

Return type

DataFrame

property system_agent_ids

Returns the names two system agents

Return type

List[str]

property system_agent_names

Returns the names two system agents

Return type

List[str]

property system_agents

Returns the two system agents

Return type

List[_SystemAgent]

trading_prices_for(discount=1.0, condition='executed')

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

Parameters
  • discount (float) – A discount factor to treat older prices less importantly (exponential discounting).

  • condition – The condition for contracts to consider. Possible values are executed, signed, concluded, nullified

Return type

ndarray

Returns

an n_products vector of trading prices

welfare(include_bankrupt=False)

Total welfare of all agents

Return type

float

property winners

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

add_financial_report(agent, factory, reports_agent, reports_time)

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

Parameters
  • agent (SCML2020Agent) – The agent

  • factory (Factory) – Its factory

  • reports_agent – A dictionary of financial reports indexed by agent id

  • reports_time – A dictionary of financial reports indexed by time

Returns:

Return type

None

property agreement_fraction

Fraction of negotiations ending in agreement and leading to signed contracts

Return type

float

property bankruptcy_rate

The fraction of factories that went bankrupt

Return type

float

breach_record(breach)

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

Return type

Dict[str, Any]

compensate(available, factory)

Called by a factory when it is going bankrupt after liquidation

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

  • factory (Factory) – The factory being bankrupted

Return type

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

Returns

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

complete_contract_execution(contract, breaches, resolution)

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

Parameters
  • contract (Contract) – The contract considered.

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

  • resolution (Contract) – The agreed upon resolution

Returns:

Return type

None

contract_record(contract)

Converts a contract to a record suitable for permanent storage

Return type

Dict[str, Any]

contract_size(contract)

Returns an estimation of the activity level associated with this contract. Higher is better :type contract: Contract :param contract:

Returns:

Return type

float

property contracts_df

Returns a pandas data frame with the contracts

Return type

DataFrame

draw(steps=None, what=['negotiation-requests-rejected', 'negotiation-requests-accepted', 'negotiations-rejected', 'negotiations-started', 'negotiations-failed', 'contracts-concluded', 'contracts-cancelled', 'contracts-signed', 'contracts-breached', 'contracts-executed'], who=None, where=None, together=True, axs=None, ncols=4, figsize=(15, 15), **kwargs)

Generates a graph showing some aspect of the simulation

Parameters
  • steps (Union[Tuple[int, int], int, None]) – The step/steps to generate the graphs for. If a tuple is given all edges within the given range (inclusive beginning, exclusive end) will be accomulated

  • what (Collection[str]) – The edges to have on the graph. Options are: negotiations, concluded, signed, executed

  • who (Optional[Callable[[Agent], bool]]) – Either a callable that receives an agent and returns True if it is to be shown or None for all

  • where (Optional[Callable[[Agent], Union[int, Tuple[float, float]]]]) – A callable that returns for each agent the position it showed by drawn at either as an integer specifying the column in which to draw the column or a tuple of two floats specifying the position within the drawing area of the agent. If None, the default Networkx layout will be used.

  • together (bool) – IF specified all edge types are put in the same graph.

  • axs (Optional[Collection[Axis]]) – The axes used for drawing. If together is true, it should be a single Axis object otherwise it should be a list of Axis objects with the same length as what.

  • show_node_labels – show node labels!

  • show_edge_labels – show edge labels!

  • kwargs – passed to networx.draw_networkx

Return type

Union[Tuple[Axis, Graph], Tuple[List[Axis], List[Graph]]]

Returns

A networkx graph representing the world if together==True else a list of graphs one for each item in what

execute_action(action, agent, callback=None)

Executes the given action by the given agent

Return type

bool

classmethod generate(agent_types, agent_params=None, n_steps=(50, 200), n_processes=(2, 4), n_lines=10, n_agents_per_process=(2, 4), process_inputs=1, process_outputs=1, production_costs=(1, 4), profit_means=(0.15, 0.2), profit_stddevs=0.001, max_productivity=1.0, initial_balance=None, cost_increases_with_level=True, equal_exogenous_supply=False, equal_exogenous_sales=False, exogenous_supply_predictability=(0.6, 0.9), exogenous_sales_predictability=(0.6, 0.9), exogenous_control=(0.2, 0.8), cash_availability=(1.5, 2.5), force_signing=False, profit_basis=<function amax>, horizon=(0.2, 0.5), inventory_valuation_trading=0.5, inventory_valuation_catalog=0.0, random_agent_types=False, cost_relativity=1.0, method='profitable', exogenous_supply_surplus=0.0, exogenous_sales_surplus=0.0, run_extra_checks=True, **kwargs)

Generates the configuration for a world

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • cost_increases_with_level – If true, production cost will be higher for processes nearer to the final product.

  • profit_basis – The statistic used when controlling catalog prices by profit arguments. It can be np.mean, np.median, np.min, np.max or any Callable[[list[float]], float] and is used to summarize production costs at every level.

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

  • equal_exogenous_supply – If true, external supply will be distributed equally among all agents in the first layer

  • equal_exogenous_sales – If true, external sales will be distributed equally among all agents in the last layer

  • exogenous_supply_predictability (Union[Tuple[float, float], float]) – How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random

  • exogenous_sales_predictability (Union[Tuple[float, float], float]) – How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random

  • cash_availability (Union[Tuple[float, float], float]) – The fraction of the total money needs of the agent to work at maximum capacity that is available as initial_balance . This is only effective if initial_balance is set to None .

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

  • exogenous_control (Union[Tuple[float, float], float]) – How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True

  • random_agent_types (bool) – If True, the final agent types used by the generato wil always be sampled from the given types. If False, this random sampling will only happin if len(agent_types) != n_agents.

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

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

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

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

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

  • **kwargs

Return type

Dict[str, Any]

Returns

world configuration as a Dict[str, Any]. A world can be generated from this dict by calling SCML2020World(**d)

Remarks:

  • Most parameters (i.e. process_inputs , process_outputs , n_agents_per_process , costs ) can take a single value, a tuple of two values, or a list of values. If it has a single value, it is repeated for all processes/factories as appropriate. If it is a tuple of two numbers $(i, j)$, each process will take a number sampled from a uniform distribution supported on $[i, j]$ inclusive. If it is a list of values, of the length n_processes , it is used as it is otherwise, it is used to sample values for each process.

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

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

Return type

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

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

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

Return type

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

get_private_state(agent)

Reads the private state of the given agent

Return type

dict

is_valid_contact(contract)

Checks whether a signed contract is valid

Return type

bool

property non_system_agent_ids

Returns names of all agents except system agents

Return type

List[str]

property non_system_agent_names

Returns names of all agents except system agents

Return type

List[str]

property non_system_agents

Returns all agents except system agents

Return type

List[SCML2020Agent]

property num_bankrupt

The fraction of factories that went bankrupt

Return type

float

on_contract_concluded(contract, to_be_signed_at)

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

Parameters
  • contract (Contract) – The contract to add

  • to_be_signed_at (int) – The timestep at which the contract is to be signed

Remarks:

  • By default this function just adds the contract to the set of contracts maintaned by the world.

  • You should ALWAYS call this function when overriding it.

Return type

None

on_contract_signed(contract)

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

Parameters

contract (Contract) – The contract to add

Return type

bool

Returns

True if everything went OK and False otherwise

Remarks:

  • By default this function just adds the contract to the set of contracts maintaned by the world.

  • You should ALWAYS call this function when overriding it.

order_contracts_for_execution(contracts)

Orders the contracts in a specific time-step that are about to be executed

Return type

Collection[Contract]

post_step_stats()

Called at the end of the simulation step to update all stats

Kept for backward compatibility and will be dropped. Override update_stats ins

pre_step_stats()

Called at the beginning of the simulation step to prepare stats or update them

Kept for backward compatibility and will be dropped. Override update_stats instead

property productivity

Fraction of production lines occupied during the simulation

Return type

float

record_bankrupt(factory)

Records agent bankruptcy

Return type

None

property relative_productivity

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

Return type

Optional[float]

relative_welfare(include_bankrupt=False)

Total welfare relative to expected value. Returns None if no expectation is found in self.info

Return type

Optional[float]

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

scores of all agents given the asset multiplier.

Parameters

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

Return type

Dict[str, float]

simulation_step(stage)

A single step of the simulation.

Parameters

stage – How many times so far was this method called within the current simulation step

Remarks:

  • Using the stage parameter, it is possible to have Operations . SimulationStep several times with the list of operations while differentiating between these calls.

start_contract_execution(contract)

Tries to execute the contract

Parameters

contract (Contract) –

Returns

The set of breaches committed if any. If there are no breaches return an empty set

Return type

Set[Breach]

Remarks:

  • You must call super() implementation of this method before doing anything

  • It is possible to return None which indicates that the contract was nullified (i.e. not executed due to a reason other than an execution exeception).

property stats_df

Returns a pandas data frame with the stats

Return type

DataFrame

property system_agent_ids

Returns the names two system agents

Return type

List[str]

property system_agent_names

Returns the names two system agents

Return type

List[str]

property system_agents

Returns the two system agents

Return type

List[SCML2020Agent]

trading_prices_for(discount=1.0, condition='executed')

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

Parameters
  • discount (float) – A discount factor to treat older prices less importantly (exponential discounting).

  • condition – The condition for contracts to consider. Possible values are executed, signed, concluded, nullified

Return type

ndarray

Returns

an n_products vector of trading prices

welfare(include_bankrupt=False)

Total welfare of all agents

Return type

float

property winners

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

class scml.SCML2021World(*args, **kwargs)
classmethod generate(*args, inventory_valuation_trading=(0.0, 0.5), horizon=(0.2, 0.5), **kwargs)

Generates the configuration for a world

Parameters
  • agent_types – All agent types

  • agent_params – Agent parameters used to initialize them

  • n_steps – Number of simulation steps

  • n_processes – Number of processes in the production chain

  • n_lines – Number of lines per factory

  • process_inputs – Number of input units per process

  • process_outputs – Number of output units per process

  • production_costs – Production cost per factory

  • profit_means – Mean profitability per production level (i.e. process).

  • profit_stddevs – Std. Dev. of the profitability of every level (i.e. process).

  • inventory_valuation_catalog – The fraction of catalog price to value items at the end.

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

  • max_productivity – Maximum possible productivity per level (i.e. process).

  • initial_balance – The initial balance of all agents

  • n_agents_per_process – Number of agents per process

  • cost_increases_with_level – If true, production cost will be higher for processes nearer to the final product.

  • profit_basis – The statistic used when controlling catalog prices by profit arguments. It can be np.mean, np.median, np.min, np.max or any Callable[[list[float]], float] and is used to summarize production costs at every level.

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

  • equal_exogenous_supply – If true, external supply will be distributed equally among all agents in the first layer

  • equal_exogenous_sales – If true, external sales will be distributed equally among all agents in the last layer

  • exogenous_supply_predictability – How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random

  • exogenous_sales_predictability – How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random

  • cash_availability – The fraction of the total money needs of the agent to work at maximum capacity that is available as initial_balance . This is only effective if initial_balance is set to None .

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

  • exogenous_control – How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True

  • random_agent_types – If True, the final agent types used by the generato wil always be sampled from the given types. If False, this random sampling will only happin if len(agent_types) != n_agents.

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

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

  • exogenous_supply_surplus – The surpolus exogenous supply contract quantity to add to the system as a fraction of the a fraction of the contracts generated by the given method.

  • exogenous_sales_surplus – The surpolus exogenous sales contract quantity to add to the system as a fraction of the a fraction of the contracts generated by the given method.

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

  • **kwargs

Return type

Dict[str, Any]

Returns

world configuration as a Dict[str, Any]. A world can be generated from this dict by calling SCML2020World(**d)

Remarks:

  • Most parameters (i.e. process_inputs , process_outputs , n_agents_per_process , costs ) can take a single value, a tuple of two values, or a list of values. If it has a single value, it is repeated for all processes/factories as appropriate. If it is a tuple of two numbers $(i, j)$, each process will take a number sampled from a uniform distribution supported on $[i, j]$ inclusive. If it is a list of values, of the length n_processes , it is used as it is otherwise, it is used to sample values for each process.

class scml.SatisficerAgent(*args, target_productivity=1.0, satisfying_profit=0.15, acceptable_loss=0.02, price_range=0.4, concession_rate_price=1.0, concession_rate_quantity=1.0, concession_rate_time=1.0, market_share=1, horizon=5, **kwargs)[source]

A simple monolithic agent that tries to carefully make small profit every step.

Parameters
  • target_productivity – The productivity level targeted by the agent defined as the fraction of its lines to be active per step.

  • satisfying_profit – A profit amount considered satisfactory. Used when deciding negotiation agenda and signing to decide if a price is a good price (see _good_price()). A fraction of the trading price.

  • acceptable_loss – A fraction of trading price that the seller/buyer is willing to go under/over the current trading price during negotiation.

  • price_range – The total range around the trading price for negotiation agendas.

  • concession_rate_price – The exponent of the consession curve for price.

  • concession_rate_quantity – The exponent of the consession curve for quantity.

  • concession_rate_time – The exponent of the consession curve for time.

  • market_share – An integer specifying the expected share of the agent in the market. The agent will assume that it can get up to (market_share / (n_competitors + market_share -1)) of all sales and supplies where n_competitors is the number of agents at the same production level. Setting it to 1 means that the agent assumes it will get the same amount of trade as all other agents. Setting it to infinity means that the agent will assume it will take all the trade in the market

  • horizon – Time horizon for negotiations. If None, the exogenous_contracts_revelation horizon will be used

before_step()[source]

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

init()[source]

Called once

on_contracts_finalized(signed, cancelled, rejectors)[source]

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

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

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

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

Remarks:

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

on_negotiation_failure(partners, annotation, mechanism, state)[source]

Called when a negotiation fails

on_negotiation_success(contract, mechanism)[source]

Called when a negotiation fails

propose(state, ami, is_selling, is_requested)[source]

Used to propose to the opponent

Parameters
  • state (SAOState) – mechanism state including current round

  • ami (SAOAMI) – Agent-mechanism-interface for accessing the negotiation mechanism

  • offer – The offer proposed by the partner

  • is_selling (bool) – Whether the agent is selling to this partner

  • is_requested (bool) – Whether the agent requested this negotiation

respond(state, ami, offer, is_selling, is_requested)[source]

Responds to an offer from one partner.

Parameters
  • state – mechanism state including current round

  • ami – Agent-mechanism-interface for accessing the negotiation mechanism

  • offer – The offer proposed by the partner

  • is_selling – Whether the agent is selling to this partner

  • is_requested – Whether the agent requested this negotiation

Remarks:

  • The main idea is to accept offers that are within the quantity limits for the delivery day if its price is good enough for the current stage of the negotiation.

  • During negotiation, the agent starts accepting highest/lowest prices for selling/buying and gradually conceeds to the minimally acceptable price (good_price) defined as being acceptable_loss above/below the trading price for buying/selling.

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

Called whenever another agent requests a negotiation with this agent.

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

  • issues – Negotiation issues

  • annotation – Annotation attached with this negotiation

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

Returns

None to reject the negotiation, otherwise a negotiator

sign_all_contracts(contracts)[source]

Signs all contracts

step()[source]

Called at the end of the day. Will request all negotiations

class scml.SignAll[source]

Signs all contracts no matter what.

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

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

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

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

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

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

class scml.SignAllPossible[source]

Signs all contracts that can in principle be honored. The only check made by this strategy is that for sell contracts there is enough production capacity

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

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

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

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

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

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

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

Provides a simulator to the agent.

Provides:
  • simulator (FactorySimulator): A simulator that can be used to simulate the effect of contracts on the future of the factory

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

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

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

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

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

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

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

Uses a time-based strategy to accept a single agreement from the set it is considering.

choose_agents(offers, outcome)[source]

Selects an appropriate way to distribute this outcome to agents with given IDs.

counter_all(offers, states)[source]

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

Parameters
  • offers – Maps negotiator IDs to offers

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

Returns

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

Remarks:
  • The response type CANNOT be WAIT.

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

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

first_proposals()[source]

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

Return type

Dict[str, Union[OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]

Returns

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

class scml.SingleAgreementRandomAgent(*args, p_accept=0.1, **kwargs)[source]

A controller that agrees randomly to one offer

best_offer(offers)[source]

Return the ID of the negotiator with the best offer

Parameters

offers (Dict[str, Union[OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]) – A mapping from negotiator ID to the offer it received

Return type

Optional[str]

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)[source]

Should decide if the given offer is acceptable

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

Return type

bool

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

Compares two outcomes of the same negotiation

Parameters
Returns

True if utility(a) > utility(b)

class scml.StepNegotiationManager(*args, negotiator_type=<class 'negmas.sao.negotiators.AspirationNegotiator'>, negotiator_params=None, **kwargs)[source]

A negotiation manager that controls a controller and another for selling for every timestep

Parameters
  • negotiator_type (Union[SAONegotiator, str]) – The negotiator type to use to manage all negotiations

  • negotiator_params (Optional[Dict[str, Any]]) – Paramters of the negotiator

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

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

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

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

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

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

all_negotiations_concluded(controller_index, is_seller)[source]

Called by the StepController to affirm that it is done negotiating for some time-step

Return type

None

buyers

Buyer controllers and seller controllers. Each of them is responsible of covering the needs for one step (either buying or selling).

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

A production strategy that converts all inputs to outputs

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

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

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

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

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

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

class scml.SyncRandomOneShotAgent(*args, **kwargs)[source]
counter_all(offers, states)[source]

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

Parameters
Return type

Dict[str, SAOResponse]

Returns

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

Remarks:
  • The response type CANNOT be WAIT.

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

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

first_proposals()[source]

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

Return type

Dict[str, Union[OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]

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.TradeDrivenProductionStrategy(*args, **kwargs)[source]

A production strategy that produces ONLY for contracts that the agent did not initiate.

Hooks Into:
  • on_contract_finalized

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

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

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

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

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

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

class scml.TradePredictionStrategy(*args, predicted_outputs=None, predicted_inputs=None, add_trade=False, **kwargs)[source]

A prediction strategy for expected inputs and outputs at every step

Parameters
  • predicted_inputs (-) – None for default, a number of an n_steps numbers giving predicted inputs

  • predicted_outputs (-) – None for default, a number of an n_steps numbers giving predicted outputs

Provides:
  • expected_inputs : n_steps vector giving the predicted inputs at every time-step. It defaults to the number of lines.

  • expected_outputs : n_steps vector giving the predicted outputs at every time-step. It defaults to the number of lines.

  • input_cost : n_steps vector giving the predicted input cost at every time-step. It defaults to catalog price.

  • output_price : n_steps vector giving the predicted output price at every time-step. It defaults to catalog price.

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

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

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

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

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

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

expected_inputs

Expected input quantity every step

expected_outputs

Expected output quantity every step

input_cost: numpy.ndarray

Expected unit price of the input

output_price: numpy.ndarray

Expected unit price of the output

trade_prediction_before_step()[source]

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

Return type

None

abstract trade_prediction_init()[source]

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

Return type

None

trade_prediction_step()[source]

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

Return type

None

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

Base class for all trading strategies.

Provides:
  • inputs_needed (np.ndarray): How many items of the input product do I need to buy at every time step (n_steps vector). This should be read but not updated by the NegotiationManager.

  • outputs_needed (np.ndarray): How many items of the output product do I need to sell at every time step (n_steps vector). This should be read but not updated by the NegotiationManager.

  • inputs_secured (np.ndarray): How many items of the input product I already contracted to buy (n_steps vector) [out of input_needed]. This can be read but not updated by the NegotiationManager.

  • outputs_secured (np.ndarray): How many units of the output product I already contracted to sell (n_steps vector) [out of outputs_secured] This can be read but not updated by the NegotiationManager.

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

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

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

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

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

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

inputs_needed: numpy.ndarray

How many items of the input product do I need at every time step

inputs_secured: numpy.ndarray

How many units of the input product I have already secured per step

outputs_needed: numpy.ndarray

How many items of the output product do I need at every time step

outputs_secured: numpy.ndarray

How many units of the output product I have already secured per step

class scml.UFunLimit(utility, input_quantity, input_price, output_quantity, output_price, exogenous_input_quantity, exogenous_input_price, exogenous_output_quantity, exogenous_output_price, producible)

Information about one utility limit (either highest or lowest). See OnShotUFun.find_limit for details.

exogenous_input_price

Alias for field number 6

exogenous_input_quantity

Alias for field number 5

exogenous_output_price

Alias for field number 8

exogenous_output_quantity

Alias for field number 7

input_price

Alias for field number 2

input_quantity

Alias for field number 1

output_price

Alias for field number 4

output_quantity

Alias for field number 3

producible

Alias for field number 9

utility

Alias for field number 0

scml.builtin_agent_types(as_str=False)[source]

Returns all built-in agents.

Parameters

as_str – If true, the full type name will be returned otherwise the type object itself.

scml.is_system_agent(aid)[source]

Checks whether an agent is a system agent or not

Parameters

aid (str) – Agent ID

Return type

bool

Returns

True if the ID is for a system agent.