scml

Subpackages

Submodules

Package Contents

Classes

SCML2019Agent

The base for all SCM Agents

SCMLAWI

A single contact point between SCML agents and the world simulation.

DefaultBank

Represents a bank in the world

Bank

Base class for all banks

Product

Process

InputOutput

An input/output to a production process

RunningCommandInfo

ManufacturingProfile

The costs/time required for running a process on a line (with associated cancellation costs etc). This

ManufacturingProfileCompiled

The costs/time required for running a process on a line (with associated cancellation costs etc).

ProductManufacturingInfo

Gives full information about a manufacturing process that can generate or consume a product.

FactoryStatusUpdate

Job

Describes a job to be run on one production line of a Factory.

ProductionNeed

Describes some quantity of a product that is needed to honor a (sell) contract.

MissingInput

ProductionReport

ProductionFailure

FinancialReport

Reports that financial standing of an agent at a given time in the simulation

SCMLAgreement

SCMLAction

CFP

A Call for proposal upon which a negotiation can start

Loan

InsurancePolicy

Factory

Represents a factory within an SCML world. It is only accessed by the SCML2020World so it need not be made public.

FactoryState

Read Only State of a factory

Consumer

Base class of all consumer classes

ConsumptionProfile

JustInTimeConsumer

Consumer class

FactoryManager

Base factory manager class that will be inherited by participant negmas in ANAC 2019.

DoNothingFactoryManager

The default factory manager that will be implemented by the committee of ANAC-SCML 2019

GreedyFactoryManager

The default factory manager that will be implemented by the committee of ANAC-SCML 2019

DefaultInsuranceCompany

Represents an insurance company in the world

InsuranceCompany

Base class for all insurance companies

Miner

Base class of all miners

MiningProfile

ReactiveMiner

Raw Material Generator

ScheduleInfo

Scheduler

Base class for all schedulers

GreedyScheduler

Default scheduler used by the DefaultFactoryManager

FactorySimulator

Simulates a factory allowing for prediction of storage/balance in the future.

SlowFactorySimulator

A slow factory simulator that runs an internal factory to find-out what will happen in the future

FastFactorySimulator

A faster implementation of the FactorySimulator interface (compared with SlowFactorySimulator.

DefaultGreedyManager

The default factory manager that will be implemented by the committee of ANAC-SCML 2019

SCML2019World

The SCML2020World class running a simulation of supply chain management.

SCML2020Agent

Base class for all SCML2020 agents (factory managers)

OneShotAdapter

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

RandomAgent

An agent that negotiates randomly.

DoNothingAgent

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

IndependentNegotiationsAgent

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

MarketAwareIndependentNegotiationsAgent

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

BuyCheapSellExpensiveAgent

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

MarketAwareBuyCheapSellExpensiveAgent

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

DecentralizingAgent

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

IndDecentralizingAgent

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

DecentralizingAgentWithLogging

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

MarketAwareDecentralizingAgent

Predicts an amount based on publicly available market information. Falls

MarketAwareIndDecentralizingAgent

Signs all contracts that have good prices

ReactiveAgent

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

MarketAwareReactiveAgent

Signs all contracts that have good prices

MovingRangeAgent

My negotiation strategy

MarketAwareMovingRangeAgent

Predicts an amount based on publicly available market information. Falls

SatisficerAgent

A simple monolithic agent that tries to carefully make small profit

AWI

The Agent SCML2020World Interface for SCML2020 world.

FactoryState

Read Only State of a factory

FinancialReport

Reports that financial standing of an agent at a given time in the simulation

FactoryProfile

Defines all private information of a factory

Failure

A production failure

ExogenousContract

Represents a contract to be revealed at revelation_time to buyer and seller between them that is not agreed upon

ProductionStrategy

Represents a strategy for controlling production.

SupplyDrivenProductionStrategy

A production strategy that converts all inputs to outputs

DemandDrivenProductionStrategy

A production strategy that produces ONLY when a contract is secured

TradeDrivenProductionStrategy

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

TradePredictionStrategy

A prediction strategy for expected inputs and outputs at every step

FixedTradePredictionStrategy

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

ExecutionRatePredictionStrategy

A prediction strategy for expected inputs and outputs at every step

FixedERPStrategy

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

MeanERPStrategy

Predicts the mean execution fraction for each partner

MarketAwareTradePredictionStrategy

Predicts an amount based on publicly available market information. Falls

SignAll

Signs all contracts no matter what.

SignAllPossible

Signs all contracts that can in principle be honored.

KeepOnlyGoodPrices

Signs all contracts that have good prices

NegotiationManager

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

StepNegotiationManager

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

IndependentNegotiationsManager

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

MovingRangeNegotiationManager

My negotiation strategy

Simulation

Provides a simulator to the agent.

Factory

Represents a factory within an SCML world. It is only accessed by the SCML2020World so it need not be made public.

SCML2020World

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

SCML2021World

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

SCML2022World

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

SCML2023World

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

SCML2024World

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

OneShotAgent

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

OneShotSyncAgent

An agent that automatically accumulate offers from opponents and allows

OneShotSingleAgreementAgent

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

OneShotIndNegotiatorsAgent

A one-shot agent that deligates all of its decisions to a set of independent

EndingNegotiator

Base class for all SAO negotiators.

SingleAgreementAspirationAgent

Uses a time-based strategy to accept a single agreement from the set

GreedyOneShotAgent

A greedy agent based on OneShotAgent

GreedySyncAgent

A greedy agent based on OneShotSyncAgent

GreedySingleAgreementAgent

A greedy agent based on OneShotSingleAgreementAgent

OneshotDoNothingAgent

An agent that does nothing.

Placeholder

An agent that always raises an exception if called to negotiate. It is useful as a placeholder (for example for RL and MARL exposition)

RandomOneShotAgent

An agent that randomly leaves the negotiation, accepts or counters with random outcomes

RandDistOneShotAgent

An agent that distributes its needs over its partners randomly.

EqualDistOneShotAgent

Same as RandDistOneShotAgent but defaulting to equal distribution of needs

SyncRandomOneShotAgent

An agent that distributes its needs over its partners randomly.

SingleAgreementRandomAgent

A controller that agrees randomly to one offer

OneShotAWI

The agent world interface for the one-shot game.

OneShotState

State of a one-shot agent

OneShotExogenousContract

Exogenous contract information

OneShotProfile

Defines all private information of a factory

FinancialReport

Reports that financial standing of an agent at a given time in the simulation

Context

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

GeneralContext

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

ANACContext

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

LimitedPartnerNumbersContext

Generates a world limiting the range of the agent level, production capacity

FixedPartnerNumbersContext

Generates a world limiting the range of the agent level, production capacity

ANACOneShotContext

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

LimitedPartnerNumbersOneShotContext

Generates a oneshot world limiting the range of the agent level, production capacity

FixedPartnerNumbersOneShotContext

Generates a world limiting the range of the agent level, production capacity

SupplierContext

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

ConsumerContext

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

StrongSupplierContext

A supplier with almost many consumers relative to competitors

StrongConsumerContext

A consumer with almost many suppliers relative to competitors

WeakSupplierContext

A supplier with few consumers relative to competitors

WeakConsumerContext

A consumer with few suppliers relative to competitors

BalancedSupplierContext

A supplier with almost same number of consumers as competitors

BalancedConsumerContext

A consumer with almost same number of suppliers as competitors

RepeatingContext

Encapsulates one or more configs and switches between them when asked to generate or make something.

ContextParams

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

MonopolicContext

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

SingleAgentPerLevelSupplierContext

A world in which every level has exactly one factory and the agent is a supplier

EutopiaContext

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

EutopiaConsumerContext

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

EutopiaSupplierContext

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

OneShotPolicy

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

ActionManager

Manges actions of an agent in an RL environment.

FlexibleActionManager

An action manager that matches any context.

OneShotRLAgent

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

OneShotEnv

The main Gymnasium class for implementing Reinforcement Learning Agents environments.

ObservationManager

Manages the observations of an agent in an RL environment

FlexibleObservationManager

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

RewardFunction

Represents a reward function.

DefaultRewardFunction

The default reward function of SCML

DefaultOneShotAdapter

The base class of all agents running in OneShot based on OneShotAgent.

_StdSystemAgent

Implements an agent for handling system operations

OneShotUFun

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

UtilityInfo

SCMLBaseWorld

Implements the a generalized form of SCML-OneShot game which supports both oneshot and standard simulations

OneShotWorld

Basic oneshot simulation

SCML2020OneShotWorld

Oneshot simulation as used in SCML 2020 competition

SCML2021OneShotWorld

Oneshot simulation as used in SCML 2021 competition

SCML2022OneShotWorld

Oneshot simulation as used in SCML 2022 competition

SCML2023OneShotWorld

Oneshot simulation as used in SCML 2023 competition

SCML2024OneShotWorld

Oneshot simulation as used in SCML 2024 competition

Functions

builtin_agent_types([as_str])

Returns all built-in agents.

pos_gauss(mu, sigma)

Returns a sample from a rectified gaussian

_safe_max(a, b)

zero_runs(→ numpy.array)

Finds all runs of zero in an array

transaction(simulator)

Runs the simulated actions then confirms them if they are not rolled back

temporary_transaction(simulator)

Runs the simulated actions then rolls them back

anac2019_world(, params, Any]] =, randomize, ...[, ...])

Creates a world compatible with the ANAC 2019 competition. Note that

anac2019_tournament(...)

The function used to run ANAC 2019 SCML tournament (collusion track).

anac2019_collusion(...)

The function used to run ANAC 2019 SCML tournament (collusion track).

anac2019_std(...)

The function used to run ANAC 2019 SCML tournament (standard track).

balance_calculator(→ negmas.tournaments.WorldRunResults)

A scoring function that scores factory managers' performance by the final balance only ignoring whatever still

anac2019_sabotage(...)

The function used to run ANAC 2019 SCML tournament (collusion track).

builtin_agent_types([as_str])

Returns all built-in agents.

is_system_agent(→ bool)

Checks whether an agent is a system agent or not

builtin_agent_types([as_str])

Returns all built-in agents.

is_system_agent(→ bool)

Checks whether an agent is a system agent or not

model_wrapper(→ RLModel)

Wraps a stable_baselines3 model as an RL model

random_action(→ numpy.ndarray)

Samples a random action from the action space of the

random_policy(→ numpy.ndarray)

Ends the negotiation or accepts with a predefined probability or samples a random response.

greedy_policy()[, debug])

A simple greedy policy.

Attributes

__author__

__email__

__version__

__all__

UNIT_PRICE

Index of unit price in negotiation issues

TIME

Index of time in negotiation issues

QUANTITY

Index of quantity in negotiation issues

INVALID_STEP

NO_PRODUCTION

DEFAULT_NEGOTIATOR

__all__

SYSTEM_BUYER_ID

ID of the system buyer agent

SYSTEM_SELLER_ID

ID of the system seller agent

COMPENSATION_ID

ID of the takeover agent

ANY_STEP

Used to indicate any time-step

NO_COMMAND

A constant indicating no command is scheduled on a factory line

ANY_LINE

Used to indicate any line

INFINITE_COST

A constant indicating an invalid cost for lines incapable of running some process

QUANTITY

Index of quantity in negotiation issues

TIME

Index of time in negotiation issues

UNIT_PRICE

Index of unit price in negotiation issues

__all__

QUANTITY

Index of quantity in negotiation issues

UNIT_PRICE

Index of unit price in negotiation issues

TIME

Index of time in negotiation issues

INFINITE_COST

A constant indicating an invalid cost for lines incapable of running some process

SYSTEM_BUYER_ID

ID of the system buyer agent

SYSTEM_SELLER_ID

ID of the system seller agent

DefaultActionManager

The default action manager

RLState

We assume that RL states are numpy arrays

RLAction

We assume that RL actions are numpy arrays

RLModel

A policy is a callable that receives a state and returns an action

DefaultObservationManager

The default observation manager

UFunLimit

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

PLACEHOLDER_AGENT_PREFIX

__all__

scml.__author__ = 'Yasser Mohammad'[source]
scml.__email__ = 'yasserfarouk@gmail.com'[source]
scml.__version__ = '0.7.5'[source]
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.__all__[source]
class scml.SCML2019Agent(name: str | None = None, ufun: negmas.UtilityFunction | None = None)[source]

Bases: negmas.situated.Agent

The base for all SCM Agents

property awi: scml.scml2019.awi.SCMLAWI

Returns the Agent-SCML2020World-Interface through which the agent does all of its actions in the world.

A single excption is request_negotiation for which it is recommended to actually call the helper method on the agent itself instead of directly calling the AWI version.

line_profiles: Dict[int, scml.scml2019.common.ManufacturingProfileCompiled]

A mapping specifying for each Line index, all the profiles used to run it in the factory

process_profiles: Dict[int, scml.scml2019.common.ManufacturingProfileCompiled]

A mapping specifying for each Process index, all the profiles used to run it in the factory

producing: Dict[int, List[scml.scml2019.common.ProductManufacturingInfo]]

Mapping from a product to all manufacturing processes that can generate it

consuming: Dict[int, List[scml.scml2019.common.ProductManufacturingInfo]]

Mapping from a product to all manufacturing processes that can consume it

compiled_profiles: List[scml.scml2019.common.ManufacturingProfileCompiled] = []

All the profiles to be used by the factory belonging to this agent compiled to use indices

immediate_negotiations = False

Whether or not negotiations start immediately upon registration (default is to start on the next production step)

negotiation_speed_multiple: int = 1

The number of negotiation rounds (steps) conducted in a single production step

transportation_delay: int = 0

Transportation delay in the system. Default is zero

products: List[scml.scml2019.common.Product] = []

List of products in the system

processes: List[scml.scml2019.common.Process] = []

List of processes in the system

reset()[source]
is_clean() bool[source]
init_()[source]

The initialization function called by the world directly.

It does the following actions by default:

  1. copies some of the static world settings to the agent to make them available without calling the AWI.

  2. prepares production related properties like producing, consuming, line_profiles, compiled_profiles, etc.

  3. registers interest in all products that the agent can produce or consume in its factory.

  4. finally it calls any custom initialization logic implemented in `init`()

See also

init, step

can_expect_agreement(cfp: scml.scml2019.common.CFP, margin: int)[source]

Checks if it is possible in principle to get an agreement on this CFP by the time it becomes executable

Parameters:
  • margin

  • cfp

Returns:

_create_annotation(cfp: scml.scml2019.common.CFP, partner: str = None)[source]

Creates full annotation based on a cfp that the agent is receiving

Parameters:
  • cfp – The call for proposal to create annotation about

  • partner – The partner who requested the negotiation

Remarks:

  • If the annotation is to be created for a CFP that was published by self, partner must be passed

_respond_to_negotiation_request(initiator: str, partners: List[str], issues: List[negmas.outcomes.Issue], annotation: Dict[str, Any], mechanism: negmas.common.NegotiatorMechanismInterface, role: str | None, req_id: str | None) negmas.negotiators.Negotiator | None[source]

Called by the mechanism to ask for joining a negotiation. The agent can refuse by returning a None

Parameters:
  • initiator – The ID of the agent that initiated the negotiation request

  • partners – The partner list (will include this agent)

  • issues – The list of issues

  • annotation – Any annotation specific to this negotiation.

  • mechanism – The mechanism that started the negotiation

  • role – The role of this agent in the negotiation

  • req_id – The req_id passed to the AWI when starting the negotiation (only to the initiator).

Returns:

None to refuse the negotiation or a Negotiator object appropriate to the given mechanism to accept it.

Remarks:

  • It is expected that world designers will introduce a better way to respond and override this function to call it

request_negotiation(cfp: scml.scml2019.common.CFP, negotiator: negmas.negotiators.Negotiator = None, ufun: negmas.UtilityFunction = None) bool[source]

Requests a negotiation from the AWI while keeping track of available negotiation requests

Parameters:
  • cfp

  • negotiator

  • ufun

Returns:

Whether the negotiation request was successful indicating that the partner accepted the negotiation

abstract on_contract_executed(contract: negmas.situated.Contract) None[source]

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

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

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

Parameters:
  • contract – The contract

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

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

abstract confirm_loan(loan: scml.scml2019.common.Loan, bankrupt_if_rejected: bool) bool[source]

called by the world manager to confirm a loan if needed by the buyer of a contract that is about to be breached

abstract on_contract_nullified(contract: negmas.situated.Contract, bankrupt_partner: str, compensation: float) None[source]

Will be called whenever a contract the agent is involved in is nullified because another partner went bankrupt

abstract on_agent_bankrupt(agent_id: str) None[source]

Will be called whenever any agent goes bankrupt

Parameters:

agent_id – The ID of the agent that went bankrupt

Remarks:

  • Agents can go bankrupt in two cases:

    1. Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it.

    2. Failing to pay a penalty on a sell contract they failed to honor (and refusing or being unable to get a loan to pay for it).

  • All built-in agents ignore this call and they use the bankruptcy list ONLY to decide whether or not to negotiate in their on_new_cfp and respond_to_negotiation_request callbacks by pulling the bulletin-board using the helper function is_bankrupt of their AWI.

abstract confirm_partial_execution(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach]) bool[source]

Will be called whenever a contract cannot be fully executed due to breaches by the other partner.

Parameters:
  • contract – The contract that was breached

  • breaches – A list of all the breaches committed.

Remarks:

  • Will not be called if both partners committed breaches.

abstract confirm_contract_execution(contract: negmas.situated.Contract) bool[source]

Called before executing any agreement

abstract respond_to_negotiation_request(cfp: scml.scml2019.common.CFP, partner: str) negmas.negotiators.Negotiator | None[source]

Called when a prospective partner requests a negotiation to start

abstract on_new_cfp(cfp: scml.scml2019.common.CFP)[source]

Called when a new CFP for a product for which the agent registered interest is published

abstract on_remove_cfp(cfp: scml.scml2019.common.CFP)[source]

Called when a new CFP for a product for which the agent registered interest is removed

abstract on_new_report(report: scml.scml2019.common.FinancialReport)[source]

Called whenever a financial report is published.

Parameters:

report – The financial report giving details of the standing of an agent at some time (see FinancialReport)

Remarks:

abstract on_inventory_change(product: int, quantity: int, cause: str) None[source]

Received whenever something moves in or out of the factory’s storage

Parameters:
  • product – Product index.

  • quantity – Negative value for products moving out and positive value for products moving in

  • cause

    The cause of the change. Possibilities include:

    • contract: Contract execution

    • insurance: Received from insurance company

    • bankruptcy: Liquidated due to bankruptcy

    • transport: Arrival of goods (when transportation delay in the system is > 0).

abstract on_cash_transfer(amount: float, cause: str) None[source]

Received whenever money is transferred to the factory or from it.

Parameters:
  • amount – Amount of money (negative for transfers out of the factory, positive for transfers to it).

  • cause

    The cause of the change. Possibilities include:

    • contract: Contract execution

    • insurance: Received from insurance company

    • bankruptcy: Liquidated due to bankruptcy

    • transfer: Arrival of transferred money (when transfer delay in the system is > 0).

class scml.SCMLAWI(world: negmas.situated.world.World, agent: negmas.situated.agent.Agent)[source]

Bases: negmas.situated.AgentWorldInterface

A single contact point between SCML agents and the world simulation.

The agent can access the world simulation in one of two ways:

  1. Attributes and methods available in this Agent-SCML2020World-Interface

  2. Attributes and methods in the FactoryManager object itself which provide handy shortcuts to the agent-world interface

Attributes

Simulation settings

  • current_step : Current simulation step

  • default_signing_delay : The grace period allowed between contract conclusion and signature by default (i.e. if not agreed upon during the negotiation)

  • n_steps : Total number of simulation steps.

  • relative_time : The fraction of total simulation time elapsed (it will be a number between 0 and 1)

Production Graph

  • products : A list of Product objects giving all products defined in the world simulation

  • processes : A list of Process objects giving all products defined in the world simulation

Agent Related

  • state : The current private state available to the agent. In SCML it is a FactoryState object.

Methods

Production Control

  • schedule_job : Schedules a Job for production sometime in the future

  • schedule_production : Schedules production using profile number instead of a Job object

  • cancel_production : Cancels already scheduled production (if it did not start yet) or stop a running production.

  • execute : A general function to execute any command on the factory. There is no need to directly call this function as the SCMLAWI provides convenient functions (e.g. schedule_job , hide_funds , etc) to achieve the same goal without having to worry about creating Action objects

Storage and Wallet Control

  • hide_funds : Hides funds from the view of the simulator. Note that when bankruptcy is considered, hidden funds are visible to the simulator.

  • hide_inventory : Hides inventory from the view of the simulator. Note that when bankruptcy is considered, hidden funds are visible to the simulator.

  • unhide_funds : Un-hides funds hidden earlier with a call to hide_funds

  • unhide_inventory : Un-hides inventory hidden earlier with a call to hide_inventory

Negotiation and CFP Control

  • register_cfp : Registers a Call-for-Proposals on the bulletin board.

  • remove_cfp : Removes a Call-for-Proposals from the bulletin board.

  • request_negotiation : Requests a negotiation based on the content of a CFP published on the bulletin-board. *It is recommended not to use this method directly and to request negotiations using the request_negotiation method of FactoryManager (i.e. use self.request_negotiation instead of self.awi.request_negotiation). This makes it possible for NegMAS to keep track of existing requested_negotiations and running_negotiations for you.

Notification Control

  • receive_financial_reports : Register/unregisters interest in receiving financial reports for an agent, a set of agents or all agents.

  • register_interest : registers interest in receiving CFPs about a set of products. By default all FactoryManager objects are registered to receive all CFPs for any product they can produce or need to consumer according to their line-profiles.

  • unregister_interest : unregisters interest in receiving CFPs about a set of products.

Information about Other Agents

  • is_bankrupt : Asks about the bankruptcy status of an agent

  • receive_financial_reports : Register/unregisters interest in receiving financial reports for an agent, a set of agents or all agents.

  • reports_at : reads all financial reports produced at a given time-step

  • reports_for : reads all financial reports of a given agent

Financial Control

  • evaluate_insurance : Asks for the premium to be paid for insuring against partner breaches for a given contract

  • buy_insurance : Buys an insurance against partner breaches for a given contract

Bulletin-Board

The bulletin-board is a key-value store. These methods allows the agent to interact with it. The `SCMLAWI` provides convenient functions for recording to the bulletin-board so you mostly need to use read/query functions.

  • bb_read : Reads a complete section or a single value from the bulletin-board

  • bb_query : Returns all records in the given section/sections of the bulletin-board that satisfy a query

  • bb_record : Registers a record in the bulletin-board.

  • bb_remove : Removes a record from the bulletin-board.

The following list of sections are available in the SCML Bulletin-Board (Use the exact string for the section parameter of any method starting with bb_):

  • cfps: All CFPs currently on the board. The key is the CFP ID

  • products: A list of all products. The key is the product index/ID

  • processes: A list of all processes. The key is the product index/ID

  • bankruptcy: The bankruptcy list giving names of all bankrupt agents.

  • reports_time: Financial reports indexed by time.

  • reports_agent: Financial reports indexed by agent

  • breaches: Breach-list indexed by breach ID giving all breaches committed in the system

  • settings: Static settings of the simulation.

    The following settings are currently available:

    • breach_penalty_society: Penalty of breaches paid to society (as a fraction of contract value). This is always paid for every breach whether or not there is a negotiated breach.

    • breach_penalty_victim: Penalty of breaches paid to victim (as a fraction of contract value). This is always paid for every breach whether or not there is a negotiated breach.

    • immediate_negotiations: Whether negotiations start immediately when registered (the other possibility – which is the default – is for them to start at the next production step).

    • negotiation_speed_multiple: Number of negotiation steps that finish in a single production step.

    • negotiation_n_steps: Maximum allowed number of steps (rounds) in any negotiation

    • negotiation_step_time_limit: The maximum real-time allowed for each negotiation step (round)

    • negotiation_time_limit: The time limit for a complete negotiation.

    • transportation_delay: Transportation delay when products are moved between factories. Default is zero.

    • transfer_delay: The delay in transferring funds between factories when executing a contract. Default is zero.

    • n_steps: Number of simulation steps

    • time_limit: Time limit for the complete simulation

  • stats: Global statistics about the simulation. Not available for SCML 2019 league.

Logging

  • logerror : Logs an error in the world simulation log file

  • logwarning : Logs a warning in the world simulation log file

  • loginfo : Logs information in the world simulation log file

  • logdebug : Logs debug information in the world simulation log file

property state: scml.scml2019.common.FactoryState

Returns the private state of the agent in that world.

In the SCML world, that is a reference to its factory. You are allowed to read information from the returned Factory but not to modify it or call ANY methods on it that modify the state.

property products: List[scml.scml2019.common.Product]

Products in the world

property processes: List[scml.scml2019.common.Process]

Processes in the world

cancel_production

Stops/cancels production scheduled at the given line at the given time.

Parameters:
  • line – One of the factory lines (index)

  • step – Step to stop/cancel production at

register_cfp(cfp: scml.scml2019.common.CFP) None[source]

Registers a CFP

register_interest(products: List[int]) None[source]

registers interest in receiving callbacks about CFPs related to these products

unregister_interest(products: List[int]) None[source]

registers interest in receiving callbacks about CFPs related to these products

remove_cfp(cfp: scml.scml2019.common.CFP) bool[source]

Removes a CFP

evaluate_insurance(contract: negmas.situated.Contract, t: int = None) float | None[source]

Can be called to evaluate the premium for insuring the given contract against breaches committed by others

Parameters:
  • contract – hypothetical contract

  • t – time at which the policy is to be bought. If None, it means current step

buy_insurance(contract: negmas.situated.Contract) bool[source]

Buys insurance for the contract by the premium calculated by the insurance company.

Remarks:

The agent can call evaluate_insurance to find the premium that will be used.

_create_annotation(cfp: scml.scml2019.common.CFP, partner: str = None)[source]

Creates full annotation based on a cfp that the agent is receiving

request_negotiation(cfp: scml.scml2019.common.CFP, req_id: str, roles: List[str] = None, mechanism_name: str = None, mechanism_params: Dict[str, Any] = None) bool[source]

Requests a negotiation with the publisher of a given CFP

Parameters:
  • cfp – The CFP to negotiate about

  • req_id – A string that is passed back to the caller in all callbacks related to this negotiation

  • roles – The roles of the CFP publisher and the agent (in that order). By default no roles are passed (None)

  • mechanism_name – The mechanism type to use. If not given the default mechanism from the world will be used

  • mechanism_params – Parameters of the mechanism

Returns:

Success of failure of the negotiation request

Remarks:

  • The SCML2019Agent class implements another request_negotiation method that does not receive a req_id. This helper method is recommended as it generates the required req_id and passes it keeping track of requested negotiations (and later of running negotiations). Call this method direclty only if you do not intend to use the requested_negotiations and running_negotiations properties of the SCML2019Agent class

request_negotiation_about(issues: List[negmas.Issue], partners: List[str], req_id: str, roles: List[str] = None, annotation: Dict[str, Any] | None = None, mechanism_name: str = None, mechanism_params: Dict[str, Any] = None)[source]

Overrides the method of the same name in the base class to disable it in SCM Worlds.

Do not call this method

is_bankrupt(agent_id: str) bool[source]

Checks whether the given agent is bankrupt

Parameters:

agent_id – Agent ID

Returns:

The bankruptcy state of the agent

reports_for(agent_id: str) List[scml.scml2019.common.FinancialReport][source]

Gets all financial reports of an agent (in the order of their publication)

Parameters:

agent_id – Agent ID

Returns:

reports_at(step: int = None) Dict[str, scml.scml2019.common.FinancialReport][source]

Gets all financial reports of all agents at a given step

Parameters:

step – Step at which the reports are required. If None, the last set of reports is returned

Returns:

A dictionary with agent IDs in keys and their financial reports at the given time as values

receive_financial_reports(receive: bool = True, agents: List[str] | None = None) None[source]

Registers/unregisters interest in receiving financial reports

Parameters:
  • receive – True to receive and False to stop receiving

  • agents – If given reception is enabled/disabled only for the given set of agents.

Remarks:

  • by default financial reports are not sent to any agents. To opt-in to receive financial reports, call this method.

schedule_production(profile: int, step: int, contract: negmas.situated.Contract | None = None, override: bool = True) None[source]

Schedules production on the agent’s factory

Parameters:
  • profile – Index of the profile in the agent’s compiled_profiles list

  • step – The step to start production according to the given profile

  • contract – The contract for which the production is scheduled (optional)

  • override – Whether to override existing production jobs schedules at the same time.

stop_production(line: int, step: int, contract: negmas.situated.Contract | None, override: bool = True)[source]

Stops/cancels production scheduled at the given line at the given time.

Parameters:
  • line – One of the factory lines (index)

  • step – Step to stop/cancel production at

  • contract – The contract for which the job is scheduled (optional)

  • override – Whether to override existing production jobs schedules at the same time.

schedule_job(job: scml.scml2019.common.Job, contract: negmas.situated.Contract | None)[source]

Schedules production using a Job object. This can be used to schedule any kind of job

Parameters:
  • job – The job description

  • contract – The contract for which the job is scheduled (optional)

Remarks:

  • Notice that actions that require the profile member of Job (run) never use the line member and vice versa.

hide_inventory(product: int, quantity: int) None[source]

Hides the given quantity of the given product so that it is not accessible by the simulator and does not appear in reports etc.

Parameters:
  • product – product index

  • quantity – the amount of the product to hide

Remarks:

  • if the current quantity in storage of the product is less than the amount to be hidden, whatever quantity exists is hidden

  • hiding is always immediate

hide_funds(amount: float) None[source]

Hides the given amount of money so that it is not accessible by the simulator and does not appear in reports etc.

Parameters:

amount – The amount of money to hide

Remarks:

  • if the current cash in the agent’s wallet is less than the amount to be hidden, all the cash is hidden.

  • hiding is always immediate

unhide_inventory(product: int, quantity: int) None[source]

Un-hides the given quantity of the given product so that it is not accessible by the simulator and does not appear in reports etc.

Parameters:
  • product – product index

  • quantity – the amount of the product to hide

Remarks:

  • if the current quantity in storage of the product is less than the amount to be hidden, whatever quantity exists is hidden

  • hiding is always immediate

unhide_funds(amount: float) None[source]

Un-hides the given amount of money so that it is not accessible by the simulator and does not appear in reports etc.

Parameters:

amount – The amount of money to unhide

Remarks:

  • if the current cash in the agent’s wallet is less than the amount to be hidden, all the cash is hidden.

  • hiding is always immediate

class scml.DefaultBank(minimum_balance: float, interest_rate: float, interest_max: float, balance_at_max_interest: float, installment_interest: float, time_increment: float, a2f: dict[str, scml.scml2019.common.Factory], disabled: bool = False, name: str | None = None)[source]

Bases: Bank

Represents a bank in the world

init()[source]

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

respond_to_negotiation_request(initiator: str, partners: list[str], issues: list[negmas.Issue], annotation: dict[str, Any], mechanism: negmas.Mechanism, role: str | None, req_id: str) negmas.Negotiator | None[source]
set_renegotiation_agenda(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach]) negmas.situated.RenegotiationRequest | None[source]

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

Parameters:
  • contract – The contract being breached

  • breaches – All breaches on contract

Returns:

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

respond_to_renegotiation_request(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach], agenda: negmas.situated.RenegotiationRequest) negmas.Negotiator | None[source]

Called to respond to a renegotiation request

Parameters:
  • agenda

  • contract

  • breaches

Returns:

_evaluate_loan(agent: scml.scml2019.agent.SCML2019Agent, amount: float, n_installments: int, starts_at: int, installment_loan=False) scml.scml2019.common.Loan | None[source]

Evaluates the interest that will be imposed on the agent to buy_loan that amount

evaluate_loan(agent: scml.scml2019.agent.SCML2019Agent, amount: float, start_at: int, n_installments: int) scml.scml2019.common.Loan | None[source]

Evaluates the interest that will be imposed on the agent to buy_loan that amount

_buy_loan(agent: scml.scml2019.agent.SCML2019Agent, loan: scml.scml2019.common.Loan, beneficiary: negmas.situated.Agent, contract: negmas.situated.Contract | None, bankrupt_if_rejected=False) scml.scml2019.common.Loan | None[source]
buy_loan(agent: scml.scml2019.agent.SCML2019Agent, amount: float, n_installments: int, beneficiary: negmas.situated.Agent, contract: negmas.situated.Contract | None, force: bool = False) scml.scml2019.common.Loan | None[source]

Gives a loan of amount to agent at the interest calculated using evaluate_loan

step()[source]

Takes payments from agents

_reduce_credit_rating(agent: negmas.situated.Agent, unavailable: float)[source]

Updates the credit rating when the agent fails to pay an installment

credit_rating(agent_id: str) float[source]
class scml.Bank(*args, **kwargs)[source]

Bases: negmas.situated.Agent, abc.ABC

Base class for all banks

_respond_to_negotiation_request(initiator: str, partners: list[str], issues: list[negmas.Issue], annotation: dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, role: str | None, req_id: str | None) negmas.Negotiator | None[source]

Called by the mechanism to ask for joining a negotiation. The agent can refuse by returning a None

Parameters:
  • initiator – The ID of the agent that initiated the negotiation request

  • partners – The partner list (will include this agent)

  • issues – The list of issues

  • annotation – Any annotation specific to this negotiation.

  • mechanism – The mechanism that started the negotiation

  • role – The role of this agent in the negotiation

  • req_id – The req_id passed to the AWI when starting the negotiation (only to the initiator).

Returns:

None to refuse the negotiation or a Negotiator object appropriate to the given mechanism to accept it.

Remarks:

  • It is expected that world designers will introduce a better way to respond and override this function to call it

on_neg_request_rejected(req_id: str, by: list[str] | None)[source]

Called when a requested negotiation is rejected

Parameters:
  • req_id – The request ID passed to _request_negotiation

  • by – A list of agents that refused to participate or None if the failure was for another reason

on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface)[source]

Called when a requested negotiation is accepted

on_negotiation_failure(partners: list[str], annotation: dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, state: negmas.MechanismState) None[source]

Called whenever a negotiation ends without agreement

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

Called whenever a negotiation ends with agreement

on_contract_signed(contract: negmas.situated.Contract) None[source]

Called whenever a contract is signed by all partners

on_contract_cancelled(contract: negmas.situated.Contract, rejectors: list[str]) None[source]

Called whenever at least a partner did not sign the contract

sign_contract(contract: negmas.situated.Contract) str | None[source]

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

respond_to_negotiation_request(initiator: str, partners: list[str], issues: list[negmas.Issue], annotation: dict[str, Any], mechanism: negmas.Mechanism, role: str | None, req_id: str) negmas.Negotiator | None[source]
on_contract_executed(contract: negmas.situated.Contract) None[source]

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

on_contract_breached(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach], resolution: negmas.situated.Contract | None) None[source]

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

Parameters:
  • contract – The contract

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

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

scml.UNIT_PRICE = 2[source]

Index of unit price in negotiation issues

scml.TIME = 1[source]

Index of time in negotiation issues

scml.QUANTITY = 0[source]

Index of quantity in negotiation issues

class scml.Product[source]
__slots__ = ['id', 'production_level', 'name', 'expires_in', 'catalog_price']

A product that can be transacted in.

id: int

Product index. Must be set during construction and MUST be unique for products in the same world

production_level: int

The level of this product in the production graph.

name: str

Object name

expires_in: int | None

Number of steps within which the product must be consumed. None means never

catalog_price: float | None

Catalog price of the product.

__str__()[source]

String representation is simply the name

__post_init__()[source]
__hash__()[source]

Return hash(self).

class scml.Process[source]
__slots__ = ['id', 'production_level', 'name', 'inputs', 'outputs', 'historical_cost']
id: int

A manufacturing process.

production_level: int

The level of this process in the production graph

name: str

Object name

inputs: List[InputOutput]

list of input product name + quantity required and time of consumption relative to the time required for production (value from 0 to 1)

outputs: List[InputOutput]

list of output product names, quantity required and when it becomes available relative to the time required for production (value from 0 to 1)

historical_cost: float | None

Average cost for running this process in some world. Filled by the world

__str__()[source]

String representation is simply the name

__post_init__()[source]
__hash__()[source]

The hash depends only on the name

class scml.InputOutput[source]

An input/output to a production process

__slots__ = ['product', 'quantity', 'step']
product: int

Index of the product used as input or output

quantity: int

Quantity needed/produced

step: float

Relative time within the production at which the input is needed (output is produced)

class scml.RunningCommandInfo[source]
property n_steps: int
property is_none
__slots__ = ['profile', 'beg', 'end', 'action', 'updates', 'step', 'paused']
profile: ManufacturingProfile

The manufacturing profile associated with this command. Most importantly, it gives the process and line

beg: int

The time the command is to be executed

end: int

The number of steps starting at beg for this command to end (it ends at end - 1)

step: int

The time-step relative to beg at the factory is currently executing the Process indicated in profile. step will always go up by one every simulation step except if the command is paused where it does not change

paused: bool

True if the command is paused

action: str

