scml

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

An agent that negotiates randomly.

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

Creates a utility function

class scml.DoNothingAgent(**kwargs)[source]

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

confirm_exogenous_sales(quantities, unit_prices)[source]

Called to confirm the amount of guaranteed sales the agent is willing to accept

Parameters
  • quantities (ndarray) – An n_products vector giving the maximum quantity that can sold (without negotiation)

  • unit_prices (ndarray) – An n_products vector giving the guaranteed unit prices

Return type

ndarray

Returns

An n_products vector specifying the quantities to be sold (up to the given quantities limit).

confirm_exogenous_supplies(quantities, unit_prices)[source]

Called to confirm the amount of guaranteed supplies the agent is willing to accept

Parameters
  • quantities (ndarray) – An n_products vector giving the maximum quantity that can bought (without negotiation)

  • unit_prices (ndarray) – An n_products vector giving the guaranteed unit prices

Return type

ndarray

Returns

An n_products vector specifying the quantities to be bought (up to the given quantities limit).

init()[source]

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

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_contract_nullified(contract, compensation_money, new_quantity)[source]

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

Parameters
  • contract (Contract) – The contract being nullified

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

  • new_quantity (int) – The new quantity that will actually be executed for this contract at its delivery time.

Remarks:

  • compensation_money and new_quantity will never be both nonzero

  • compensation_money and new_quantity may both be zero which means that the contract will be cancelled without compensation

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

Return type

None

on_contract_signed(contract)[source]

