scml.scml2019

The implementation file for all entities needed for ANAC-SCML 2019.

Participants need to provide a class inherited from FactoryManager that implements all of its abstract functions.

Participants can optionally override any other methods of this class or implement new NegotiatorUtility class.

Simulation steps:

  1. prepare custom stats (call _pre_step_stats)

  2. sign contracts that are to be signed at this step calling on_contract_signed as needed

  3. step all existing negotiations negotiation_speed_multiple times handling any failed negotiations and creating contracts for any resulting agreements

  4. run all Entity objects registered (i.e. all agents). Consumer s run first then FactoryManager s then Miner s

  5. execute contracts that are executable at this time-step handling any breaches

  6. Custom Simulation Steps:
    1. step all factories (Factory objects) running any pre-scheduled commands

    2. Apply interests and pay loans

    3. remove expired CFP s

    4. Deliver any products that are in transportation

  7. remove any negotiations that are completed!

  8. update basic stats

  9. update custom stats (call _post_step_stats)

Remarks about re-negotiation on breaches:

  • The victim is asked first to specify the negotiation agenda (issues) then the perpetrator

  • renegotiations for breaches run immediately to completion independent from settings of negotiation_speed_multiplier and immediate_negotiations. That include conclusion and signing of any resulting agreements.

Remarks about timing:

  • The order of events within a single time-step are as follows:

    1. Contracts scheduled to be signed are signed.

    2. Scheduled negotiations run for the predefined number of steps. Any negotiation that result in a contract or fail may trigger other negotiations.

    3. If immediate_negotiations, some of the newly added negotiations may be concluded/failed.

    4. Any newly concluded contracts that are to be signed at this step are signed

    5. Contracts are executed including full execution of any re-negotiations and breaches are handled. Notice that if re-negotiation leads to new contracts, these will be concluded and signed immediately at this step. Please note the following about contract execution:

      • Products are moved from the seller’s storage to a temporary truck as long as they are available at the time of contract execution. Because contract execution happens before actual production, outputs from production processes CANNOT be sold at the same time-step.

    6. Production is executed on all factories. For a Process to start/continue on a Line, all its inputs required at this time-step MUST be available in storage of the corresponding factory by this point. This implies that it is impossible for any processes to start at time-step 0 except if initial storage was nonzero. FactoryManager s are informed about processes that cannot start due to storage or fund shortage (or cannot continue due to storage shortage) through an on_production_failure call.

    7. Outputs of the Process are generated at the end of the corresponding time-step. It is immediately moved to storage. Because outputs are generated at the end of the step and inputs are consumed at the beginning, a factory cannot use outputs of a process as inputs to another process that starts at the same time-step.

    8. Products are moved from the temporary truck to the buyer’s storage after the transportation_delay have passed at the end of the time-step. Transportation completes at the end of the time-step no matter what is the value for transportation_delay. This means that if a FactoryManager believes that it can produce some product at time t, it should never contract to sell it before t+d + 1 where d is the transportation_delay (the 1 comes from the fact that contract execution happens before production). Even for a zero transportation delay, you cannot produce something and sell it in the same time-step. Moreover, the buyer should never use the product to be delivered at time t as an input to a production process that needs it before step t+1.

    9. When contracts are executed, the funds are deducted from the buyer’s wallet at the beginning of the simulation step and deposited in the seller’s wallet at the end of that step (similar to what happens to the products). This means that a factory manager cannot use funds it receives from sales at time t for buying products before t + 1.

Remarks about ANAC 2019 SCML League:

Given the information above, and settings for the ANAC 2019 SCML you can confirm for yourself that the following rules are all correct:

  1. No agents except miners should contract on delivery at time 0.

  2. FactoryManager s should never sign contracts to sell the output of their production with delivery at t except if this production starts at step t and the contract is signed no later than than t-1.

  3. If not all inputs are available in storage, FactoryManager s should never sign contracts to sell the output of production with delivery at t later than t-2 (and that is optimistic).

Subpackages

Submodules

Attributes

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__

__all__

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.

Factory

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

Functions

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.

Package Contents

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

Bases: negmas.situated.Agent

The base for all SCM Agents

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

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.

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

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.

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

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.

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

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.scml2019.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.scml2019.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.scml2019.UNIT_PRICE = 2[source]

Index of unit price in negotiation issues

scml.scml2019.TIME = 1[source]

Index of time in negotiation issues

scml.scml2019.QUANTITY = 0[source]

Index of quantity in negotiation issues

class scml.scml2019.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.scml2019.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.scml2019.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.scml2019.RunningCommandInfo[source]
__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

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

Return str(self).

property is_none
classmethod do_nothing()[source]
scml.scml2019.INVALID_STEP[source]
scml.scml2019.NO_PRODUCTION[source]
class scml.scml2019.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.scml2019.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.scml2019.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.scml2019.FactoryStatusUpdate[source]
__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:

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

Return str(self).

class scml.scml2019.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.scml2019.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.scml2019.MissingInput[source]
__slots__ = ['product', 'quantity']
product: int
quantity: int
__str__()[source]

Return str(self).

class scml.scml2019.ProductionReport[source]
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

property failed
property is_empty
property no_production
__str__()[source]

Return str(self).

class scml.scml2019.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.scml2019.FinancialReport[source]

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

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

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.

class scml.scml2019.SCMLAgreement[source]
time: int

delivery time

unit_price: float

unit price

quantity: int

quantity

penalty: float | None = 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.scml2019.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.scml2019.CFP[source]

A Call for proposal upon which a negotiation can start

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

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

money_resolution: float | None = 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

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
to_dict()[source]
classmethod from_dict(idict: Dict[str, Any], class_name: str | None = None) CFP[source]
class scml.scml2019.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.scml2019.InsurancePolicy[source]
premium: float
contract: negmas.situated.Contract
at_time: int
against: scml.scml2019.agent.SCML2019Agent
class scml.scml2019.Factory[source]

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

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]
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
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.scml2019.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.scml2019.DEFAULT_NEGOTIATOR = 'negmas.sao.AspirationNegotiator'[source]
class scml.scml2019.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.scml2019.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.scml2019.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

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

MAX_UNIT_PRICE = 100.0
RELATIVE_MAX_PRICE = 1.5
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

scml.scml2019.__all__[source]
class scml.scml2019.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 = 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.scml2019.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.scml2019.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.scml2019.pos_gauss(mu, sigma)[source]

Returns a sample from a rectified gaussian

scml.scml2019._safe_max(a, b)[source]
scml.scml2019.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.scml2019.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.scml2019.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.scml2019.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.scml2019.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.scml2019.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.scml2019.ScheduleInfo[source]
final_balance: float

balance at the end of the schedule

valid: bool = True

Is this a valid schedule?

start: int | None = None

The starting step of this schedule

end: int | None = 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.scml2019.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.scml2019.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.scml2019.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.

_as_array(storage: Dict[int, int])[source]
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

property final_balance: float
Abstractmethod:

Final balance given everything scheduled so-far

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 property fixed_before

Gives the time before which the schedule is fixed.

See also

fix_before

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

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)

property final_balance: float

Final balance given everything scheduled so-far

property n_lines
Number of lines
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

property fixed_before
Gives the time before which the schedule is fixed.

See also

fix_before

class scml.scml2019.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.

_as_array(storage: Dict[int, int]) numpy.array[source]
init(*args, **kwargs)[source]
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

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.scml2019.transaction(simulator)[source]

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

scml.scml2019.temporary_transaction(simulator)[source]

Runs the simulated actions then rolls them back

scml.scml2019.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=