The command type. For the current implementation it will always be run or none for no command

updates: Dict[int, FactoryStatusUpdate]

The status updates implied by this command with their times relative to beg

ended_before(t: int)[source]
started_on_or_after(t: int)[source]
__str__()[source]

Return str(self).

classmethod do_nothing()[source]
scml.INVALID_STEP[source]
scml.NO_PRODUCTION[source]
class scml.ManufacturingProfile[source]

The costs/time required for running a process on a line (with associated cancellation costs etc). This data-structure carries full information about the Process es instead of just its index as in ManufacturingProfileCompiled. It is intended to be used to construct factories

See also

Factory

__slots__ = ['n_steps', 'cost', 'initial_pause_cost', 'running_pause_cost', 'resumption_cost',...
n_steps: int

Number of steps needed to complete the manufacturing

cost: float

Cost of manufacturing

initial_pause_cost: float

Cost of pausing incurred only at the step a pause is started

running_pause_cost: float

Running cost of pausing

resumption_cost: float

Cost of resuming a process

cancellation_cost: float

Cost of cancelling the process before the last step

line: int

The line index

process: Process

The Process associated with this profile

class scml.ManufacturingProfileCompiled[source]

The costs/time required for running a process on a line (with associated cancellation costs etc).

See also

Factory

__slots__ = ['n_steps', 'cost', 'initial_pause_cost', 'running_pause_cost', 'resumption_cost',...
n_steps: int

Number of steps needed to complete the manufacturing

cost: float

Cost of manufacturing

initial_pause_cost: float

Cost of pausing incurred only at the step a pause is started

running_pause_cost: float

Running cost of pausing

resumption_cost: float

Cost of resuming a process

cancellation_cost: float

Cost of cancelling the process before the last step

line: int

The line index

process: int

The Process index

classmethod from_manufacturing_profile(profile: ManufacturingProfile, process2ind: Dict[Process, int])[source]
class scml.ProductManufacturingInfo[source]

Gives full information about a manufacturing process that can generate or consume a product.

See also

consuming and producing of Factory

__slots__ = ['profile', 'quantity', 'step']
profile: int

The ManufacturingProfile index

quantity: int

The quantity generated/consumed by running this manufacturing info

step: int

The step from the beginning at which the Product is received/consumed

class scml.FactoryStatusUpdate[source]
property is_empty
__slots__ = ['balance', 'storage']
balance: float

The update to the balance

storage: Dict[int, int]

The updates to be applied to the storage after this step

__post_init__()[source]
make_empty() None[source]

Makes the update an empty one.

combine(other: FactoryStatusUpdate) None[source]

Combines this status update with another one in place

Parameters:

other – The other status update

Returns:

None

classmethod combine_sets(dst: Dict[int, FactoryStatusUpdate], src: Dict[int, FactoryStatusUpdate])[source]

Combines a set of updates over time with another in place (overriding first) :param dst: First set of updates to be combined into :param src: second set of updates to be combined from

Returns:

classmethod empty()[source]
__str__()[source]

Return str(self).

class scml.Job[source]

Describes a job to be run on one production line of a Factory.

__slots__ = ['profile', 'time', 'line', 'action', 'contract', 'override']
profile: int

The process for run commands

time: int

The time the command is to be executed

line: int

Index of the line on which the job is to be scheduled. Notice that it will be ignored for run actions.

action: str

The command type. For the current implementation it can be run/pause/resume/stop/cancel with cancel cancelling any other command type.

contract: negmas.situated.Contract | None

The sell contract associated with the command

override: bool

Whether to override existing commands when the job is to be executed.

__str__()[source]

Return str(self).

is_cancelling(job: Job) bool[source]

Determines if the given jobs cancels this one

Parameters:

job

Returns:

class scml.ProductionNeed[source]

Describes some quantity of a product that is needed to honor a (sell) contract.

__slots__ = ['product', 'needed_for', 'quantity_to_buy', 'quantity_in_storage', 'step']
product: int

The product needed

needed_for: negmas.situated.Contract

The contract for which the product is needed

quantity_to_buy: int

The quantity need to be bought

quantity_in_storage: int

The quantity already found in storage

step: int

The time step at which the product is needed

__str__()[source]

String representation is simply the name

class scml.MissingInput[source]
__slots__ = ['product', 'quantity']
product: int
quantity: int
__str__()[source]

Return str(self).

class scml.ProductionReport[source]
property failed
property is_empty
property no_production
line: int

ID of the line

started: RunningCommandInfo | None

Commands started

continuing: RunningCommandInfo | None

Command that is continuing

finished: RunningCommandInfo | None

Command finished

failure: ProductionFailure | None

Failures

updates: FactoryStatusUpdate

Updates applied to the factory

__str__()[source]

Return str(self).

class scml.ProductionFailure[source]
__slots__ = ['line', 'command', 'missing_inputs', 'missing_money', 'missing_space']
line: int

ID of the line that failed

command: RunningCommandInfo

Information about the command that failed

missing_inputs: List[MissingInput]

The missing inputs if any with their quantities

missing_money: float

The amount of money needed for production that is not available

missing_space: int

The amount space needed in storage but not found

__str__()[source]

Return str(self).

class scml.FinancialReport[source]

Reports that financial standing of an agent at a given time in the simulation

property balance

The balance of the agent defined as the difference between its available cash + inventory and its liabilities

Remarks:

  • If the inventory was not calculated (due to having at least one product with unknown catalog price), it is used as zero in the equation.

agent: str

Agent ID

step: int

Time of the report

cash: float

Cash at hand

liabilities: float

Total liabilities (loans)

inventory: float

Value of everything in the inventory priced at catalog prices.

credit_rating: float

The agent’s credit rating as a fraction of the maximum credit rating (1 indicates highest credit rating).

class scml.SCMLAgreement[source]
time: int

delivery time

unit_price: float

unit price

quantity: int

quantity

penalty: float | None

penalty

signing_delay: int

Delay between agreement conclusion and signing it to be binding

__getitem__(k)[source]
get(k, default=None)[source]
asdict()[source]
to_dict()[source]
keys()[source]
values()[source]
items()[source]
class scml.SCMLAction[source]
line: str

Line to execute the action on (need not be given if the profile is given

profile: int | None

Index of the profile to execute

action: str

The action which may be start, stop, pause, resume

time: int = 0

Time to execute the action at

class scml.CFP[source]

A Call for proposal upon which a negotiation can start

property issues

Returns the set of issues associated with this CFP. Notice that some of the issues may have a single value

property outcomes
property min_time
property max_time
property min_quantity
property max_quantity
property min_unit_price
property max_unit_price
property min_signing_delay
property max_signing_delay
property min_penalty
property max_penalty
is_buy: bool

If true, the author wants to buy otherwise to sell. Non-negotiable.

publisher: str

the publisher name. Non-negotiable.

product: int

product ID. Non-negotiable.

time: int | Tuple[int, int] | List[int]

delivery time. May be negotiable.

unit_price: float | Tuple[float, float] | List[float]

unit price. May be negotiable.

quantity: int | Tuple[int, int] | List[int]

quantity. May be negotiable.

penalty: float | Tuple[float, float] | List[float] | None

penalty per missing item in case the seller cannot provide the required quantity. May be negotiable.

signing_delay: int | Tuple[int, int] | List[int] | None

The grace period after which the agents are asked to confirm signing the contract

money_resolution: float | None

If not None then it is the minimum unit of money (e.g. 1 for dollar, 0.01 for cent, etc)

id: str

Unique CFP ID

__str__()[source]

Return str(self).

satisfies(query: Dict[str, Any]) bool[source]

Tests whether the CFP satisfies the conditions set by the query

Parameters:

query – A dictionary given the conditions. See Remarks for details

Remarks:

  • The query dictionary can be used to specify any conditions that are required in the CFP. Only CFPs that satisfy ALL the conditions specified in the query are considered satisfying the query. The following keys can be set with corresponding meanings:

    is_buy

    True or False. If both are OK, just do not add this key

    publisher

    A string or SCML2019Agent specifying a specific publisher

    publishers

    A list of publishers (see publisher key)

    product

    A string specifying a product name

    products

    A list of products (see product key)

    time

    A number, list or 2-items-tuple (range) specifying possible times to consider satisfactory

    unit_price

    A number, list or 2-items-tuple (range) specifying possible prices to consider satisfactory

    quantity

    A number, list or 2-items-tuple (range) specifying possible quantities to consider OK

    penalty

    A number, list or 2-items-tuple (range) specifying possible penalties to consider satisfactory

to_dict()[source]
classmethod from_dict(idict: Dict[str, Any], class_name: str | None = None) CFP[source]
class scml.Loan[source]
amount: float

Loan amount

starts_at: int

The time-step at which payment starts

total: float

The total to be paid including the amount + interests

interest: float

The interest rate per step

installment: float

The amount to be paid in one installment

n_installments: int

The number of installments

__str__()[source]

Return str(self).

class scml.InsurancePolicy[source]
premium: float
contract: negmas.situated.Contract
at_time: int
against: scml.scml2019.agent.SCML2019Agent
class scml.Factory[source]

Represents a factory within an SCML world. It is only accessed by the SCML2020World so it need not be made public.

property hidden_money: float
property hidden_storage: Dict[int, int]
property n_lines: int
property jobs: Dict[Tuple[int, int], Job]
property commands: numpy.ndarray
property line_schedules: numpy.ndarray
property wallet: float
property storage: Dict[int, int]
property loans: float
property total_storage: int
property balance: float

The total balance of the factory

property total_balance: float

total balance including hidden money

property next_step: int
initial_storage: dataclasses.InitVar[Dict[int, int]]

Initial storage

initial_wallet: dataclasses.InitVar[float] = 0.0

Initial Wallet

id: str

Object name

profiles: List[ManufacturingProfile]

A list of profiles used to initialize the factory

max_storage: int

Maximum storage allowed in this factory

min_storage: int = 0

Minimum allowed storage per product

min_balance: int | float = 0

Minimum allowed balance

initial_balance: float

Initial balance of the factory

_commands: numpy.ndarray

The production command currently running

_line_schedules: numpy.ndarray
_storage: Dict[int, int]

Mapping from product index to the amount available in the inventory

_total_storage: int

Total storage

_wallet: float

Money available for purchases

_hidden_money: float

Amount of money hidden by the agent

_hidden_storage: Dict[int, int]

Mapping from product index to the amount hidden by the agent

_loans: float

The total money owned as loans

_n_lines: int

The number of lines in the factory, will be set using the profiles input

_jobs: Dict[Tuple[int, int], Job]

The jobs waiting to be run on the factory indexed by (time, line) tuples

_next_step: int

Current simulation step

_carried_updates: FactoryStatusUpdate

Carried updates from last executed command

_world: negmas.situated.World
attach_to_world(world)[source]
__post_init__(initial_storage: Dict[int, int], initial_wallet=0.0)[source]
add_loan(total: float) None[source]
receive(payment: float) None[source]
pay(payment: float) None[source]
transport_to(product: int, quantity: int) None[source]
buy(product: int, quantity: int, price: float) None[source]
sell(product: int, quantity: int, price: float) None[source]
transport_from(product: int, quantity: int) None[source]
hide_funds(amount: float) None[source]
hide_product(product: int, quantity: int) None[source]
unhide_funds(amount: float) None[source]
unhide_product(product: int, quantity: int) None[source]
schedule(job: Job, override=False) None[source]

Schedules the given job at its time and line optionally overriding whatever was already scheduled :param job: :param override:

Returns:

Success/failure

_apply_updates(updates: FactoryStatusUpdate) None[source]
step() List[ProductionReport][source]
_run(profile: ManufacturingProfile, override=True) None[source]

running is executed at the beginning of the step t

Parameters:
  • profile – the profile to start giving both the line and process

  • override – If true, override any running processes paying cancellation cost for these processes

Remarks:

  • The output of a process that runs from step t to step t + n - 1 will only be in storage at step t + n

_pause(line: int) None[source]

pausing is executed at the end of the step

Parameters:

line – the line on which the process is running

Returns:

The status updated for all times that need to be updated to cancel the command if it is not None. If None is returned then scheduling failed.

Return type:

Optional[Dict[int, FactoryStatusUpdate]]

Remarks:

  • Not implemented yet

  • pausing when nothing is running is not an error and will return an empty status update

_resume(line: int) None[source]

resumption is executed at the end of the step (starting next step count down)

Parameters:

line – the line on which the process is running

Returns:

The status updated for all times that need to be updated to cancel the command if it is not None. If None is returned then scheduling failed.

Return type:

Optional[Dict[int, FactoryStatusUpdate]]

Remarks:

  • Not implemented yet

  • resuming when nothing is paused is not an error and will return an empty status update

_stop(line: int) None[source]

stopping is executed at the beginning of the current step

Parameters:

line – the line on which the process is running

Returns:

The status updated for all times that need to be updated to cancel the command if it is not None. If None is returned then scheduling failed.

Return type:

Optional[Dict[int, FactoryStatusUpdate]]

Remarks:

  • stopping when nothing is running is not an error and will just return an empty schedule

_step_line(line: int) ProductionReport[source]

Steps the line to the time-step t assuming that it is already stepped to time-step t-1 given the storage

Parameters:

line – the line to step

Returns:

ProductionReport

class scml.FactoryState[source]

Read Only State of a factory

max_storage: int

Maximum storage allowed in this factory

line_schedules: numpy.ndarray

An array of n_lines * n_steps giving the line schedules

storage: Dict[int, int]

Mapping from product index to the amount available in the inventory

wallet: float

Money available for purchases

hidden_money: float

Amount of money hidden by the agent

hidden_storage: Dict[int, int]

Mapping from product index to the amount hidden by the agent

loans: float

The total money owned as loans

n_lines: int

The number of lines in the factory, will be set using the profiles input

profiles: List[ManufacturingProfile]

A list of profiles used to initialize the factory

next_step: int

Next simulation step for this factory

commands: numpy.ndarray

The production command currently running

jobs: Dict[Tuple[int, int], Job]

The jobs waiting to be run on the factory indexed by (time, line) tuples

scml.DEFAULT_NEGOTIATOR = 'negmas.sao.AspirationNegotiator'[source]
class scml.Consumer(name: str | None = None, ufun: negmas.UtilityFunction | None = None)[source]

Bases: scml.scml2019.agent.SCML2019Agent, abc.ABC

Base class of all consumer classes

class scml.ConsumptionProfile[source]
schedule: int | List[int] = 0
underconsumption: float = 0.1
overconsumption: float = 0.01
dynamicity: float = 0.0
cv: float = 0.1
alpha_q: float = 0.5
alpha_u: float = 1.0
beta_q: float = 10.0
beta_u: float = 10.0
tau_q: float = 2
tau_u: float = 0.25
classmethod random()[source]
schedule_at(time: int) int[source]
schedule_within(time: int | List[int] | Tuple[int, int]) int[source]
set_schedule_at(time: int, value: int, n_steps: int) None[source]
class scml.JustInTimeConsumer(profiles: Dict[int, ConsumptionProfile] = None, negotiator_type=DEFAULT_NEGOTIATOR, consumption_horizon: int | None = 20, immediate_cfp_update: bool = True, name=None)[source]

Bases: Consumer

Consumer class

MAX_UNIT_PRICE = 100.0
RELATIVE_MAX_PRICE = 1.5
on_contract_executed(contract: negmas.situated.Contract) None[source]

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

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

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

Parameters:
  • contract – The contract

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

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

on_inventory_change(product: int, quantity: int, cause: str) None[source]

Received whenever something moves in or out of the factory’s storage

Parameters:
  • product – Product index.

  • quantity – Negative value for products moving out and positive value for products moving in

  • cause

    The cause of the change. Possibilities include:

    • contract: Contract execution

    • insurance: Received from insurance company

    • bankruptcy: Liquidated due to bankruptcy

    • transport: Arrival of goods (when transportation delay in the system is > 0).

on_cash_transfer(amount: float, cause: str) None[source]

Received whenever money is transferred to the factory or from it.

Parameters:
  • amount – Amount of money (negative for transfers out of the factory, positive for transfers to it).

  • cause

    The cause of the change. Possibilities include:

    • contract: Contract execution

    • insurance: Received from insurance company

    • bankruptcy: Liquidated due to bankruptcy

    • transfer: Arrival of transferred money (when transfer delay in the system is > 0).

on_new_report(report: scml.scml2019.common.FinancialReport)[source]

Called whenever a financial report is published.

Parameters:

report – The financial report giving details of the standing of an agent at some time (see FinancialReport)

Remarks:

on_neg_request_rejected(req_id: str, by: List[str] | None)[source]

Called when a requested negotiation is rejected

Parameters:
  • req_id – The request ID passed to _request_negotiation

  • by – A list of agents that refused to participate or None if the failure was for another reason

on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface)[source]

Called when a requested negotiation is accepted

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

Called whenever a negotiation ends without agreement

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

Called whenever a negotiation ends with agreement

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

Called whenever at least a partner did not sign the contract

on_contract_nullified(contract: negmas.situated.Contract, bankrupt_partner: str, compensation: float) None[source]

Will be called whenever a contract the agent is involved in is nullified because another partner went bankrupt

on_agent_bankrupt(agent_id: str) None[source]

Will be called whenever any agent goes bankrupt

Parameters:

agent_id – The ID of the agent that went bankrupt

Remarks:

  • Agents can go bankrupt in two cases:

    1. Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it.

    2. Failing to pay a penalty on a sell contract they failed to honor (and refusing or being unable to get a loan to pay for it).

  • All built-in agents ignore this call and they use the bankruptcy list ONLY to decide whether or not to negotiate in their on_new_cfp and respond_to_negotiation_request callbacks by pulling the bulletin-board using the helper function is_bankrupt of their AWI.

confirm_partial_execution(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach]) bool[source]

Will be called whenever a contract cannot be fully executed due to breaches by the other partner.

Parameters:
  • contract – The contract that was breached

  • breaches – A list of all the breaches committed.

Remarks:

  • Will not be called if both partners committed breaches.

on_remove_cfp(cfp: scml.scml2019.common.CFP)[source]

Called when a new CFP for a product for which the agent registered interest is removed

on_new_cfp(cfp: scml.scml2019.common.CFP) None[source]

Called when a new CFP for a product for which the agent registered interest is published

init()[source]

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

set_profiles(profiles: Dict[int, ConsumptionProfile])[source]
register_product_cfps(p: int, t: int, profile: ConsumptionProfile)[source]
step()[source]

Called by the simulator at every simulation step

confirm_contract_execution(contract: negmas.situated.Contract) bool[source]

Called before executing any agreement

static _qufun(outcome: Dict[str, Any], tau: float, profile: ConsumptionProfile)[source]

The ufun value for quantity

respond_to_negotiation_request(cfp: scml.scml2019.common.CFP, partner: str) negmas.negotiators.Negotiator | None[source]

Called when a prospective partner requests a negotiation to start

set_renegotiation_agenda(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach]) negmas.situated.RenegotiationRequest | None[source]

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

Parameters:
  • contract – The contract that was breached about which re-negotiation is offered

  • breaches – The list of breaches by all parties for the breached contract.

Returns:

None if renegotiation is not to be started, otherwise a re-negotiation agenda.

respond_to_renegotiation_request(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach], agenda: negmas.situated.RenegotiationRequest) negmas.negotiators.Negotiator | None[source]

Called to respond to a renegotiation request

Parameters:
  • agenda – Renegotiation agenda (issues to renegotiate about).

  • contract – The contract that was breached

  • breaches – All breaches on that contract

Returns:

None to refuse to enter the negotiation, otherwise, a negotiator to use for this negotiation.

confirm_loan(loan: scml.scml2019.common.Loan, bankrupt_if_rejected: bool) bool[source]

called by the world manager to confirm a loan if needed by the buyer of a contract that is about to be breached

sign_contract(contract: negmas.situated.Contract) str | None[source]

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

on_contract_signed(contract: negmas.situated.Contract)[source]

Called whenever a contract is signed by all partners

class scml.FactoryManager(name=None, simulator_type: str | Type[scml.scml2019.simulators.FactorySimulator] = FastFactorySimulator)[source]

Bases: scml.scml2019.agent.SCML2019Agent, abc.ABC

Base factory manager class that will be inherited by participant negmas in ANAC 2019.

The agent can access the world simulation in one of two ways:

  1. Attributes and methods available in the Agent-SCML2020World-Interface (See SCMLAWI documentation for those).

  2. Attributes and methods in the FactoryManager object itself. All factory managers will have the following attributes and methods that simplify the interaction with the world simulation. Some of these attributes/methods are convenient ways to access functionality already available in the agent’s internal SCMLAWI.

Attributes

Agent information

  • id : The unique ID assigned to this agent. This is unique system-wide and is what is used in contracts, CFPs, etc.

  • name: A name of the agent used for display purposes only. The simulator never accesses or uses this name except in printing and logging.

  • uuid : Another name of the id .

  • type_name : A string giving the type of the agent (as a fully qualified python class name).

Capabilities/Profiles

  • line_profiles : A mapping specifying for each line index, all the profiles that can be run on it

  • process_profiles : A mapping specifying for each Process index, all the profiles used to run it in the factory

  • producing : Mapping from a product index to all manufacturing processes that can generate it

  • consuming : Mapping from a product index to all manufacturing processes that can consume it

  • compiled_profiles : All the profiles to be used by the factory belonging to this agent compiled to use process indices

  • max_storage : Maximum storage available to the agent. Zero, None or float(‘inf’) all indicate unlimited storage.

Production Graph (also accessible through awi)

  • products : List of products in the system

  • processes : List of processes in the system

Helper Objects

  • awi : The SCMLAWI instance assigned to this agent. It can be used to interact with the simulation (See SCMLAWI documentation).

  • simulator : A FactorySimulator object that can be used to simulate what happens in the Factory assigned to this agent when given operations are conducted (e.g. production, paying money, etc).

Negotiations/Contracts

  • requested_negotiations : A dynamic list of negotiations currently requested by the agent but not started. Correct management of this list is only possible if the agent **always* uses request_negotiation method of this class (see methods later) rather than directly calling request_method on the SCMLAWI ( awi ) member.

  • running_negotiations : A dynamic list of negotiations currently running involving this agent. Correct management of this list is only possible if the agent **always* uses request_negotiation method of this class (see methods later) rather than directly calling request_method on the SCMLAWI ( awi ) member.

  • unsigned_contracts : A dynamic list of negotiations contracts concluded involving this agent but not yet signed. Correct management of this list is only possible if the agent **always* uses request_negotiation method of this class (see methods later) rather than directly calling request_method on the SCMLAWI ( awi ) member.

Simulation attributes (also accessible through awi)

Methods (Callable by the agent)

Actions on the world

Scheduling and simulation helpers

  • can_expect_agreement : Checks if it is possible in principle to get an agreement on this CFP by the time it becomes executable.

Callbacks (Callable by the simulation)

Decision callbacks (Called to make decisions)

  • Negotiation and Contracts

    • respond_to_negotiation_request : Decide whether or not to engage in a negotiation on a CFP that was published earlier by this factory manager. If accepted, the agent should return a SAONegotiator object.

    • sign_contract : Decide whether or not to sign the contract. If accepted, the agent should return its own ID.

    • confirm_contract_execution : Decide whether or not to go on with executing a contract that the agent already signed. If rejected (by returning False ), a refusal-to-execute breach will be recorded.

  • Breach related

    • confirm_partial_execution : Decide whether the agent agrees to partial execution. Called only when the the partner of this agent commits a partial breach (of level < 1) and this agent commits no breaches.

    • set_renegotiation_agenda : Decide what are the issues and ranges of acceptable values to re-negotiate about. Called only in case of breaches.

    • respond_to_renegotiation_request : Decide whether or not to engage in a re-negotiation.

  • Financial

    • confirm_loan : Decide whether or not to accept an offered loan. *In ANAC 2019 league, loans are not allowed and this callback will never be called by the simulator.

Time-dependent callbacks (Information callback called at predefined times)

  • init : Called once before any production or negotiations to initiate the agent.

  • step : Called at every production step.

Information callbacks (Called to inform the agent about events)

  • CFP related

    • on_new_cfp : Called whenever a CFP on a Product for which the agent has already registered interest (using register_interest method of its awi) is published. By default all agents register interest in the products they can consume or produce according to their profiles.

    • on_remove_cfp : Called whenever a CFP on a Product for which the agent has already registered interest (using register_interest method of its awi) is removed from the bulletin-board.

  • Negotiation related

  • Contract related

    • on_contract_cancelled : Called whenever a Contract of which the agent is a party is cancelled because the other party refused to sign it.

    • on_contract_signed : Called whenever a Contract of which the agent is a party is signed by both patners.

    • on_contract_nullified : Called whenever a Contract of which the agent is a party is nullified by the simulator as a part of bankruptcy processing.

    • on_contract_executed : Called when a contract executes completely and successfully.

    • on_contract_breached : Called when a contract is breached after complete contract processing.

  • Production and factory related

    • on_production_failure : Called whenever a scheduled production (see SCMLAWI for production commands) fails

    • on_inventory_change : Called whenever there is a change in the inventory (something is moved in or out or out of storage due to an event other than production (e.g. contract execution).

    • on_cash_transfer : Called whenever cash is transferred to or from the factory’s wallet.

  • About other agents

transportation_delay = 0

Transportation delay in the world

simulator: scml.scml2019.simulators.FactorySimulator | None

The simulator used by this agent

simulator_type: Type[scml.scml2019.simulators.FactorySimulator]

Simulator type (as a class)

current_step = 0

Current simulation step

max_storage: int = 0

Maximum storage available to the agent

init_()[source]

The initialization function called by the world directly.

It does the following actions by default:

  1. copies some of the static world settings to the agent to make them available without calling the AWI.

  2. prepares production related properties like producing, consuming, line_profiles, compiled_profiles, etc.

  3. registers interest in all products that the agent can produce or consume in its factory.

  4. finally it calls any custom initialization logic implemented in `init`()

See also

init, step

step_()[source]

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

abstract on_production_failure(failures: List[scml.scml2019.common.ProductionFailure]) None[source]

Called with a list of ProductionFailure records on production failure.

abstract on_production_success(reports: List[scml.scml2019.common.ProductionReport]) None[source]

Called with a list of ProductionReport records on production success

class scml.DoNothingFactoryManager(name=None, simulator_type: str | Type[scml.scml2019.simulators.FactorySimulator] = FastFactorySimulator)[source]

Bases: FactoryManager

The default factory manager that will be implemented by the committee of ANAC-SCML 2019

init()[source]

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

step()[source]

Called by the simulator at every simulation step

on_neg_request_rejected(req_id: str, by: List[str] | None)[source]

Called when a requested negotiation is rejected

Parameters:
  • req_id – The request ID passed to _request_negotiation

  • by – A list of agents that refused to participate or None if the failure was for another reason

on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface)[source]

Called when a requested negotiation is accepted

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

Called whenever a negotiation ends without agreement

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

Called whenever a negotiation ends with agreement

on_contract_signed(contract: negmas.Contract) None[source]

Called whenever a contract is signed by all partners

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

Called whenever at least a partner did not sign the contract

on_contract_executed(contract: negmas.Contract) None[source]

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

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

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

Parameters:
  • contract – The contract

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

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

sign_contract(contract: negmas.Contract) str | None[source]

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

on_contract_nullified(contract: negmas.Contract, bankrupt_partner: str, compensation: float) None[source]

Will be called whenever a contract the agent is involved in is nullified because another partner went bankrupt

on_agent_bankrupt(agent_id: str) None[source]

Will be called whenever any agent goes bankrupt

Parameters:

agent_id – The ID of the agent that went bankrupt

Remarks:

  • Agents can go bankrupt in two cases:

    1. Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it.

    2. Failing to pay a penalty on a sell contract they failed to honor (and refusing or being unable to get a loan to pay for it).

  • All built-in agents ignore this call and they use the bankruptcy list ONLY to decide whether or not to negotiate in their on_new_cfp and respond_to_negotiation_request callbacks by pulling the bulletin-board using the helper function is_bankrupt of their AWI.

confirm_partial_execution(contract: negmas.Contract, breaches: List[negmas.Breach]) bool[source]

Will be called whenever a contract cannot be fully executed due to breaches by the other partner.

Parameters:
  • contract – The contract that was breached

  • breaches – A list of all the breaches committed.

Remarks:

  • Will not be called if both partners committed breaches.

on_remove_cfp(cfp: scml.scml2019.common.CFP) None[source]

Called when a new CFP for a product for which the agent registered interest is removed

on_production_failure(failures: List[scml.scml2019.common.ProductionFailure]) None[source]

Called with a list of ProductionFailure records on production failure.

respond_to_negotiation_request(cfp: scml.scml2019.common.CFP, partner: str) negmas.Negotiator | None[source]

Called when a prospective partner requests a negotiation to start

confirm_contract_execution(contract: negmas.Contract) bool[source]

Called before executing any agreement

set_renegotiation_agenda(contract: negmas.Contract, breaches: List[negmas.Breach]) negmas.RenegotiationRequest | None[source]

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

Parameters:
  • contract – The contract being breached

  • breaches – All breaches on contract

Returns:

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

respond_to_renegotiation_request(contract: negmas.Contract, breaches: List[negmas.Breach], agenda: negmas.RenegotiationRequest) negmas.Negotiator | None[source]

Called to respond to a renegotiation request

Parameters:
  • agenda

  • contract

  • breaches

Returns:

confirm_loan(loan: scml.scml2019.common.Loan, bankrupt_if_rejected: bool) bool[source]

called by the world manager to confirm a loan if needed by the buyer of a contract that is about to be breached

on_new_cfp(cfp: scml.scml2019.common.CFP) None[source]

Called when a new CFP for a product for which the agent registered interest is published

on_inventory_change(product: int, quantity: int, cause: str) None[source]

Received whenever something moves in or out of the factory’s storage

Parameters:
  • product – Product index.

  • quantity – Negative value for products moving out and positive value for products moving in

  • cause

    The cause of the change. Possibilities include:

    • contract: Contract execution

    • insurance: Received from insurance company

    • bankruptcy: Liquidated due to bankruptcy

    • transport: Arrival of goods (when transportation delay in the system is > 0).

on_production_success(reports: List[scml.scml2019.common.ProductionReport]) None[source]

Called with a list of ProductionReport records on production success

on_cash_transfer(amount: float, cause: str) None[source]

Received whenever money is transferred to the factory or from it.

Parameters:
  • amount – Amount of money (negative for transfers out of the factory, positive for transfers to it).

  • cause

    The cause of the change. Possibilities include:

    • contract: Contract execution

    • insurance: Received from insurance company

    • bankruptcy: Liquidated due to bankruptcy

    • transfer: Arrival of transferred money (when transfer delay in the system is > 0).

on_new_report(report: scml.scml2019.common.FinancialReport)[source]

Called whenever a financial report is published.

Parameters:

report – The financial report giving details of the standing of an agent at some time (see FinancialReport)

Remarks:

class scml.GreedyFactoryManager(name=None, simulator_type: str | Type[scml.scml2019.simulators.FactorySimulator] = FastFactorySimulator, scheduler_type: str | Type[scml.scml2019.schedulers.Scheduler] = GreedyScheduler, scheduler_params: Dict[str, Any] | None = None, optimism: float = 0.0, negotiator_type: str | Type[negmas.Negotiator] = DEFAULT_NEGOTIATOR, negotiator_params: Dict[str, Any] | None = None, n_retrials=5, use_consumer=True, reactive=True, sign_only_guaranteed_contracts=False, riskiness=0.0, max_insurance_premium: float = 0.1, reserved_value: float = -float('inf'))[source]

Bases: DoNothingFactoryManager

The default factory manager that will be implemented by the committee of ANAC-SCML 2019

on_production_failure(failures: List[scml.scml2019.common.ProductionFailure]) None[source]

Called with a list of ProductionFailure records on production failure.

on_production_success(reports: List[scml.scml2019.common.ProductionReport]) None[source]

Called with a list of ProductionReport records on production success

confirm_loan(loan: scml.scml2019.common.Loan, bankrupt_if_rejected: bool) bool[source]

called by the world manager to confirm a loan if needed by the buyer of a contract that is about to be breached

confirm_contract_execution(contract: negmas.Contract) bool[source]

Called before executing any agreement

set_renegotiation_agenda(contract: negmas.Contract, breaches: List[negmas.Breach]) negmas.RenegotiationRequest | None[source]

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

Parameters:
  • contract – The contract being breached

  • breaches – All breaches on contract

Returns:

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

respond_to_renegotiation_request(contract: negmas.Contract, breaches: List[negmas.Breach], agenda: negmas.RenegotiationRequest) negmas.Negotiator | None[source]

Called to respond to a renegotiation request

Parameters:
  • agenda

  • contract

  • breaches

Returns:

total_utility(contracts: Collection[negmas.Contract] = ()) float[source]

Calculates the total utility for the agent of a collection of contracts

init()[source]

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

respond_to_negotiation_request(cfp: scml.scml2019.common.CFP, partner: str) negmas.Negotiator | None[source]

Called when a prospective partner requests a negotiation to start

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

Called whenever a negotiation ends with agreement

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

Called whenever a negotiation ends without agreement

_execute_schedule(schedule: scml.scml2019.schedulers.ScheduleInfo, contract: negmas.Contract) None[source]
sign_contract(contract: negmas.Contract)[source]

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

on_contract_signed(contract: negmas.Contract)[source]

Called whenever a contract is signed by all partners

_process_buy_cfp(cfp: scml.scml2019.common.CFP) None[source]
_process_sell_cfp(cfp: scml.scml2019.common.CFP)[source]
on_new_cfp(cfp: scml.scml2019.common.CFP) None[source]

Called when a new CFP for a product for which the agent registered interest is published

step()[source]

Called by the simulator at every simulation step

can_produce(cfp: scml.scml2019.common.CFP, assume_no_further_negotiations=False) bool[source]

Whether or not we can produce the required item in time

can_secure_needs(schedule: scml.scml2019.schedulers.ScheduleInfo, step: int)[source]

Finds if it is possible in principle to arrange these needs at the given time.

Parameters:
  • schedule

  • step

Returns:

scml.pos_gauss(mu, sigma)[source]

Returns a sample from a rectified gaussian

scml._safe_max(a, b)[source]
scml.zero_runs(a: numpy.array) numpy.array[source]

Finds all runs of zero in an array

Parameters:

a – Input array (assumed to be 1D)

Returns:

A 2D array giving beginning and end (exclusive) of zero stretches in the input array.

Return type:

np.array

class scml.DefaultInsuranceCompany(premium: float, premium_breach_increment: float, premium_time_increment: float, a2f: Dict[str, scml.scml2019.common.Factory], disabled=False, name: str = None)[source]

Bases: InsuranceCompany

Represents an insurance company in the world

init()[source]

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

set_renegotiation_agenda(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach]) negmas.situated.RenegotiationRequest | None[source]

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

Parameters:
  • contract – The contract being breached

  • breaches – All breaches on contract

Returns:

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

respond_to_renegotiation_request(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach], agenda: negmas.situated.RenegotiationRequest) negmas.negotiators.Negotiator | None[source]

Called to respond to a renegotiation request

Parameters:
  • agenda

  • contract

  • breaches

Returns:

evaluate_insurance(contract: negmas.situated.Contract, insured: scml.scml2019.agent.SCML2019Agent, against: scml.scml2019.agent.SCML2019Agent, t: int = None) float | None[source]

Can be called to evaluate the premium for insuring the given contract against breaches committed by others

Parameters:
  • against – The SCML2019Agent to insure against

  • contract – hypothetical contract

  • insured – The SCML2019Agent to buy the insurance

  • t – time at which the policy is to be bought. If None, it means current step

Remarks:

  • The premium returned is relative to the contract price. To actually calculate the cost of buying this insurance, you need to multiply this by the contract value (quantity * unit_price).

buy_insurance(contract: negmas.situated.Contract, insured: scml.scml2019.agent.SCML2019Agent, against: scml.scml2019.agent.SCML2019Agent) scml.scml2019.common.InsurancePolicy | None[source]

Buys insurance for the contract at the premium calculated by the insurance company.

Remarks:

The agent can call evaluate_insurance to find the premium that will be used.

See also

evaluate_premium

is_insured(contract: negmas.situated.Contract, perpetrator: scml.scml2019.agent.SCML2019Agent) bool[source]
Parameters:
  • contract

  • perpetrator

Returns:

step()[source]

does nothing

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

Bases: negmas.situated.Agent, abc.ABC

Base class for all insurance companies

_respond_to_negotiation_request(initiator: str, partners: List[str], issues: List[negmas.outcomes.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, role: str | None, req_id: str | None) negmas.negotiators.Negotiator | None[source]

Called by the mechanism to ask for joining a negotiation. The agent can refuse by returning a None

Parameters:
  • initiator – The ID of the agent that initiated the negotiation request

  • partners – The partner list (will include this agent)

  • issues – The list of issues

  • annotation – Any annotation specific to this negotiation.

  • mechanism – The mechanism that started the negotiation

  • role – The role of this agent in the negotiation

  • req_id – The req_id passed to the AWI when starting the negotiation (only to the initiator).

Returns:

None to refuse the negotiation or a Negotiator object appropriate to the given mechanism to accept it.

Remarks:

  • It is expected that world designers will introduce a better way to respond and override this function to call it

on_neg_request_rejected(req_id: str, by: List[str] | None)[source]

Called when a requested negotiation is rejected

Parameters:
  • req_id – The request ID passed to _request_negotiation

  • by – A list of agents that refused to participate or None if the failure was for another reason

on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface)[source]