Called whenever a contract is signed by all 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[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_contract(contract)[source]

Called after the signing delay from contract conclusion to sign the contract. Contracts become binding only after they are signed.

Return type

Optional[str]

step()[source]

Called by the simulator at every simulation step

class scml.IndependentNegotiationsAgent(*args, negotiator_type=<class 'negmas.sao.AspirationNegotiator'>, negotiator_params=None, horizon=5, **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.

Parameters
  • negotiator_type (Union[SAONegotiator, str]) – The type of the negotiator to use. The default is AspirationNegotiator

  • negotiator_params (Optional[Dict[str, Any]]) – key-value pairs to pass to the constructor of negotiators

  • horizon – The number of production step to handle together using a single set of negotiations. See step for details

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.

confirm_exogenous_sales(quantities, unit_prices)[source]

Called to confirm the amount of guaranteed sales the agent is willing to accept

Parameters
  • quantities (ndarray) – An n_products vector giving the maximum quantity that can sold (without negotiation)

  • unit_prices (ndarray) – An n_products vector giving the guaranteed unit prices

Return type

ndarray

Returns

An n_products vector specifying the quantities to be sold (up to the given quantities limit).

confirm_exogenous_supplies(quantities, unit_prices)[source]

Called to confirm the amount of guaranteed supplies the agent is willing to accept

Parameters
  • quantities (ndarray) – An n_products vector giving the maximum quantity that can bought (without negotiation)

  • unit_prices (ndarray) – An n_products vector giving the guaranteed unit prices

Return type

ndarray

Returns

An n_products vector specifying the quantities to be bought (up to the given quantities limit).

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

Creates a utility function

init()[source]

Initializes the agent by finding the average production cost.

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

Creates a negotiator

Return type

SAONegotiator

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

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]

Called to sign all contracts concluded in a single step by this agent

Remarks:

default implementation calls sign_contract for each contract returning the results

Return type

List[Optional[str]]

start_negotiations(product, quantity, unit_price, time, to_buy)[source]

Starts a set of negotiations to by/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

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

  • to_buy (bool) – Is the negotiation to buy or to sell

Remarks:

  • This method assumes that products cannot be in my_input_products and my_output_products

Return type

None

step()[source]

Every horizon steps, create new negotiations based on external supplies and sales.

class scml.BuyCheapSellExpensiveAgent(*args, negotiator_type=<class 'negmas.sao.AspirationNegotiator'>, negotiator_params=None, horizon=5, **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.AspirationNegotiator'>, negotiator_params=None, horizon=5, predicted_demand=None, predicted_supply=None, agreement_fraction=0.5, adapt_prices=False, **kwargs)[source]

An agent that keeps schedules of what it needs to buy and sell and tries to satisfy them.

It assumes that the agent can run a single process.

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

  • negotiator_params (Optional[Dict[str, Any]]) – The parameters used to initialize all negotiators

  • horizon – The number of steps in the future to consider for securing inputs and outputs.

  • predicted_demand (Union[int, ndarray, None]) – A prediction of the number of units needed by the market of the output product at each timestep

  • predicted_supply (Union[int, ndarray, None]) – A prediction of the nubmer of units available within the market of the input product at each timestep

  • agreement_fraction (float) – A prediction about the fraction of the quantity negotiated about that will be secured

  • adapt_prices (bool) – If true, the agent tries to adapt the unit price range it negotites about to market conditions (i.e. previous trade). If false, catalog prices will be used to constrain the unit price ranges to (1, catalog price) for buying and (catalog price, 2* catalog price) for selling

  • *args – Position arguments to pass the the base SCML2020Agent constructor

  • **kwargs – Keyword arguments to pass to the base SCML2020Agent constructor

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

confirm_exogenous_sales(quantities, unit_prices)[source]

Called to confirm the amount of guaranteed sales the agent is willing to accept

Parameters
  • quantities (ndarray) – An n_products vector giving the maximum quantity that can sold (without negotiation)

  • unit_prices (ndarray) – An n_products vector giving the guaranteed unit prices

Return type

ndarray

Returns

An n_products vector specifying the quantities to be sold (up to the given quantities limit).

confirm_exogenous_supplies(quantities, unit_prices)[source]

Called to confirm the amount of guaranteed supplies the agent is willing to accept

Parameters
  • quantities (ndarray) – An n_products vector giving the maximum quantity that can bought (without negotiation)

  • unit_prices (ndarray) – An n_products vector giving the guaranteed unit prices

Return type

ndarray

Returns

An n_products vector specifying the quantities to be bought (up to the given quantities limit).

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:

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

generate_buy_negotiations(step)[source]

Creates the controller and starts negotiations to acquire all required inputs (supplies) at the given step

generate_sell_negotiations(step)[source]

Creates the controller and starts negotiations to sell all required outputs (sales) at the given step

init()[source]

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

max_consumption_till(step)[source]

Returns the maximum number of units that can be consumed until the given step given current production schedule

Return type

int

max_production_till(step)[source]

Returns the maximum number of units that can be produced until the given step given current production schedule

Return type

int

on_contract_nullified(contract, compensation_money, new_quantity)[source]

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

Parameters
  • contract (Contract) – The contract being nullified

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

  • new_quantity (int) – The new quantity that will actually be executed for this contract at its delivery time.

Remarks:

  • compensation_money and new_quantity will never be both nonzero

  • compensation_money and new_quantity may both be zero which means that the contract will be cancelled without compensation

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

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

Called to sign all contracts concluded in a single step by this agent

Remarks:

default implementation calls sign_contract for each contract returning the results

Return type

List[Optional[str]]

start_negotiations(product, quantity, unit_price, step)[source]

Starts a set of negotiations to by/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

Remarks:

  • This method assumes that products cannot be in my_input_products and my_output_products

Return type

None

step()[source]

Generates buy and sell negotiations as needed

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

Current balance in the wallet

balance_change = None

Change in the balance in the last step

commands = None

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

contracts = None

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

inventory = None

An n_products vector giving current quantity of every product in storage

inventory_changes = None

Changes in the inventory in the last step

class scml.SCML2020Agent(**kwargs)[source]

Base class for all SCML2020 agents (factory managers)

abstract confirm_exogenous_sales(quantities, unit_prices)[source]

Called to confirm the amount of guaranteed sales the agent is willing to accept

Parameters
  • quantities (ndarray) – An n_products vector giving the maximum quantity that can sold (without negotiation)

  • unit_prices (ndarray) – An n_products vector giving the guaranteed unit prices

Return type

ndarray

Returns

An n_products vector specifying the quantities to be sold (up to the given quantities limit).

abstract confirm_exogenous_supplies(quantities, unit_prices)[source]

Called to confirm the amount of guaranteed supplies the agent is willing to accept

Parameters
  • quantities (ndarray) – An n_products vector giving the maximum quantity that can bought (without negotiation)

  • unit_prices (ndarray) – An n_products vector giving the guaranteed unit prices

Return type

ndarray

Returns

An n_products vector specifying the quantities to be bought (up to the given quantities limit).

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:

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

abstract on_contract_nullified(contract, compensation_money, new_quantity)[source]

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

Parameters
  • contract (Contract) – The contract being nullified

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

  • new_quantity (int) – The new quantity that will actually be executed for this contract at its delivery time.

Remarks:

  • compensation_money and new_quantity will never be both nonzero

  • compensation_money and new_quantity may both be zero which means that the contract will be cancelled without compensation

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

Return type

None

abstract 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_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

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

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

The Agent SCML2020World Interface for SCML2020 world allowing a single process per agent

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 inputs

Returns the number of inputs to every production process

Return type

ndarray

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_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

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 1. Seeling an output product (i.e. product $in$ my_output_products

request_negotiations(is_buy, product, quantity, unit_price, time, controller, partners=None, 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)

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

  • 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

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 1. Seeling an output product (i.e. product $in$ my_output_products

schedule_production(process, repeats, step=-1, line=-1, override=True, method='latest')[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

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

property state

Receives the factory state

Return type

FactoryState

class scml.SCML2020World(process_inputs, process_outputs, catalog_prices, profiles, agent_types, agent_params=None, exogenous_contracts=(), initial_balance=1000, buy_missing_products=False, borrow_on_breach=True, bankruptcy_limit=1.0, breach_penalty=0.15, interest_rate=0.05, financial_report_period=5, compensation_fraction=1.0, compensate_immediately=False, compensate_before_past_debt=True, exogenous_force_max=True, exogenous_buy_missing=False, exogenous_no_borrow=False, exogenous_no_bankruptcy=False, exogenous_penalty=0.15, exogenous_supply_limit=None, exogenous_sales_limit=None, exogenous_horizon=None, production_confirm=True, 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, signing_delay=0, force_signing=False, batch_signing=True, name=None, agent_name_reveals_position=True, agent_name_reveals_type=True, **kwargs)[source]

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.

  • breach_penalty – The total penalty paid upon a breach will be calculated as (breach_level * breach_penalty * contract_quantity * contract_unit_price).

  • exogenous_supply_limit (Optional[ndarray]) – An n_steps * n_products array giving the total supply available of each product over time. Only affects guaranteed supply.

  • exogenous_sales_limit (Optional[ndarray]) – An n_steps * n_products array giving the total sales to happen for each product over time. Only affects guaranteed sales.

  • 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

  • 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_force_max – If true, agents are not asked to confirm guaranteed transactions and they are carried out up to bankruptcy

  • exogenous_no_borrow – If true, agents will not borrow if they fail to satisfy an external transaction. The transaction will just fail silently

  • exogenous_no_bankruptcy – If true, agents will not go bankrupt because of an external transaction. The transaction will just fail silently

  • exogenous_penalty – The penalty paid for failure to honor external contracts

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

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

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 bankruptcy_rate

The fraction of factories that went bankrupt

Return type

float

breach_record(breach)[source]

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

Return type

Dict[str, Any]

compensate(available, factory)[source]

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

Returns:

Return type

None

complete_contract_execution(contract, breaches, resolution)[source]

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

Converts a contract to a record suitable for permanent storage

Return type

Dict[str, Any]

contract_size(contract)[source]

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

Returns:

Return type

float

execute_action(action, agent, callback=None)[source]

Executes the given action by the given agent

Return type

bool

classmethod generate(agent_types, agent_params=None, n_steps=100, n_processes=4, n_lines=10, n_agents_per_process=3, process_inputs=1, process_outputs=1, production_costs=(1, 10), profit_means=(0.1, 0.2), profit_stddevs=0.05, max_productivity=1.0, initial_balance=None, cost_increases_with_level=True, horizon=(0.5, 0.9), equal_exogenous_supply=False, equal_exogenous_sales=False, use_exogenous_contracts=True, exogenous_control=(0.0, 1.0), cash_availability=2.5, profit_basis=<function mean>, force_signing=False, **kwargs)[source]

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

  • 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

  • use_exogenous_contracts – If true, external supply and sales are revealed as exogenous contracts instead of using exogenous_* parts of the factory profile

  • 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

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

Reads the private state of the given agent

Return type

dict

property num_bankrupt

The fraction of factories that went bankrupt

Return type

float

on_contract_concluded(contract, to_be_signed_at)[source]

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

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

Parameters

contract (Contract) – The contract to add

Remarks:

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

  • You should ALWAYS call this function when overriding it.

order_contracts_for_execution(contracts)[source]

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

Return type

Collection[Contract]

post_step_stats()[source]

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

pre_step_stats()[source]

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

property productivity

Fraction of production lines occupied during the simulation

Return type

float

record_bankrupt(factory)[source]

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

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

Return type

Optional[float]

simulation_step_after_execution()[source]

A single step of the simulation if any (after entity and contract execution)

simulation_step_before_execution()[source]

A single step of the simulation if any (before entity and contract execution)

start_contract_execution(contract)[source]

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

welfare(include_bankrupt=False)[source]

Total welfare of all agents

Return type

float

property winners

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

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.FactoryProfile(costs, exogenous_sales, exogenous_supplies, exogenous_sale_prices, exogenous_supply_prices)[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)

exogenous_sale_prices

A n_steps * n_products array giving guaranteed unit prices for the exogenous_quantities . It will be zero for times and products for which there are no guaranteed quantities (i.e. (exogenous_quantities[…] == 0) =>

(exogenous_prices[…] == 0) )

exogenous_sales

A n_steps * n_products array giving guaranteed sales of different products for the whole simulation time

exogenous_supplies

A n_steps * n_products array giving guaranteed sales of different products for the whole simulation time

exogenous_supply_prices

A n_steps * n_products array giving guaranteed unit prices for the exogenous_quantities . It will be zero for times and products for which there are no guaranteed quantities (i.e. (exogenous_quantities[…] == 0) =>

(exogenous_prices[…] == 0) )

class scml.Factory(profile, initial_balance, inputs, outputs, catalog_prices, world, compensate_before_past_debt, buy_missing_products, production_buy_missing, exogenous_buy_missing, exogenous_penalty, exogenous_no_bankruptcy, exogenous_no_borrow, production_penalty, production_no_bankruptcy, production_no_borrow, agent_id, agent_name=None, confirm_production=True, initial_inventory=None)[source]

A simulated factory

agent_id = None

A unique ID for the agent owning the factory

agent_name = None

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 = None

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 = None

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

contracts = None

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 = None

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

inventory_changes = None

Changes in the inventory in the last step

is_bankrupt = None

Will be true when the factory is bankrupt

min_balance = None

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 = None

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

Return type

int

Returns

The amount actually paid

profile = None

The readonly factory profile (See FactoryProfile )

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.

step(accepted_sales, accepted_supplies)[source]

Override this method to modify stepping logic.

Parameters
  • accepted_sales (ndarray) – Sales per product accepted by the factory manager

  • accepted_supplies (ndarray) – Supplies per product accepted by the factory manager

Returns:

Return type

List[Failure]

store(product, quantity, unit_price, buy_missing, penalty, 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)

  • unit_price (int) – Unit price

  • 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

  • penalty (float) – The fraction of unit_price added because we are buying from the spot market. Only effectivec 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)