Called when a requested negotiation is accepted

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

Called whenever a negotiation ends without agreement

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

Called whenever a negotiation ends with agreement

on_contract_signed(contract: negmas.situated.Contract) None[source]

Called whenever a contract is signed by all partners

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

Called whenever at least a partner did not sign the contract

sign_contract(contract: negmas.situated.Contract) str | None[source]

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

respond_to_negotiation_request(initiator: str, partners: List[str], issues: List[negmas.outcomes.Issue], annotation: Dict[str, Any], mechanism: negmas.Mechanism, role: str | None, req_id: str) negmas.negotiators.Negotiator | None[source]
on_contract_breached(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach], resolution: negmas.situated.Contract | None) None[source]

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

Parameters:
  • contract – The contract

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

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

on_contract_executed(contract: negmas.situated.Contract) None[source]

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

class scml.Miner(name: str | None = None, ufun: negmas.UtilityFunction | None = None)[source]

Bases: scml.scml2019.agent.SCML2019Agent, abc.ABC

Base class of all miners

class scml.MiningProfile[source]
cv: float = 0.05
alpha_t: float = 1.0
alpha_q: float = 1.0
alpha_u: float = 1.0
beta_t: float = 1.0
beta_q: float = 100.0
beta_u: float = 100.0
tau_t: float
tau_q: float = 0.25
tau_u: float = 1.0
classmethod random()[source]
class scml.ReactiveMiner(profiles: dict[int, MiningProfile] | None = None, negotiator_type=DEFAULT_NEGOTIATOR, n_retrials=0, reactive=True, name=None)[source]

Bases: Miner

Raw Material Generator

on_contract_executed(contract: negmas.situated.Contract) None[source]

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

on_contract_breached(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach], resolution: negmas.situated.Contract | None) None[source]

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

Parameters:
  • contract – The contract

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

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

on_inventory_change(product: int, quantity: int, cause: str) None[source]

Received whenever something moves in or out of the factory’s storage

Parameters:
  • product – Product index.

  • quantity – Negative value for products moving out and positive value for products moving in

  • cause

    The cause of the change. Possibilities include:

    • contract: Contract execution

    • insurance: Received from insurance company

    • bankruptcy: Liquidated due to bankruptcy

    • transport: Arrival of goods (when transportation delay in the system is > 0).

on_cash_transfer(amount: float, cause: str) None[source]

Received whenever money is transferred to the factory or from it.

Parameters:
  • amount – Amount of money (negative for transfers out of the factory, positive for transfers to it).

  • cause

    The cause of the change. Possibilities include:

    • contract: Contract execution

    • insurance: Received from insurance company

    • bankruptcy: Liquidated due to bankruptcy

    • transfer: Arrival of transferred money (when transfer delay in the system is > 0).

on_new_report(report: scml.scml2019.common.FinancialReport)[source]

Called whenever a financial report is published.

Parameters:

report – The financial report giving details of the standing of an agent at some time (see FinancialReport)

Remarks:

on_neg_request_rejected(req_id: str, by: list[str] | None)[source]

Called when a requested negotiation is rejected

Parameters:
  • req_id – The request ID passed to _request_negotiation

  • by – A list of agents that refused to participate or None if the failure was for another reason

on_neg_request_accepted(req_id: str, mechanism: negmas.common.NegotiatorMechanismInterface)[source]

Called when a requested negotiation is accepted

on_negotiation_success(contract: negmas.situated.Contract, mechanism: negmas.common.NegotiatorMechanismInterface) None[source]

Called whenever a negotiation ends with agreement

on_contract_signed(contract: negmas.situated.Contract) None[source]

Called whenever a contract is signed by all partners

on_contract_cancelled(contract: negmas.situated.Contract, rejectors: list[str]) None[source]

Called whenever at least a partner did not sign the contract

sign_contract(contract: negmas.situated.Contract) str | None[source]

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

on_contract_nullified(contract: negmas.situated.Contract, bankrupt_partner: str, compensation: float) None[source]

Will be called whenever a contract the agent is involved in is nullified because another partner went bankrupt

on_agent_bankrupt(agent_id: str) None[source]

Will be called whenever any agent goes bankrupt

Parameters:

agent_id – The ID of the agent that went bankrupt

Remarks:

  • Agents can go bankrupt in two cases:

    1. Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it.

    2. Failing to pay a penalty on a sell contract they failed to honor (and refusing or being unable to get a loan to pay for it).

  • All built-in agents ignore this call and they use the bankruptcy list ONLY to decide whether or not to negotiate in their on_new_cfp and respond_to_negotiation_request callbacks by pulling the bulletin-board using the helper function is_bankrupt of their AWI.

confirm_partial_execution(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach]) bool[source]

Will be called whenever a contract cannot be fully executed due to breaches by the other partner.

Parameters:
  • contract – The contract that was breached

  • breaches – A list of all the breaches committed.

Remarks:

  • Will not be called if both partners committed breaches.

on_remove_cfp(cfp: scml.scml2019.common.CFP)[source]

Called when a new CFP for a product for which the agent registered interest is removed

init()[source]

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

on_negotiation_failure(partners: list[str], annotation: dict[str, Any], mechanism: negmas.common.NegotiatorMechanismInterface, state: negmas.common.MechanismState) None[source]

Called whenever a negotiation ends without agreement

set_profiles(profiles: dict[int, MiningProfile])[source]
_process_cfp(cfp: scml.scml2019.common.CFP)[source]
on_new_cfp(cfp: scml.scml2019.common.CFP)[source]

Called when a new CFP for a product for which the agent registered interest is published

step()[source]

Called by the simulator at every simulation step

confirm_contract_execution(contract: negmas.situated.Contract) bool[source]

Called before executing any agreement

respond_to_negotiation_request(cfp: scml.scml2019.common.CFP, partner: str) negmas.negotiators.Negotiator | None[source]

Called when a prospective partner requests a negotiation to start

set_renegotiation_agenda(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach]) negmas.situated.RenegotiationRequest | None[source]

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

Parameters:
  • contract – The contract being breached

  • breaches – All breaches on contract

Returns:

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

respond_to_renegotiation_request(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach], agenda: negmas.situated.RenegotiationRequest) negmas.negotiators.Negotiator | None[source]

Called to respond to a renegotiation request

Parameters:
  • agenda

  • contract

  • breaches

Returns:

confirm_loan(loan: scml.scml2019.common.Loan, bankrupt_if_rejected: bool) bool[source]

called by the world manager to confirm a loan if needed by the buyer of a contract that is about to be breached

class scml.ScheduleInfo[source]
final_balance: float

balance at the end of the schedule

valid: bool = True

Is this a valid schedule?

start: int | None

The starting step of this schedule

end: int | None

The step after the last step in this simulation

needs: List[scml.scml2019.common.ProductionNeed]

The products needed but not still in storage needed to complete this schedule.

jobs: List[scml.scml2019.common.Job]

The jobs that need to be scheduled

failed_contracts: List[negmas.situated.Contract]

A list of contracts that failed to be scheduled.

ignored_contracts: List[negmas.situated.Contract]

A list of contracts ignored for this schedule because they are in the past.

__str__()[source]

Return str(self).

combine(other: ScheduleInfo) None[source]
class scml.Scheduler(manager_id: str, awi: scml.scml2019.awi.SCMLAWI, max_insurance_premium: float = float('inf'), horizon: int | None = None)[source]

Bases: abc.ABC

Base class for all schedulers

bookmark() int[source]

Sets a bookmark to the current location

Returns:

bookmark ID

rollback(bookmark_id: int) bool[source]

Rolls back to the given bookmark ID

Parameters:

bookmark (bookmark_id The bookmark ID returned from) –

Remarks:

  • You can only rollback in the reverse order of bookmarks. If the bookmark ID given here is not the one at the top of the bookmarks stack, the rollback will fail (return False)

delete_bookmark(bookmark_id: int) bool[source]

Commits everything since the bookmark so it cannot be rolled back

Parameters:

bookmark (bookmark_id The bookmark ID returned from) –

Remarks:

  • You can only rollback in the reverse order of bookmarks. If the bookmark ID given here is not the one at the top of the bookmarks stack, the deletion will fail (return False)

init(simulator: scml.scml2019.simulators.FactorySimulator, products: List[scml.scml2019.common.Product], processes: List[scml.scml2019.common.Process], profiles: List[scml.scml2019.common.ManufacturingProfileCompiled], producing: Dict[int, List[scml.scml2019.common.ProductManufacturingInfo]])[source]

Called by the FactoryManager after it is initialized

schedule(contracts: Collection[negmas.situated.Contract] = (), assume_no_further_negotiations=False, ensure_storage_for: int = 0, start_at: int = 0) ScheduleInfo[source]

Schedules a set of contracts and returns either the search_for_schedule or None if infeasible

Parameters:
  • given (whatever it has scheduled before. If the state is) –

  • scheduling (it is taken as the initial state for) –

  • contracts – The contracts to be scheduled

  • assume_no_further_negotiations – whether to assume that more negotiations can take place (to secure

  • needs) (production) –

  • ensure_storage_for – A minimum time to ensure that products are available in storage before contract delivery

  • times (sell contracts) –

  • start_at – The time at which to start scheduling. No jobs will be scheduled before this time.

Returns:

ScheduleInfo describing the schedulo and any production needs and updates to be carried out.

abstract find_schedule(contracts: Collection[negmas.situated.Contract], start: int, end: int, assume_no_further_negotiations=False, ensure_storage_for: int = 0, start_at: int = 0) ScheduleInfo[source]

Schedules a set of contracts and returns either the search_for_schedule or None if infeasible

Parameters:
  • start

  • end

  • contracts

  • assume_no_further_negotiations

  • ensure_storage_for

  • start_at – The time at which to start scheduling. No jobs will be scheduled before this time.

Returns:

Schedule information (See ScheduleInfo for its contents).

class scml.GreedyScheduler(manager_id: str, awi: scml.scml2019.awi.SCMLAWI, max_insurance_premium: float = float('inf'), horizon: int | None = None, add_catalog_prices=True, strategy: str = 'latest', profile_sorter: str = 'total-cost>time')[source]

Bases: Scheduler

Default scheduler used by the DefaultFactoryManager

__getstate__()[source]

Helper for pickle.

__setstate__(state)[source]
init(simulator: scml.scml2019.simulators.FactorySimulator, products: List[scml.scml2019.common.Product], processes: List[scml.scml2019.common.Process], profiles: List[scml.scml2019.common.ManufacturingProfileCompiled], producing: Dict[int, List[scml.scml2019.common.ProductManufacturingInfo]])[source]

Called by the FactoryManager after it is initialized

_profile_sorter(info: scml.scml2019.common.ProductManufacturingInfo) Any[source]
unit_time(info: scml.scml2019.common.ProductManufacturingInfo) float[source]
total_cost(info: scml.scml2019.common.ProductManufacturingInfo) float[source]
total_unit_cost(info: scml.scml2019.common.ProductManufacturingInfo) float[source]
production_cost(info: scml.scml2019.common.ProductManufacturingInfo) float[source]
production_unit_cost(info: scml.scml2019.common.ProductManufacturingInfo) float[source]
input_cost(info: scml.scml2019.common.ProductManufacturingInfo)[source]
input_unit_cost(info: scml.scml2019.common.ProductManufacturingInfo) float[source]
schedule_contract(contract: negmas.situated.Contract, assume_no_further_negotiations=False, end: int = None, ensure_storage_for: int = 0, start_at: int = 0) ScheduleInfo[source]

Schedules this contract if possible and returns information about the resulting schedule

Parameters:
  • contract – The contract being scheduled

  • assume_no_further_negotiations – If true no further negotiations will be assumed possible

  • end – The scheduling horizon (None for the default).

  • ensure_storage_for – The number of steps all needs must be in storage before they are consumed in production

  • start_at – No jobs will be scheduled before that time.

Returns:

Full schedule information including validity, line schedulers, production needs, etc (see SchedulerInfo).

schedule_contracts(contracts: Collection[negmas.situated.Contract], end: int = None, assume_no_further_negotiations=False, ensure_storage_for: int = 0, start_at: int = 0) ScheduleInfo[source]

Schedules a set of contracts and returns the ScheduleInfo.

Parameters:
  • contracts – Contracts to schedule

  • assume_no_further_negotiations – If true, no further negotiations will be assumed to be possible

  • end – The end of the simulation for the schedule (exclusive)

  • ensure_storage_for – Ensure that the outcome will be at the storage for at least this time

  • start_at – The timestep at which to start scheduling

Returns:

ScheduleInfo giving the schedule after these contracts is included. valid member can be used to check whether this is a valid contract

find_schedule(contracts: Collection[negmas.situated.Contract], start: int, end: int, assume_no_further_negotiations=False, ensure_storage_for: int = 0, start_at: int = 0)[source]

Schedules a set of contracts and returns either the search_for_schedule or None if infeasible

Parameters:
  • start

  • end

  • contracts

  • assume_no_further_negotiations

  • ensure_storage_for

  • start_at – The time at which to start scheduling. No jobs will be scheduled before this time.

Returns:

Schedule information (See ScheduleInfo for its contents).

class scml.FactorySimulator(initial_wallet: float, initial_storage: Dict[int, int], n_steps: int, n_products: int, profiles: List[scml.scml2019.common.ManufacturingProfile], max_storage: int | None = None)[source]

Bases: abc.ABC

Simulates a factory allowing for prediction of storage/balance in the future.

Parameters:
  • initial_wallet – The initial amount of cash in the wallet

  • initial_storage – initial inventory

  • n_steps – number of simulation steps

  • n_products – number of products in the world

  • profiles – all profiles that the factory being simulated can run

  • max_storage – maximum available storage space.

property max_storage: int | None

Maximum storage available

property n_steps: int

Number of steps to predict ahead.

property initial_wallet: float

Initial cash in wallet

property initial_storage: numpy.array

Initial inventory

abstract property n_lines

Number of lines

abstract property final_balance: float

Final balance given everything scheduled so-far

abstract property fixed_before

Gives the time before which the schedule is fixed.

See also

fix_before

_as_array(storage: Dict[int, int])[source]
abstract wallet_to(t: int) numpy.array[source]

Returns the cash in wallet up to and including time t.

Parameters:

t – Time

Returns:

wallet_at(t: int) float[source]

Returns the cash in wallet at a given timestep (given all simulated actions)

Parameters:

t

Returns:

abstract storage_to(t: int) numpy.array[source]

Returns the storage of all products up to time t

Parameters:

t – Time

Returns:

An array of size n_products * t giving the quantity of each product in storage at every step up to t.

storage_at(t: int) numpy.array[source]

Returns the storage of all products at time t

Parameters:

t – Time

Returns:

An array of size n_products giving the quantity of each product in storage at time-step t.

abstract line_schedules_to(t: int) numpy.array[source]

Returns the schedule of each line up to a given timestep

Parameters:

t – time

Returns:

An array of n_lines * t values giving the schedule up to t.

Remarks:

  • A NO_PRODUCTION value means no production, otherwise the index of the process being run

line_schedules_at(t: int) numpy.array[source]

Returns the schedule of each line at a given timestep

Parameters:

t – time

Returns:

An array of n_lines values giving the schedule up at t.

Remarks:

  • A NO_PRODUCTION value means no production, otherwise the index of the process being run

total_storage_to(t: int) numpy.array[source]

The total storage up to a given time

Parameters:

t – time

Returns:

an array of size t giving the total quantity of stored products in the inventory up to timestep t

total_storage_at(t: int) int[source]

The total storage at a given time

Parameters:

t – time

Returns:

an integer giving the total quantity of stored products in the inventory at timestep t

reserved_storage_to(t: int) numpy.array[source]

Returns the reserved storage of all products up to time t

Parameters:

t – Time

Returns:

An array of size n_products * t giving the quantity of each product reserved at every step up to t.

Remarks:

  • Reserved storage is counted in calls to storage_at , total_storage_at , storage_to , total_storage_to

  • Reserving quantities of products is a tool that can be used to avoid double counting availability of given products in the inventory for multiple contracts.

reserved_storage_at(t: int) numpy.array[source]

Returns the reserved storage of all products at time t

Parameters:

t – Time

Returns:

An array of size n_products giving the quantity of each product reserved at time-step t.

Remarks:

  • Reserved storage is counted in calls to storage_at , total_storage_at , storage_to , total_storage_to

  • Reserving quantities of products is a tool that can be used to avoid double counting availability of given products in the inventory for multiple contracts.

available_storage_to(t: int) numpy.array[source]

Returns the available storage of all products up to time t.

Parameters:

t – Time

Returns:

An array of size n_products * t giving the quantity of each product available at every step up to t.

Remarks:

  • Available storage is defined as the difference between storage and reserved storage.

  • Reserved storage is counted in calls to storage_at , total_storage_at , storage_to , total_storage_to

  • Reserving quantities of products is a tool that can be used to avoid double counting availability of given products in the inventory for multiple contracts.

available_storage_at(t: int) numpy.array[source]

Returns the available storage of all products at time t

Parameters:

t – Time

Returns:

An array of size n_products giving the quantity of each product available at time-step t.

Remarks:

  • Available storage is defined as the difference between storage and reserved storage.

  • Reserved storage is counted in calls to storage_at , total_storage_at , storage_to , total_storage_to

  • Reserving quantities of products is a tool that can be used to avoid double counting availability of given products in the inventory for multiple contracts.

abstract loans_to(t: int) numpy.array[source]

Returns loans up to time t

Parameters:

t – time

Returns:

An array of t real numbers giving the loans registered at time-steps up to t

loans_at(t: int) float[source]

Returns loans at time t

Parameters:

t – time

balance_at(t: int) float[source]

Returns the balance fo the factory at time t.

Parameters:

t – time

Remarks:

  • The balance is defined as the cash in wallet minus loans

See also

loans_at wallet_at

balance_to(t: int) numpy.array[source]

Returns the balance fo the factory up to time t.

Parameters:

t – time

Remarks:

  • The balance is defined as the cash in wallet minus loans

See also

loans_to wallet_to

abstract set_state(t: int, storage: numpy.array, wallet: float, loans: float, line_schedules: numpy.array) None[source]

Sets the current state at the given time-step. It implicitly causes a fix_before(t + 1)

Parameters:
  • t – Time step to set the state at

  • storage – quantity of every product (array of integers of size n_products)

  • wallet – Cash in wallet

  • loans – Loans

  • line_schedules – Line schedules (array of process numbers/NO_PRODUCTION of size n_lines)

abstract add_loan(total: float, t: int) bool[source]

Adds a loan at the given time

Parameters:
  • total – Total amount of the loan

  • t – time step to take the loan

Returns:

Success or failure

Remarks:

  • Taking a loan is simulated as reception of money. Payment back of the loan is not simulated in this call. To simulate paying back the loan, use pay at the times of installment payments.

receive(payment: float, t: int) bool[source]

Simulates receiving payment at time t

Parameters:
  • payment – Amount received

  • t – time

Returns:

Success or failure

abstract pay(payment: float, t: int, ignore_money_shortage: bool = True) bool[source]

Simulate payment at time t

Parameters:
  • payment – Amount payed

  • t – time

  • ignore_money_shortage – If True, shortage in money will be ignored and the wallet can go negative

Returns:

Success or failure

abstract transport_to(product: int, quantity: int, t: int, ignore_inventory_shortage: bool = True, ignore_space_shortage: bool = True) bool[source]

Simulates transporting products to/from storage at time t

Parameters:
  • product – product ID (index)

  • quantity – quantity to transport

  • t – time

  • ignore_inventory_shortage – Ignore shortage in the product which may lead to negative storage[product]

  • ignore_space_shortage – Ignore the limit on total storage which may lead to total_storage > max_storage

Returns:

Success or failure

abstract buy(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_space_shortage: bool = True) bool[source]

Buy a given quantity of a product for a given price at some time t

Parameters:
  • product – Product to buy (ID/index)

  • quantity – quantity to buy

  • price – unit price

  • t – time

  • ignore_money_shortage – If True, shortage in money will be ignored and the wallet can go negative

  • ignore_space_shortage – Ignore the limit on total storage which may lead to total_storage > max_storage

Returns:

Success or failure

Remarks:

  • buy cannot ever have inventory shortage

See also

sell

abstract sell(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_inventory_shortage: bool = True) bool[source]

sell a given quantity of a product for a given price at some time t

Parameters:
  • product – Index/ID of the product to be sold

  • quantity – quantity to be sold

  • price – unit price

  • t – time

  • ignore_money_shortage – If True, shortage in money will be ignored and the wallet can go negative

  • ignore_inventory_shortage – Ignore shortage in the product which may lead to negative storage[product]

Returns:

Success or failure

Remarks:

  • sell cannot ever have space shortage

See also

buy

abstract schedule(job: scml.scml2019.common.Job, ignore_inventory_shortage=True, ignore_money_shortage=True, ignore_space_shortage=True, override=True) bool[source]

Simulates scheduling the given job at its time and line optionally overriding whatever was already scheduled

Parameters:
  • job – Production job

  • ignore_inventory_shortage – If true shortages in inputs will be ignored

  • ignore_money_shortage – If true, shortage in money will be ignored

  • ignore_space_shortage – If true, shortage in space will be ignored

  • override – Whether the job should override any already registered job at its time-step

Returns:

Success/failure

reserve(product: int, quantity: int, t: int) bool[source]

Simulates reserving the given quantity of the given product at times >= t.

Parameters:
  • product – Index/ID of the product being reserved

  • quantity – quantity being reserved

  • t – time

Returns:

Success/failure

Remarks:

  • Reserved products show in calls to storage_at , total_storage_at etc.

  • Reserving a product does nothing more than mark some quantity as reserved for calls to reserved_storage_at and available_storage_at.

  • This feature can be used to simulate inventory hiding commands in the real factory and to avoid double counting of inventory when calculating needs for future contracts.

abstract fix_before(t: int) bool[source]

Fix the history before this point

Parameters:

t – time

Returns:

Success/failure

Remarks:

  • After this function is called at any time-step t, there is no way to change any component of the factory state at any timestep before t.

  • This function is useful for fixing any difference between the simulator and the real state (in conjunction with set_state).

abstract bookmark() int[source]

Sets a bookmark to the current location

Returns:

bookmark ID

Remarks:

  • Bookmarks can be used to implement transactions.

abstract rollback(bookmark_id: int) bool[source]

Rolls back to the given bookmark ID

Parameters:

bookmark (bookmark_id The bookmark ID returned from) –

Remarks:

  • You can only rollback in the reverse order of bookmarks. If the bookmark ID given here is not the one at the top of the bookmarks stack, the rollback will fail (return False)

abstract delete_bookmark(bookmark_id: int) bool[source]

Commits everything since the bookmark so it cannot be rolled back

Parameters:

bookmark (bookmark_id The bookmark ID returned from) –

Returns:

Success/failure

Remarks:

  • You can delete bookmarks in the reverse order of their creation only. If the bookmark ID given here is not the one at the top of the bookmarks stack, the deletion will fail (return False).

class scml.SlowFactorySimulator(initial_wallet: float, initial_storage: Dict[int, int], n_steps: int, n_products: int, profiles: List[scml.scml2019.common.ManufacturingProfile], max_storage: int | None)[source]

Bases: FactorySimulator

A slow factory simulator that runs an internal factory to find-out what will happen in the future

Remarks:

  • It is much faster to always access the properties/methods of this class in ascending time. If that is not the case, each time reversal will cause a complete reset.

  • It is recommended to call fix_before () to fix the past once a production step is completed. That will speed up operations

property final_balance: float

Final balance given everything scheduled so-far

property n_lines

Number of lines

property fixed_before

Gives the time before which the schedule is fixed.

See also

fix_before

set_state(t: int, storage: numpy.array, wallet: float, loans: float, line_schedules: numpy.array) None[source]

Sets the current state at the given time-step. It implicitly causes a fix_before(t + 1)

Parameters:
  • t – Time step to set the state at

  • storage – quantity of every product (array of integers of size n_products)

  • wallet – Cash in wallet

  • loans – Loans

  • line_schedules – Line schedules (array of process numbers/NO_PRODUCTION of size n_lines)

delete_bookmark(bookmark_id: int) bool[source]

Commits everything since the bookmark so it cannot be rolled back

Parameters:

bookmark (bookmark_id The bookmark ID returned from) –

Returns:

Success/failure

Remarks:

  • You can delete bookmarks in the reverse order of their creation only. If the bookmark ID given here is not the one at the top of the bookmarks stack, the deletion will fail (return False).

bookmark() int[source]

Sets a bookmark to the current location

Returns:

bookmark ID

Remarks:

  • Bookmarks can be used to implement transactions.

rollback(bookmark_id: int) bool[source]

Rolls back to the given bookmark ID

Parameters:

bookmark (bookmark_id The bookmark ID returned from) –

Remarks:

  • You can only rollback in the reverse order of bookmarks. If the bookmark ID given here is not the one at the top of the bookmarks stack, the rollback will fail (return False)

fix_before(t: int) bool[source]

Fix the history before this point

Parameters:

t – time

Returns:

Success/failure

Remarks:

  • After this function is called at any time-step t, there is no way to change any component of the factory state at any timestep before t.

  • This function is useful for fixing any difference between the simulator and the real state (in conjunction with set_state).

_update_state() None[source]
reset_to(t: int) None[source]
goto(t: int) None[source]

Steps the factory to the end of step t :param t: time

Returns:

wallet_to(t: int) numpy.array[source]

Returns the cash in wallet up to and including time t.

Parameters:

t – Time

Returns:

line_schedules_to(t: int) numpy.array[source]

Returns the schedule of each line up to a given timestep

Parameters:

t – time

Returns:

An array of n_lines * t values giving the schedule up to t.

Remarks:

  • A NO_PRODUCTION value means no production, otherwise the index of the process being run

storage_to(t: int) numpy.array[source]

Returns the storage of all products up to time t

Parameters:

t – Time

Returns:

An array of size n_products * t giving the quantity of each product in storage at every step up to t.

loans_to(t: int) float[source]

Returns loans up to time t

Parameters:

t – time

Returns:

An array of t real numbers giving the loans registered at time-steps up to t

add_loan(total: float, t: int) bool[source]

Adds a loan at the given time

Parameters:
  • total – Total amount of the loan

  • t – time step to take the loan

Returns:

Success or failure

Remarks:

  • Taking a loan is simulated as reception of money. Payment back of the loan is not simulated in this call. To simulate paying back the loan, use pay at the times of installment payments.

pay(payment: float, t: int, ignore_money_shortage: bool = True) bool[source]

Simulate payment at time t

Parameters:
  • payment – Amount payed

  • t – time

  • ignore_money_shortage – If True, shortage in money will be ignored and the wallet can go negative

Returns:

Success or failure

transport_to(product: int, quantity: int, t: int, ignore_inventory_shortage: bool = True, ignore_space_shortage: bool = True) bool[source]

Simulates transporting products to/from storage at time t

Parameters:
  • product – product ID (index)

  • quantity – quantity to transport

  • t – time

  • ignore_inventory_shortage – Ignore shortage in the product which may lead to negative storage[product]

  • ignore_space_shortage – Ignore the limit on total storage which may lead to total_storage > max_storage

Returns:

Success or failure

schedule(job: scml.scml2019.common.Job, ignore_inventory_shortage=True, ignore_money_shortage=True, ignore_space_shortage=True, override=True) bool[source]

Simulates scheduling the given job at its time and line optionally overriding whatever was already scheduled

Parameters:
  • job – Production job

  • ignore_inventory_shortage – If true shortages in inputs will be ignored

  • ignore_money_shortage – If true, shortage in money will be ignored

  • ignore_space_shortage – If true, shortage in space will be ignored

  • override – Whether the job should override any already registered job at its time-step

Returns:

Success/failure

buy(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_space_shortage: bool = True) bool[source]

Buy a given quantity of a product for a given price at some time t

Parameters:
  • product – Product to buy (ID/index)

  • quantity – quantity to buy

  • price – unit price

  • t – time

  • ignore_money_shortage – If True, shortage in money will be ignored and the wallet can go negative

  • ignore_space_shortage – Ignore the limit on total storage which may lead to total_storage > max_storage

Returns:

Success or failure

Remarks:

  • buy cannot ever have inventory shortage

See also

sell

sell(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_inventory_shortage: bool = True) bool[source]

sell a given quantity of a product for a given price at some time t

Parameters:
  • product – Index/ID of the product to be sold

  • quantity – quantity to be sold

  • price – unit price

  • t – time

  • ignore_money_shortage – If True, shortage in money will be ignored and the wallet can go negative

  • ignore_inventory_shortage – Ignore shortage in the product which may lead to negative storage[product]

Returns:

Success or failure

Remarks:

  • sell cannot ever have space shortage

See also

buy

class scml.FastFactorySimulator(initial_wallet: float, initial_storage: Dict[int, int], n_steps: int, n_products: int, profiles: List[scml.scml2019.common.ManufacturingProfile], max_storage: int | None)[source]

Bases: FactorySimulator

A faster implementation of the FactorySimulator interface (compared with SlowFactorySimulator.

property fixed_before

Gives the time before which the schedule is fixed.

See also

fix_before

property n_lines

Number of lines

property final_balance: float

Final balance given everything scheduled so-far

_as_array(storage: Dict[int, int]) numpy.array[source]
init(*args, **kwargs)[source]
wallet_to(t: int) numpy.array[source]

Returns the cash in wallet up to and including time t.

Parameters:

t – Time

Returns:

storage_to(t: int) numpy.array[source]

Returns the storage of all products up to time t

Parameters:

t – Time

Returns:

An array of size n_products * t giving the quantity of each product in storage at every step up to t.

line_schedules_to(t: int) numpy.array[source]

Returns the schedule of each line up to a given timestep

Parameters:

t – time

Returns:

An array of n_lines * t values giving the schedule up to t.

Remarks:

  • A NO_PRODUCTION value means no production, otherwise the index of the process being run

loans_to(t: int) numpy.array[source]

Returns loans up to time t

Parameters:

t – time

Returns:

An array of t real numbers giving the loans registered at time-steps up to t

add_loan(total: float, t: int) bool[source]

Adds a loan at the given time

Parameters:
  • total – Total amount of the loan

  • t – time step to take the loan

Returns:

Success or failure

Remarks:

  • Taking a loan is simulated as reception of money. Payment back of the loan is not simulated in this call. To simulate paying back the loan, use pay at the times of installment payments.

pay(payment: float, t: int, ignore_money_shortage: bool = True) bool[source]

Simulate payment at time t

Parameters:
  • payment – Amount payed

  • t – time

  • ignore_money_shortage – If True, shortage in money will be ignored and the wallet can go negative

Returns:

Success or failure

transport_to(product: int, quantity: int, t: int, ignore_inventory_shortage: bool = True, ignore_space_shortage: bool = True) bool[source]

Simulates transporting products to/from storage at time t

Parameters:
  • product – product ID (index)

  • quantity – quantity to transport

  • t – time

  • ignore_inventory_shortage – Ignore shortage in the product which may lead to negative storage[product]

  • ignore_space_shortage – Ignore the limit on total storage which may lead to total_storage > max_storage

Returns:

Success or failure

buy(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_space_shortage: bool = True) bool[source]

Buy a given quantity of a product for a given price at some time t

Parameters:
  • product – Product to buy (ID/index)

  • quantity – quantity to buy

  • price – unit price

  • t – time

  • ignore_money_shortage – If True, shortage in money will be ignored and the wallet can go negative

  • ignore_space_shortage – Ignore the limit on total storage which may lead to total_storage > max_storage

Returns:

Success or failure

Remarks:

  • buy cannot ever have inventory shortage

See also

sell

sell(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_inventory_shortage: bool = True) bool[source]

sell a given quantity of a product for a given price at some time t

Parameters:
  • product – Index/ID of the product to be sold

  • quantity – quantity to be sold

  • price – unit price

  • t – time

  • ignore_money_shortage – If True, shortage in money will be ignored and the wallet can go negative

  • ignore_inventory_shortage – Ignore shortage in the product which may lead to negative storage[product]

Returns:

Success or failure

Remarks:

  • sell cannot ever have space shortage

See also

buy

schedule(job: scml.scml2019.common.Job, ignore_inventory_shortage=True, ignore_money_shortage=True, ignore_space_shortage=True, override=True) bool[source]

Simulates scheduling the given job at its time and line optionally overriding whatever was already scheduled

Parameters:
  • job – Production job

  • ignore_inventory_shortage – If true shortages in inputs will be ignored

  • ignore_money_shortage – If true, shortage in money will be ignored

  • ignore_space_shortage – If true, shortage in space will be ignored

  • override – Whether the job should override any already registered job at its time-step

Returns:

Success/failure

fix_before(t: int) bool[source]

Fix the history before this point

Parameters:

t – time

Returns:

Success/failure

Remarks:

  • After this function is called at any time-step t, there is no way to change any component of the factory state at any timestep before t.

  • This function is useful for fixing any difference between the simulator and the real state (in conjunction with set_state).

delete_bookmark(bookmark_id: int) bool[source]

Commits everything since the bookmark so it cannot be rolled back

Parameters:

bookmark (bookmark_id The bookmark ID returned from) –

Returns:

Success/failure

Remarks:

  • You can delete bookmarks in the reverse order of their creation only. If the bookmark ID given here is not the one at the top of the bookmarks stack, the deletion will fail (return False).

bookmark() int[source]

Sets a bookmark to the current location

Returns:

bookmark ID

Remarks:

  • Bookmarks can be used to implement transactions.

rollback(bookmark_id: int) bool[source]

Rolls back to the given bookmark ID

Parameters:

bookmark (bookmark_id The bookmark ID returned from) –

Remarks:

  • You can only rollback in the reverse order of bookmarks. If the bookmark ID given here is not the one at the top of the bookmarks stack, the rollback will fail (return False)

set_state(t: int, storage: numpy.array, wallet: float, loans: float, line_schedules: numpy.array) None[source]

Sets the current state at the given time-step. It implicitly causes a fix_before(t + 1)

Parameters:
  • t – Time step to set the state at

  • storage – quantity of every product (array of integers of size n_products)

  • wallet – Cash in wallet

  • loans – Loans

  • line_schedules – Line schedules (array of process numbers/NO_PRODUCTION of size n_lines)

scml.transaction(simulator)[source]

Runs the simulated actions then confirms them if they are not rolled back

scml.temporary_transaction(simulator)[source]

Runs the simulated actions then rolls them back

scml.anac2019_world(competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]] = (), params: Sequence[Dict[str, Any]] = (), randomize: bool = True, log_file_name: str = None, name: str = None, agent_names_reveal_type: bool = False, n_intermediate: Tuple[int, int] = (1, 4), n_miners=5, n_factories_per_level=11, n_agents_per_competitor=1, n_consumers=5, n_lines_per_factory=10, guaranteed_contracts=False, use_consumer=True, max_insurance_premium=float('inf'), n_retrials=5, negotiator_type: str = DEFAULT_NEGOTIATOR, transportation_delay=0, default_signing_delay=0, max_storage=sys.maxsize, consumption_horizon=15, consumption=(3, 5), negotiation_speed=21, neg_time_limit=60 * 4, neg_n_steps=20, n_steps=100, time_limit=90 * 90, n_default_per_level: int = 5, compact: bool = False, **kwargs) scml.scml2019.world.SCML2019World[source]

Creates a world compatible with the ANAC 2019 competition. Note that

Parameters:
  • n_agents_per_competitor – Number of instantiations of each competing type.

  • name – SCML2020World name to use

  • agent_names_reveal_type – If true, a snake_case version of the agent_type will prefix agent names

  • randomize – If true, managers are assigned to factories randomly otherwise in the order

  • giving (they are) –

  • n_intermediate

  • n_default_per_level

  • competitors – A list of class names for the competitors

  • params – A list of dictionaries giving parameters to pass to the competitors

  • n_miners – number of miners of the single raw material

  • n_factories_per_level – number of factories at every production level

  • n_consumers – number of consumers of the final product

  • n_steps – number of simulation steps

  • n_lines_per_factory – number of lines in each factory

  • negotiation_speed – The number of negotiation steps per simulation step. None means infinite

  • default_signing_delay – The number of simulation between contract conclusion and signature

  • neg_n_steps – The maximum number of steps of a single negotiation (that is double the number of rounds)

  • neg_time_limit – The total time-limit of a single negotiation

  • time_limit – The total time-limit of the simulation

  • transportation_delay – The transportation delay

  • n_retrials – The number of retrials the Miner and GreedyFactoryManager will try if negotiations fail

  • max_insurance_premium – The maximum insurance premium accepted by GreedyFactoryManager (-1 to disable)

  • use_consumer – If true, the GreedyFactoryManager will use an internal consumer for buying its needs

  • guaranteed_contracts – If true, the GreedyFactoryManager will only sign contracts that it can guaratnee not to

  • break.

  • consumption_horizon – The number of steps for which Consumer publishes CFP s

  • consumption – The consumption schedule will be sampled from a uniform distribution with these limits inclusive

  • log_file_name – File name to store the logs

  • negotiator_type – The negotiation factory used to create all negotiators

  • max_storage – maximum storage capacity for all factory managers If None then it is unlimited

  • compact – If True, then compact logs will be created to reduce memory footprint

  • kwargs – key-value pairs to be passed as argument to chain_world() and then to SCML2019World()

Returns:

SCML2019World ready to run

Remarks:

  • Every production level n has one process only that takes n steps to complete

scml.anac2019_tournament(competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]], agent_names_reveal_type=False, n_configs: int = 5, max_worlds_per_config: int = 1000, n_runs_per_world: int = 5, n_agents_per_competitor: int = 5, tournament_path: str = None, total_timeout: int | None = None, parallelism='parallel', scheduler_ip: str | None = None, scheduler_port: str | None = None, tournament_progress_callback: Callable[[negmas.tournaments.WorldRunResults | None], None] = None, world_progress_callback: Callable[[scml.scml2019.world.SCML2019World | None], None] = None, name: str = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) negmas.tournaments.TournamentResults | os.PathLike[source]

The function used to run ANAC 2019 SCML tournament (collusion track).

Parameters:
  • name – Tournament name

  • competitors – A list of class names for the competitors

  • agent_names_reveal_type – If true then the type of an agent should be readable in its name (most likely at its beginning).

  • n_configs – The number of different world configs (up to competitor assignment) to be generated.

  • max_worlds_per_config – The maximum number of worlds to run per config. If None, then all possible assignments of competitors within each config will be tried (all permutations).

  • n_runs_per_world – Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration.

  • n_agents_per_competitor – Number of agents per competitor

  • total_timeout – Total timeout for the complete process

  • tournament_path – Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs

  • parallelism – Type of parallelism. Can be ‘serial’ for serial, ‘parallel’ for parallel and ‘distributed’ for distributed

  • scheduler_port – Port of the dask scheduler if parallelism is dask, dist, or distributed

  • scheduler_ip – IP Address of the dask scheduler if parallelism is dask, dist, or distributed

  • world_progress_callback – A function to be called after everystep of every world run (only allowed for serial evaluation and should be used with cautious).

  • tournament_progress_callback – A function to be called with WorldRunResults after each world finished processing

  • verbose – Verbosity

  • configs_only – If true, a config file for each

  • compact – If true, effort will be made to reduce memory footprint including disableing most logs

  • kwargs – Arguments to pass to the world_generator function

Returns:

TournamentResults The results of the tournament or a PathLike giving the location where configs were saved

Remarks:

Default parameters will be used in the league with the exception of parallelism which may use distributed processing

scml.anac2019_collusion(competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]], competitor_params: Sequence[Dict[str, Any]] | None = None, agent_names_reveal_type=False, n_configs: int = 5, max_worlds_per_config: int | None = 1000, n_runs_per_world: int = 5, n_agents_per_competitor: int = 5, min_factories_per_level: int = 5, tournament_path: str = None, total_timeout: int | None = None, parallelism='parallel', scheduler_ip: str | None = None, scheduler_port: str | None = None, tournament_progress_callback: Callable[[negmas.tournaments.WorldRunResults | None], None] | None = None, world_progress_callback: Callable[[scml.scml2019.world.SCML2019World | None], None] | None = None, non_competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]] | None = None, non_competitor_params: Sequence[Dict[str, Any]] | None = None, name: str | None = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) negmas.tournaments.TournamentResults | os.PathLike[source]

The function used to run ANAC 2019 SCML tournament (collusion track).

Parameters:
  • name – Tournament name

  • competitors – A list of class names for the competitors

  • competitor_params – A list of competitor parameters (used to initialize the competitors).

  • agent_names_reveal_type – If true then the type of an agent should be readable in its name (most likely at its beginning).

  • n_configs – The number of different world configs (up to competitor assignment) to be generated.

  • max_worlds_per_config – The maximum number of worlds to run per config. If None, then all possible assignments of competitors within each config will be tried (all permutations).

  • n_runs_per_world – Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration.

  • n_agents_per_competitor – Number of agents per competitor

  • min_factories_per_level – Minimum number of factories for each production level

  • total_timeout – Total timeout for the complete process

  • tournament_path – Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs

  • parallelism – Type of parallelism. Can be ‘serial’ for serial, ‘parallel’ for parallel and ‘distributed’ for distributed

  • scheduler_port – Port of the dask scheduler if parallelism is dask, dist, or distributed

  • scheduler_ip – IP Address of the dask scheduler if parallelism is dask, dist, or distributed

  • world_progress_callback – A function to be called after everystep of every world run (only allowed for serial evaluation and should be used with cautious).

  • tournament_progress_callback – A function to be called with WorldRunResults after each world finished processing

  • non_competitors – A list of agent types that will not be competing in the sabotage competition but will exist in the world

  • non_competitor_params – parameters of non competitor agents

  • verbose – Verbosity

  • configs_only – If true, a config file for each

  • compact – If true, compact logs will be created and effort will be made to reduce the memory footprint

  • kwargs – Arguments to pass to the world_generator function

Returns:

TournamentResults The results of the tournament or a PathLike giving the location where configs were saved

Remarks:

Default parameters will be used in the league with the exception of parallelism which may use distributed processing

scml.anac2019_std(competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]], competitor_params: Sequence[Dict[str, Any]] | None = None, agent_names_reveal_type=False, n_configs: int = 5, max_worlds_per_config: int | None = 1000, n_runs_per_world: int = 5, min_factories_per_level: int = 5, tournament_path: str = None, total_timeout: int | None = None, parallelism='parallel', scheduler_ip: str | None = None, scheduler_port: str | None = None, tournament_progress_callback: Callable[[negmas.tournaments.WorldRunResults | None], None] = None, world_progress_callback: Callable[[scml.scml2019.world.SCML2019World | None], None] = None, non_competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]] | None = None, non_competitor_params: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]] | None = None, name: str = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) negmas.tournaments.TournamentResults | os.PathLike[source]

The function used to run ANAC 2019 SCML tournament (standard track).

Parameters:
  • name – Tournament name

  • competitors – A list of class names for the competitors

  • competitor_params – A list of competitor parameters (used to initialize the competitors).

  • agent_names_reveal_type – If true then the type of an agent should be readable in its name (most likely at its beginning).

  • n_configs – The number of different world configs (up to competitor assignment) to be generated.

  • max_worlds_per_config – The maximum number of worlds to run per config. If None, then all possible assignments of competitors within each config will be tried (all permutations).

  • n_runs_per_world – Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration.

  • min_factories_per_level – Minimum number of factories for each production level

  • total_timeout – Total timeout for the complete process

  • tournament_path – Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs

  • parallelism – Type of parallelism. Can be ‘serial’ for serial, ‘parallel’ for parallel and ‘distributed’ for distributed

  • scheduler_port – Port of the dask scheduler if parallelism is dask, dist, or distributed

  • scheduler_ip – IP Address of the dask scheduler if parallelism is dask, dist, or distributed

  • world_progress_callback – A function to be called after everystep of every world run (only allowed for serial evaluation and should be used with cautious).

  • tournament_progress_callback – A function to be called with WorldRunResults after each world finished processing

  • non_competitors – A list of agent types that will not be competing in the sabotage competition but will exist in the world

  • non_competitor_params – parameters of non competitor agents

  • verbose – Verbosity

  • configs_only – If true, a config file for each

  • compact – If true, compact logs will be created and effort will be made to reduce the memory footprint

  • kwargs – Arguments to pass to the world_generator function

Returns:

TournamentResults The results of the tournament or a PathLike giving the location where configs were saved

Remarks:

Default parameters will be used in the league with the exception of parallelism which may use distributed processing

scml.balance_calculator(worlds: List[scml.scml2019.world.SCML2019World], scoring_context: Dict[str, Any], dry_run: bool, ignore_default=True) negmas.tournaments.WorldRunResults[source]

A scoring function that scores factory managers’ performance by the final balance only ignoring whatever still in their inventory.

Parameters:
  • worlds – The world which is assumed to be run up to the point at which the scores are to be calculated.

  • scoring_context – A dict of context parameters passed by the world generator or assigner.

  • dry_run – A boolean specifying whether this is a dry_run. For dry runs, only names and types are expected in the returned WorldRunResults

Returns:

WorldRunResults giving the names, scores, and types of factory managers.

scml.anac2019_sabotage(competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]], competitor_params: Sequence[Dict[str, Any]] | None = None, agent_names_reveal_type=False, n_configs: int = 5, max_worlds_per_config: int | None = 1000, n_runs_per_world: int = 5, n_agents_per_competitor: int = 5, min_factories_per_level: int = 5, tournament_path: str | pathlib.Path | None = None, total_timeout: int | None = None, parallelism='parallel', scheduler_ip: str | None = None, scheduler_port: str | None = None, tournament_progress_callback: Callable[[negmas.tournaments.WorldRunResults | None], None] = None, world_progress_callback: Callable[[scml.scml2019.world.SCML2019World | None], None] = None, non_competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]] | None = None, non_competitor_params: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]] | None = None, name: str = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) negmas.tournaments.TournamentResults | os.PathLike[source]

The function used to run ANAC 2019 SCML tournament (collusion track).

Parameters:
  • name – Tournament name

  • competitors – A list of class names for the competitors

  • competitor_params – A list of competitor parameters (used to initialize the competitors).

  • agent_names_reveal_type – If true then the type of an agent should be readable in its name (most likely at its beginning).

  • n_configs – The number of different world configs (up to competitor assignment) to be generated.

  • max_worlds_per_config – The maximum number of worlds to run per config. If None, then all possible assignments of competitors within each config will be tried (all permutations).

  • n_runs_per_world – Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration.

  • n_agents_per_competitor – Number of agents per competitor

  • min_factories_per_level – Minimum number of factories for each production level

  • total_timeout – Total timeout for the complete process

  • tournament_path – Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs

  • parallelism – Type of parallelism. Can be ‘serial’ for serial, ‘parallel’ for parallel and ‘distributed’ for distributed

  • scheduler_port – Port of the dask scheduler if parallelism is dask, dist, or distributed

  • scheduler_ip – IP Address of the dask scheduler if parallelism is dask, dist, or distributed

  • world_progress_callback – A function to be called after every step of every world run (only allowed for serial evaluation and should be used with cautious).

  • tournament_progress_callback – A function to be called with WorldRunResults after each world finished processing

  • non_competitors – A list of agent types that will not be competing in the sabotage competition but will exist in the world

  • non_competitor_params – parameters of non competitor agents

  • verbose – Verbosity

  • configs_only – If true, a config file for each

  • compact – If true, compact logs will be created and effort will be made to reduce the memory footprint

  • kwargs – Arguments to pass to the world_generator function

Returns:

TournamentResults The results of the tournament or a PathLike giving the location where configs were saved

Remarks:

Default parameters will be used in the league with the exception of parallelism which may use distributed processing

class scml.DefaultGreedyManager(*args, reserved_value=0.0, negotiator_params=None, optimism=0.0, negotiator_type=DEFAULT_NEGOTIATOR, n_retrials=5, use_consumer=True, reactive=True, sign_only_guaranteed_contracts=False, riskiness=0.0, max_insurance_premium: float = float('inf'), **kwargs)[source]

Bases: scml.scml2019.factory_managers.builtins.GreedyFactoryManager

The default factory manager that will be implemented by the committee of ANAC-SCML 2019

class scml.SCML2019World(products: Collection[scml.scml2019.common.Product], processes: Collection[scml.scml2019.common.Process], factories: List[scml.scml2019.common.Factory], consumers: List[scml.scml2019.consumers.Consumer], miners: List[scml.scml2019.miners.Miner], factory_managers: List[scml.scml2019.factory_managers.builtins.FactoryManager] | None = None, n_steps=100, time_limit=60 * 90, mechanisms: Dict[str, Dict[str, Any]] | None = None, neg_n_steps=20, neg_time_limit=2 * 60, neg_step_time_limit=60, negotiation_speed=21, no_bank=False, minimum_balance=0, interest_rate=0.1, interest_max=0.3, installment_interest=0.2, interest_time_increment=0.02, balance_at_max_interest=None, loan_installments=1, no_insurance=False, premium=0.03, premium_time_increment=0.03, premium_breach_increment=0.001, max_allowed_breach_level=None, breach_processing=BreachProcessing.VICTIM_THEN_PERPETRATOR, breach_penalty_society=0.1, breach_penalty_society_min=0.0, breach_penalty_victim=0.0, breach_move_max_product=True, initial_wallet_balances: int | None = None, money_resolution=0.5, default_signing_delay=0, transportation_delay: int = 0, transfer_delay: int = 0, start_negotiations_immediately=False, catalog_profit=0.15, avg_process_cost_is_public=True, catalog_prices_are_public=True, strip_annotations=True, financial_reports_period=10, ignore_negotiated_penalties=False, prevent_cfp_tampering=False, default_price_for_products_without_one=1, compensation_fraction=0.5, compact=False, log_folder=None, log_to_file: bool = False, log_to_screen: bool = False, log_file_level=logging.DEBUG, log_screen_level=logging.ERROR, log_file_name: str = 'log.txt', log_ufuns: bool = False, log_negotiations: bool = False, save_mechanism_state_in_contract=False, save_signed_contracts: bool = True, save_cancelled_contracts: bool = True, save_negotiations: bool = True, save_resolved_breaches: bool = True, save_unresolved_breaches: bool = True, ignore_agent_exceptions: bool = False, ignore_contract_execution_exceptions: bool = False, name: str | None = None, **kwargs)[source]

Bases: negmas.situated.TimeInAgreementMixin, negmas.situated.World

The SCML2020World class running a simulation of supply chain management.

property winners

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

join(x: negmas.situated.Agent, simulation_priority: int = 0)[source]

Add an agent to the world.

Parameters:
  • x – The agent to be registered

  • simulation_priority – The simulation priority. Entities with lower priorities will be stepped first during

Returns:

save_config(file_name: str) None[source]

Saves the config of the world as a yaml file

Parameters:

file_name – Name of file to save the config to

Returns:

assign_managers(factory_managers=Iterable[Union[str, Type[FactoryManager], FactoryManager]], params: Iterable[Dict[str, Any]] | None = None) None[source]

Assigns existing factories to new factory managers created from the given types and parameters or manager objects.

Parameters:
  • factory_managers – An iterable of FactoryManager objects type names or FactoryManager types to assign to

  • params – parameters of the newly created managers

Remarks:

  • factories are assigned in the same order they exist in the local factories attribute cycling through the input managers or types/params

  • If a FactoryManager object is given instead of a type or a string in the factory_managers collection, and the number of factory_managers is less than the number of factories in the world causing this object to cycle for more than one factory, it is assigned to the first such factory but then deep copies of it with new ids and names are assigned to the rest of the factories. That ensures that each manager has exactly one factory and that all factories are assigned exactly one unique manager.

classmethod random_small(n_production_levels: int = 1, n_factories: int = 10, factory_kwargs: Dict[str, Any] = None, miner_kwargs: Dict[str, Any] = None, consumer_kwargs: Dict[str, Any] = None, **kwargs)[source]
classmethod chain_world(n_intermediate_levels=0, n_miners=5, n_factories_per_level=5, n_consumers: int | Tuple[int, int] | List[int] = 5, n_steps=100, n_lines_per_factory=10, n_max_assignable_factories=None, log_file_name: str = None, agent_names_reveal_type: bool = False, negotiator_type: str = DEFAULT_NEGOTIATOR, miner_type: str | Type[scml.scml2019.miners.Miner] = ReactiveMiner, consumer_type: str | Type[scml.scml2019.consumers.Consumer] = JustInTimeConsumer, max_storage: int = sys.maxsize, default_manager_params: Dict[str, Any] = None, miner_kwargs: Dict[str, Any] = None, consumption: int | Tuple[int, int] = (0, 5), consumer_kwargs: Dict[str, Any] = None, negotiation_speed: int | None = 21, manager_types: Sequence[Type[scml.scml2019.factory_managers.builtins.FactoryManager]] = (GreedyFactoryManager,), manager_params: Sequence[Dict[str, Any]] | None = None, n_default_per_level: int = 0, default_factory_manager_type: Type[scml.scml2019.factory_managers.builtins.FactoryManager] = GreedyFactoryManager, randomize: bool = True, initial_wallet_balances=1000, process_cost: float | Tuple[float, float] = (1.0, 5.0), process_time: int | Tuple[int, int] = 1, interest_rate=float('inf'), interest_max=float('inf'), shared_profile_per_factory=False, **kwargs)[source]

Creates a very small world in which only one raw material and one final product. The production graph is a series with n_intermediate_levels intermediate levels between the single raw material and single final product

Parameters:
  • n_max_assignable_factories – The maximum number of factories assigned to managers other than the default

  • randomize – If true, the factory assignment is randomized

  • n_default_per_level – The number of GreedyFactoryManager objects guaranteed at every level

  • default_factory_manager_type – The FactoryManager type to use as the base for default_factory_managers. You can specify how many of this type exist at every level by specifying n_default_per_level. If n_default_per_level is zero, this parameter has no effect.

  • manager_types – A sequence of factory manager types to control the factories.

  • manager_params – An optional sequence of dictionaries giving the parameters to pass to manager_types.

  • consumer_type – Consumer type to use for all consumers

  • miner_type – Miner type to use for all miners

  • consumption – Consumption schedule

  • n_intermediate_levels – The number of intermediate products

  • n_miners – number of miners of the single raw material

  • n_factories_per_level – number of factories at every production level

  • n_consumers – number of consumers of the final product

  • n_steps – number of simulation steps

  • n_lines_per_factory – number of lines in each factory

  • process_cost – The range of process costs. A uniform distribution will be used

  • process_time – The range of process times. A uniform distribution will be used

  • log_file_name – File name to store the logs

  • agent_names_reveal_type – If true, agent names will start with a snake_case version of their type name

  • negotiator_type – The negotiation factory used to create all negotiators

  • max_storage – maximum storage capacity for all factory managers If None then it is unlimited

  • default_manager_params – keyword arguments to be used for constructing factory managers

  • consumer_kwargs – keyword arguments to be used for constructing consumers

  • miner_kwargs – keyword arguments to be used for constructing miners

  • negotiation_speed – The number of negotiation steps per simulation step. None means infinite

  • interest_max – Maximum interest rate

  • interest_rate – Minimum interest rate

  • initial_wallet_balances – initial wallet balances for all factories

  • shared_profile_per_factory – If true, all lines in the same factory will have the same profile costs

  • kwargs – Any other parameters are just passed to the world constructor

Returns:

SCML2019World ready to run

Remarks:

  • Every production level n has one process only that takes n steps to complete

classmethod random(n_raw_materials: int | Tuple[int, int] = (5, 10), raw_material_price: float | Tuple[float, float] = (1.0, 30.0), n_final_products: int | Tuple[int, int] = (3, 5), n_production_levels: int | Tuple[int, int] = (3, 5), n_products_per_level: int | Tuple[int, int] = (3, 5), n_processes_per_level: int | Tuple[int, int] = (6, 10), n_inputs_per_process: int | Tuple[int, int] = (2, 5), bias_toward_last_level_products: float = 0.0, quantity_per_input: int | Tuple[int, int] = (1, 10), input_step: float | Tuple[float, float] = 0.0, quantity_per_output: int | Tuple[int, int] = (1, 1), output_step: float | Tuple[float, float] = 1.0, process_relative_cost: float | Tuple[float, float] = (0.05, 0.4), n_outputs_per_process: int | Tuple[int, int] = (1, 1), n_lines: int | Tuple[int, int] = (3, 5), lines_are_similar: bool = False, n_processes_per_line: int | Tuple[int, int] = None, cost_for_line: float | Tuple[float, float] = (5.0, 50.0), n_production_steps: int | Tuple[int, int] = (2, 10), max_storage: int | Tuple[int, int] = 2000, n_factories: int | Tuple[int, int] = 20, n_consumers: int | Tuple[int, int] = 5, n_products_per_consumer: int | Tuple[int, int] = None, n_miners: int | Tuple[int, int] = 5, n_products_per_miner: int | Tuple[int, int] | None = None, factory_manager_types: Type[scml.scml2019.factory_managers.builtins.FactoryManager] | List[Type[scml.scml2019.factory_managers.builtins.FactoryManager]] = GreedyFactoryManager, consumer_types: Type[scml.scml2019.consumers.Consumer] | List[Type[scml.scml2019.consumers.Consumer]] = JustInTimeConsumer, miner_types: Type[scml.scml2019.miners.Miner] | List[Type[scml.scml2019.miners.Miner]] = ReactiveMiner, negotiator_type=DEFAULT_NEGOTIATOR, initial_wallet_balance: float | Tuple[float, float] = 1000, factory_kwargs: Dict[str, Any] = None, miner_kwargs: Dict[str, Any] = None, consumer_kwargs: Dict[str, Any] = None, **kwargs)[source]

Creates a random SCML scenario with adjustable parameters.

Parameters:
  • n_raw_materials – Number of raw materials. Can be a value or a range.

  • raw_material_price – Catalog prices for raw materials. Can be a value or a range.

  • n_final_products – Number of final products. Can be a value or a range.

  • n_production_levels – How deep is the production graph (number of intermediate products). Can be a value or

  • range. (miner. Can be a value or a) –

  • n_products_per_level – How many intermediate products per intermediate level. Can be a value or a range.

  • n_processes_per_level – Number of processes in intermediate levels. Can be a value or a range.

  • n_inputs_per_process – Number of inputs per process. Can be a value or a range.

  • bias_toward_last_level_products – How biased are production processes toward using products from the last

  • them (level below) –

  • quantity_per_input – How many items are needed for each input to a process. Can be a value or a range.

  • input_step – When are inputs consumed during the production process. Can be a value or a range. Default 0

  • quantity_per_output – How many items are produced per output. Can be a value or a range.

  • output_step – When are outputs created during the production process. Can be a value or a range. Default 1

  • process_relative_cost – Intrinsic relative cost of processes [Outputs will be produced

  • sum (at a cost of) –

  • n_outputs_per_process – Number of outputs per process. Can be a value or a range.

  • n_lines – Number of lines per factory. Can be a value or a range.

  • lines_are_similar – If true then all lins of the same factory will have the same production processes.

  • n_processes_per_line – Number of processes that can be run on each line per factory. Can be a value or a

  • range.

  • cost_for_line – Cost for running a process on a line. Can be a value or a range.

  • n_production_steps – Number of production steps per line. Can be a value or a range.

  • max_storage – Maximum storage per factory. Can be a value or a range.

  • n_factories – Number of factories. Can be a value or a range.

  • n_consumers – Number of consumers. Can be a value or a range.

  • n_products_per_consumer – Number of products per miner. If None then all final products will be assigned to

  • range.

  • n_miners – Number of miners. Can be a value or a range.

  • n_products_per_miner – Number of products per miner. If None then all raw materials will be assigned to every

  • range.

  • factory_manager_types – A callable for creating factory managers for the factories

  • consumer_types – A callable for creating Consumer objects

  • miner_types – A callable for creating Miner objects

  • negotiator_type – A string that can be `eval`uated to a negotiator.

  • initial_wallet_balance – The initial balance of all wallets

  • factory_kwargs – keyword arguments to be used for constructing factory managers

  • consumer_kwargs – keyword arguments to be used for constructing consumers

  • miner_kwargs – keyword arguments to be used for constructing miners

  • **kwargs

Returns:

SCML2019World The random world generated

Remarks:

  • Most parameters accept either a single value or a 2-valued tuple. In the later case, it will sample a value within the range specified by the tuple (low, high) inclusive. For example the number of lines (n_lines) follows this pattern

_update_dynamic_product_process_info()[source]

Updates the catalog prices of all products based on the prices of their inputs

set_consumers(consumers: List[scml.scml2019.consumers.Consumer])[source]
set_miners(miners: List[scml.scml2019.miners.Miner])[source]
set_factory_managers(factory_managers: List[scml.scml2019.factory_managers.builtins.FactoryManager] | None)[source]
set_processes(processes: Collection[scml.scml2019.common.Process])[source]
set_products(products: Collection[scml.scml2019.common.Product])[source]
order_contracts_for_execution(contracts: Collection[negmas.situated.Contract])[source]

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

execute_action(action: negmas.situated.Action, agent: negmas.situated.Agent, callback: Callable[[negmas.situated.Action, bool], Any] = None) bool[source]

Executes the given action by the given agent

get_private_state(agent: negmas.situated.Agent) scml.scml2019.common.FactoryState[source]

Reads the private state of the given agent

receive_financial_reports(agent: scml.scml2019.agent.SCML2019Agent, receive: bool, agents: List[str] | None)[source]

Registers interest/disinterest in receiving financial reports

simulation_step(stage)[source]

A step of SCML simulation

pre_step_stats()[source]

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

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

post_step_stats()[source]

Saves relevant stats

start_contract_execution(contract: negmas.situated.Contract) Set[negmas.situated.Breach][source]

Tries to execute the contract

Parameters:

contract

Returns:

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

Return type:

Set[Breach]

Remarks:

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

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

_move_product(buyer: scml.scml2019.agent.SCML2019Agent, seller: scml.scml2019.agent.SCML2019Agent, product_id: int, quantity: int, money: float)[source]

Moves as much product and money between the buyer and seller

complete_contract_execution(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach], resolution: negmas.situated.Contract | None)[source]

The resolution can either be None or a contract with the following items:

The issues can be any or all of the following:

immediate_quantity: int immediate_unit_price: float later_quantity: int later_unit_price: int later_penalty: float later_time: int

_move_product_force(buyer: scml.scml2019.agent.SCML2019Agent, seller: scml.scml2019.agent.SCML2019Agent, product_id: int, quantity: int, money: float)[source]

Moves as much product and money between the buyer and seller

register_interest(agent: scml.scml2019.agent.SCML2019Agent, products: List[int]) None[source]
unregister_interest(agent: scml.scml2019.agent.SCML2019Agent, products: List[int]) None[source]
make_bankrupt(agent: scml.scml2019.agent.SCML2019Agent, amount: float, beneficiary: negmas.situated.Agent, contract: negmas.situated.Contract | None) None[source]

Marks the agent as bankrupt

nullify_contract(contract: negmas.situated.Contract)[source]
evaluate_insurance(contract: negmas.situated.Contract, agent: scml.scml2019.agent.SCML2019Agent, t: int = None) float | None[source]

Can be called to evaluate the premium for insuring the given contract against breachs committed by others

Parameters:
  • agent – The agent buying the contract

  • contract – hypothetical contract

  • t – time at which the policy is to be bought. If None, it means current step

buy_insurance(contract: negmas.situated.Contract, agent: scml.scml2019.agent.SCML2019Agent) bool[source]

Buys insurance for the contract by the premium calculated by the insurance company.

Remarks:

The agent can call evaluate_insurance to find the premium that will be used.

_process_annotation(annotation: Dict[str, Any] | None) Dict[str, Any] | None[source]

Processes an annotation stripping any extra information not allowed if necessary. Will return None if the annotation is suspecious

run_negotiation(caller: negmas.situated.Agent, issues: Collection[negmas.outcomes.Issue], partners: Collection[negmas.situated.Agent], negotiator: negmas.Negotiator, ufun: negmas.UtilityFunction = None, caller_role: str = None, roles: Collection[str] = None, annotation: Dict[str, Any] | None = None, mechanism_name: str = None, mechanism_params: Dict[str, Any] = None) Tuple[negmas.situated.Contract, negmas.NegotiatorMechanismInterface] | None[source]

Runs a negotiation until completion

Parameters:
  • caller – The agent requesting the negotiation

  • partners – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/Agent or as a list containing a single string/Agent, then he caller will be added at the beginning of the list. This will only be done if roles was passed as None.

  • negotiator – The negotiator to be used in the negotiation

  • preferences – The utility function. Only needed if the negotiator does not already know it

  • caller_role – The role of the caller in the negotiation

  • issues – Negotiation issues

  • annotation – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation

  • roles – The roles of different partners. If None then each role for each partner will be None

  • mechanism_name – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be) –

  • my_role (then roles and) –

  • None

  • mechanism_params – A dict of parameters used to initialize the mechanism object

Returns:

A Tuple of a contract and the nmi of the mechanism used to get it in case of success. None otherwise

run_negotiations(caller: negmas.situated.Agent, issues: List[negmas.outcomes.Issue] | List[List[negmas.outcomes.Issue]], partners: List[List[negmas.situated.Agent]], negotiators: List[negmas.Negotiator], ufuns: List[negmas.UtilityFunction] = None, caller_roles: List[str] = None, roles: List[List[str] | None] | None = None, annotations: List[Dict[str, Any] | None] | None = None, mechanism_names: str | List[str] | None = None, mechanism_params: Dict[str, Any] | List[Dict[str, Any]] | None = None, all_or_none: bool = False) List[Tuple[negmas.situated.Contract, negmas.NegotiatorMechanismInterface]][source]

Requests to run a set of negotiations simultaneously. Returns after all negotiations are run to completion

Parameters:
  • caller – The agent requesting the negotiation

  • partners – A list of list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners[i] is passed as a single string/Agent or as a list containing a single string/Agent, then he caller will be added at the beginning of the list. This will only be done if roles was passed as None.

  • issues – Negotiation issues

  • negotiators – The negotiator to be used in the negotiation

  • ufuns – The utility function. Only needed if the negotiator does not already know it

  • caller_roles – The role of the caller in the negotiation

  • annotations – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation

  • roles – The roles of different partners. If None then each role for each partner will be None

  • mechanism_names – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be) –

  • my_role (then roles and) –

  • None

  • mechanism_params – A dict of parameters used to initialize the mechanism object

  • all_of_none – If True, ALL partners must agree to negotiate to go through.

Returns:

contract (None for failure) and nmi (The mechanism info [None if the partner refused the negotiation])

Return type:

A list of tuples each with two values

request_negotiation_about(req_id: str, caller: negmas.situated.Agent, issues: List[negmas.outcomes.Issue], partners: List[negmas.situated.Agent], roles: List[str] = None, annotation: Dict[str, Any] | None = None, mechanism_name: str = None, mechanism_params: Dict[str, Any] = None, group=None)[source]

Requests to start a negotiation with some other agents

Parameters:
  • req_id – An ID For the request that is unique to the caller

  • caller – The agent requesting the negotiation

  • partners – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/Agent or as a list containing a single string/Agent, then he caller will be added at the beginning of the list. This will only be done if roles was passed as None.

  • issues – Negotiation issues

  • annotation – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation

  • roles – The roles of different partners. If None then each role for each partner will be None

  • mechanism_name – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be) –

  • my_role (then roles and) –

  • None

  • mechanism_params – A dict of parameters used to initialize the mechanism object

  • group – An identifier for the group to which the negotiation belongs. This is not not used by the system.

Returns:

None. The caller will be informed by a callback function on_neg_request_accepted or on_neg_request_rejected about the status of the negotiation.

on_event(event: negmas.events.Event, sender: negmas.events.EventSource) None[source]

Called whenever an event is raised for which the SCML2020World is registered asa listener

Parameters:
  • event – The event

  • sender – The sender

Returns:

None

contract_record(contract: negmas.situated.Contract) Dict[str, Any][source]

Converts a contract to a record suitable for permanent storage

breach_record(breach: negmas.situated.Breach) Dict[str, Any][source]

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

contract_size(contract: negmas.situated.Contract) float[source]

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

Returns:

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.__all__[source]
class scml.SCML2020Agent(name: str | None = None, type_postfix: str = '', preferences: negmas.preferences.Preferences | None = None, ufun: negmas.preferences.UtilityFunction | None = None)[source]

Bases: negmas.Agent

Base class for all SCML2020 agents (factory managers)

property internal_state: Dict[str, Any]

Returns the internal state of the agent for debugging purposes

reset()[source]
is_clean() bool[source]
init()[source]

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

before_step()[source]
step_()[source]

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

step()[source]

Called by the simulator at every simulation step

to_dict()[source]
_respond_to_negotiation_request(initiator: str, partners: List[str], issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, role: str | None, req_id: str | None) negmas.Negotiator | None[source]

Called by the mechanism to ask for joining a negotiation. The agent can refuse by returning a None

Parameters:
  • initiator – The ID of the agent that initiated the negotiation request

  • partners – The partner list (will include this agent)

  • issues – The list of issues

  • annotation – Any annotation specific to this negotiation.

  • mechanism – The mechanism that started the negotiation

  • role – The role of this agent in the negotiation

  • req_id – The req_id passed to the AWI when starting the negotiation (only to the initiator).

Returns:

None to refuse the negotiation or a Negotiator object appropriate to the given mechanism to accept it.

Remarks:

  • It is expected that world designers will introduce a better way to respond and override this function to call it

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

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

Parameters:
  • contract – The contract

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

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

on_contract_executed(contract: negmas.Contract) None[source]

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

set_renegotiation_agenda(contract: negmas.Contract, breaches: List[negmas.Breach]) negmas.RenegotiationRequest | None[source]

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

Parameters:
  • contract – The contract being breached

  • breaches – All breaches on contract

Returns:

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

respond_to_renegotiation_request(contract: negmas.Contract, breaches: List[negmas.Breach], agenda: negmas.RenegotiationRequest) negmas.Negotiator | None[source]

Called to respond to a renegotiation request

Parameters:
  • agenda

  • contract

  • breaches

Returns:

on_neg_request_rejected(req_id: str, by: List[str] | None)[source]

Called when a requested negotiation is rejected

Parameters:
  • req_id – The request ID passed to _request_negotiation

  • by – A list of agents that refused to participate or None if the failure was for another reason

on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface)[source]

Called when a requested negotiation is accepted

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

Called whenever a negotiation ends without agreement

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

Called whenever a negotiation ends with agreement

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

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

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

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

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

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

Remarks:

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

on_failures(failures: List[scml.scml2020.common.Failure]) None[source]

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

Parameters:

failures – A list of Failure s.

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

Called whenever another agent requests a negotiation with this agent.

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

  • issues – Negotiation issues

  • annotation – Annotation attached with this negotiation

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

Returns:

None to reject the negotiation, otherwise a negotiator

confirm_production(commands: numpy.ndarray, balance: int, inventory) numpy.ndarray[source]

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

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

  • balance – The current balance of the factory

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

Returns:

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

Remarks:

  • Not called in SCML2020 competition.

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

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

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

Signs all contracts

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

Bases: scml.scml2020.components.signing.SignAll, scml.scml2020.components.production.DemandDrivenProductionStrategy, scml.scml2020.components.trading.MarketAwareTradePredictionStrategy, SCML2020Agent, negmas.situated.Adapter, scml.oneshot.mixins.OneShotUFunCreatorMixin

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

property price_multiplier
property is_perishable: bool

Are all products perishable (original design of OneShot)

property current_disposal_cost: float

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

property current_storage_cost: float

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

property current_shortfall_penalty: float

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

property allow_zero_quantity: bool

Does negotiations allow zero quantity?

init()[source]

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

_make_issues(product)[source]
before_step()[source]
step()[source]

Called by the simulator at every simulation step

make_ufun(add_exogenous: bool)[source]
to_dict()[source]
respond_to_negotiation_request(initiator, issues, annotation, mechanism)[source]

Called whenever another agent requests a negotiation with this agent.

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

  • issues – Negotiation issues

  • annotation – Annotation attached with this negotiation

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

Returns:

None to reject the negotiation, otherwise a negotiator

get_disposal_cost() float[source]
get_shortfall_penalty_mean()[source]
get_disposal_cost_mean()[source]
get_shortfall_penalty_dev()[source]
get_disposal_cost_dev()[source]
get_storage_cost_mean()[source]
get_storage_cost_dev()[source]
get_profile()[source]
get_shortfall_penalty()[source]
get_current_balance()[source]
get_exogenous_output() Tuple[int, int][source]
get_exogenous_input() Tuple[int, int][source]
class scml.RandomAgent(*args, **kwargs)[source]

Bases: scml.scml2020.agents.indneg.IndependentNegotiationsAgent

An agent that negotiates randomly.

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

Creates a utility function

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

Bases: scml.scml2020.agent.SCML2020Agent

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

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

Called whenever another agent requests a negotiation with this agent.

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

  • issues – Negotiation issues

  • annotation – Annotation attached with this negotiation

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

Returns:

None to reject the negotiation, otherwise a negotiator

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

Signs all contracts

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

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

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

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

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

Remarks:

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

step()[source]

Called by the simulator at every simulation step

init()[source]

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

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

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

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

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

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

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

Remarks:

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

on_failures(failures: List[scml.scml2020.common.Failure]) None[source]

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

Parameters:

failures – A list of Failure s.

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

Called whenever a negotiation ends without agreement

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

Called whenever a negotiation ends with agreement

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

Called whenever at least a partner did not sign the contract

on_contract_executed(contract: negmas.Contract) None[source]

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

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

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

Parameters:
  • contract – The contract

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

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

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

Bases: scml.scml2020.components.negotiation.IndependentNegotiationsManager, scml.scml2020.components.prediction.FixedTradePredictionStrategy, scml.scml2020.components.trading.ReactiveTradingStrategy, scml.scml2020.world.SCML2020Agent

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

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

Remarks:

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

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

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

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

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

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

Parameters:
  • step – Simulation step

  • sell – Sell or buy

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

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

Parameters:
  • step – Simulation step

  • sell – Sell or buy

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

Bases: scml.scml2020.components.signing.KeepOnlyGoodPrices, IndependentNegotiationsAgent

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

Bases: scml.scml2020.agents.indneg.IndependentNegotiationsAgent

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

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

Creates a utility function

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

Bases: scml.scml2020.agents.indneg.MarketAwareIndependentNegotiationsAgent, BuyCheapSellExpensiveAgent

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

class scml.DecentralizingAgent(*args, negotiator_type: negmas.SAONegotiator | str = AspirationNegotiator, negotiator_params: Dict[str, Any] | None = None, **kwargs)[source]

Bases: _NegotiationCallbacks, scml.scml2020.components.StepNegotiationManager, scml.scml2020.components.trading.PredictionBasedTradingStrategy, scml.scml2020.components.SupplyDrivenProductionStrategy, scml.scml2020.world.SCML2020Agent

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

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

  • negotiator_params – Paramters of the negotiator

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

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

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

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

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

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

class scml.IndDecentralizingAgent(*args, negotiator_type: negmas.SAONegotiator | str = AspirationNegotiator, negotiator_params: Dict[str, Any] | None = None, **kwargs)[source]

Bases: _NegotiationCallbacks, scml.scml2020.components.IndependentNegotiationsManager, scml.scml2020.components.trading.PredictionBasedTradingStrategy, scml.scml2020.components.SupplyDrivenProductionStrategy, scml.scml2020.world.SCML2020Agent

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

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

  • negotiator_params – Parameters of the negotiator

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

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

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

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

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

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

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

Creates a utility function

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

Bases: _NegotiationCallbacks, scml.scml2020.components.StepNegotiationManager, scml.scml2020.components.trading.PredictionBasedTradingStrategy, scml.scml2020.components.SupplyDrivenProductionStrategy, scml.scml2020.world.SCML2020Agent

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

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

  • negotiator_params – Paramters of the negotiator

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

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

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

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

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

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

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

Bases: scml.scml2020.components.prediction.MarketAwareTradePredictionStrategy, _NegotiationCallbacks, scml.scml2020.components.MovingRangeNegotiationManager, scml.scml2020.components.trading.PredictionBasedTradingStrategy, scml.scml2020.components.signing.KeepOnlyGoodPrices, scml.scml2020.components.SupplyDrivenProductionStrategy, scml.scml2020.world.SCML2020Agent

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.

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

Bases: scml.scml2020.components.signing.KeepOnlyGoodPrices, scml.scml2020.components.prediction.MarketAwareTradePredictionStrategy, IndDecentralizingAgent

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.ReactiveAgent(*args, negotiator_type: negmas.SAONegotiator | str = AspirationNegotiator, negotiator_params: Dict[str, Any] | None = None, **kwargs)[source]

Bases: scml.scml2020.components.StepNegotiationManager, scml.scml2020.components.trading.ReactiveTradingStrategy, scml.scml2020.components.production.TradeDrivenProductionStrategy, scml.scml2020.components.FixedTradePredictionStrategy, scml.scml2020.world.SCML2020Agent

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

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

  • negotiator_params – Paramters of the negotiator

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

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

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

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

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

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

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

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

Parameters:
  • step – Simulation step

  • sell – Sell or buy

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

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

Parameters:
  • step – Simulation step

  • sell – Sell or buy

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

Implemented for speed but not really required

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

Bases: scml.scml2020.components.signing.KeepOnlyGoodPrices, ReactiveAgent

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

Bases: scml.scml2020.components.MovingRangeNegotiationManager, scml.scml2020.components.trading.PredictionBasedTradingStrategy, scml.scml2020.components.SupplyDrivenProductionStrategy, scml.scml2020.world.SCML2020Agent

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.MarketAwareMovingRangeAgent(*args, min_price_margin=0.5, max_price_margin=0.5, **kwargs)[source]

Bases: scml.scml2020.components.prediction.MarketAwareTradePredictionStrategy, MovingRangeAgent

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.

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]

Bases: scml.scml2020.agent.SCML2020Agent

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

init()[source]

Called once

before_step()[source]

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

step()[source]

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

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

Called whenever another agent requests a negotiation with this agent.

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

  • issues – Negotiation issues

  • annotation – Annotation attached with this negotiation

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

Returns:

None to reject the negotiation, otherwise a negotiator

sign_all_contracts(contracts)[source]

Signs all contracts

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

do_production() int[source]
propose(state: negmas.sao.SAOState, ami: negmas.sao.SAONMI, is_selling: bool, is_requested: bool)[source]

Used to propose to the opponent

Parameters:
  • state – mechanism state including current round

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

  • offer – The offer proposed by the partner

  • is_selling – Whether the agent is selling to this partner

  • is_requested – Whether the agent requested this negotiation

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

Responds to an offer from one partner.

Parameters:
  • state – mechanism state including current round

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

  • offer – The offer proposed by the partner

  • is_selling – Whether the agent is selling to this partner

  • is_requested – Whether the agent requested this negotiation

Remarks:

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

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

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

Called when a negotiation fails

on_negotiation_success(contract, mechanism)[source]

Called when a negotiation fails

_remove_tentative_offer(selling, partner)[source]

Removes my last offer from the tentative offers

_is_good_price(is_selling: bool, u: float, slack: float = 0.0)[source]

Checks whether a price is good relative to current trading prices, and satisfying profit (with possible slack).

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

Bases: negmas.AgentWorldInterface

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 trading_prices: numpy.ndarray

Returns the current trading prices of all products

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

The exogenous contracts in the current step for all products

Returns:

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

property allow_zero_quantity: bool

Does negotiations allow zero quantity?

property state: scml.scml2020.common.FactoryState

Receives the factory state

property current_balance

Current balance of the agent

property current_inventory

Current inventory of the agent

property profile: scml.scml2020.common.FactoryProfile

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

property all_suppliers: List[List[str]]

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

property all_consumers: List[List[str]]

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

property inputs: numpy.ndarray

Returns the number of inputs to every production process

property outputs: numpy.ndarray

Returns the number of outputs to every production process

property n_competitors: int

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

property my_input_product: int

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

property my_output_product: int

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

property my_input_products: numpy.ndarray

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

property my_output_products: numpy.ndarray

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

property my_suppliers: List[str]

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

Remarks:

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

property my_consumers: List[str]

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

Remarks:

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

property n_lines: int

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

property catalog_prices: numpy.ndarray

Returns the catalog prices of all products

property n_products: int

Number of products in the world

property n_processes: int

Returns the number of processes in the system

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 level

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

property is_middle_level

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

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

Requests a negotiation

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

  • product – The product to negotiate about

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

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

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

  • controller – The controller to manage the complete set of negotiations

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

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

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

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

Returns:

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

Remarks:

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

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

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

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

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

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

Requests a negotiation

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

  • product – The product to negotiate about

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

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

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

  • partner – ID of the partner to negotiate with.

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

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

Returns:

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

Remarks:

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

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

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

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

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

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

Parameters:
  • process – The process to run

  • repeats – How many times to repeat the process

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

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

  • override – Whether to override existing production commands or not

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

  • partial_ok – If true, allows partial scheduling

Returns:

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

Remarks:

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

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

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

Orders production of the given process

Parameters:
  • process – The process to run

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

  • lines – The corresponding lines to run the process at

Remarks:

  • len(steps) must equal len(lines)

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

available_for_production(repeats: int, step: int | Tuple[int, int] = ANY_STEP, line: int = ANY_LINE, override: bool = True, method: str = 'latest') Tuple[numpy.ndarray, numpy.ndarray][source]

Finds available times and lines for scheduling production.

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

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

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

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

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

Returns:

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

Remarks:

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

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

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

Sets the production commands for all lines in the given step

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

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

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

Cancels any production commands on that line at this step

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

  • line – The production line

Returns:

success/failure

Remarks:

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

reports_of_agent(aid: str) Dict[int, scml.scml2020.common.FinancialReport][source]

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

reports_at_step(step: int) Dict[str, scml.scml2020.common.FinancialReport][source]

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

is_system(aid: str) bool[source]

Checks whether an agent is a system agent or not

Parameters:

aid – Agent ID

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

Checks whether the agent is bankrupt

Parameters:

aid – Agent ID (None means self)

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

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

Parameters:

step – The simulation step (day)

Remarks:

If step is None, the current step will be used

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

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

Parameters:

step – The simulation step (day)

Remarks:

If step is None, the current step will be used

scml.SYSTEM_BUYER_ID = 'BUYER'[source]

ID of the system buyer agent

scml.SYSTEM_SELLER_ID = 'SELLER'[source]

ID of the system seller agent

scml.COMPENSATION_ID = 'COMPENSATOR'[source]

ID of the takeover agent

scml.ANY_STEP[source]

Used to indicate any time-step

scml.NO_COMMAND[source]

A constant indicating no command is scheduled on a factory line

scml.ANY_LINE[source]

Used to indicate any line

scml.INFINITE_COST[source]

A constant indicating an invalid cost for lines incapable of running some process

scml.QUANTITY = 0[source]

Index of quantity in negotiation issues

scml.TIME = 1[source]

Index of time in negotiation issues

scml.UNIT_PRICE = 2[source]

Index of unit price in negotiation issues

scml.is_system_agent(aid: str) bool[source]

Checks whether an agent is a system agent or not

Parameters:

aid – Agent ID

Returns:

True if the ID is for a system agent.

class scml.FactoryState[source]
property n_lines: int
property n_steps: int
property n_products: int
property n_processes: int
inventory: numpy.ndarray

An n_products vector giving current quantity of every product in storage

balance: int

Current balance in the wallet

commands: numpy.ndarray

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

inventory_changes: numpy.ndarray

Changes in the inventory in the last step

balance_change: int

Change in the balance in the last step

contracts: list[list[ContractInfo]]

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

class scml.FinancialReport[source]

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

__slots__ = ['agent_id', 'step', 'cash', 'assets', 'breach_prob', 'breach_level', 'is_bankrupt', 'agent_name']
agent_id: str

Agent ID

step: int

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

cash: int

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

assets: int

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

breach_prob: float

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

breach_level: float

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

is_bankrupt: bool

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

agent_name: str

Agent name for printing purposes

__str__()

Return str(self).

class scml.FactoryProfile[source]

Defines all private information of a factory

property n_lines
property n_products
property n_processes
property processes: numpy.ndarray

The processes that have valid costs

property input_products: numpy.ndarray

The input products to all processes runnable (See processes )

property output_products: numpy.ndarray

The output products to all processes runnable (See processes )

__slots__ = ['costs']
costs: numpy.ndarray

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

class scml.Failure[source]

A production failure

__slots__ = ['is_inventory', 'line', 'step', 'process']
is_inventory: bool

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

line: int

The line at which the failure happened

step: int

The step at which the failure happened

process: int

The process that failed to execute

class scml.ExogenousContract[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

product: int

Product

quantity: int

Quantity

unit_price: int

Unit price

time: int

Delivery time

revelation_time: int

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

seller: int

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

buyer: int

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

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.

schedule_range: dict[str, tuple[int, int, bool]]

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

can_be_produced(contract_id: str)[source]

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

Remarks:

  • Cannot be called before calling on_contracts_finalized

on_contract_executed(contract: negmas.Contract) None[source]
on_contract_breached(contract: negmas.Contract, breaches, resolution) None[source]
class scml.SupplyDrivenProductionStrategy(*args, **kwargs)[source]

Bases: ProductionStrategy

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.

step()[source]
on_contracts_finalized(signed: list[negmas.Contract], cancelled: list[negmas.Contract], rejectors: list[list[str]]) None[source]
class scml.DemandDrivenProductionStrategy(*args, **kwargs)[source]

Bases: ProductionStrategy

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.

on_contracts_finalized(signed: list[negmas.Contract], cancelled: list[negmas.Contract], rejectors: list[list[str]]) None[source]
class scml.TradeDrivenProductionStrategy(*args, **kwargs)[source]

Bases: ProductionStrategy

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.

on_contracts_finalized(signed: list[negmas.Contract], cancelled: list[negmas.Contract], rejectors: list[list[str]]) None[source]
class scml.TradePredictionStrategy(*args, predicted_outputs: int | numpy.ndarray = None, predicted_inputs: int | numpy.ndarray = None, add_trade=False, **kwargs)[source]

A prediction strategy for expected inputs and outputs at every step

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

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

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

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

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

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

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

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

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

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

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

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

expected_outputs

Expected output quantity every step

expected_inputs

Expected input quantity every step

input_cost: numpy.ndarray

Expected unit price of the input

output_price: numpy.ndarray

Expected unit price of the output

abstract trade_prediction_init() None[source]

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

trade_prediction_before_step() None[source]

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

trade_prediction_step() None[source]

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

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

Bases: TradePredictionStrategy

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.

property internal_state
trade_prediction_init()[source]

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

on_contracts_finalized(signed: List[negmas.Contract], cancelled: List[negmas.Contract], rejectors: List[List[str]]) None[source]
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.

abstract predict_quantity(contract: negmas.Contract)[source]
class scml.FixedERPStrategy(*args, execution_fraction=0.95, **kwargs)[source]

Bases: ExecutionRatePredictionStrategy

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.

predict_quantity(contract: negmas.Contract)[source]
class scml.MeanERPStrategy(*args, execution_fraction=0.95, **kwargs)[source]

Bases: ExecutionRatePredictionStrategy

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.

property internal_state
predict_quantity(contract: negmas.Contract)[source]
init()[source]
on_contract_executed(contract: negmas.Contract) None[source]
on_contract_breached(contract: negmas.Contract, breaches: List[negmas.Breach], resolution: negmas.Contract | None) None[source]
class scml.MarketAwareTradePredictionStrategy(*args, predicted_outputs: int | numpy.ndarray = None, predicted_inputs: int | numpy.ndarray = None, add_trade=False, **kwargs)[source]

Bases: TradePredictionStrategy

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.

property internal_state
init()[source]
trade_prediction_init()[source]

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

__update()[source]
trade_prediction_step()[source]

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

trade_prediction_before_step()[source]

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

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.

sign_all_contracts(contracts: List[negmas.Contract]) List[str | None][source]
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.

sign_all_contracts(contracts: List[negmas.Contract]) List[str | None][source]
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.

sign_all_contracts(contracts: List[negmas.Contract]) List[str | None][source]
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.

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

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

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

  • quantity – The maximum quantity to negotiate about

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

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

  • partners – A list of partners to negotiate with

Remarks:

  • This method assumes that product is either my_input_product or my_output_product

step()[source]

Generates buy and sell negotiations as needed

on_contracts_finalized(signed: List[negmas.Contract], cancelled: List[negmas.Contract], rejectors: List[List[str]]) None[source]
_generate_negotiations(step: int, sell: bool) None[source]

Generates all the required negotiations for selling/buying for the given step

_urange(step, is_seller, time_range)[source]
_trange(step, is_seller)[source]
target_quantities(steps: Tuple[int, int], sell: bool) numpy.ndarray[source]

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

Parameters:
  • steps – Simulation step

  • sell – Sell or buy

abstract _start_negotiations(product: int, sell: bool, step: int, qvalues: Tuple[int, int], uvalues: Tuple[int, int], tvalues: Tuple[int, int], partners: List[str]) None[source]

Actually start negotiations with the given agenda

Parameters:
  • product – The product to negotiate about.

  • sell – If true, this is a sell negotiation

  • step – The step

  • qvalues – the range of quantities

  • uvalues – the range of unit prices

  • tvalues – the range of times

  • partners – partners

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

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

Parameters:
  • step – Simulation step

  • sell – Sell or buy

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

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

Parameters:
  • step – Simulation step

  • sell – Sell or buy

abstract respond_to_negotiation_request(initiator: str, issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) negmas.Negotiator | None[source]
class scml.StepNegotiationManager(*args, negotiator_type: negmas.SAONegotiator | str = AspirationNegotiator, negotiator_params: Dict[str, Any] | None = None, **kwargs)[source]

Bases: scml.scml2020.components.prediction.MeanERPStrategy, NegotiationManager

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

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

  • negotiator_params – Paramters of the negotiator

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

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

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

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

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

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

init()[source]
_start_negotiations(product: int, sell: bool, step: int, qvalues: Tuple[int, int], uvalues: Tuple[int, int], tvalues: Tuple[int, int], partners: List[str]) None[source]

Actually start negotiations with the given agenda

Parameters:
  • product – The product to negotiate about.

  • sell – If true, this is a sell negotiation

  • step – The step

  • qvalues – the range of quantities

  • uvalues – the range of unit prices

  • tvalues – the range of times

  • partners – partners

respond_to_negotiation_request(initiator: str, issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) negmas.Negotiator | None[source]
all_negotiations_concluded(controller_index: int, is_seller: bool) None[source]

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

add_controller(is_seller: bool, target, urange: Tuple[int, int], expected_quantity: int, step: int) scml.scml2020.services.controllers.StepController[source]
insert_controller(controller: scml.scml2020.services.controllers.StepController, is_seller: bool, target, urange: Tuple[int, int], expected_quantity: int, step: int = None) scml.scml2020.services.controllers.StepController[source]
create_controller(is_seller: bool, target, urange: Tuple[int, int], expected_quantity: int, step: int) scml.scml2020.services.controllers.StepController[source]
_get_controller(mechanism) scml.scml2020.services.controllers.StepController[source]
class scml.IndependentNegotiationsManager(*args, negotiator_type: negmas.SAONegotiator | str = AspirationNegotiator, negotiator_params: Dict[str, Any] | None = None, **kwargs)[source]

Bases: NegotiationManager

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

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

  • negotiator_params – Parameters of the negotiator

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

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

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

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

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

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

_start_negotiations(product: int, sell: bool, step: int, qvalues: Tuple[int, int], uvalues: Tuple[int, int], tvalues: Tuple[int, int], partners: List[str]) None[source]

Actually start negotiations with the given agenda

Parameters:
  • product – The product to negotiate about.

  • sell – If true, this is a sell negotiation

  • step – The step

  • qvalues – the range of quantities

  • uvalues – the range of unit prices

  • tvalues – the range of times

  • partners – partners

respond_to_negotiation_request(initiator: str, issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) negmas.Negotiator | None[source]
create_ufun(is_seller: bool, issues=None, outcomes=None) negmas.UtilityFunction[source]

Creates a utility function

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

Creates a negotiator

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.

step()[source]
respond_to_negotiation_request(initiator: str, issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) negmas.Negotiator | None[source]
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.

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

A simulated factory

property state: scml.scml2020.common.FactoryState
property current_inventory: numpy.ndarray

Current inventory contents

property current_balance: int

Current wallet balance

_disallow_concurrent_negs_with_same_partners

The readonly factory profile (See FactoryProfile )

commands

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

_balance

Current balance

_inventory

Current inventory

agent_id

A unique ID for the agent owning the factory

inputs

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

outputs

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

inventory_changes

Changes in the inventory in the last step

balance_change = 0

Change in the balance in the last step

min_balance

The minimum balance possible

is_bankrupt = False

Will be true when the factory is bankrupt

agent_name

SCML2020Agent names used for logging purposes

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

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

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

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

Parameters:
  • process – The process index

  • repeats – How many times to repeat the process

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

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

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

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

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

Returns:

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

Remarks:

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

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

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

Orders production of the given process

Parameters:
  • process – The process to run

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

  • lines – The corresponding lines to run the process at

Remarks:

  • len(steps) must equal len(lines)

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

available_for_production(repeats: int, step: int | Tuple[int, int] = ANY_STEP, line: int = ANY_LINE, override: bool = True, method: str = 'latest') Tuple[numpy.ndarray, numpy.ndarray]

Finds available times and lines for scheduling production.

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

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

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

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

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

Returns:

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

Remarks:

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

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

cancel_production(step: int, line: int) bool

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

Parameters:
  • step – Step to cancel at

  • line – Line to cancel at

Returns:

True if step >= self.current_step

Remarks:

  • Cannot cancel a process in the past or present.

step() List[scml.scml2020.common.Failure][source]

Override this method to modify stepping logic.

spot_price(product: int, spot_loss: float) int

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

Parameters:
  • product – Product

  • spot_loss – Spot loss specific to that agent

Returns:

The unit price

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

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

Parameters:
  • product – Product

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

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

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

  • no_bankruptcy – Never bankrupt the agent on this transaction

  • no_borrowing – Never borrow for this transaction

Returns:

The quantity actually stored or taken out (always positive)

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

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

Parameters:
  • product – The product transacted on

  • quantity – The quantity (added)

  • unit_price – The unit price (paid)

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

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

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

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

Returns:

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

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

Pays money

Parameters:
  • money – amount to pay

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

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

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

Returns:

The amount actually paid

bankrupt(required: int) int

Bankruptcy processing for the given agent

Parameters:

required – The money required after the bankruptcy is processed

Returns:

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

class scml.SCML2020World(process_inputs: numpy.ndarray, process_outputs: numpy.ndarray, catalog_prices: numpy.ndarray, profiles: list[scml.scml2020.common.FactoryProfile], agent_types: list[type[scml.scml2020.agent.SCML2020Agent]], agent_params: list[dict[str, Any]] | None = None, exogenous_contracts: Collection[scml.scml2020.common.ExogenousContract] = (), initial_balance: numpy.ndarray | tuple[int, int] | int = 1000, allow_buying_output=False, allow_selling_input=False, catalog_quantities: int | numpy.ndarray = 50, buy_missing_products=True, borrow_on_breach=True, bankruptcy_limit=0.0, liquidation_rate=1.0, spot_market_global_loss=0.3, interest_rate=0.05, financial_report_period: int = 5, compensation_fraction: float = 1.0, compensate_immediately=False, compensate_before_past_debt=True, exogenous_horizon: int | None = None, exogenous_force_max: bool = False, production_confirm=False, production_buy_missing=False, production_no_borrow=True, production_no_bankruptcy=False, production_penalty=0.15, compact=False, no_logs=False, n_steps=1000, time_limit=60 * 90, neg_n_steps=20, neg_time_limit=2 * 60, neg_step_time_limit=60, negotiation_speed=21, negotiation_quota_per_step=None, negotiation_quota_per_simulation=float('inf'), n_concurrent_negs_between_partners=float('inf'), shuffle_negotiations=False, end_negotiation_on_refusal_to_propose=True, trading_price_discount=0.9, spot_discount=0.9, spot_multiplier=0.05, signing_delay=0, force_signing=False, batch_signing=True, name: str = None, publish_exogenous_summary=True, publish_trading_prices=True, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_trading: float = 0.5, inventory_valuation_catalog: float = 0.0, **kwargs)[source]

Bases: negmas.situated.TimeInAgreementMixin, negmas.situated.World

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

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

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

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

  • profiles – An n_agents list of FactoryProfile objects specifying the private profile of the factory associated with each agent.

  • agent_types – An n_agents list of strings/ SCML2020Agent classes specifying the type of each agent

  • agent_params – An n_agents dictionaries giving the parameters of each agent

  • initial_balance – The initial balance in each agent’s wallet. All agents will start with this same value.

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

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

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

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

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

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

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

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

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

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

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

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

  • exogenous_horizon – The horizon for revealing external contracts

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

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

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

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

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

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

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

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

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

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

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

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

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

  • name – The name of the simulations

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

property productivity: float

Fraction of production lines occupied during the simulation

property relative_productivity: float | None

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

property bankruptcy_rate: float

The fraction of factories that went bankrupt

property num_bankrupt: float

The fraction of factories that went bankrupt

property winners

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

property trading_prices
property stats_df: pandas.DataFrame

Returns a pandas data frame with the stats

property contracts_df: pandas.DataFrame

Returns a pandas data frame with the contracts

property system_agents: list[scml.scml2020.agent.SCML2020Agent]

Returns the two system agents

property system_agent_names: list[str]

Returns the names two system agents

property non_system_agents: list[scml.scml2020.agent.SCML2020Agent]

Returns all agents except system agents

property non_system_agent_names: list[str]

Returns names of all agents except system agents

property agreement_fraction: float

Fraction of negotiations ending in agreement and leading to signed contracts

system_agent_ids
non_system_agent_ids
classmethod generate(agent_types: list[type[scml.scml2020.agent.SCML2020Agent] | str], agent_params: list[dict[str, Any]] | None = None, agent_processes: list[int] | None = None, n_steps: tuple[int, int] | int = (50, 200), n_processes: tuple[int, int] | int = (2, 4), n_lines: numpy.ndarray | tuple[int, int] | int = 10, n_agents_per_process: numpy.ndarray | tuple[int, int] | int = (2, 4), process_inputs: numpy.ndarray | tuple[int, int] | int = 1, process_outputs: numpy.ndarray | tuple[int, int] | int = 1, production_costs: numpy.ndarray | tuple[int, int] | int = (1, 4), profit_means: numpy.ndarray | tuple[float, float] | float = (0.15, 0.2), profit_stddevs: numpy.ndarray | tuple[float, float] | float = 0.001, max_productivity: numpy.ndarray | tuple[float, float] | float = 1.0, initial_balance: numpy.ndarray | tuple[int, int] | int | None = None, cost_increases_with_level=True, equal_exogenous_supply=False, equal_exogenous_sales=False, exogenous_supply_predictability: tuple[float, float] | float = (0.6, 0.9), exogenous_sales_predictability: tuple[float, float] | float = (0.6, 0.9), exogenous_control: tuple[float, float] | float = (0.2, 0.8), cash_availability: tuple[float, float] | float = (1.5, 2.5), force_signing=False, profit_basis=np.max, horizon: tuple[float, float] | float = (0.2, 0.5), inventory_valuation_trading: numpy.ndarray | tuple[float, float] | float = 0.5, inventory_valuation_catalog: numpy.ndarray | tuple[float, float] | float = 0.0, random_agent_types: bool = False, cost_relativity: float = 1.0, exogenous_generation_method='profitable', exogenous_supply_surplus: tuple[float, float] | float = 0.0, exogenous_sales_surplus: tuple[float, float] | float = 0.0, run_extra_checks: bool = True, **kwargs) dict[str, Any][source]

Generates the configuration for a world

Parameters:
  • agent_types – All agent types

  • agent_params – Agent parameters used to initialize them

  • n_steps – Number of simulation steps

  • n_processes – Number of processes in the production chain

  • n_lines – Number of lines per factory

  • process_inputs – Number of input units per process

  • process_outputs – Number of output units per process

  • production_costs – Production cost per factory

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

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

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

  • inventory_valuation_trading – The fraction of trading price to value items at the end.

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

  • initial_balance – The initial balance of all agents

  • n_agents_per_process – Number of agents per process

  • agent_processes – The process for each agent. If not None , it will override n_agents_per_process and must be a list/tuple of the same length as agent_types . Morevoer, random_agent_types must be False in this case

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • **kwargs

Returns:

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

Remarks:

  • There are two general ways to use this generator:
    1. Pass random_agent_types = True, and pass agent_types, agent_processes to control placement of each agent in each level of the production graph.

    2. Pass random_agent_types = False and pass agent_types, n_agents_per_process to make the system randomly place the specified number of agents in each production level

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

classmethod generate_guaranteed_profit(n_steps: int, n_lines: int, n_agents_per_process: int, process_of_agent: list[int], first_agent: list[int], last_agent: list[int], production_costs: list[int], exogenous_control: float, cash_availability: float, force_signing: bool, horizon: int, exogenous_supplies: list[int], max_productivity_process: list[float], max_productivity_agent: list[float], equal_exogenous_sales: bool, process_inputs: list[int], process_outputs: list[int], exogenous_sales_predictability: float, costs: numpy.ndarray, profit_stddevs_agent=list[float], profit_means_agent=list[float], initial_balance: numpy.ndarray | tuple[int, int] | int | None = None, cost_relativity: float = 1.0, profit_basis=np.max, inventory_valuation_trading: float = 0.5, inventory_valuation_catalog: float = 0.0, run_extra_checks=True) tuple[list[scml.scml2020.common.ExogenousContract], list[int], list[scml.scml2020.common.FactoryProfile], list[float], dict[str, Any]][source]

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

classmethod generate_profitable(n_steps: int, n_lines: int, n_agents_per_process: int, process_of_agent: list[int], first_agent: list[int], last_agent: list[int], production_costs: list[int], exogenous_control: float, cash_availability: float, force_signing: bool, horizon: int, exogenous_supplies: list[int], max_productivity_process: list[float], max_productivity_agent: list[float], equal_exogenous_sales: bool, process_inputs: list[int], process_outputs: list[int], exogenous_sales_predictability: float, costs: numpy.ndarray, profit_stddevs_agent=list[float], profit_means_agent=list[float], initial_balance: numpy.ndarray | tuple[int, int] | int | None = None, cost_relativity: float = 1.0, profit_basis=np.max, inventory_valuation_trading: float = 0.5, inventory_valuation_catalog: float = 0.0, run_extra_checks: bool = True) tuple[list[scml.scml2020.common.ExogenousContract], list[int], list[scml.scml2020.common.FactoryProfile], list[float], dict[str, Any]][source]

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

get_private_state(agent: scml.scml2020.agent.SCML2020Agent) dict[source]

Reads the private state of the given agent

add_financial_report(agent: scml.scml2020.agent.SCML2020Agent, factory: scml.scml2020.factory.Factory, reports_agent, reports_time) None[source]

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

Parameters:
  • agent – The agent

  • factory – Its factory

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

  • reports_time – A dictionary of financial reports indexed by time

Returns:

negs_between(a1, a2)[source]
current_balance(agent_id: str)[source]
can_negotiate(a1, a2)[source]
simulation_step(stage)[source]

A single step of the simulation.

Parameters:

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

Remarks:

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

contract_size(contract: negmas.Contract) float[source]

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

Returns:

contract_record(contract: negmas.Contract) dict[str, Any][source]

Converts a contract to a record suitable for permanent storage

breach_record(breach: negmas.Breach) dict[str, Any][source]

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

execute_action(action: negmas.Action, agent: scml.scml2020.agent.SCML2020Agent, callback: Callable = None) bool[source]

Executes the given action by the given agent

post_step_stats()[source]

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

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

pre_step_stats()[source]

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

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

welfare(include_bankrupt: bool = False) float[source]

Total welfare of all agents

relative_welfare(include_bankrupt: bool = False) float | None[source]

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

order_contracts_for_execution(contracts: Collection[negmas.Contract]) Collection[negmas.Contract][source]

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

_execute(product: int, q: int, p: int, u: int, buyer_factory: scml.scml2020.factory.Factory, seller_factory: scml.scml2020.factory.Factory, has_breaches: bool)[source]

Executes the contract

__register_contract(agent_id: str, level: float) None[source]

Registers execution of the contract in the agent’s stats

record_bankrupt(factory: scml.scml2020.factory.Factory) None[source]

Records agent bankruptcy

on_contract_concluded(contract: negmas.Contract, to_be_signed_at: int) None[source]

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

Parameters:
  • contract – The contract to add

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

Remarks:

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

  • You should ALWAYS call this function when overriding it.

is_valid_contact(contract: negmas.Contract) bool[source]

Checks whether a signed contract is valid

on_contract_signed(contract: negmas.Contract) bool[source]

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

Parameters:

contract – The contract to add

Returns:

True if everything went OK and False otherwise

Remarks:

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

  • You should ALWAYS call this function when overriding it.

nullify_contract(contract: negmas.Contract, new_quantity: int)[source]
__register_breach(agent_id: str, level: float, contract_total: float, factory: scml.scml2020.factory.Factory) int[source]

Registers a breach of the given level on the given agent. Assume that the contract is already added to the agent_contracts

Parameters:
  • agent_id – The perpetrator of the breach

  • level – The breach level

  • contract_total – The total of the contract breached (quantity * unit_price)

  • factory – The factory corresponding to the perpetrator

Returns:

If nonzero, the agent should go bankrupt and this amount taken from them

_spot_loss(aid: str) float[source]
start_contract_execution(contract: negmas.Contract) set[negmas.Breach] | None[source]

Tries to execute the contract

Parameters:

contract

Returns:

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

Return type:

Set[Breach]

Remarks:

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

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

complete_contract_execution(contract: negmas.Contract, breaches: list[negmas.Breach], resolution: negmas.Contract) None[source]

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

Parameters:
  • contract – The contract considered.

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

  • resolution – The agreed upon resolution

Returns:

compensate(available: int, factory: scml.scml2020.factory.Factory) dict[str, list[tuple[negmas.Contract, int, int]]][source]

Called by a factory when it is going bankrupt after liquidation

Parameters:
  • available – The amount available from liquidation

  • factory – The factory being bankrupted

Returns:

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

scores(assets_multiplier_trading: float | None = None, assets_multiplier_catalog: float | None = None, assets_multiplier: float | None = None) dict[str, float][source]

scores of all agents given the asset multiplier.

Parameters:

assets_multiplier – a multiplier to multiply the assets with.

trading_prices_for(discount: float = 1.0, condition='executed') numpy.ndarray[source]

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

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

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

Returns:

an n_products vector of trading prices

draw(steps: tuple[int, int] | int | None = None, what: Collection[str] = DEFAULT_EDGE_TYPES, who: Callable[[negmas.Agent], bool] = None, where: Callable[[negmas.Agent], int | tuple[float, float]] = None, together: bool = True, axs: Collection[matplotlib.axis.Axis] = None, ncols: int = 4, figsize: tuple[int, int] = (15, 15), **kwargs) tuple[matplotlib.axis.Axis, networkx.Graph] | tuple[list[matplotlib.axis.Axis], list[networkx.Graph]][source]
class scml.SCML2021World(*args, **kwargs)[source]

Bases: SCML2020World

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

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

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

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

  • profiles – An n_agents list of FactoryProfile objects specifying the private profile of the factory associated with each agent.

  • agent_types – An n_agents list of strings/ SCML2020Agent classes specifying the type of each agent

  • agent_params – An n_agents dictionaries giving the parameters of each agent

  • initial_balance – The initial balance in each agent’s wallet. All agents will start with this same value.

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

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

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

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

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

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

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

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

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

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

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

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

  • exogenous_horizon – The horizon for revealing external contracts

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

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

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

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

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

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

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

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

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

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

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

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

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

  • name – The name of the simulations

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

classmethod generate(*args, inventory_valuation_trading: numpy.ndarray | tuple[float, float] | float = (0.0, 0.5), horizon: tuple[float, float] | float = (0.2, 0.5), **kwargs) dict[str, Any][source]

Generates the configuration for a world

Parameters:
  • agent_types – All agent types

  • agent_params – Agent parameters used to initialize them

  • n_steps – Number of simulation steps

  • n_processes – Number of processes in the production chain

  • n_lines – Number of lines per factory

  • process_inputs – Number of input units per process

  • process_outputs – Number of output units per process

  • production_costs – Production cost per factory

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

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

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

  • inventory_valuation_trading – The fraction of trading price to value items at the end.

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

  • initial_balance – The initial balance of all agents

  • n_agents_per_process – Number of agents per process

  • agent_processes – The process for each agent. If not None , it will override n_agents_per_process and must be a list/tuple of the same length as agent_types . Morevoer, random_agent_types must be False in this case

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  • **kwargs

Returns:

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

Remarks:

  • There are two general ways to use this generator:
    1. Pass random_agent_types = True, and pass agent_types, agent_processes to control placement of each agent in each level of the production graph.

    2. Pass random_agent_types = False and pass agent_types, n_agents_per_process to make the system randomly place the specified number of agents in each production level

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

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

Bases: SCML2021World

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

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

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

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

  • profiles – An n_agents list of FactoryProfile objects specifying the private profile of the factory associated with each agent.

  • agent_types – An n_agents list of strings/ SCML2020Agent classes specifying the type of each agent

  • agent_params – An n_agents dictionaries giving the parameters of each agent

  • initial_balance – The initial balance in each agent’s wallet. All agents will start with this same value.

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

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

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

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

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

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

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

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

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

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

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

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

  • exogenous_horizon – The horizon for revealing external contracts

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

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

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

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

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

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

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

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

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

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

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

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

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

  • name – The name of the simulations

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

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

Bases: SCML2022World

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

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

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

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

  • profiles – An n_agents list of FactoryProfile objects specifying the private profile of the factory associated with each agent.

  • agent_types – An n_agents list of strings/ SCML2020Agent classes specifying the type of each agent

  • agent_params – An n_agents dictionaries giving the parameters of each agent

  • initial_balance – The initial balance in each agent’s wallet. All agents will start with this same value.

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

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

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

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

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

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

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

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

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

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

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

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

  • exogenous_horizon – The horizon for revealing external contracts

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

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

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

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

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

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

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

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

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

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

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

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

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

  • name – The name of the simulations

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

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

Bases: SCML2022World

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

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

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

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

  • profiles – An n_agents list of FactoryProfile objects specifying the private profile of the factory associated with each agent.

  • agent_types – An n_agents list of strings/ SCML2020Agent classes specifying the type of each agent

  • agent_params – An n_agents dictionaries giving the parameters of each agent

  • initial_balance – The initial balance in each agent’s wallet. All agents will start with this same value.

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

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

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

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

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

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

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

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

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

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

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

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

  • exogenous_horizon – The horizon for revealing external contracts

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

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

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

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

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

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

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

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

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

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

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

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

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

  • name – The name of the simulations

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

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.__all__[source]
class scml.OneShotAgent(owner=None, ufun: scml.oneshot.OneShotUFun | None = None, name=None)[source]

Bases: negmas.SAOController, negmas.Entity, abc.ABC

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

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

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

property awi: scml.oneshot.OneShotAWI

Returns a OneShotAWI object for accessing the simulation.

property running_negotiations: list[negmas.situated.RunningNegotiationInfo]

The negotiations currently requested by the agent.

Returns:

A list of negotiation information objects (RunningNegotiationInfo)

property unsigned_contracts: list[negmas.Contract]

All contracts that are not yet signed.

property internal_state: dict[str, Any]

Returns the internal state of the agent for debugging purposes.

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

init()[source]

Called once after the AWI is set.

Remarks:
  • Use this for any proactive initialization code.

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.

before_step()[source]

Called at the beginning of every step.

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

step()[source]

Called at the end of every step.

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

connect_to_oneshot_adapter(owner)[source]

Connects the agent to its adapter (used internally)

connect_to_2021_adapter(owner)[source]

Connects the agent to its adapter (used internally)

abstract propose(negotiator_id: str, state: negmas.SAOState) negmas.Outcome | None[source]

Proposes an offer to one of the partners.

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

  • state – Mechanism state including current step

Returns:

an outcome to offer.

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

Responds to an offer from one of the partners.

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

  • state – Mechanism state including current step

Returns:

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

Remarks:

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

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

Called whenever a negotiation ends without agreement.

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

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

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

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

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

Called whenever a negotiation ends with agreement.

Parameters:
  • contract – The Contract agreed upon.

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

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

Signs all contracts (used internally)

on_contract_executed(contract) None[source]
on_contract_breached(contract, breaches, resolution) None[source]
get_negotiator(partner_id: str) negmas.sao.SAONegotiator[source]

Returns the negotiator corresponding to the given partner ID.

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

get_ami(partner_id: str) negmas.sao.SAONMI[source]

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

get_nmi(partner_id: str) negmas.sao.SAONMI[source]

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

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

Bases: negmas.SAOSyncController, OneShotAgent, abc.ABC

An agent that automatically accumulate offers from opponents and allows you to control all negotiations centrally in the counter_all method.

abstract counter_all(offers: dict[str, negmas.Outcome | None], states: dict[str, negmas.SAOState]) dict[str, negmas.SAOResponse][source]

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

Parameters:
  • offers – Maps negotiator IDs to offers

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

Returns:

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

Remarks:
  • The response type CANNOT be WAIT.

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

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

abstract first_proposals() dict[str, negmas.Outcome | None][source]

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

Returns:

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

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

Signs all contracts (used internally)

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

Bases: negmas.SAOSingleAgreementController, OneShotSyncAgent

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

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

The general algorithm for this controller is something like this:

  • Receive offers from all partners.

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

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

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

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

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

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

Parameters:

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

abstract is_acceptable(offer: negmas.Outcome, source: str, state: negmas.SAOState) bool[source]

Should decide if the given offer is acceptable

Parameters:
  • offer – The offer being tested

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

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

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

abstract best_offer(offers: dict[str, negmas.Outcome]) str | None[source]

Return the ID of the negotiator with the best offer

Parameters:

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

Returns:

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

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

Compares two outcomes of the same negotiation

Parameters:
  • a – “Outcome”

  • b – “Outcome”

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

  • state – Current state of the negotiation

Returns:

True if utility(a) > utility(b)

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

Bases: OneShotAgent

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

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

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

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

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

Remarks:

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

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

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

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

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

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

abstract generate_ufuns() dict[str, negmas.preferences.UtilityFunction][source]

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

generate_negotiator(partner_id: str) negmas.sao.SAONegotiator[source]

Returns a negotiator to be used with some partner.

Remarks:

The default implementation will use the default_negotiator_type and default_negotiator_params.

_urange(u: negmas.preferences.UtilityFunction, issues: tuple[negmas.Issue, Ellipsis])[source]
_unorm(u: negmas.preferences.UtilityFunction, mn, mx)[source]
_get_ufuns()[source]

Internal method that makes sure the reservation value is set to a meaningful value and that the ufun is normalized if needed

init()[source]

Called once after the AWI is set.

Remarks:
  • Use this for any proactive initialization code.

step()[source]

Called at the end of every step.

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

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

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

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

  • name – negotiator name

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

Returns:

The negotiator to be controlled. None for failure

Remarks:

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

propose(negotiator_id, state)[source]

Proposes an offer to one of the partners.

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

  • state – Mechanism state including current step

Returns:

an outcome to offer.

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

Bases: negmas.sao.SAONegotiator, negmas.ControlledNegotiator

Base class for all SAO negotiators.

Parameters:
  • name – Negotiator name

  • parent – Parent controller if any

  • preferences – The preferences of the negotiator

  • ufun – The utility function of the negotiator (overrides preferences if given)

  • owner – The Agent that owns the negotiator.

Remarks:
  • The only method that must be implemented by any SAONegotiator is propose.

  • The default respond method, accepts offers with a utility value no less than whatever propose returns with the same mechanism state.

propose(state)[source]

Propose an offer or None to refuse.

Parameters:

stateGBState giving current state of the negotiation.

Returns:

The outcome being proposed or None to refuse to propose

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

respond(state, source=None)[source]

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

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

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

Returns:

The response to the offer

Return type:

ResponseType

Remarks:
  • The default implementation never ends the negotiation

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

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

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

Bases: scml.oneshot.agent.OneShotSyncAgent

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

before_step()[source]

Called at the beginning of every step.

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

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.

choose_agents(offers, outcome)[source]

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

first_proposals() Dict[str, negmas.Outcome | None][source]

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

Returns:

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

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

Bases: scml.oneshot.agent.OneShotAgent

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

init()[source]

Initialize the quantities and best prices received so far

before_step()[source]

Initialize the quantities and best prices received for next step

on_negotiation_success(contract, mechanism)[source]

Record sales/supplies secured

propose(negotiator_id: str, state, source=None) negmas.Outcome | None[source]

Proposes an offer to one of the partners.

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

  • state – Mechanism state including current step

Returns:

an outcome to offer.

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

Responds to an offer from one of the partners.

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

  • state – Mechanism state including current step

Returns:

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

Remarks:

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

best_offer(negotiator_id)[source]
_needed(negotiator_id)[source]
_is_selling(nmi)[source]
_is_good_price(nmi, state, price)[source]

Checks if a given price is good enough at this stage

_find_good_price(nmi, state)[source]

Finds a good-enough price conceding linearly over time

_price_range(nmi)[source]

Limits the price by the best price received

_th(step, n_steps)[source]

calculates a descending threshold (0 <= th <= 1)

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

Bases: scml.oneshot.agent.OneShotSyncAgent, GreedyOneShotAgent

A greedy agent based on OneShotSyncAgent

before_step()[source]

Called at the beginning of every step.

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

first_proposals()[source]

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

counter_all(offers, states) dict[source]

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

_needs()[source]

Returns both input and output needs

propose(negotiator_id, state)[source]

Proposes an offer to one of the partners.

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

  • state – Mechanism state including current step

Returns:

an outcome to offer.

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

Responds to an offer from one of the partners.

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

  • state – Mechanism state including current step

Returns:

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

Remarks:

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

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

Bases: scml.oneshot.agent.OneShotSingleAgreementAgent

A greedy agent based on OneShotSingleAgreementAgent

before_step()[source]

Called at the beginning of every step.

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

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

Should decide if the given offer is acceptable

Parameters:
  • offer – The offer being tested

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

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

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

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_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.OneshotDoNothingAgent(owner=None, ufun: scml.oneshot.OneShotUFun | None = None, name=None)[source]

Bases: scml.oneshot.agent.OneShotAgent

An agent that does nothing.

Remarks:

Note that this agent will lose money whenever it is at the edges (i.e. it is an input or an output agent trading in raw material or final product).

propose(negotiator_id, state)[source]

Proposes an offer to one of the partners.

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

  • state – Mechanism state including current step

Returns:

an outcome to offer.

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

Responds to an offer from one of the partners.

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

  • state – Mechanism state including current step

Returns:

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

Remarks:

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

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

Bases: scml.oneshot.policy.OneShotPolicy

An agent that always raises an exception if called to negotiate. It is useful as a placeholder (for example for RL and MARL exposition)

act(state)[source]

The main policy. Generates an action given a state

class scml.RandomOneShotAgent(*args, p_accept=PROB_ACCEPTANCE, p_end=PROB_END, **kwargs)[source]

Bases: scml.oneshot.agent.OneShotAgent

An agent that randomly leaves the negotiation, accepts or counters with random outcomes

_random_offer(negotiator_id: str)[source]
propose(negotiator_id, state) negmas.outcomes.Outcome | None[source]

Proposes an offer to one of the partners.

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

  • state – Mechanism state including current step

Returns:

an outcome to offer.

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

Responds to an offer from one of the partners.

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

  • state – Mechanism state including current step

Returns:

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

Remarks:

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

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

Bases: SyncRandomOneShotAgent

An agent that distributes its needs over its partners randomly.

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

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

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

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

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

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

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

Bases: SyncRandomOneShotAgent

Same as RandDistOneShotAgent but defaulting to equal distribution of needs

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

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

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

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

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

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

class scml.SyncRandomOneShotAgent(*args, equal: bool = False, overordering_max: float = 0.2, overordering_min: float = 0.0, overordering_exp: float = 0.4, mismatch_exp: float = 4.0, mismatch_max: float = 0.3, **kwargs)[source]

Bases: scml.oneshot.agent.OneShotSyncAgent

An agent that distributes its needs over its partners randomly.

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

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

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

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

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

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

init()[source]

Called once after the AWI is set.

Remarks:
  • Use this for any proactive initialization code.

distribute_needs(t: float) dict[str, int][source]

Distributes my needs randomly over all my partners

first_proposals()[source]

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

Returns:

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

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.

_allowed_mismatch(r: float)[source]
_overordering_fraction(t: float)[source]
_step_and_price(best_price=False)[source]

Returns current step and a random (or max) price

class scml.SingleAgreementRandomAgent(*args, p_accept: float = PROB_ACCEPTANCE, **kwargs)[source]

Bases: scml.oneshot.agent.OneShotSingleAgreementAgent

A controller that agrees randomly to one offer

is_acceptable(offer: negmas.outcomes.Outcome, source: str, state: negmas.sao.SAOState) bool[source]

Should decide if the given offer is acceptable

Parameters:
  • offer – The offer being tested

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

  • state – The state of the negotiation handled by that negotiator

Remarks:
  • If True is returned, this offer will be accepted and all other negotiations will be ended.

best_offer(offers: dict[str, negmas.outcomes.Outcome]) str | None[source]

Return the ID of the negotiator with the best offer

Parameters:

offers – A mapping from negotiator ID to the offer it received

Returns:

The ID of the negotiator with best offer. Ties should be broken. Return None only if there is no way to calculate the best offer.

is_better(a: negmas.outcomes.Outcome | None, b: negmas.outcomes.Outcome | None, negotiator: str, state: negmas.sao.SAOState) bool[source]

Compares two outcomes of the same negotiation

Parameters:
  • a – “Outcome”

  • b – “Outcome”

  • negotiator – The negotiator for which the comparison is to be made

  • state – Current state of the negotiation

Returns:

True if utility(a) > utility(b)

class scml.OneShotAWI(world: scml.oneshot.world.SCMLBaseWorld, agent: scml.oneshot.agent.OneShotAgent)[source]

Bases: negmas.situated.AgentWorldInterface

The agent world interface for the one-shot game.

This class contains all the methods needed to access the simulation to extract information which are divided into 4 groups:

Static World Information:

Information about the world and the agent that does not change over time. These include:

  1. Market Information:

  • n_products: Number of products in the production chain.

  • n_processes: Number of processes in the production chain.

  • n_competitors: Number of other factories on the same production level.

  • all_suppliers: A list of all suppliers by product.

  • all_consumers: A list of all consumers by product.

  • proudction_capacities: The total production capacity (i.e. number of lines)

    for each production level (i.e. manufacturing process).

  • is_system: Is the given system ID corresponding to a system agent?

  • is_bankrupt: Is the given agent bankrupt? None asks about self

  • catalog_prices: A list of the catalog prices (by product).

  • price_multiplier: The multiplier multiplied by the trading/catalog price when the negotiation agendas are created to decide the maximum and lower quantities.

  • is_exogenous_forced: Are exogenous contracts always forced or can the agent decide not to sign them.

  • current_step: Current simulation step (inherited from negmas.situated.AgentWorldInterface ).

  • n_steps: Number of simulation steps (inherited from negmas.situated.AgentWorldInterface ).

  • relative_time: fraction of the simulation completed (inherited from negmas.situated.AgentWorldInterface).

  • state: The full state of the agent ( OneShotState ).

  • **settings* The system settings (inherited from negmas.situated.AgentWorldInterface ).

  • **quantity_range* The maximum quantity in all negotiation agendas (new in 0.6.1)

  • **price_range* The maximum number of different prices in any negotiation agenda (new in 0.6.1)

  1. Agent Information:

  • profile: Gives the agent profile including its production cost, number of production lines, input product index, mean of its delivery penalties, mean of its disposal costs, standard deviation of its shortfall penalties and standard deviation of its disposal costs. See OneShotProfile for full description. This information is private information and no other agent knows it.

  • n_lines: the number of production lines in the factory (private information).

  • is_first_level: Is the agent in the first production level (i.e. it is an input agent that buys the raw material).

  • is_last_level: Is the agent in the last production level (i.e. it is an output agent that sells the final product).

  • is_middle_level: Is the agent neither a first level nor a last level agent

  • my_input_product: The input product to the factory controlled by the agent.

  • my_output_product: The output product from the factory controlled by the agent.

  • level: The production level which is numerically the same as the input product.

  • my_suppliers: A list of IDs for all suppliers to the agent (i.e. agents that can sell the input product of the agent).

  • my_consumers: A list of IDs for all consumers to the agent (i.e. agents that can buy the output product of the agent).

  • penalties_scale: The scale at which to calculate disposal cost/delivery penalties. “trading” and “catalog” mean trading and catalog prices. “unit” means the contract’s unit price while “none” means that disposal cost/shortfall penalty are absolute.

  • n_input_negotiations: Number of negotiations with suppliers.

  • n_output_negotiations: Number of negotiations with consumers.

Dynamic World Information:

Information about the world and the agent that changes over time.

  1. Market Information:

  • trading_prices: The trading prices of all products. This information is only available if publish_trading_prices is set in the world.

  • exogenous_contract_summary: A list of n_products tuples each giving the total quantity and average price of exogenous contracts for a product. This information is only available if publish_exogenous_summary is set in the world.

  • is_perishable: Are all products perishable?

  1. Other Agents’ Information:

  • reports_of_agent: Gives all past financial reports of a given agent. See FinancialReport for details.

  • reports_at_step: Gives all reports of all agents at a given step. See FinancialReport for details.

  1. Current Negotiations Information:

  • current_input_outcome_space: The current outcome-space for all negotiations to buy the input product of the agent. If the agent is at level zero, this will have no issues.

  • current_output_outcome_space: The current outcome-space for all negotiations to buy the output product of the agent. If the agent is at level n_products - 1, this will have no issues.

  • current_negotiation_details: Details on all current negotiations separated into “buy” and “sell” dictionaries.

Useful helpers about current negotiations:

  • current_input_issues: The current issues for all negotiations to buy the input product of the agent. If the agent is at level zero, this will be empty. This is exactly the same as current_input_outcome_space.issues

  • current_output_issues: The current issues for all negotiations to buy the output product of the agent. If the agent is at level n_products - 1, this will be empty. This is exactly the same as current_output_outcome_space.issues

  • current_buy_nmis: All NMIs for current buy negotiations.

  • current_sell_nmis: All NMIs for current sell negotiations.

  • current_nmis: All states for current negotiations.

  • current_buy_states: All states for current buy negotiations.

  • current_sell_states: All states for current sell negotiations.

  • current_states: All states for current negotiations.

  • current_buy_offers: All offers for current buy negotiations.

  • current_sell_offers: All offers for current sell negotiations.

  • current_offers: All offers for current negotiations.

  • running_buy_nmis: All NMIs for running buy negotiations.

  • running_sell_nmis: All NMIs for running sell negotiations.

  • running_nmis: All states for running negotiations.

  • running_buy_states: All states for running buy negotiations.

  • running_sell_states: All states for running sell negotiations.

  • running_states: All states for running negotiations.

  1. Agent Information:

  • current_exogenous_input_quantity: The total quantity the agent have in its input exogenous contract.

  • current_exogenous_input_price: The total price of the agent’s input exogenous contract.

  • current_exogenous_output_quantity: The total quantity the agent have in its output exogenous contract.

  • current_exogenous_output_price: The total price of the agent’s output exogenous contract

  • current_disposal_cost: The disposal cost per unit item in the current step.

  • current_shortfall_penalty: The shortfall penalty per unit item in the current step.

  • current_balance: The current balance of the agent

  • current_score: The current score (balance / initial balance) of the agent

  • current_inventory_input: The total quantity remaining in the inventory of the input product

  • current_inventory_output: The total quantity remaining in the inventory of the output product

  • current_inventory: The total quantity remaining in the inventory of the input and output product

  1. Sales and Supplies (quantities) for today:

  • sales: Today’s sales per customer so far.

  • supplies: Today’s supplies per supplier so far.

  • total_sales: Today’s total sales so far.

  • total_supplies: Today’s total supplies so far.

  • needed_sales: Today’s needed sales as of now (exogenous input + total supplies - exogenous output - total sales so far).

  • needed_supplies: Today’s needed supplies as of now (exogenous output + total sales - exogenous input - total supplies so far).

Services (All inherited from negmas.situated.AgentWorldInterface):
  • logdebug/loginfo/logwarning/logerror: Logs to the world log at the given log level.

  • logdebug_agent/loginf_agnet/…: Logs to the agent specific log at the given log level.

  • bb_query: Queries the bulletin-board.

  • bb_read: Read a section of the bulletin-board.

property max_n_lines: int

Maximum number of lines in the whole system

property quantity_range: int

The maximum cardinality of the quantity issue in all negotiations

property price_range: int

The maximum cardinality of the quantity issue in all negotiations

property n_products: int

Returns the number of products in the system

property n_competitors: int

Returns the number of factories/agents in the same production level

property n_processes: int

Returns the number of processes in the system

property all_suppliers: list[list[str]]

Returns a list of agent IDs for all suppliers for every product

property production_capacities: list[int]

Returns the total production capacity in the market for each process

property all_consumers: list[list[str]]

Returns a list of agent IDs for all consumers for every product

property horizon: int

Horizon for negotiations

property catalog_prices: numpy.ndarray

Returns the catalog prices of all products

property price_multiplier: float

Controls the minimum and maximum prices in the negotiation agendas

Remarks:
  • The base price is either the catalog price if trading price information is not public or the trading price.

  • The minimum unit price in any negotiation agenda is the base price of the previous product in the chain **divided by the multiplier. If that is less than 1, the minimum unit price becomes 1.

  • The maximum unit price in any negotiation agenda is the base price of the previous product in the chain **multiplied by the multiplier. If that is less than 1, the minimum unit price becomes 1.

property is_exogenous_forced: bool

Are exogenous contracts forced in the sense that the agent cannot decide not to sign them?

property allow_zero_quantity: bool

Does negotiations allow zero quantity?

property profile: scml.oneshot.common.OneShotProfile

Gets the profile (static private information) associated with the agent

property n_lines: int

The number of lines in the corresponding factory. You can read state to get this among other information

property n_input_negotiations: int

Number of negotiations with suppliers at every step

property n_output_negotiations: int

Number of negotiations with consumers at every step

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 level

The production level which is the index of the process for this factory (or the index of its input product)

property is_middle_level

Whether this agent is in neither in the first nor in the last level

property my_input_product: int

the product I need to buy

property my_output_product: int

the product I need to sell

property my_competitors: list[str]

Returns the names of all factories in the same level as me

property my_suppliers: list[str]

Returns a list of IDs for all of the agent’s suppliers (agents that can supply the product I need).

property my_consumers: list[str]

Returns a list of IDs for all the agent’s consumers (agents that can consume at least one product it may produce).

property my_partners: list[str]

Returns a list of IDs for all of the agent’s partners starting with suppliers

property penalties_scale: Literal[trading, catalog, unit, none]
property state: scml.oneshot.common.OneShotState

Returns the private state of the agent in that world

property current_balance
property current_score: float

Returns the current score (profit) of the agent

property current_inventory: tuple[int, int]

Current input and output inventory quantity

property current_inventory_input: int

Current input inventory quantity

property current_inventory_output: int

Current output inventory quantity

property current_exogenous_input_quantity: int

The exogenous contracts for the input (this step)

property current_exogenous_input_price: int

The exogenous contracts for the input (this step)

property current_exogenous_output_quantity: int

The exogenous contracts for the input (this step)

property current_exogenous_output_price: int

The exogenous contracts for the input (this step)

property is_perishable: bool

Are all products perishable (original design of OneShot)

property current_disposal_cost: float

Cost of storing one unit (penalizes buying too much/ selling too little)

property current_storage_cost: float

Cost of storing one unit (penalizes buying too much/ selling too little)

property current_shortfall_penalty: float

Cost of failure to deliver one unit (penalizes buying too little / selling too much)

property trading_prices: numpy.ndarray

Returns the current trading prices of all products

property exogenous_contract_summary: list[tuple[int, int]]

The exogenous contracts in the current step for all products

Returns:

A list of tuples giving the total quantity and total price of all revealed exogenous contracts of all products at the current step. Will be empty if the world has “publish_exogenous_summary==False”

property current_input_issues: list[negmas.ContiguousIssue]
property current_output_issues: list[negmas.ContiguousIssue]
property current_input_outcome_space: negmas.outcomes.DiscreteCartesianOutcomeSpace
property current_output_outcome_space: negmas.outcomes.DiscreteCartesianOutcomeSpace
property current_negotiation_details: dict[str, dict[str, scml.oneshot.common.NegotiationDetails]]

Details of current negotiations separated as two dicts for buying and selling.

Remarks:
  • current_negotiation_details[“buy”] gives details on all negotiations for buying

  • current_negotiation_details[“sell”] gives details on all negotiations for selling

property current_buy_states: dict[str, negmas.sao.SAOState]

All running buy negotiations as a mapping from partner ID to current negotiation state

property current_sell_states: dict[str, negmas.sao.SAOState]

All running sell negotiations as a mapping from partner ID to current negotiation state

property current_states: dict[str, negmas.sao.SAOState]

All running negotiations as a mapping from partner ID to current negotiation state

property current_buy_nmis: dict[str, negmas.sao.SAONMI]

All running buy negotiations as a mapping from partner ID to current negotiation nmi

property current_sell_nmis: dict[str, negmas.sao.SAONMI]

All running negotiations as a mapping from partner ID to current negotiation state

property current_nmis: dict[str, negmas.sao.SAONMI]

All running negotiations as a mapping from partner ID to current negotiation nmi

property current_buy_offers: dict[str, negmas.outcomes.Outcome]

All current buy negotiations as a mapping from partner ID to current offer

property current_sell_offers: dict[str, negmas.outcomes.Outcome]

All current sell negotiations as a mapping from partner ID to current offer

property current_offers: dict[str, negmas.outcomes.Outcome]

All current negotiations as a mapping from partner ID to current offer

property running_buy_states: dict[str, negmas.sao.SAOState]

All running buy negotiations as a mapping from partner ID to current negotiation state

property running_sell_states: dict[str, negmas.sao.SAOState]

All running sell negotiations as a mapping from partner ID to current negotiation state

property running_states: dict[str, negmas.sao.SAOState]

All running negotiations as a mapping from partner ID to current negotiation state

property running_sell_nmis: dict[str, negmas.sao.SAONMI]

All running sell negotiations as a mapping from partner ID to current negotiation nmi

property running_buy_nmis: dict[str, negmas.sao.SAONMI]

All running buy negotiations as a mapping from partner ID to current negotiation nmi

property running_nmis: dict[str, negmas.sao.SAONMI]

All running negotiations as a mapping from partner ID to current negotiation nmi

property sales: dict[str, int]

Sales (quantity) per customer so far (this day)

property supplies: dict[str, int]

Supplies (quantity) per supplier so far (this day)

property sales_cost: dict[str, int]

Sales (total price) per customer so far (this day)

property supplies_cost: dict[str, int]

Supplies (total price) per supplier so far (this day)

property future_sales: dict[int, dict[str, int]]

Future sales (quantity) per customer so far (excluding this day)

property future_supplies: dict[int, dict[str, int]]

Future supplies (quantity) per supplier so far (excluding this day)

property future_sales_cost: dict[int, dict[str, int]]

Future sales (total price) per customer so far (excluding this day)

property future_supplies_cost: dict[int, dict[str, int]]

Future supplies (total price) per supplier so far (excluding this day)

property total_sales: int

Total sales so far (this day)

property total_supplies: int

Total supplies so far (this day)

property total_future_sales: int

Total sales so far (this day)

property total_future_supplies: int

Total supplies so far (this day)

property needed_sales: int

Sales that need to be secured (exogenous input + total supplies - exogenous output - total sales so far)

property needed_supplies: int

Supplies that need to be secured (exogenous output + total sales - exogenous input - total supplies so far)

is_system(aid: str) bool[source]

Checks whether an agent is a system agent or not

Parameters:

aid – Agent ID

is_bankrupt(aid: str | None = None) bool[source]

Checks whether an agent is a system agent or not

Parameters:

aid – Agent ID

penalty_multiplier(is_input: bool, unit_price: float | None) float[source]

Returns the penalty multiplier for a contract with the give unit price.

Remarks:
  • The unit price is only needed if the penalties_scale is unit. For all other options (trading, catalog, none), the penalty scale does not depend on the unit price.

reports_of_agent(aid: str) dict[int, scml.oneshot.common.FinancialReport][source]

Returns a dictionary mapping time-steps to financial reports of the given agent

reports_at_step(step: int) dict[str, scml.oneshot.common.FinancialReport][source]

Returns a dictionary mapping agent ID to its financial report for the given time-step

total_sales_from(start: int) int[source]

Total sales starting at start and ending at end (inclusive). Past days are ignored

total_supplies_from(start: int) int[source]

Total supplies starting at start and ending at end (inclusive). Past days are ignored

total_sales_between(start: int, end: int) int[source]

Total sales starting at start and ending at end (inclusive). Past days are ignored

total_supplies_between(start: int, end: int) int[source]

Total supplies starting at start and ending at end (inclusive). Past days are ignored

total_supplies_until(step: int) int[source]

Total supplies starting today until the given step (inclusive). Past days are ignored

total_sales_until(step: int) int[source]

Total sales starting today until the given step (inclusive). Past days are ignored

total_sales_at(step: int) int[source]

Total sales already signed at a future step

total_supplies_at(step: int) int[source]

Total supplies already signed at a future step

_register_sale(customer: str, quantity: int, unit_price: int, step: int) None[source]
_register_supply(supplier: str, quantity: int, unit_price: int, step: int) None[source]
_reset_sales_and_supplies() None[source]
scml.QUANTITY = 0[source]

Index of quantity in negotiation issues

scml.UNIT_PRICE = 2[source]

Index of unit price in negotiation issues

scml.TIME = 1[source]

Index of time in negotiation issues

class scml.OneShotState[source]

State of a one-shot agent

property running_buy_states: dict[str, negmas.sao.common.SAOState]

All running buy negotiations as a mapping from partner ID to current negotiation state

property current_sell_states: dict[str, negmas.sao.common.SAOState]

All running sell negotiations as a mapping from partner ID to current negotiation state

property current_states: dict[str, negmas.sao.common.SAOState]

All running negotiations as a mapping from partner ID to current negotiation state

property current_buy_nmis: dict[str, negmas.sao.SAONMI]

All running buy negotiations as a mapping from partner ID to current negotiation nmi

property current_sell_nmis: dict[str, negmas.sao.SAONMI]

All running sell negotiations as a mapping from partner ID to current negotiation nmi

property current_nmis: dict[str, negmas.sao.SAONMI]

All running negotiations as a mapping from partner ID to current negotiation state

property current_buy_offers: dict[str, negmas.outcomes.Outcome]

All current buy negotiations as a mapping from partner ID to current offer

property current_sell_offers: dict[str, negmas.outcomes.Outcome]

All current sell negotiations as a mapping from partner ID to current offer

property current_offers: dict[str, negmas.outcomes.Outcome]

All current negotiations as a mapping from partner ID to current offer

exogenous_input_quantity: int

Exogenous input quantity for the current step

exogenous_input_price: int

Exogenous input unit price for the current step

exogenous_output_quantity: int

Exogenous output quantity for the current step

exogenous_output_price: int

Exogenous output unit price for the current step

disposal_cost: float

Current unit disposal cost

shortfall_penalty: float

Current unit shortfall penalty

current_balance: int

Current balance of the agent.

total_sales: int

Total quantity registered as sales today using awi.register_sale.

total_supplies: int

Total quantity registered as supplies today using awi.register_supply.

total_future_sales: int

Total quantity registered as sales in the future using awi.register_sale.

total_future_supplies: int

Total quantity registered as supplies in the future using awi.register_supply.

n_products: int

Number of products in the production chain.

n_processes: int

Number of processes in the production chain.

n_competitors: int

Number of other factories on the same production level.

all_suppliers: list[list[str]]

A list of all suppliers by product.

all_consumers: list[list[str]]

A list of all consumers by product.

production_capacities: list[int]

A list of total production capacity per production level.

bankrupt_agents: list[str]

list of bankrupt agents

catalog_prices: list[float]

A list of the catalog prices (by product).

price_multiplier: float

The multiplier multiplied by the trading/catalog price when the negotiation agendas are created to decide the maximum and lower quantities.

is_exogenous_forced: bool

exogenous contracts always forced or can the agent decide not to sign them.

current_step: int

Current simulation step (inherited from negmas.situated.AgentWorldInterface ).

n_steps: int

Number of simulation steps (inherited from negmas.situated.AgentWorldInterface ).

relative_simulation_time: float

Fraction of the simulation completed (inherited from negmas.situated.AgentWorldInterface).

profile: OneShotProfile

Gives the agent profile including its production cost, number of production lines, input product index, mean of its delivery penalties, mean of its disposal costs, standard deviation of its shortfall penalties and standard deviation of its disposal costs. See OneShotProfile for full description. This information is private information and no other agent knows it.

n_lines: int

The number of production lines in the factory (private information).

is_first_level: bool

Is the agent in the first production level (i.e. it is an input agent that buys the raw material).

is_last_level: bool

Is the agent in the last production level (i.e. it is an output agent that sells the final product).

is_middle_level: bool

Is the agent neither a first level nor a last level agent

my_input_product: int

The input product to the factory controlled by the agent.

my_output_product: int

The output product from the factory controlled by the agent.

level: int

The production level which is numerically the same as the input product.

my_suppliers: list[str]

A list of IDs for all suppliers to the agent (i.e. agents that can sell the input product of the agent).

my_consumers: list[str]

A list of IDs for all consumers to the agent (i.e. agents that can buy the output product of the agent).

my_partners: list[str]

A list of IDs for all negotiation partners of the agent (in the order suppliers then consumers).

penalties_scale: Literal[trading, catalog, unit, none]

The scale at which to calculate disposal cost/delivery penalties. “trading” and “catalog” mean trading and catalog prices. “unit” means the contract’s unit price while “none” means that disposal cost/shortfall penalty are absolute.

n_input_negotiations: int

Number of negotiations with suppliers.

n_output_negotiations: int

Number of negotiations with consumers.

trading_prices: list[float]

The trading prices of all products. This information is only available if publish_trading_prices is set in the world.

exogenous_contract_summary: list[tuple[int, int]]

A list of n_products lists each giving the total quantity and average price of exogenous contracts for a product. This information is only available if publish_exogenous_summary is set in the world.

reports_of_agents: dict[str, dict[int, FinancialReport]]

Gives all past financial reports of a given agent. See FinancialReport for details.

current_input_outcome_space: negmas.outcomes.DiscreteCartesianOutcomeSpace

The current issues for all negotiations to buy the input product of the agent. If the agent is at level zero, this will be empty. This is exactly the same as current_input_outcome_space.issues

current_output_outcome_space: negmas.outcomes.DiscreteCartesianOutcomeSpace

The current issues for all negotiations to buy the output product of the agent. If the agent is at level n_products - 1, this will be empty. This is exactly the same as current_output_outcome_space.issues

current_negotiation_details: dict[str, dict[str, NegotiationDetails]]

Details on all current negotiations separated into “buy” and “sell” dictionaries.

sales: dict[str, int]

Today’s sales per customer so far.

supplies: dict[str, int]

Today supplies per supplier so far.

needed_sales: int

Today’s needed sales as of now (exogenous input - exogenous output - total sales so far).

needed_supplies: int

Today needed supplies as of now (exogenous output - exogenous input - total supplies).

perishable: bool = True

Is this a perishable domain (oneshot) of not (std)

allow_zero_quantity: bool = False

Does this world allow zero quantity in negotiated offers

storage_cost: float = 0.0

Current unit storage cost. Only used in standard worlds where products are not perishable

classmethod random(oneshot: bool | None = None) OneShotState[source]
class scml.OneShotExogenousContract[source]

Exogenous contract information

__slots__ = ['quantity', 'unit_price', 'product', 'seller', 'buyer', 'time', 'revelation_time']
quantity: int

Contract quantity

unit_price: int

Contract unit price

product: int

Product index

seller: str

Seller ID (when passing contrtacts to the constructor of SCML2020OneShotWorld, you can also pass an interged index referring to the agent’s index in the agent_types list)

buyer: str

Buyer ID (when passing contrtacts to the constructor of SCML2020OneShotWorld, you can also pass an interged index referring to the agent’s index in the agent_types list)

time: int

Simulation step at which the contract is exceucted

revelation_time: int

Simulation step at which the contract is revealed to its owner. Should not exceed time and the default generate() method sets it to time

class scml.OneShotProfile[source]

Defines all private information of a factory

property level
property output_product
property process
cost: float

The cost of production

input_product: int

The index of the input product (x for $L_x$ factories)

n_lines: int

Number of lines for this factory

shortfall_penalty_mean: float

A positive number specifying the average penalty for selling too much.

disposal_cost_mean: float

A positive number specifying the average penalty buying too much.

shortfall_penalty_dev: float

A positive number specifying the std. dev. of penalty for selling too much.

disposal_cost_dev: float

A positive number specifying the std. dev. penalty buying too much.

storage_cost_mean: float

A positive number specifying the average cost for keeping inventory for one step. This is only used if the products are not perishable.

storage_cost_dev: float

A positive number specifying the std. dev. cost for keeping inventory for one step. This is only used if the products are not perishable.

classmethod random(input_product: int, oneshot: bool) OneShotProfile[source]
class scml.FinancialReport[source]

A report published periodically by the system showing the financial standing of an agent

__slots__ = ['agent_id', 'step', 'cash', 'assets', 'breach_prob', 'breach_level', 'is_bankrupt', 'agent_name']
agent_id: str

Agent ID

step: int

Simulation step at the beginning of which the report was published.

cash: int

Cash in the agent’s wallet. Negative numbers indicate liabilities.

assets: int

Value of the products in the agent’s inventory @ catalog prices.

breach_prob: float

Number of times the agent breached a contract over the total number of contracts it signed.

breach_level: float

Sum of the agent’s breach levels so far divided by the number of contracts it signed.

is_bankrupt: bool

Whether the agent is already bankrupt (i.e. incapable of doing any more transactions).

agent_name: str

Agent name for printing purposes

__str__()

Return str(self).

scml.is_system_agent(aid: str) bool[source]

Checks whether an agent is a system agent or not

Parameters:

aid – Agent ID

Returns:

True if the ID is for a system agent.

scml.INFINITE_COST[source]

A constant indicating an invalid cost for lines incapable of running some process

scml.SYSTEM_BUYER_ID = 'BUYER'[source]

ID of the system buyer agent

scml.SYSTEM_SELLER_ID = 'SELLER'[source]

ID of the system seller agent

class scml.Context[source]

Bases: abc.ABC

A context used for generating worlds satisfying predefined conditions and testing for them

__call__(*args, **kwargs)[source]
abstract generate(types: tuple[type[scml.oneshot.agent.OneShotAgent], Ellipsis] | None = None, params: tuple[dict[str, Any], Ellipsis] | None = None, name: str | None = None) tuple[scml.oneshot.world.SCMLBaseWorld, tuple[scml.oneshot.agent.OneShotAgent]][source]

Generates a world with one or more agents to be controlled externally and returns both

Parameters:
  • agent_types – The types of a list of agents to be guaranteed to exist in the world

  • agent_params – The parameters to pass to the constructors of these agents. None means no parameters for any agents

  • name – The name of the worlds to generate. Uses a random name if not given

Returns:

The constructed world and a tuple of the agents created corresponding (in order) to the given agent types/params

abstract is_valid_world(world: scml.oneshot.world.SCMLBaseWorld) bool[source]

Checks that the given world could have been generated from this context

abstract is_valid_awi(awi: scml.oneshot.awi.OneShotAWI) bool[source]

Checks that the given AWI is connected to a world that could have been generated from this context

abstract contains_context(context: Context) bool[source]

Checks that the any world generated from the given context could have been generated from this context

__contains__(other: SCMLBaseWorld | OneShotAWI | Context) bool[source]
class scml.GeneralContext[source]

Bases: BaseContext

A context that generates oneshot worlds with agents of a given types with predetermined structure and settings

perishable: bool = True
price_multiplier: numpy.ndarray | tuple[float, float] | float = (1.5, 2.0)
force_signing = True
n_steps: tuple[int, int] | int = (20, 200)
n_processes: tuple[int, int] | int = 2
n_lines: tuple[int, int] | int = 10
n_agents_per_process: numpy.ndarray | list[int] | tuple[int, int] | int = ()
production_costs: numpy.ndarray | tuple[int, int] | int = (1, 4)
cash_availability: tuple[float, float] | float = (1.5, 2.5)
shortfall_penalty: tuple[float, float] | float = (0.2, 1.0)
shortfall_penalty_dev: tuple[float, float] | float = (0.0, 0.1)
disposal_cost: tuple[float, float] | float = (0.0, 0.2)
disposal_cost_dev: tuple[float, float] | float = (0.0, 0.02)
storage_cost: tuple[float, float] | float = (0.0, 0.02)
storage_cost_dev: tuple[float, float] | float = 0
cost_increases_with_level = True
penalties_scale: str | list[str] = 'trading'
process_inputs: tuple[int, int] | int = 1
process_outputs: numpy.ndarray | tuple[int, int] | int = 1
exogenous_generation_method = 'profitable'
profit_means: numpy.ndarray | tuple[float, float] | float = (0.1, 0.2)
profit_stddevs: numpy.ndarray | tuple[float, float] | float = 0.05
max_productivity: numpy.ndarray | tuple[float, float] | float = (0.8, 1.0)
initial_balance: numpy.ndarray | tuple[int, int] | int | None
exogenous_supply_predictability: tuple[float, float] | float = (0.6, 0.9)
exogenous_sales_predictability: tuple[float, float] | float = (0.6, 0.9)
exogenous_control: tuple[float, float] | float
exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2)
equal_exogenous_supply = False
equal_exogenous_sales = False
cap_exogenous_quantities: bool = True
__attrs_post_init__()[source]
extract_context_params(min_values: bool, level: int | None = None) ContextParams[source]
make_predefined_config(agent_types: list[type[scml.oneshot.agent.OneShotAgent]], agent_processes: list[int], agent_params: list[dict[str, Any]], n_agents_per_process: list[int]) dict[str, Any][source]

Generates a config for a world

contains_context(context: Context, raise_on_failure: bool = False, warn_on_failure: bool = False, n_tests: int = NTESTS) bool[source]

Checks that the any world generated from the given context could have been generated from this context

_assign_types(n_processes, types, params, levels, n_agents_per_process)[source]
_distribute_agents(n_types)[source]
make_config() dict[str, Any][source]

Generates a config for a world

is_valid_world(world: scml.oneshot.world.SCMLBaseWorld, raise_on_failure: bool = False, warn_on_failure: bool = False, types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | None = None) bool[source]

Checks that the given world could have been generated from this context

contains_general_context(context: GeneralContext) bool[source]

Checks that the any world generated from the given context could have been generated from this context

class scml.ANACContext[source]

Bases: GeneralContext

Generates a oneshot world with no constraints except compatibility with a specific ANAC competition year.

year: int = 2024
__attrs_post_init__()[source]
class scml.LimitedPartnerNumbersContext[source]

Bases: GeneralContext

Generates a world limiting the range of the agent level, production capacity and the number of suppliers, consumers, and optionally same-level competitors.

level: int = 0
n_consumers: tuple[int, int]
n_suppliers: tuple[int, int] = (0, 0)
n_competitors: tuple[int, int] = ()
buying_strength: Strength | None
selling_strength: Strength | None
__attrs_post_init__()[source]
extract_context_params(min_values: bool, level: int | None = None) ContextParams[source]
make_config() dict[str, Any][source]

Generates a config

find_test_agents(world: scml.oneshot.world.SCMLBaseWorld, types: tuple[type[scml.oneshot.agent.OneShotAgent], Ellipsis] | None = None) list[str][source]
is_valid_world(world: scml.oneshot.world.SCMLBaseWorld, types: tuple[type[scml.oneshot.agent.OneShotAgent], Ellipsis] | None = None, raise_on_failure: bool = False, warn_on_failure: bool = False) bool[source]

Checks that the given world could have been generated from this context

contains_limited_partner_context(context: LimitedPartnerNumbersContext, raise_on_failure: bool = False, warn_on_failure: bool = False) bool[source]
contains_context(context: Context, raise_on_failure: bool = False, warn_on_failure: bool = False, n_tests: int = NTESTS) bool[source]

Checks that the any world generated from the given context could have been generated from this context

class scml.FixedPartnerNumbersContext[source]

Bases: LimitedPartnerNumbersContext

Generates a world limiting the range of the agent level, production capacity and the number of suppliers, consumers, and optionally same-level competitors.

level: int = 0
n_consumers: int = 4
n_suppliers: int = 0
n_competitors: int = 3
__attrs_post_init__()[source]
extract_context_params(min_values: bool, level: int | None = None) ContextParams[source]
class scml.ANACOneShotContext[source]

Bases: ANACContext

Generates a oneshot world with no constraints except compatibility with a specific ANAC competition year.

__attrs_post_init__()[source]
class scml.LimitedPartnerNumbersOneShotContext[source]

Bases: LimitedPartnerNumbersContext

Generates a oneshot world limiting the range of the agent level, production capacity and the number of suppliers, consumers, and optionally same-level competitors.

year: int = 2024
__attrs_post_init__()[source]
class scml.FixedPartnerNumbersOneShotContext[source]

Bases: FixedPartnerNumbersContext

Generates a world limiting the range of the agent level, production capacity and the number of suppliers, consumers, and optionally same-level competitors.

class scml.SupplierContext(*args, **kwargs)[source]

Bases: LimitedPartnerNumbersOneShotContext

A world context that can generate any world compatible with the observation manager

class scml.ConsumerContext(*args, **kwargs)[source]

Bases: LimitedPartnerNumbersOneShotContext

A world context that can generate any world compatible with the observation manager

class scml.StrongSupplierContext(*args, **kwargs)[source]

Bases: SupplierContext

A supplier with almost many consumers relative to competitors

class scml.StrongConsumerContext(*args, **kwargs)[source]

Bases: ConsumerContext

A consumer with almost many suppliers relative to competitors

class scml.WeakSupplierContext(*args, **kwargs)[source]

Bases: SupplierContext

A supplier with few consumers relative to competitors

class scml.WeakConsumerContext(*args, **kwargs)[source]

Bases: ConsumerContext

A consumer with few suppliers relative to competitors

class scml.BalancedSupplierContext(*args, **kwargs)[source]

Bases: SupplierContext

A supplier with almost same number of consumers as competitors

class scml.BalancedConsumerContext(*args, **kwargs)[source]

Bases: ConsumerContext

A consumer with almost same number of suppliers as competitors

class scml.RepeatingContext[source]

Bases: BaseContext

Encapsulates one or more configs and switches between them when asked to generate or make something.

configs: tuple[dict[str, Any], Ellipsis]
randomize: bool = True
rename: bool = True
_next: int
__attrs_post_init__()[source]
extract_context_params(min_values: bool, level: int | None = None) ContextParams[source]
make_config(types: tuple[type[scml.oneshot.agent.OneShotAgent], Ellipsis] = DEFAULT_PLACEHOLDER_AGENT_TYPES, params: tuple[dict[str, Any], Ellipsis] | None = None) dict[str, Any][source]

Generates a config for a world

classmethod from_context(context: BaseContext, n: int = 1, types: tuple[type[scml.oneshot.agent.OneShotAgent]] = DEFAULT_PLACEHOLDER_AGENT_TYPES, rename: bool = False, randomize: bool = False)[source]
contains_repeating_context(context: RepeatingContext, raise_on_failure: bool = False, warn_on_failure: bool = False)[source]
is_valid_world(world: scml.oneshot.world.SCMLBaseWorld, raise_on_failure=RAISE_ON_FAILURE, warn_on_failure=WARN_ON_FAILURE, types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | None = None) bool[source]

Checks that the given world could have been generated from this context

contains_context(context: Context, raise_on_failure: bool = False, warn_on_failure: bool = False, n_tests: int = NTESTS) bool[source]

Checks that the any world generated from the given context could have been generated from this context

class scml.ContextParams[source]

Basic Parameters you can assume about a context. Returned by extract_context_params

perishable: bool
nlines: int
nsuppliers: int
nconsumers: int
class scml.MonopolicContext[source]

Bases: LimitedPartnerNumbersContext

An agent that has no competitors in the same level as themselves

n_competitors: tuple[int, int] = (0, 0)
n_agents_per_process: numpy.ndarray | list[int] | tuple[int, int] | int
__attrs_post_init__()[source]
class scml.SingleAgentPerLevelSupplierContext[source]

Bases: MonopolicContext

A world in which every level has exactly one factory and the agent is a supplier

level: int = 0
n_consumers: tuple[int, int] = (1, 1)
n_suppliers: tuple[int, int] = (0, 0)
n_agents_per_process: numpy.ndarray | list[int] | tuple[int, int] | int
class scml.EutopiaContext[source]

Bases: MonopolicContext

An unrealistic context in which the agent is the only one in its level and all other agents are nice.

non_competitors: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis]
class scml.EutopiaConsumerContext[source]

Bases: EutopiaContext

An unrealistic context in which the agent is the only consumer and all suppliers are nice.

level: int
n_consumers: tuple[int, int] = (0, 0)
n_suppliers: tuple[int, int]
class scml.EutopiaSupplierContext[source]

Bases: EutopiaContext

An unrealistic context in which the agent is the only supplier and all consumers are nice.

level: int
n_consumers: tuple[int, int]
n_suppliers: tuple[int, int] = (0, 0)
class scml.OneShotPolicy(*args, **kwargs)[source]

Bases: scml.oneshot.agent.OneShotSyncAgent, abc.ABC

A oneshot agent structured in three components, state encoder, policy (action) and action decoder.

The agent is divided into three components:

  1. State encoder (encode_state()) which takes the current state of all negotiation mechanisms, access the awi as needed, and generates a state which can be of any type to be passed to the next component.

  2. Policy (act()) which takes the state generated from the state encoder and returns an action which may be encoded as any type to be passed to the next component. The policy (i.e. `act` () method) is not supposed to access the AWI or any other members of the class. It is preferred to be a pure function. This makes it easy to test the policy at predefined conditions (i.e. states) without having to construct a simulation.

  3. Action decoder (decode_action()) which takes the action generated from the policy and generates the appropriate set of responses to all partners.

Remarks:
  • The simplest form of state encoder which is implemented by default is to return the state member of the AWI.

  • The simplest form of action encoding is to simply return the responses as a dict[str, SAOResponse] from act which is then passed as it is by decode_action . This is the default implementation of decode_action

encode_state(mechanism_states: dict[str, negmas.sao.common.SAOState]) Any[source]

Called to generate a state to be passed to the act() method. The default is all of awi of type OneShotState

abstract act(state: Any) Any[source]

The main policy. Generates an action given a state

decode_action(action: Any) dict[str, negmas.sao.common.SAOResponse][source]

Generates offers to all partners from an encoded action. Default is to return the action as it is assuming it is a dict[str, SAOResponse]

encode_action(responses: dict[str, negmas.sao.common.SAOResponse]) dict[str, negmas.sao.common.SAOResponse][source]

Receives offers for all partners and generates the corresponding action. Used mostly for debugging and testing.

__call__(state)[source]

A policy is a callable that receives a state and generates an action

counter_all(offers: dict[str, negmas.outcomes.Outcome | None], states: dict[str, negmas.sao.common.SAOState]) dict[str, negmas.sao.common.SAOResponse][source]

Calculate a response to all offers from all negotiators (negotiator ID is the key).

Parameters:
  • offers – Maps negotiator IDs to offers

  • states – Maps negotiator IDs to offers AT the time the offers were made.

Returns:

A dictionary mapping negotiator ID to an SAOResponse. The response per agent consist of a tuple. In case of acceptance or ending the negotiation the second item of the tuple should be None. In case of rejection, the second item should be the counter offer.

Remarks:
  • The response type CANNOT be WAIT.

  • If the system determines that a loop is formed, the agent may

receive this call for a subset of negotiations not all of them.

first_proposals() dict[str, negmas.outcomes.Outcome | None][source]

Gets a set of proposals to use for initializing the negotiation.

Returns:

A dictionary mapping each negotiator (in self.negotiators dict) to an outcome to be used as the first proposal if the agent is to start a negotiation.

class scml.ActionManager[source]

Bases: abc.ABC

Manges actions of an agent in an RL environment.

context: scml.oneshot.context.BaseContext
continuous: bool = False
n_suppliers: int
n_consumers: int
n_partners: int
abstract make_space() gymnasium.Space[source]

Creates the action space

abstract decode(awi: scml.oneshot.awi.OneShotAWI, action: numpy.ndarray) dict[str, negmas.sao.common.SAOResponse][source]

Decodes an action from an array to a PurchaseOrder and a CounterMessage.

encode(awi: scml.oneshot.awi.OneShotAWI, responses: dict[str, negmas.sao.common.SAOResponse]) numpy.ndarray[source]

Encodes an action as an array. This is only used for testing so it is optional

class scml.FlexibleActionManager[source]

Bases: ActionManager

An action manager that matches any context.

Parameters:
  • n_prices – Number of distinct prices allowed in the action.

  • max_quantity – Maximum allowed quantity to offer in any negotiation. The number of quantities is one plus that because zero is allowed to model ending negotiation.

  • n_partners – Maximum of partners allowed in the action.

Remarks:
  • This action manager will always generate offers that are within the price and quantity limits given in its parameters. Wen decoding them, it will scale them up so that the maximum corresponds to the actual value in the world it finds itself. For example, if n_prices is 10 and the world has only two prices currently in the price issue, it will use any value less than 5 as the minimum price and any value above 5 as the maximum price. If on the other hand the current price issue has 20 values, then it will scale by multiplying the number given in the encoded action (ranging from 0 to 9) by 19/9 which makes it range from 0 to 19 which is what is expected by the world.

  • This action manager will adjust offers for different number of partners as follows: - If the true number of partners is larger than n_partners used by this action manager,

    it will simply use n_partners of them and always end negotiations with the rest of them.

    • If the true number of partners is smaller than n_partners, it will use the first n_partners values in the encoded action and increase the quantities of any counter offers (i.e. ones in which the response is REJECT_OFFER) by the amount missing from the ignored partners in the encoded action up to the maximum quantities allowed by the current negotiation context. For example, if n_partneers is 4 and we have only 2 partners in reality, and the received quantities from partners were [4, 3] while the maximum quantity allowed is 10 and the encoded action was [2, *, 3, *, 2, *, 1, *] (where we ignored prices), then the encoded action will be converted to [(Reject, 5, *), (Accept, 3, *)] where the 3 extra units that were supposed to be offered to the last two partners are moved to the first partner. If the maximum quantity allowed was 4 in that example, the result will be [(Reject, 4, *), (Accept, 3, *)].

capacity_multiplier: int = 1
n_prices: int = 2
max_group_size: int = 2
reduce_space_size: bool = True
extra_checks: bool = False
max_quantity: int
__attrs_post_init__()[source]
make_space() gymnasium.spaces.MultiDiscrete | gymnasium.spaces.Box[source]

Creates the action space

decode(awi: scml.oneshot.awi.OneShotAWI, action: numpy.ndarray) dict[str, negmas.sao.common.SAOResponse][source]

Generates offers to all partners from an encoded action. Default is to return the action as it is assuming it is a dict[str, SAOResponse]

encode(awi: scml.oneshot.awi.OneShotAWI, responses: dict[str, negmas.sao.common.SAOResponse]) numpy.ndarray[source]

Receives offers for all partners and generates the corresponding action. Used mostly for debugging and testing.

scml.DefaultActionManager[source]

The default action manager

class scml.OneShotRLAgent(*args, models: list[scml.oneshot.rl.common.RLModel] | tuple[scml.oneshot.rl.common.RLModel, Ellipsis] = tuple(), observation_managers: list[scml.oneshot.rl.observation.ObservationManager] | tuple[scml.oneshot.rl.observation.ObservationManager, Ellipsis] = tuple(), action_managers: list[scml.oneshot.rl.action.ActionManager] | tuple[scml.oneshot.rl.action.ActionManager, Ellipsis] | None = None, fallback_type: type[scml.oneshot.agent.OneShotAgent] | None = GreedyOneShotAgent, fallback_params: dict[str, Any] | None = None, dynamic_context_switching: bool = False, randomize_test_order: bool = False, **kwargs)[source]

Bases: scml.oneshot.policy.OneShotPolicy

A oneshot agent that can execute trained RL models in appropriate worlds. It falls back to the given agent type otherwise

Parameters:
  • models – List of models to choose from.

  • observation_managers – List of observation managers. Must be the same length as models

  • action_managers – List of action managers of the same length as models or None to use the default action manager.

  • fallback_type – A OneShotAgent type to use as a fall-back if the current world is not compatible with any observation/action managers

  • fallback_params – Parameters of the fallback_type

  • dynamic_context_switching – If True, the world is tested each step (instead of only at init) to find the appropriate model

  • randomize_test_order – If True, the order at which the observation/action managers are checked for compatibility with the current world is randomized.

  • **kwargs – Any other OneShotPolicy parameters

setup_fallback()[source]
has_no_valid_model()[source]
context_switch()[source]
init()[source]

Called once after the AWI is set.

Remarks:
  • Use this for any proactive initialization code.

encode_state(mechanism_states: dict[str, negmas.sao.common.SAOState]) scml.oneshot.rl.common.RLState[source]

Called to generate a state to be passed to the act() method. The default is all of awi of type OneShotState

decode_action(action: scml.oneshot.rl.common.RLAction) dict[str, negmas.sao.common.SAOResponse][source]

Generates offers to all partners from an encoded action. Default is to return the action as it is assuming it is a dict[str, SAOResponse]

act(state: scml.oneshot.rl.common.RLState) scml.oneshot.rl.common.RLAction[source]

The main policy. Generates an action given a state

propose(*args, **kwargs) negmas.outcomes.Outcome | None[source]

Called when the agent is asking to propose in one negotiation

respond(*args, **kwargs) negmas.gb.common.ResponseType[source]

Called when the agent is asked to respond to an offer

before_step()[source]

Called at at the BEGINNING of every production step (day)

step()[source]

Called at at the END of every production step (day)

on_negotiation_failure(*args, **kwargs) None[source]

Called when a negotiation the agent is a party of ends without agreement

on_negotiation_success(*args, **kwargs) None[source]

Called when a negotiation the agent is a party of ends with agreement

scml.RLState[source]

We assume that RL states are numpy arrays

scml.RLAction[source]

We assume that RL actions are numpy arrays

scml.RLModel[source]

A policy is a callable that receives a state and returns an action

scml.model_wrapper(model, deterministic: bool = False) RLModel[source]

Wraps a stable_baselines3 model as an RL model

class scml.OneShotEnv(action_manager: scml.oneshot.rl.action.ActionManager, observation_manager: scml.oneshot.rl.observation.ObservationManager, reward_function: scml.oneshot.rl.reward.RewardFunction = DefaultRewardFunction(), context: scml.oneshot.context.BaseContext = FixedPartnerNumbersOneShotContext(), agent_type: type[scml.oneshot.agent.OneShotAgent] = Placeholder, agent_params: dict[str, Any] | None = None, extra_checks: bool = True, skip_after_negotiations: bool = True, render_mode=None, debug=False)[source]

Bases: gymnasium.Env

The main Gymnasium class for implementing Reinforcement Learning Agents environments.

The class encapsulates an environment with arbitrary behind-the-scenes dynamics through the step() and reset() functions. An environment can be partially or fully observed by single agents. For multi-agent environments, see PettingZoo.

The main API methods that users of this class need to know are:

  • step() - Updates an environment with actions returning the next agent observation, the reward for taking that actions, if the environment has terminated or truncated due to the latest action and information from the environment about the step, i.e. metrics, debug info.

  • reset() - Resets the environment to an initial state, required before calling step. Returns the first agent observation for an episode and information, i.e. metrics, debug info.

  • render() - Renders the environments to help visualise what the agent see, examples modes are “human”, “rgb_array”, “ansi” for text.

  • close() - Closes the environment, important when external software is used, i.e. pygame for rendering, databases

Environments have additional attributes for users to understand the implementation

  • action_space - The Space object corresponding to valid actions, all valid actions should be contained within the space.

  • observation_space - The Space object corresponding to valid observations, all valid observations should be contained within the space.

  • reward_range - A tuple corresponding to the minimum and maximum possible rewards for an agent over an episode. The default reward range is set to \((-\infty,+\infty)\).

  • spec - An environment spec that contains the information used to initialize the environment from gymnasium.make()

  • metadata - The metadata of the environment, i.e. render modes, render fps

  • np_random - The random number generator for the environment. This is automatically assigned during super().reset(seed=seed) and when assessing self.np_random.

See also

For modifying or extending environments use the gymnasium.Wrapper class

Note

To get reproducible sampling of actions, a seed can be set with env.action_space.seed(123).

_get_obs()[source]
calc_info()[source]

Calculates info to be returned from step().

_render_frame()[source]

Used for rendering. Override with your rendering code

close()[source]

After the user has finished using the environment, close contains the code necessary to “clean up” the environment.

This is critical for closing rendering windows, database or HTTP connections. Calling close on an already closed environment has no effect and won’t raise an error.

render()[source]

Compute the render frames as specified by render_mode during the initialization of the environment.

The environment’s metadata render modes (env.metadata["render_modes"]) should contain the possible ways to implement the render modes. In addition, list versions for most render modes is achieved through gymnasium.make which automatically applies a wrapper to collect rendered frames.

Note

As the render_mode is known during __init__, the objects used to render the environment state should be initialised in __init__.

By convention, if the render_mode is:

  • None (default): no render is computed.

  • “human”: The environment is continuously rendered in the current display or terminal, usually for human consumption. This rendering should occur during step() and render() doesn’t need to be called. Returns None.

  • “rgb_array”: Return a single frame representing the current state of the environment. A frame is a np.ndarray with shape (x, y, 3) representing RGB values for an x-by-y pixel image.

  • “ansi”: Return a strings (str) or StringIO.StringIO containing a terminal-style text representation for each time step. The text can include newlines and ANSI escape sequences (e.g. for colors).

  • “rgb_array_list” and “ansi_list”: List based version of render modes are possible (except Human) through the wrapper, gymnasium.wrappers.RenderCollection that is automatically applied during gymnasium.make(..., render_mode="rgb_array_list"). The frames collected are popped after render() is called or reset().

Note

Make sure that your class’s metadata "render_modes" key includes the list of supported modes.

Changed in version 0.25.0: The render function was changed to no longer accept parameters, rather these parameters should be specified in the environment initialised, i.e., gymnasium.make("CartPole-v1", render_mode="human")

reset(*, seed: int | None = None, options: dict[str, Any] | None = None) tuple[Any, dict[str, Any]][source]

Resets the environment to an initial internal state, returning an initial observation and info.

This method generates a new starting state often with some randomness to ensure that the agent explores the state space and learns a generalised policy about the environment. This randomness can be controlled with the seed parameter otherwise if the environment already has a random number generator and reset() is called with seed=None, the RNG is not reset.

Therefore, reset() should (in the typical use case) be called with a seed right after initialization and then never again.

For Custom environments, the first line of reset() should be super().reset(seed=seed) which implements the seeding correctly.

Changed in version v0.25: The return_info parameter was removed and now info is expected to be returned.

Parameters:
  • seed (optional int) – The seed that is used to initialize the environment’s PRNG (np_random). If the environment does not already have a PRNG and seed=None (the default option) is passed, a seed will be chosen from some source of entropy (e.g. timestamp or /dev/urandom). However, if the environment already has a PRNG and seed=None is passed, the PRNG will not be reset. If you pass an integer, the PRNG will be reset even if it already exists. Usually, you want to pass an integer right after the environment has been initialized and then never again. Please refer to the minimal example above to see this paradigm in action.

  • options (optional dict) – Additional information to specify how the environment is reset (optional, depending on the specific environment)

Returns:

Observation of the initial state. This will be an element of observation_space

(typically a numpy array) and is analogous to the observation returned by step().

info (dictionary): This dictionary contains auxiliary information complementing observation. It should be analogous to

the info returned by step().

Return type:

observation (ObsType)

step(action)[source]

Run one timestep of the environment’s dynamics using the agent actions.

When the end of an episode is reached (terminated or truncated), it is necessary to call reset() to reset this environment’s state for the next episode.

Changed in version 0.26: The Step API was changed removing done in favor of terminated and truncated to make it clearer to users when the environment had terminated or truncated which is critical for reinforcement learning bootstrapping algorithms.

Parameters:

action (ActType) – an action provided by the agent to update the environment state.

Returns:

An element of the environment’s observation_space as the next observation due to the agent actions.

An example is a numpy array containing the positions and velocities of the pole in CartPole.

reward (SupportsFloat): The reward as a result of taking the action. terminated (bool): Whether the agent reaches the terminal state (as defined under the MDP of the task)

which can be positive or negative. An example is reaching the goal state or moving into the lava from the Sutton and Barton, Gridworld. If true, the user needs to call reset().

truncated (bool): Whether the truncation condition outside the scope of the MDP is satisfied.

Typically, this is a timelimit, but could also be used to indicate an agent physically going out of bounds. Can be used to end the episode prematurely before a terminal state is reached. If true, the user needs to call reset().

info (dict): Contains auxiliary diagnostic information (helpful for debugging, learning, and logging).

This might, for instance, contain: metrics that describe the agent’s performance state, variables that are hidden from observations, or individual reward terms that are combined to produce the total reward. In OpenAI Gym <v26, it contains “TimeLimit.truncated” to distinguish truncation and termination, however this is deprecated in favour of returning terminated and truncated variables.

done (bool): (Deprecated) A boolean value for if the episode has ended, in which case further step() calls will

return undefined results. This was removed in OpenAI Gym v26 in favor of terminated and truncated attributes. A done signal may be emitted for different reasons: Maybe the task underlying the environment was solved successfully, a certain timelimit was exceeded, or the physics simulation has entered an invalid state.

Return type:

observation (ObsType)

class scml.ObservationManager[source]

Bases: Protocol

Manages the observations of an agent in an RL environment

property context: scml.oneshot.context.BaseContext
make_space() gymnasium.spaces.Space[source]

Creates the observation space

encode(awi: scml.oneshot.awi.OneShotAWI) numpy.ndarray[source]

Encodes an observation from the agent’s awi

make_first_observation(awi: scml.oneshot.awi.OneShotAWI) numpy.ndarray[source]

Creates the initial observation (returned from gym’s reset())

get_offers(awi: scml.oneshot.awi.OneShotAWI, encoded: numpy.ndarray) dict[str, negmas.outcomes.Outcome | None][source]

Gets the offers from an encoded awi

class scml.FlexibleObservationManager[source]

Bases: BaseObservationManager

An observation manager that can be used with any SCML world.

Parameters:
  • capacity_multiplier – A factor to multiply by the number of lines to give the maximum quantity allowed in offers

  • exogenous_multiplier – A factor to multiply maximum production capacity with when encoding exogenous quantities

  • continuous – If given the observation space will be a Box otherwise it will be a MultiDiscrete

  • n_prices – The number of prices to use for encoding the unit price (if not continuous)

  • max_production_cost – The limit for production cost. Anything above that will be mapped to this max

  • max_group_size – Maximum size used for grouping observations from multiple partners. This will be used in the number of partners in the simulation is larger than the number used for training.

  • n_past_received_offers – Number of past received offers to add to the observation.

  • n_bins

    1. bins to use for discretization (if not continuous)

  • n_sigmas – The number of sigmas used for limiting the range of randomly distributed variables

  • extra_checks – If given, extra checks are applied to make sure encoding and decoding make sense

Remarks:

capacity_multiplier: int = 1
n_prices: int = 2
max_group_size: int = 2
reduce_space_size: bool = True
n_past_received_offers: int = 1
extra_checks: bool = False
n_bins: int = 40
n_sigmas: int = 2
max_production_cost: int = 10
exogenous_multiplier: int = 1
max_quantity: int
_chosen_partner_indices: list[int] | None
_previous_offers: collections.deque
_dims: list[int] | None
__attrs_post_init__()[source]
get_dims() list[int][source]

Get the sizes of all dimensions in the observation space. Used if not continuous.

make_space() gymnasium.spaces.MultiDiscrete | gymnasium.spaces.Box[source]

Creates the action space

make_first_observation(awi: scml.oneshot.awi.OneShotAWI) numpy.ndarray[source]

Creates the initial observation (returned from gym’s reset())

encode(awi: scml.oneshot.awi.OneShotAWI) numpy.ndarray[source]

Encodes the awi as an array

extra_obs(awi: scml.oneshot.awi.OneShotAWI) list[tuple[float, int] | float][source]

The observation values other than offers and previous offers.

Returns:

A list of tuples. Each is some observation variable as a real number between zero and one and a number of bins to use for discrediting this variable. If a single value, the number of bins will be self.n_bin

get_offers(awi: scml.oneshot.awi.OneShotAWI, encoded: numpy.ndarray) dict[str, negmas.outcomes.Outcome | None][source]

Gets offers from an encoded awi.

scml.DefaultObservationManager[source]

The default observation manager

scml.random_action(obs: numpy.ndarray, env: scml.oneshot.rl.env.OneShotEnv) numpy.ndarray[source]

Samples a random action from the action space of the

scml.random_policy(obs: numpy.ndarray, env: scml.oneshot.rl.env.OneShotEnv, pend: float = 0.05, paccept: float = 0.15) numpy.ndarray[source]

Ends the negotiation or accepts with a predefined probability or samples a random response.

scml.greedy_policy(obs: numpy.ndarray, awi: scml.oneshot.awi.OneShotAWI, obs_manager: scml.oneshot.rl.observation.ObservationManager, action_manager: scml.oneshot.rl.action.ActionManager = FlexibleActionManager(ANACOneShotContext()), debug=False, distributor: Callable[[int, int], list[int]] = all_but_concentrated) numpy.ndarray[source]

A simple greedy policy.

Parameters:
  • obs – The current observation

  • awi – The AWI of the agent running the policy

  • obs_manager – The observation manager used to encode the observation

  • action_manager – The action manager to be used to encode the action

  • debug – If True, extra assertions are tested

  • distributor – A callable that receives a total quantity to be distributed over n partners and returns a list of n values that sum to this total quantity

Remarks:
  • Accepts the subset of offers with maximum total quantity under current needs.

  • The remaining quantity is distributed over the remaining partners using the distributor function

  • Prices are set to the worst for the agent if the price range is small else they are set randomly

class scml.RewardFunction[source]

Bases: Protocol

Represents a reward function.

Remarks:
  • before_action is called before the action is executed for initialization and should return info to be passed to the call

  • __call__ is called with the awi (to get the state), action and info and should return the reward

before_action(awi: scml.oneshot.awi.OneShotAWI) Any[source]

Called before executing the action from the RL agent to save any required information for calculating the reward in its return

Remarks:

The returned value will be passed as info to __call__() when it is time to calculate the reward.

__call__(awi: scml.oneshot.awi.OneShotAWI, action: dict[str, negmas.SAOResponse], info: Any) float[source]

Called to calculate the reward to be given to the agent at the end of a step.

Parameters:
  • awiOneShotAWI to access the agent’s state

  • action – The action (decoded) as a mapping from partner ID to responses to their last offer.

  • info – Information generated from before_action(). You an use this to store baselines for calculating the reward

Returns:

The reward (a number) to be given to the agent at the end of the step.

class scml.DefaultRewardFunction[source]

Bases: RewardFunction

The default reward function of SCML

Remarks:
  • The reward is the difference between the balance before the action and after it.

before_action(awi: scml.oneshot.awi.OneShotAWI) float[source]

Called before executing the action from the RL agent to save any required information for calculating the reward in its return

Remarks:

The returned value will be passed as info to __call__() when it is time to calculate the reward.

__call__(awi: scml.oneshot.awi.OneShotAWI, action: dict[str, negmas.SAOResponse], info: float)[source]

Called to calculate the reward to be given to the agent at the end of a step.

Parameters:
  • awiOneShotAWI to access the agent’s state

  • action – The action (decoded) as a mapping from partner ID to responses to their last offer.

  • info – Information generated from before_action(). You an use this to store baselines for calculating the reward

Returns:

The reward (a number) to be given to the agent at the end of the step.

class scml.DefaultOneShotAdapter(*args, **kwargs)[source]

Bases: negmas.Adapter, scml.oneshot.mixins.OneShotUFunCreatorMixin

The base class of all agents running in OneShot based on OneShotAgent.

Remarks:

  • It inherits from Adapter allowing it to just pass any calls not defined explicity in it to the internal _obj object representing the OneShotAgent.

property awi: scml.oneshot.awi.OneShotAWI

Gets the Agent-world interface.

property short_type_name

Returns a short name of the type of this entity

make_ufun(add_exogenous: bool, in_adapter=False)[source]
on_negotiation_failure(partners, annotation, mechanism, state)[source]

Called whenever a negotiation ends without agreement

on_negotiation_success(contract: negmas.Contract, mechanism)[source]

Called whenever a negotiation ends with agreement

on_contract_executed(contract: negmas.Contract) None[source]

Called after successful contract execution for which the agent is one of the partners.

on_contract_breached(contract: negmas.Contract, breaches: list[negmas.Breach], resolution: negmas.Contract | None) None[source]

Called after complete processing of a contract that involved a breach.

Parameters:
  • contract – The contract

  • breaches – All breaches committed (even if they were resolved)

  • resolution – The resolution contract if re-negotiation was successful. None if not.

init_()[source]

Called to initialize the agent after the world is initialized. the AWI is accessible at this point.

init()[source]

Override this method to modify initialization logic

reset()[source]
is_clean() bool[source]
before_step()[source]
step()[source]

Override this method to modify stepping logic

to_dict()[source]
_respond_to_negotiation_request(initiator: str, partners: list[str], issues: list[negmas.Issue], annotation: dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, role: str | None, req_id: str | None) negmas.Negotiator | None[source]

Called by the mechanism to ask for joining a negotiation. The agent can refuse by returning a None

Parameters:
  • initiator – The ID of the agent that initiated the negotiation request

  • partners – The partner list (will include this agent)

  • issues – The list of issues

  • annotation – Any annotation specific to this negotiation.

  • mechanism – The mechanism that started the negotiation

  • role – The role of this agent in the negotiation

  • req_id – The req_id passed to the AWI when starting the negotiation (only to the initiator).

Returns:

None to refuse the negotiation or a Negotiator object appropriate to the given mechanism to accept it.

Remarks:

  • It is expected that world designers will introduce a better way to respond and override this function to call it

set_renegotiation_agenda(contract: negmas.Contract, breaches: list[negmas.Breach]) negmas.RenegotiationRequest | None[source]

Received by partners in ascending order of their total breach levels in order to set the renegotiation agenda when contract execution fails

Parameters:
  • contract – The contract being breached

  • breaches – All breaches on contract

Returns:

Renegotiation agenda (issues to negotiate about to avoid reporting the breaches).

respond_to_renegotiation_request(contract: negmas.Contract, breaches: list[negmas.Breach], agenda: negmas.RenegotiationRequest) negmas.Negotiator | None[source]

Called to respond to a renegotiation request

Parameters:
  • agenda

  • contract

  • breaches

Returns:

on_neg_request_rejected(req_id: str, by: list[str] | None)[source]

Called when a requested negotiation is rejected

Parameters:
  • req_id – The request ID passed to _request_negotiation

  • by – A list of agents that refused to participate or None if the failure was for another reason

on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface)[source]

Called when a requested negotiation is accepted

class scml._StdSystemAgent(*args, role, **kwargs)[source]

Bases: DefaultOneShotAdapter

Implements an agent for handling system operations

property type_name

Returns a short name of the type of this entity

property short_type_name

Returns a short name of the type of this entity

respond_to_negotiation_request(initiator: str, issues: list[negmas.Issue], annotation: dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) negmas.Negotiator | None[source]
before_step()[source]
step()[source]

Override this method to modify stepping logic

init()[source]

Override this method to modify initialization logic

on_negotiation_failure(partners: list[str], annotation: dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, state: negmas.MechanismState) None[source]

Called whenever a negotiation ends without agreement

on_negotiation_success(contract: negmas.Contract, mechanism: negmas.NegotiatorMechanismInterface) None[source]

Called whenever a negotiation ends with agreement

sign_all_contracts(contracts: list[negmas.Contract]) list[str | None][source]

Signs all contracts

class scml.OneShotUFun(ex_pin: int, ex_qin: int, ex_pout: int, ex_qout: int, input_product: int, input_agent: bool, output_agent: bool, production_cost: float, disposal_cost: float, storage_cost: float, shortfall_penalty: float, input_penalty_scale: float | None, output_penalty_scale: float | None, storage_penalty_scale: float | None, n_input_negs: int, n_output_negs: int, current_step: int, agent_id: str | None, time_range: tuple[int, int], inventory_in: int = 0, inventory_out: int = 0, input_qrange: tuple[int, int] = (0, 0), input_prange: tuple[int, int] = (0, 0), output_qrange: tuple[int, int] = (0, 0), output_prange: tuple[int, int] = (0, 0), force_exogenous: bool = True, n_lines: int = 10, normalized: bool = False, current_balance: int | float = float('inf'), suppliers: set[str] = set(), consumers: set[str] = set(), perishable=True, **kwargs)[source]

Bases: negmas.preferences.StationaryMixin, negmas.preferences.UtilityFunction

Calculates the utility function of a list of contracts or offers.

Parameters:
  • force_exogenous – Is the agent forced to accept exogenous contracts given through ex_* arguments?

  • ex_pin – total price of exogenous inputs for this agent

  • ex_qin – total quantity of exogenous inputs for this agent

  • ex_pout – total price of exogenous outputs for this agent

  • ex_qout – total quantity of exogenous outputs for this agent.

  • cost – production cost of the agent.

  • disposal_cost – disposal cost per unit of input/output.

  • shortfall_penalty – penalty for failure to deliver one unit of output.

  • input_agent – Is the agent an input agent which means that its input product is the raw material

  • output_agent – Is the agent an output agent which means that its output product is the final product

  • n_lines – Number of production lines. If None, will be read through the AWI.

  • input_product – Index of the input product. If None, will be read through the AWI

  • input_qrange – A 2-int tuple giving the range of input quantities negotiated. If not given will be read through the AWI

  • input_prange – A 2-int tuple giving the range of input unit prices negotiated. If not given will be read through the AWI

  • output_qrange – A 2-int tuple giving the range of output quantities negotiated. If not given will be read through the AWI

  • output_prange – A 2-int tuple giving the range of output unit prices negotiated. If not given will be read through the AWI

  • n_input_negs – How many input negotiations are allowed. If not given, it will be the number of suppliers as given by the AWI

  • n_output_negs – How many output negotiations are allowed. If not given, it will be the number of consumers as given by the AWI

  • current_step – Current simulation step. Needed only for ufun_range when returning best outcomes

  • normalized – If given the values returned by from_*, utility_range and __call__ will all be normalized between zero and one.

Remarks:
  • The utility function assumes that the agent will have to pay for all its input products but will receive money only for the output products it could generate and sell.

  • The utility function respects production capacity (n. lines). The agent cannot produce more than the number of lines it has.

  • disposal cost is paid for items bought but not produced only. Items consumed in production (i.e. sold) are not counted.

property best_option: UFunLimit

Best possible options

property worst_option: UFunLimit

Best possible options

property max_utility

The maximum possible utility value

property min_utility

The minimum possible utility value

register_supply_failure(supplier_id: str)[source]
register_sale_failure(consumer_id: str)[source]
register_sale(q: int, p: int, t: int)[source]

Registers a sale to be considered when calculating utilities

register_supply(q: int, p: int, t: int)[source]

Registers a supply to be considered when calculating utilities

abstract xml(issues) str[source]
eval(offer: tuple[int, int, int] | None) float[source]

Calculates the utility function given a single contract.

Remarks:
  • This method calculates the utility value of a single offer assuming all other negotiations end in failure.

  • It can only be called for agents that exist in the first or last layer of the production graph.

from_contracts(contracts: Iterable[negmas.Contract], return_info: Literal[False] = False, ignore_exogenous=True) float[source]
from_contracts(contracts: Iterable[negmas.Contract], return_info: Literal[True], ignore_exogenous=True) UtilityInfo

Calculates the utility function given a list of contracts

Parameters:
  • contracts – A list/tuple of contracts

  • ignore_exogenous – If given, any contracts with a system agent will be ignored.

Remarks:
  • This method ignores any unsigned contracts passed to it.

  • We do not consider time at all so it is implicitly assumed that all contracts have the same delivery time value.

  • The reason for having the ignore_exogenous parameter is to avoid double counting exogenous contracts if their information is passed during construction of the ufun and they also exist in the list of contracts passed here.

static outcome_as_tuple(offer)[source]
from_offers(offers: tuple[tuple[int, int, int | float] | None, Ellipsis] | dict[str, tuple[int, int, int] | None], outputs: tuple[bool, Ellipsis] | None = None, return_info: Literal[False] = False, ignore_signed_contracts: bool = True) float[source]
from_offers(offers: tuple[tuple[int, int, int | float] | None, Ellipsis] | dict[str, tuple[int, int, int] | None], outputs: tuple[bool, Ellipsis] | None, return_info: Literal[True], ignore_signed_contracts: bool = True) UtilityInfo

Calculates the utility value given a list of offers and whether each offer is for output or not (= input).

Parameters:
  • offers – An iterable (e.g. list) of tuples each with three values: (quantity, time, unit price) IN THAT ORDER. Time is ignored and can be set to any value.

  • outputs – An iterable of the same length as offers of booleans specifying for each offer whether it is an offer for buying the agent’s output product.

  • return_info – If true, detailed utility information is returned as Utility Info

  • ignore_signed_contracts – If true, ignores the registered signed contracts. This means that only exogenous contracts and offers will be used in evaluating the utility.

Remarks:
  • This method takes into account the exogenous contract information passed when constructing the ufun.

  • You can pass a dictionary mapping partner ID to an offer and the system will use the correct value for the corresponding outputs array.

from_aggregates(qin: int, qout_signed: int, qout_sold: int, pin: int, pout: int, input_penalty: float, output_penalty: float, storage_penalty: float) float[source]

Calculates the utility from aggregates of input/output quantity/prices

Parameters:
  • qin – Input quantity (total including all exogenous contracts).

  • qout_signed – Output quantity (total including all exogenous contracts) that the agent agreed to sell.

  • qout_sold – Output quantity (total including all exogenous contracts) that the agent will actually sell.

  • pin – Input total price (i.e. unit price * qin).

  • pout – Output total price (i.e. unit price * qin).

  • input_penalty – total disposal cost

  • output_penalty – total shortfall penalty

  • storage_penalty – total storage penalty

Remarks:
  • Most likely, you do not need to directly call this method. Consider from_offers and from_contracts that take current balance and exogenous contract information (passed during ufun construction) into account.

  • The method respects production capacity (n. lines). The agent cannot produce more than the number of lines it has.

  • This method does not take exogenous contracts or current balance into account.

  • The method assumes that the agent CAN pay for all input and production.

breach_level(qin: int = 0, qout: int = 0)[source]

Calculates the breach level that would result from a given quantities

is_breach(qin: int = 0, qout: int = 0)[source]

Whether the given quantities would lead to a breach.

minmax(*args, **kwargs) tuple[float, float][source]

Finds the range of the given utility function for the given outcomes

Parameters:
  • self – The utility function

  • issues – List of issues (optional)

  • outcomes – A collection of outcomes (optional)

  • max_cardinality – the maximum number of outcomes to try sampling (if sampling is used and outcomes are not given)

  • above_reserve – If given, the minimum and maximum will be set to reserved value if they were less than it.

Returns:

(lowest, highest) utilities in that order

extreme_outcomes(outcome_space: negmas.outcomes.OutcomeSpace | None = None, issues: Iterable[negmas.outcomes.Issue] | None = None, outcomes: Iterable[negmas.outcomes.Outcome] | None = None, max_cardinality=1000) tuple[negmas.outcomes.Outcome, negmas.outcomes.Outcome][source]
utility_range(outcome_space: negmas.outcomes.OutcomeSpace | None = None, issues: list[negmas.outcomes.Issue] | None = None, outcomes: list[negmas.outcomes.Outcome] | None = None, return_outcomes=False, max_n_outcomes=1000) tuple[float, float] | tuple[float, float, negmas.outcomes.Outcome, negmas.outcomes.Outcome][source]

Finds the utility range and optionally returns the corresponding outcomes from a given issue space or in a single negotiation.

Parameters:
  • issues – The set of issues of the negotiation. If not given it will be read from the AWI. Note that you cannot specify these issues except for agent in the first or last layer of the production graph (because otherwise, the agent cannot know whether this negotiation is for buying of selling).

  • outcomes – A list of outcomes to consider. Using outcomes is much slower than using issues and you should never pass both.

  • infeasible_cutoff – A utility value under which we consider the outcome infeasible.

  • return_outcomes – If given the worst and best outcomes (in that order) will be returned.

  • max_n_outcomes – Maximum number of outcomes to try. Not used.

Returns:

A tuple of worst and best utility values if return_outcomes is False. otherwise, the worst and best outcomes are appended to the returned utilities leading to a 4-items tuple instead of two.

Remarks:
  • You will get a warning if you use a list of outcomes here because it is too slow.

  • You should only pass issues if you know that the agent is either an input agent or an output agent. Agents in the middle of the production graph cannot know whether these issues are for buying of for selling. To find the utility range for these agents, you can use worst and best that allow specifying input and output issues separately.

  • It is always assumed that the range required is for a single negotiation not a set of negotiations and under the assumption that all other negotiations if any will end in failure

_is_midlevel()[source]
find_limit(best: bool, n_input_negs=None, n_output_negs=None, secured_input_quantity=0, secured_input_unit_price=0.0, secured_output_quantity=0, secured_output_unit_price=0.0, ignore_signed_contracts: bool = True) UFunLimit[source]

Finds either the maximum or the minimum of the ufun.

Parameters:
  • best – Best(max) or worst (min) ufun value?

  • n_input_negs – How many input negs are we to consider? None means all

  • n_output_negs – How many output negs are we to consider? None means all

  • secured_input_quantity – A quantity that MUST be bought

  • secured_input_unit_price – The (average) unit price of the quantity that MUST be bought.

  • secured_output_quantity – A quantity that MUST be sold.

  • secured_output_unit_price – The (average) unit price of the quantity that MUST be sold.

  • ignore_signed_contracts – If True all signed contracts will be ignored. Use secured_* to pass this information if you need to in this case.

Remarks:
  • You can use the secured_* arguments and control over the number of negotiations to consider to find the utility limits given some already concluded and signed contracts

best() negmas.outcomes.Outcome[source]
worst() negmas.outcomes.Outcome[source]
find_limit_brute_force(best, n_input_negs=None, n_output_negs=None, secured_input_quantity=0, secured_input_unit_price=0.0, secured_output_quantity=0, secured_output_unit_price=0.0, ignore_signed_contracts=True) UFunLimit[source]

Finds either the maximum and the minimum of the ufun.

Parameters:
  • best – Best(max) or worst (min) ufun value?

  • n_input_negs – How many input negs are we to consider? None means all

  • n_output_negs – How many output negs are we to consider? None means all

  • secured_input_quantity – A quantity that MUST be bought

  • secured_input_unit_price – The (average) unit price of the quantity that MUST be bought.

  • secured_output_quantity – A quantity that MUST be sold.

  • secured_output_unit_price – The (average) unit price of the quantity that MUST be sold.

Remarks:
  • You can use the secured_* arguments and control over the number of negotiations to consider to find the utility limits given some already concluded and signed contracts

  • Note that this function CANNOT take into account the sales or supplies already signed (and registered via register_sale and/or register_supply). You MUST pass the quantities and prices for signed contracts through the secured_* parameters.

Returns:

worst and best outcome information in the form of UFunLimit tuple.

ok_to_buy_at(unit_price: float) bool[source]

Checks if the unit price can – even in principle – be acceptable for buying

Remarks:
  • This method is very optimistic. If it returns False, an agent should never buy at this price. If it returns True, it may still be a bad idea to buy at this price.

  • If we buy at this price, the best case scenario is that we pay it and pay production cost then receive the unit price of one output.

  • If we do not buy at this price, the worst case scenario is that we will pay shortfall penalty for one item

  • We should NOT buy if the best case scenario when buying is worse than the worst case scenario when not buying.

  • If called for agents not at the end of the production chain, it will always return True because in these cases we do not know what the the unit price for the output so there is nothing to compare with.

ok_to_sell_at(unit_price: float) bool[source]

Checks if the unit price can – even in principle – be acceptable for selling

Remarks:
  • This method is very optimistic. If it returns False, an agent should never sell at this price. If it returns True, it may still be a bad idea to sell at this price.

  • Sales decisions does not affect in any way the amount we pay for input materials. It only affects the amount we produce, the amout we get paid in sales and the amount we pay as disposal cost and shortfall penalty.

  • If we agree to sell an item at this price, the best case scenario is that we can actually produce this item and sell it. We pay production cost and receive the given unit price.

  • If we do not sell at this price, the worst case scenario is that we really needed that sale. In this case, we will pay disposal cost for one item.

  • We should NOT sell if the best case scenario when selling is worse than the worst case scenario when not selling.

  • If called for agents not at the beginning of the production chain, it will always return True because in these cases we do not know what the the unit price for the input so there is nothing to compare with.

scml.UFunLimit[source]

Information about one utility limit (either highest or lowest). See OnShotUFun.find_limit for details.

class scml.UtilityInfo[source]
producible: int
total_input: int
total_output: int
shortfall_quantity: int
shortfall_penalty: float
remaining_quantity: int
disposal_cost: float
storage_cost: float
utility: float
class scml.SCMLBaseWorld(catalog_prices: numpy.ndarray, profiles: list[scml.oneshot.common.OneShotProfile], agent_types: list[type[scml.oneshot.agent.OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | numpy.ndarray = 50, financial_report_period=5, bankruptcy_limit=0.0, penalize_bankrupt_for_future_contracts=True, penalties_scale: Literal[trading, catalog, unit, none] = 'trading', exogenous_contracts: Collection[scml.oneshot.common.OneShotExogenousContract] = tuple(), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: numpy.ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=60 * 15, sync_calls=False, neg_n_steps=20, neg_time_limit=None, neg_hidden_time_limit=60, neg_step_time_limit=20, negotiation_speed=None, shuffle_negotiations=False, one_offer_per_step=False, publish_exogenous_summary=True, publish_trading_prices=True, publish_assets=False, publish_production_capacity=True, price_multiplier=0.0, price_range_fraction=0.0, wide_price_range=False, allow_zero_quantity: bool = False, trading_price_discount=0.9, signing_delay=0, force_signing=False, batch_signing=True, name: str | None = None, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_catalog=0, inventory_valuation_trading=0, perishable=True, horizon=0, one_time_per_negotiation=True, quantity_multiplier: float = 1.0, nullify_bankrupt_contracts: bool = False, debug: bool = False, verbose: bool = False, **kwargs)[source]

Bases: negmas.TimeInAgreementMixin, negmas.World[scml.oneshot.awi.OneShotAWI, scml.oneshot.sysagents.DefaultOneShotAdapter]

Implements the a generalized form of SCML-OneShot game which supports both oneshot and standard simulations

Parameters:
  • catalog_prices – An n_products vector (i.e. n_processes+1 vector) giving the catalog price of all products

  • profiles – An n_agents list of OneShotFactoryProfile objects specifying the private profile of the factory associated with each agent.

  • agent_types – An n_agents list of strings/ OneShotAgent classes specifying the type of each agent

  • agent_params – An n_agents dictionaries giving the parameters of each agent

  • catalog_quantities – The quantities in the past for which catalog_prices are the average unit prices. This is used when updating the trading prices. If set to zero then the trading price will follow the market price and will not use the catalog_price (except for products that are never sold in the market for which the trading price will take the default value of the catalog price). If set to a large value (e.g. 10000), the price at which a product is sold will not affect the trading price

  • financial_report_period – The number of steps between financial reports. If < 1, it is a fraction of n_steps

  • exogenous_force_max – If true, exogenous contracts are forced to be signed independent of the setting of force_signing

  • compact – If True, no logs will be kept and the whole simulation will use a smaller memory footprint

  • n_steps – Number of simulation steps (can be considered as days).

  • time_limit – Total time allowed for the complete simulation in seconds.

  • neg_n_steps – Number of negotiation steps allowed for all negotiations.

  • neg_time_limit – Total time allowed for a complete negotiation in seconds.

  • neg_step_time_limit – Total time allowed for a single step of a negotiation. in seconds.

  • negotiation_speed – The number of negotiation steps that pass in every simulation step. If 0, negotiations will be guaranteed to finish within a single simulation step

  • signing_delay – The number of simulation steps to pass between a contract is concluded and signed

  • name – The name of the simulations

  • **kwargs – Other parameters that are passed directly to SCML2020World constructor.

property negotiated_contract_records: list[dict[str, Any]]
property exogenous_contract_records: list[dict[str, Any]]
property agent_contracts
property winners

The winners of this world (factory managers with maximum wallet balance

property trading_prices
property stats_df: pandas.DataFrame

Returns a pandas data frame with the stats

property contracts_df: pandas.DataFrame

Returns a pandas data frame with the contracts

property system_agents: list[scml.oneshot.sysagents._StdSystemAgent]

Returns the two system agents

property system_agent_names: list[str]

Returns the names two system agents

property non_system_agents: list[scml.oneshot.sysagents.DefaultOneShotAdapter]

Returns all agents except system agents

property non_system_agent_names: list[str]

Returns names of all agents except system agents

property agreement_fraction: float

Fraction of negotiations ending in agreement and leading to signed contracts

system_agent_ids
non_system_agent_ids
action_info_cols() list[tuple[str, type]][source]
extract_action_info(action: Any) list[int][source]
agreement_info_cols() list[tuple[str, type]][source]
extract_agreement_info(agreement: negmas.Outcome | None) list[int][source]
extra_neg_info(info: negmas.situated.NegotiationInfo) dict[str, Any][source]
classmethod replace_agents(config: dict, old_types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | list[str | type[scml.oneshot.agent.OneShotAgent]], types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | list[str | type[scml.oneshot.agent.OneShotAgent]], params: list[dict[str, Any]] | tuple[dict[str, Any], Ellipsis] | None = None)[source]

Replaces all agents of a given type by agents of a new type

classmethod generate(agent_types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | list[str | type[scml.oneshot.agent.OneShotAgent]] | type[scml.oneshot.agent.OneShotAgent] | str, agent_params: list[dict[str, Any]] | tuple[dict[str, Any], Ellipsis] | None = None, agent_processes: list[int] | None = None, n_steps: tuple[int, int] | int = (50, 200), n_processes: tuple[int, int] | int = 2, n_lines: numpy.ndarray | tuple[int, int] | int = 10, n_agents_per_process: numpy.ndarray | tuple[int, int] | int = (4, 8), process_inputs: numpy.ndarray | tuple[int, int] | int = 1, process_outputs: numpy.ndarray | tuple[int, int] | int = 1, production_costs: numpy.ndarray | tuple[int, int] | int = (1, 4), profit_means: numpy.ndarray | tuple[float, float] | float = (0.1, 0.2), profit_stddevs: numpy.ndarray | tuple[float, float] | float = 0.05, max_productivity: numpy.ndarray | tuple[float, float] | float = (0.8, 1.0), initial_balance: numpy.ndarray | tuple[int, int] | int | None = None, exogenous_supply_predictability: tuple[float, float] | float = (0.6, 0.9), exogenous_sales_predictability: tuple[float, float] | float = (0.6, 0.9), exogenous_control: tuple[float, float] | float = -1, cash_availability: tuple[float, float] | float = (1.5, 2.5), shortfall_penalty: tuple[float, float] | float = (0.2, 1.0), shortfall_penalty_dev: tuple[float, float] | float = (0.0, 0.1), disposal_cost: tuple[float, float] | float = (0.0, 0.2), disposal_cost_dev: tuple[float, float] | float = (0.0, 0.02), storage_cost: tuple[float, float] | float = (0.0, 0.02), storage_cost_dev: tuple[float, float] | float = 0, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), price_multiplier: numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), cost_increases_with_level=True, equal_exogenous_supply=False, equal_exogenous_sales=False, force_signing=True, profit_basis=np.max, random_agent_types: bool = False, penalties_scale: str | list[str] = 'trading', cap_exogenous_quantities: bool = True, exogenous_generation_method='profitable', perishable: bool | None = True, max_supply: numpy.ndarray | tuple[float, float] | float = (0.8, 1.0), **kwargs) dict[str, Any][source]

Generates the configuration for a world

Parameters:
  • agent_types – All agent types

  • agent_params – Agent parameters used to initialize them

  • n_steps – Number of simulation steps

  • n_processes – Number of processes in the production chain

  • n_lines – Number of lines per factory

  • process_inputs – Number of input units per process

  • process_outputs – Number of output units per process

  • production_costs – Production cost per factory

  • profit_means – Mean profitability per production level (i.e. process).

  • profit_stddevs – Std. Dev. of the profitability of every level (i.e. process).

  • max_productivity – Maximum possible productivity per level (i.e. process).

  • max_supply – Maximum possible supply level to the market,

  • initial_balance – The initial balance of all agents

  • n_agents_per_process – Number of agents per process

  • agent_processes – The process for each agent. If not None , it will override n_agents_per_process and must be a list/tuple of the same length as agent_types . Morevoer, random_agent_types must be False in this case

  • cost_increases_with_level – If true, production cost will be higher for processes nearer to the final product.

  • profit_basis – The statistic used when controlling catalog prices by profit arguments. It can be np.mean, np.median, np.min, np.max or any Callable[[list[float]], float] and is used to summarize production costs at every level.

  • equal_exogenous_supply – If true, external supply will be distributed equally among all agents in the first layer

  • equal_exogenous_sales – If true, external sales will be distributed equally among all agents in the last layer

  • exogenous_supply_predictability – How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random

  • exogenous_sales_predictability – How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random

  • force_signing – Whether to force contract signatures (exogenous contracts are treated in the same way).

  • exogenous_control – How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True

  • cap_exogenous_quantities – If True, all exogenous quantities in all contracts are capped to be no more than the number of lines

  • cash_availability – The fraction of the total money needs of the agent to work at maximum capacity that is available as initial_balance . This is only effective if initial_balance is set to None .

  • exogenous_control – How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True

  • disposal_cost – A range to sample mean-disposal costs for all factories from (only used if perishable is True)

  • shortfall_penalty – A range to sample mean-shortfall penalty for all factories from

  • storage_cost – A range to sample mean-storage costs fro all factories from (only used if perishable is False)

  • disposal_cost_dev – A range to sample std. dev of disposal costs for all factories from

  • shortfall_penalty_dev – A range to sample std. dev of shortfall penalty for all factories from

  • storage_cost_dev – The standard deviation of storage cost relative to the mean price

  • exogenous_price_dev – The standard deviation of exogenous contract prices relative to the mean price

  • price_multiplier – A value to multiply with trading/catalog price to get the upper limit on prices for all negotiations

  • random_agent_types – If True, the final agent types used by the generator will always be sampled from the given types. If False, this random sampling will only happen if len(agent_types) != n_agents.

  • penalties_scale – What are disposal_cost and shortfall_penalty relative to. There are four options: trading, catalog mean trading and catalog prices of the product. unit means the unit price in the contract and none means the storage-cost and shortfall_penalty are absolute values (in money unit). If not given will be read through the AWI

  • exogenous_generation_method – the generation method. This is only for compatibility with SCML2020World and is not used.

  • perishable – If True, storage_cost is set to zero as there is no storage and if False, disposal_cost is set to zero as there is no disposal. If None, neither is overridden.

  • **kwargs

Returns:

world configuration as a Dict[str, Any]. A world can be generated from this dict by calling OneShotWorld(**d)

Remarks:

  • There are two general ways to use this generator:
    1. Pass random_agent_types = False, and pass agent_types, agent_processes to control placement of each agent in each level of the production graph.

    2. Pass random_agent_types = True and pass agent_types, n_agents_per_process to make the system randomly place the specified number of agents in each production level

  • Most parameters (i.e. process_inputs , process_outputs , n_agents_per_process , costs ) can take a single value, a tuple of two values, or a list of values. If it has a single value, it is repeated for all processes/factories as appropriate. If it is a tuple of two numbers $(i, j)$, each process will take a number sampled from a uniform distribution supported on $[i, j]$ inclusive. If it is a list of values, of the length n_processes , it is used as it is otherwise, it is used to sample values for each process.

type_name_for_logs(agent: scml.oneshot.agent.OneShotAgent | None) str | None[source]
current_balance(agent_id: str)[source]
add_financial_report(agent: scml.oneshot.sysagents.DefaultOneShotAdapter, reports_agent, reports_time) None[source]

Records a financial report for the given agent in the agent indexed reports and time indexed reports

Parameters:
  • agent – The agent

  • reports_agent – A dictionary of financial reports indexed by agent id

  • reports_time – A dictionary of financial reports indexed by time

Returns:

_update_exogenous(s)[source]
step_with(actions: dict[str, dict[str, negmas.SAOResponse]], init=False) bool[source]

Runs a simulation step for the agents given in keys passing the corresponding values as counter offers.

Returns:

False if this is the last negotiation.

Remarks:
  • You must call this with init=True once at the beginning of every simulation to make sure that init() and other initialization code is called correctly.

  • Every step advances all negotiations one step.

  • Negotiators belonging to the given agents are never called as long as a corresponding action (response) is given in the agents dict.

  • The world MUST be created with one_offer_per_step passed as True (default is False).

simulation_step(stage=0)[source]

A single step of the simulation.

Parameters:

stage – How many times so far was this method called within the current simulation step

Remarks:

  • Using the stage parameter, it is possible to have Operations . SimulationStep several times with the list of operations while differentiating between these calls.

_breach_record(perpetrator, level, type_) dict[str, Any][source]
_adjust_contract_types(contract)[source]
on_contract_signed(contract: negmas.Contract) bool[source]

Called to add a contract to the existing set of contract after it is signed

Parameters:

contract – The contract to add

Returns:

True if everything went OK and False otherwise

Remarks:

  • By default this function just adds the contract to the set of contracts maintaned by the world.

  • You should ALWAYS call this function when overriding it.

contract_record(contract: negmas.Contract) dict[str, Any][source]

Converts a contract to a record suitable for permanent storage

breach_record(breach: negmas.Breach) dict[str, Any][source]

Converts a breach to a record suitable for storage during the simulation

execute_action(action, agent, callback: Callable | None = None) bool[source]

Executes the given action by the given agent

contract_size(contract: negmas.Contract) float[source]

Returns an estimation of the activity level associated with this contract. Higher is better :param contract:

Returns:

post_step_stats()[source]

Called at the end of the simulation step to update all stats

Kept for backward compatibility and will be dropped. Override update_stats ins

pre_step_stats()[source]

Called at the beginning of the simulation step to prepare stats or update them

Kept for backward compatibility and will be dropped. Override update_stats instead

welfare(include_bankrupt: bool = False) float[source]

Total welfare of all agents

relative_welfare(include_bankrupt: bool = False) float | None[source]

Total welfare relative to expected value. Returns None if no expectation is found in self.info

is_valid_contact(contract: negmas.Contract) bool[source]

Checks whether a signed contract is valid

scores(assets_multiplier: float = 0.0) dict[str, float][source]

Scores of all agents given the asset multiplier.

Parameters:

assets_multiplier – A multiplier to multiply the assets with.

trading_prices_for(discount: float = 1.0, condition='executed') numpy.ndarray[source]

Calculates the prices at which all products traded using an optional discount factor

Parameters:
  • discount – A discount factor to treat older prices less importantly (exponential discounting).

  • condition – The condition for contracts to consider. Possible values are executed, signed, concluded, nullified

Returns:

an n_products vector of trading prices

draw(steps: tuple[int, int] | int | None = None, what: Collection[str] = DEFAULT_EDGE_TYPES, who: Callable[[negmas.Agent], bool] | None = None, where: Callable[[negmas.Agent], int | tuple[float, float]] | None = None, together: bool = True, axs: Collection[matplotlib.axis.Axis] | None = None, ncols: int = 4, figsize: tuple[int, int] = (15, 15), **kwargs) tuple[matplotlib.axis.Axis, networkx.Graph] | tuple[list[matplotlib.axis.Axis], list[networkx.Graph]][source]
_request_negotiations(agent_id: str, controller: negmas.sao.SAOController | None = None, negotiators: list[negmas.sao.SAONegotiator] | None = None, extra: dict[str, Any] | None = None) bool[source]

Requests negotiations (used internally)

Parameters:
  • agent_id – the agent requesting

  • product – The product to negotiate about

  • quantity – The minimum and maximum quantities. Passing a single value q is equivalent to passing (q,q)

  • unit_price – The minimum and maximum unit prices. Passing a single value u is equivalent to passing (u,u)

  • time – The minimum and maximum delivery step. Passing a single value t is equivalent to passing (t,t)

  • controller – The controller to manage the complete set of negotiations

  • negotiators – An optional list of negotiators to use for negotiating with the given partners (in the same order).

  • extra – Extra information accessible through the negotiation annotation to the caller

  • consumer_starts (#) – Whether the consumer or supplier sends the first offer in the negotiation

Returns:

True if the partner accepted and the negotiation is ready to start

_request_negotiation(agent_id: str, product: int, partner: str, negotiator: negmas.sao.SAONegotiator, extra: dict[str, Any] | None = None, is_buy: bool = True) negmas.situated.NegotiationInfo | None[source]

Requests a negotiation

Parameters:
  • product – The product to negotiate about

  • quantity – The minimum and maximum quantities. Passing a single value q is equivalent to passing (q,q)

  • unit_price – The minimum and maximum unit prices. Passing a single value u is equivalent to passing (u,u)

  • time – The minimum and maximum delivery step. Passing a single value t is equivalent to passing (t,t)

  • partner – ID of the partner to negotiate with.

  • negotiator – The negotiator to use for this negotiation (if the partner accepted to negotiate)

  • extra – Extra information accessible through the negotiation annotation to the caller

  • is_buy – whether the consumer starts the negotiation

Returns:

True if the partner accepted and the negotiation is ready to start

_make_issues(product) tuple[tuple[int, int], tuple[int, int], tuple[int, int]][source]

Creates the negotiation agendas

Parameters:

product (int) – The product to be negotiated about

Returns:

A tuple of minimum and maximum values for unit-price, time, and quantity in that order

_make_negotiations()[source]
order_contracts_for_execution(contracts: Collection[negmas.Contract]) Collection[negmas.Contract][source]

Orders the contracts in a specific time-step that are about to be executed

get_private_state(agent: negmas.Agent) dict[source]

Reads the private state of the given agent

_contract_record(contract)[source]

Converts a contract to a record suitable for permanent storage

start_contract_execution(contract: negmas.Contract) set[negmas.Breach] | None[source]

Tries to execute the contract

Parameters:

contract

Returns:

The set of breaches committed if any. If there are no breaches return an empty set

Return type:

Set[Breach]

Remarks:

  • You must call super() implementation of this method before doing anything

  • It is possible to return None which indicates that the contract was nullified (i.e. not executed due to a reason other than an execution exeception).

complete_contract_execution(contract: negmas.Contract, breaches: list[negmas.Breach], resolution: negmas.Contract) None[source]

Called after breach resolution is completed for contracts for which some potential breaches occurred.

Parameters:
  • contract – The contract considered.

  • breaches – The list of potential breaches that was generated by _execute_contract.

  • resolution – The agreed upon resolution

Returns:

classmethod plot_combined_stats(worlds: tuple[SCMLBaseWorld, Ellipsis] | SCMLBaseWorld, stats: str | tuple[str, Ellipsis] | None = None, pertype=False, makefig=False, title=True, ylabel=False, xlabel=False, legend=True, figsize=None, perishable: bool = False, **kwargs)[source]

Plots combined statistics of multiple worlds in a single plot

Parameters:
  • stats – The statistics to plot. If None, some selected stats will be displayed

  • pertype – combine agent-statistics per type

  • use_sum – plot sum for type statistics instead of mean

  • title – If given a title will be added to each subplot

  • ylabel – If given, the ylabel will be added to each subplot

  • xlabel – If given The xlabel will be added (Simulation Step)

  • legend – If given, a legend will be displayed

  • makefig – If given a new figure will be started

  • figsize – Size of the figure to host the plot

  • ylegend – y-axis of legend for cases with large number of labels

  • legend_n_cols – number of columns in the legend

plot_stats(stats: str | tuple[str, Ellipsis] | None = None, pertype=False, use_sum=False, makefig=False, title=True, ylabel=False, xlabel=False, legend=True, figsize=None, ylegend=2.0, legend_ncols=8)[source]

Plots statistics of the world in a single plot

Parameters:
  • stats – The statistics to plot. If None, some selected stats will be displayed

  • pertype – combine agent-statistics per type

  • use_sum – plot sum for type statistics instead of mean

  • title – If given a title will be added to each subplot

  • ylabel – If given, the ylabel will be added to each subplot

  • xlabel – If given The xlabel will be added (Simulation Step)

  • legend – If given, a legend will be displayed

  • makefig – If given a new figure will be started

  • figsize – Size of the figure to host the plot

  • ylegend – y-axis of legend for cases with large number of labels

class scml.OneShotWorld(catalog_prices: numpy.ndarray, profiles: list[scml.oneshot.common.OneShotProfile], agent_types: list[type[scml.oneshot.agent.OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | numpy.ndarray = 50, financial_report_period=5, bankruptcy_limit=0.0, penalize_bankrupt_for_future_contracts=True, penalties_scale: Literal[trading, catalog, unit, none] = 'trading', exogenous_contracts: Collection[scml.oneshot.common.OneShotExogenousContract] = tuple(), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: numpy.ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=60 * 15, sync_calls=False, neg_n_steps=20, neg_time_limit=None, neg_hidden_time_limit=60, neg_step_time_limit=20, negotiation_speed=None, shuffle_negotiations=False, one_offer_per_step=False, publish_exogenous_summary=True, publish_trading_prices=True, publish_assets=False, publish_production_capacity=True, price_multiplier=0.0, price_range_fraction=0.0, wide_price_range=False, allow_zero_quantity: bool = False, trading_price_discount=0.9, signing_delay=0, force_signing=False, batch_signing=True, name: str | None = None, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_catalog=0, inventory_valuation_trading=0, perishable=True, horizon=0, one_time_per_negotiation=True, quantity_multiplier: float = 1.0, nullify_bankrupt_contracts: bool = False, debug: bool = False, verbose: bool = False, **kwargs)[source]

Bases: SCMLBaseWorld

Basic oneshot simulation

class scml.SCML2020OneShotWorld(catalog_prices: numpy.ndarray, profiles: list[scml.oneshot.common.OneShotProfile], agent_types: list[type[scml.oneshot.agent.OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | numpy.ndarray = 50, financial_report_period=5, bankruptcy_limit=0.0, penalize_bankrupt_for_future_contracts=True, penalties_scale: Literal[trading, catalog, unit, none] = 'trading', exogenous_contracts: Collection[scml.oneshot.common.OneShotExogenousContract] = tuple(), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: numpy.ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=60 * 15, sync_calls=False, neg_n_steps=20, neg_time_limit=None, neg_hidden_time_limit=60, neg_step_time_limit=20, negotiation_speed=None, shuffle_negotiations=False, one_offer_per_step=False, publish_exogenous_summary=True, publish_trading_prices=True, publish_assets=False, publish_production_capacity=True, price_multiplier=0.0, price_range_fraction=0.0, wide_price_range=False, allow_zero_quantity: bool = False, trading_price_discount=0.9, signing_delay=0, force_signing=False, batch_signing=True, name: str | None = None, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_catalog=0, inventory_valuation_trading=0, perishable=True, horizon=0, one_time_per_negotiation=True, quantity_multiplier: float = 1.0, nullify_bankrupt_contracts: bool = False, debug: bool = False, verbose: bool = False, **kwargs)[source]

Bases: OneShotWorld

Oneshot simulation as used in SCML 2020 competition

class scml.SCML2021OneShotWorld(*args, **kwargs)[source]

Bases: SCML2020OneShotWorld

Oneshot simulation as used in SCML 2021 competition

class scml.SCML2022OneShotWorld(*args, **kwargs)[source]

Bases: SCML2021OneShotWorld

Oneshot simulation as used in SCML 2022 competition

class scml.SCML2023OneShotWorld(*args, **kwargs)[source]

Bases: SCML2020OneShotWorld

Oneshot simulation as used in SCML 2023 competition

class scml.SCML2024OneShotWorld(*args, **kwargs)[source]

Bases: SCML2023OneShotWorld

Oneshot simulation as used in SCML 2024 competition

scml.PLACEHOLDER_AGENT_PREFIX = 'PlaceHolder__'[source]
scml.__all__[source]