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:
prepare custom stats (call
_pre_step_stats
)sign contracts that are to be signed at this step calling
on_contract_signed
as neededstep all existing negotiations
negotiation_speed_multiple
times handling any failed negotiations and creating contracts for any resulting agreementsrun all
Entity
objects registered (i.e. all agents).Consumer
s run first thenFactoryManager
s thenMiner
sexecute contracts that are executable at this time-step handling any breaches
remove any negotiations that are completed!
update basic stats
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
andimmediate_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:
Contracts scheduled to be signed are signed.
Scheduled negotiations run for the predefined number of steps. Any negotiation that result in a contract or fail may trigger other negotiations.
If
immediate_negotiations
, some of the newly added negotiations may be concluded/failed.Any newly concluded contracts that are to be signed at this step are signed
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.
Production is executed on all factories. For a
Process
to start/continue on aLine
, 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 anon_production_failure
call.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.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 fortransportation_delay
. This means that if aFactoryManager
believes that it can produce some product at time t, it should never contract to sell it before t+d + 1 where d is thetransportation_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.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:
No agents except miners should contract on delivery at time 0.
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.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).
Submodules
- scml.scml2019.agent
- scml.scml2019.awi
- scml.scml2019.bank
- scml.scml2019.common
- scml.scml2019.consumers
- scml.scml2019.factory_managers
- scml.scml2019.helpers
- scml.scml2019.insurance
- scml.scml2019.miners
- scml.scml2019.schedulers
- scml.scml2019.simulators
- scml.scml2019.utils19
- scml.scml2019.visualizers
- scml.scml2019.world
Attributes
Index of unit price in negotiation issues |
|
Index of time in negotiation issues |
|
Index of quantity in negotiation issues |
|
Classes
The base for all SCM Agents |
|
A single contact point between SCML agents and the world simulation. |
|
Represents a bank in the world |
|
Base class for all banks |
|
An input/output to a production process |
|
The costs/time required for running a process on a line (with associated cancellation costs etc). This |
|
The costs/time required for running a process on a line (with associated cancellation costs etc). |
|
Gives full information about a manufacturing process that can generate or consume a product. |
|
Describes a job to be run on one production line of a |
|
Describes some quantity of a product that is needed to honor a (sell) contract. |
|
Reports that financial standing of an agent at a given time in the simulation |
|
A Call for proposal upon which a negotiation can start |
|
Represents a factory within an SCML world. It is only accessed by the SCML2020World so it need not be made public. |
|
Read Only State of a factory |
|
Base class of all consumer classes |
|
Consumer class |
|
Base factory manager class that will be inherited by participant negmas in ANAC 2019. |
|
The default factory manager that will be implemented by the committee of ANAC-SCML 2019 |
|
The default factory manager that will be implemented by the committee of ANAC-SCML 2019 |
|
Represents an insurance company in the world |
|
Base class for all insurance companies |
|
Base class of all miners |
|
Raw Material Generator |
|
Base class for all schedulers |
|
Default scheduler used by the DefaultFactoryManager |
|
Simulates a factory allowing for prediction of storage/balance in the future. |
|
A slow factory simulator that runs an internal factory to find-out what will happen in the future |
|
A faster implementation of the |
|
The default factory manager that will be implemented by the committee of ANAC-SCML 2019 |
|
The |
|
Represents a factory within an SCML world. It is only accessed by the SCML2020World so it need not be made public. |
Functions
|
Returns a sample from a rectified gaussian |
|
|
|
Finds all runs of zero in an array |
|
Runs the simulated actions then confirms them if they are not rolled back |
|
Runs the simulated actions then rolls them back |
|
Creates a world compatible with the ANAC 2019 competition. Note that |
|
The function used to run ANAC 2019 SCML tournament (collusion track). |
|
The function used to run ANAC 2019 SCML tournament (collusion track). |
|
The function used to run ANAC 2019 SCML tournament (standard track). |
|
A scoring function that scores factory managers' performance by the final balance only ignoring whatever still |
|
The function used to run ANAC 2019 SCML tournament (collusion track). |
|
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
- 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.
- init_()[source]
The initialization function called by the world directly.
It does the following actions by default:
copies some of the static world settings to the agent to make them available without calling the AWI.
prepares production related properties like producing, consuming, line_profiles, compiled_profiles, etc.
registers interest in all products that the agent can produce or consume in its factory.
finally it calls any custom initialization logic implemented in `init`()
- 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:
Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it.
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
andrespond_to_negotiation_request
callbacks by pulling the bulletin-board using the helper functionis_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:
Agents must opt-in to receive these calls by calling
receive_financial_reports
on their AWI
- 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:
Attributes and methods available in this Agent-SCML2020World-Interface
Attributes and methods in the
FactoryManager
object itself which provide handy shortcuts to the agent-world interface
Attributes
Simulation settings
current_step
: Current simulation stepdefault_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 ofProduct
objects giving all products defined in the world simulationprocesses
: A list ofProcess
objects giving all products defined in the world simulation
Agent Related
state
: The current private state available to the agent. In SCML it is aFactoryState
object.
Methods
Production Control
schedule_job
: Schedules aJob
for production sometime in the futureschedule_production
: Schedules production using profile number instead of aJob
objectcancel_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 creatingAction
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 tohide_funds
unhide_inventory
: Un-hides inventory hidden earlier with a call tohide_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 ofFactoryManager
(i.e. use self.request_negotiation instead of self.awi.request_negotiation). This makes it possible for NegMAS to keep track of existingrequested_negotiations
andrunning_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 allFactoryManager
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 agentreceive_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-stepreports_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 contractbuy_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-boardbb_query
: Returns all records in the given section/sections of the bulletin-board that satisfy a querybb_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 withbb_
):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 filelogwarning
: Logs a warning in the world simulation log fileloginfo
: Logs information in the world simulation log filelogdebug
: 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 areq_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 therequested_negotiations
andrunning_negotiations
properties of theSCML2019Agent
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
liststep – 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]
- disabled = False
- minimum_balance
- interest_rate
- interest_max
- installment_interest
- time_increment
- balance_at_max_interest
- a2f
- 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
- class scml.scml2019.Bank(*args, **kwargs)[source]
Bases:
negmas.situated.Agent
,abc.ABC
Base class for all banks
- _world = None
- _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.
- class scml.scml2019.Product[source]
- __slots__ = ['id', 'production_level', 'name', 'expires_in', 'catalog_price']
A product that can be transacted in.
- class scml.scml2019.Process[source]
- __slots__ = ['id', 'production_level', 'name', 'inputs', 'outputs', 'historical_cost']
- 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)
- class scml.scml2019.InputOutput[source]
An input/output to a production process
- __slots__ = ['product', 'quantity', 'step']
- 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
- step: int
The time-step relative to
beg
at the factory is currently executing theProcess
indicated inprofile
.step
will always go up by one every simulation step except if the command is paused where it does not change
- 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 is_none
- 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 inManufacturingProfileCompiled
. It is intended to be used to construct factoriesSee also
- __slots__ = ['n_steps', 'cost', 'initial_pause_cost', 'running_pause_cost', 'resumption_cost',...
- class scml.scml2019.ManufacturingProfileCompiled[source]
The costs/time required for running a process on a line (with associated cancellation costs etc).
See also
- __slots__ = ['n_steps', 'cost', 'initial_pause_cost', 'running_pause_cost', 'resumption_cost',...
- 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.
- __slots__ = ['profile', 'quantity', 'step']
- profile: int
The
ManufacturingProfile
index
- class scml.scml2019.FactoryStatusUpdate[source]
- __slots__ = ['balance', 'storage']
- 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 fromReturns:
- property is_empty
- 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']
- line: int
Index of the line on which the job is to be scheduled. Notice that it will be ignored for
run
actions.
- 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']
- needed_for: negmas.situated.Contract
The contract for which the product is needed
- class scml.scml2019.ProductionReport[source]
-
- 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
- class scml.scml2019.ProductionFailure[source]
- __slots__ = ['line', 'command', 'missing_inputs', 'missing_money', 'missing_space']
- command: RunningCommandInfo
Information about the command that failed
- missing_inputs: List[MissingInput]
The missing inputs if any with their quantities
- class scml.scml2019.FinancialReport[source]
Reports that financial standing of an agent at a given time in the simulation
- 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.CFP[source]
A Call for proposal upon which a negotiation can start
- 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)
- 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
- class scml.scml2019.InsurancePolicy[source]
- contract: negmas.situated.Contract
- 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.
- profiles: List[ManufacturingProfile] = []
A list of profiles used to initialize the factory
- _commands: numpy.ndarray
The production command currently running
- _line_schedules: numpy.ndarray
Amount of money hidden by the agent
Mapping from product index to the amount hidden by the agent
- _jobs: Dict[Tuple[int, int], Job]
The jobs waiting to be run on the factory indexed by (time, line) tuples
- _carried_updates: FactoryStatusUpdate
Carried updates from last executed command
- _world: negmas.situated.World = None
- property commands: numpy.ndarray
- property line_schedules: numpy.ndarray
- schedule(job: Job, override=False) None [source]
Schedules the given job at its
time
andline
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
- line_schedules: numpy.ndarray
An array of n_lines * n_steps giving the line schedules
Amount of money hidden by the agent
Mapping from product index to the amount hidden by the agent
- profiles: List[ManufacturingProfile]
A list of profiles used to initialize the factory
- commands: numpy.ndarray
The production command currently running
- 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.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:
Agents must opt-in to receive these calls by calling
receive_financial_reports
on their AWI
- 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:
Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it.
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
andrespond_to_negotiation_request
callbacks by pulling the bulletin-board using the helper functionis_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
- negotiator_type = 'negmas.sao.AspirationNegotiator'
- profiles: Dict[int, ConsumptionProfile]
- consumption_horizon = 20
- immediate_cfp_update = True
- 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]
- 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
- 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:
Attributes and methods available in the Agent-SCML2020World-Interface (See
SCMLAWI
documentation for those).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 internalSCMLAWI
.
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.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 itprocess_profiles
: A mapping specifying for eachProcess
index, all the profiles used to run it in the factoryproducing
: Mapping from a product index to all manufacturing processes that can generate itconsuming
: Mapping from a product index to all manufacturing processes that can consume itcompiled_profiles
: All the profiles to be used by the factory belonging to this agent compiled to use process indicesmax_storage
: Maximum storage available to the agent. Zero, None or float(‘inf’) all indicate unlimited storage.
Production Graph (also accessible through awi)
Helper Objects
awi
: TheSCMLAWI
instance assigned to this agent. It can be used to interact with the simulation (SeeSCMLAWI
documentation).simulator
: AFactorySimulator
object that can be used to simulate what happens in theFactory
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* usesrequest_negotiation
method of this class (see methods later) rather than directly calling request_method on theSCMLAWI
(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* usesrequest_negotiation
method of this class (see methods later) rather than directly calling request_method on theSCMLAWI
(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* usesrequest_negotiation
method of this class (see methods later) rather than directly calling request_method on theSCMLAWI
(awi
) member.
Simulation attributes (also accessible through awi)
transportation_delay
: The transportation delay in the system.current_step
: Current simulation step.immediate_negotiations
: Whether or not negotiations start immediately upon registration (default is to start on the next production step)negotiation_speed_multiple
: The number of negotiation rounds (steps) conducted in a single production steptransportation_delay
: Transportation delay in the system. Default is zero
Methods (Callable by the agent)
Actions on the world
request_negotiation
: Called to request a negotiation based on aCFP
.
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 aCFP
that was published earlier by this factory manager. If accepted, the agent should return aSAONegotiator
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 returningFalse
), 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)
Information callbacks (Called to inform the agent about events)
CFP related
on_new_cfp
: Called whenever aCFP
on aProduct
for which the agent has already registered interest (usingregister_interest
method of itsawi
) 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 aCFP
on aProduct
for which the agent has already registered interest (usingregister_interest
method of itsawi
) is removed from the bulletin-board.
Negotiation related
on_neg_request_accepted
: Called when a negotiation request of the agent is acceptedon_neg_request_rejected
: Called when a negotiation request of the agent is rejectedon_negotiation_success
: Called when a negotiation of which the agent is a party succeeds with an agreement.on_negotiation_failure
: Called when a negotiation of which the agent is a party ends without agreement.
Contract related
on_contract_cancelled
: Called whenever aContract
of which the agent is a party is cancelled because the other party refused to sign it.on_contract_signed
: Called whenever aContract
of which the agent is a party is signed by both patners.on_contract_nullified
: Called whenever aContract
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 (seeSCMLAWI
for production commands) failson_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
on_agent_bankrupt
: Called whenever another agent goes bankrupton_new_report
: Called whenever a new report of another agent for which this agent has registered interest is published. Interest is registered using the agent’sawi
‘sreceive_financial_reports
method.
- 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
- init_()[source]
The initialization function called by the world directly.
It does the following actions by default:
copies some of the static world settings to the agent to make them available without calling the AWI.
prepares production related properties like producing, consuming, line_profiles, compiled_profiles, etc.
registers interest in all products that the agent can produce or consume in its factory.
finally it calls any custom initialization logic implemented in `init`()
- 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.
- 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:
Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it.
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
andrespond_to_negotiation_request
callbacks by pulling the bulletin-board using the helper functionis_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:
Agents must opt-in to receive these calls by calling
receive_financial_reports
on their AWI
- 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:
- negotiator_type = 'negmas.sao.AspirationNegotiator'
- negotiator_params = None
- optimism = 0.0
- ufun_factory: Type[NegotiatorUtility] | Callable[[Any, Any], NegotiatorUtility]
- __reserved_value
- n_retrials = 5
- consumer = None
- use_consumer = True
- reactive = True
- sign_only_guaranteed_contracts = False
- contract_schedules: Dict[str, scml.scml2019.schedulers.ScheduleInfo]
- riskiness = 0.0
- negotiation_margin
- scheduler_type: Type[scml.scml2019.schedulers.Scheduler]
- scheduler: scml.scml2019.schedulers.Scheduler = None
- 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
- 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.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
- disabled = False
- insured_contracts: Dict[Tuple[negmas.situated.Contract, str], scml.scml2019.common.InsurancePolicy]
- a2f
- 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 againstcontract – hypothetical contract
insured – The
SCML2019Agent
to buy the insurancet – 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:
- class scml.scml2019.InsuranceCompany(*args, **kwargs)[source]
Bases:
negmas.situated.Agent
,abc.ABC
Base class for all insurance companies
- _world: scml.scml2019.world.SCML2019World | None = None
- _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.
- 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.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:
Agents must opt-in to receive these calls by calling
receive_financial_reports
on their AWI
- 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:
Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it.
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
andrespond_to_negotiation_request
callbacks by pulling the bulletin-board using the helper functionis_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
- negotiator_type = 'negmas.sao.AspirationNegotiator'
- profiles: dict[int, MiningProfile]
- n_retrials = 0
- reactive = True
- 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
- 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]
-
- 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.
- 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
- horizon = None
- n_steps = 0
- n_lines = 0
- simulator: scml.scml2019.simulators.FactorySimulator | None = None
- 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]]
- manager_id
- awi
- 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
- add_catalog_prices = True
- strategy = 'latest'
- fields: List[Callable[[scml.scml2019.common.ProductManufacturingInfo], float]]
- producing: Dict[int, List[scml.scml2019.common.ProductManufacturingInfo]]
- 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.
- _n_steps
- _max_storage = None
- _initial_wallet
- _initial_storage
- _profiles
- _n_products
- _reserved_storage
- property initial_storage: numpy.array
Initial inventory
- abstract property n_lines
Number of lines
- 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 tot
.
- 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-stept
.
See also
- 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 tot
.
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 att
.
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 timestept
See also
- 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
See also
- 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 tot
.
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-stept
.
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 tot
.
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-stept
.
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 tot
- 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
- 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
- abstract property fixed_before
Gives the time before which the schedule is fixed.
See also
- 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
- 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
- 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
andline
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
andavailable_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 beforet
.This function is useful for fixing any difference between the simulator and the real state (in conjunction with
set_state
).
See also
- 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 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 beforet
.This function is useful for fixing any difference between the simulator and the real state (in conjunction with
set_state
).
See also
- _factory
- _wallet
- _loans
- _storage
- _line_schedules
- _fixed_before = 0
- _bookmarks: List[_Bookmark] = []
- 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 tot
.
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 tot
.
- 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 tot
- 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
andline
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(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
- property fixed_before
Gives the time before which the schedule is fixed.
See also
- 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 withSlowFactorySimulator
.- _wallet
- _loans
- _storage
- _total_storage
- _profiles = []
- _n_lines
- _line_schedules
- _has_jobs
- _fixed_before = 0
- _bookmarks: List[_FullBookmark] = []
- property fixed_before
Gives the time before which the schedule is fixed.
See also
- property n_lines
Number of lines
- 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 tot
.
- 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 tot
.
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 tot
- 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(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
- 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
andline
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 beforet
.This function is useful for fixing any difference between the simulator and the real state (in conjunction with
set_state
).
See also
- 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=5, n_lines_per_factory=10, guaranteed_contracts=False, use_consumer=True, max_insurance_premium=float('inf'), n_retrials=5, negotiator_type: str = DEFAULT_NEGOTIATOR, transportation_delay=0, default_signing_delay=0, max_storage=sys.maxsize, consumption_horizon=15, consumption=(3, 5), negotiation_speed=21, neg_time_limit=60 * 4, neg_n_steps=20, n_steps=100, time_limit=90 * 90, n_default_per_level: int = 5, compact: bool = False, **kwargs) scml.scml2019.world.SCML2019World [source]
Creates a world compatible with the ANAC 2019 competition. Note that
- Parameters:
n_agents_per_competitor – Number of instantiations of each competing type.
name – SCML2020World name to use
agent_names_reveal_type – If true, a snake_case version of the agent_type will prefix agent names
randomize – If true, managers are assigned to factories randomly otherwise in the order
giving (they are)
n_intermediate
n_default_per_level
competitors – A list of class names for the competitors
params – A list of dictionaries giving parameters to pass to the competitors
n_miners – number of miners of the single raw material
n_factories_per_level – number of factories at every production level
n_consumers – number of consumers of the final product
n_steps – number of simulation steps
n_lines_per_factory – number of lines in each factory
negotiation_speed – The number of negotiation steps per simulation step. None means infinite
default_signing_delay – The number of simulation between contract conclusion and signature
neg_n_steps – The maximum number of steps of a single negotiation (that is double the number of rounds)
neg_time_limit – The total time-limit of a single negotiation
time_limit – The total time-limit of the simulation
transportation_delay – The transportation delay
n_retrials – The number of retrials the
Miner
andGreedyFactoryManager
will try if negotiations failmax_insurance_premium – The maximum insurance premium accepted by
GreedyFactoryManager
(-1 to disable)use_consumer – If true, the
GreedyFactoryManager
will use an internal consumer for buying its needsguaranteed_contracts – If true, the
GreedyFactoryManager
will only sign contracts that it can guaratnee not tobreak.
consumption_horizon – The number of steps for which
Consumer
publishesCFP
sconsumption – The consumption schedule will be sampled from a uniform distribution with these limits inclusive
log_file_name – File name to store the logs
negotiator_type – The negotiation factory used to create all negotiators
max_storage – maximum storage capacity for all factory managers If None then it is unlimited
compact – If True, then compact logs will be created to reduce memory footprint
kwargs – key-value pairs to be passed as argument to chain_world() and then to SCML2019World()
- Returns:
SCML2019World ready to run
Remarks:
Every production level n has one process only that takes n steps to complete
- scml.scml2019.anac2019_tournament(competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]], agent_names_reveal_type=False, n_configs: int = 5, max_worlds_per_config: int = 1000, n_runs_per_world: int = 5, n_agents_per_competitor: int = 5, tournament_path: str = None, total_timeout: int | None = None, parallelism='parallel', scheduler_ip: str | None = None, scheduler_port: str | None = None, tournament_progress_callback: Callable[[negmas.tournaments.WorldRunResults | None], None] = None, world_progress_callback: Callable[[scml.scml2019.world.SCML2019World | None], None] = None, name: str = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) negmas.tournaments.TournamentResults | os.PathLike [source]
The function used to run ANAC 2019 SCML tournament (collusion track).
- Parameters:
name – Tournament name
competitors – A list of class names for the competitors
agent_names_reveal_type – If true then the type of an agent should be readable in its name (most likely at its beginning).
n_configs – The number of different world configs (up to competitor assignment) to be generated.
max_worlds_per_config – The maximum number of worlds to run per config. If None, then all possible assignments of competitors within each config will be tried (all permutations).
n_runs_per_world – Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration.
n_agents_per_competitor – Number of agents per competitor
total_timeout – Total timeout for the complete process
tournament_path – Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs
parallelism – Type of parallelism. Can be ‘serial’ for serial, ‘parallel’ for parallel and ‘distributed’ for distributed
scheduler_port – Port of the dask scheduler if parallelism is dask, dist, or distributed
scheduler_ip – IP Address of the dask scheduler if parallelism is dask, dist, or distributed
world_progress_callback – A function to be called after everystep of every world run (only allowed for serial evaluation and should be used with cautious).
tournament_progress_callback – A function to be called with
WorldRunResults
after each world finished processingverbose – Verbosity
configs_only – If true, a config file for each
compact – If true, effort will be made to reduce memory footprint including disableing most logs
kwargs – Arguments to pass to the
world_generator
function
- Returns:
TournamentResults
The results of the tournament or aPathLike
giving the location where configs were saved
Remarks:
Default parameters will be used in the league with the exception of
parallelism
which may use distributed processing
- scml.scml2019.anac2019_collusion(competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]], competitor_params: Sequence[Dict[str, Any]] | None = None, agent_names_reveal_type=False, n_configs: int = 5, max_worlds_per_config: int | None = 1000, n_runs_per_world: int = 5, n_agents_per_competitor: int = 5, min_factories_per_level: int = 5, tournament_path: str = None, total_timeout: int | None = None, parallelism='parallel', scheduler_ip: str | None = None, scheduler_port: str | None = None, tournament_progress_callback: Callable[[negmas.tournaments.WorldRunResults | None], None] | None = None, world_progress_callback: Callable[[scml.scml2019.world.SCML2019World | None], None] | None = None, non_competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]] | None = None, non_competitor_params: Sequence[Dict[str, Any]] | None = None, name: str | None = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) negmas.tournaments.TournamentResults | os.PathLike [source]
The function used to run ANAC 2019 SCML tournament (collusion track).
- Parameters:
name – Tournament name
competitors – A list of class names for the competitors
competitor_params – A list of competitor parameters (used to initialize the competitors).
agent_names_reveal_type – If true then the type of an agent should be readable in its name (most likely at its beginning).
n_configs – The number of different world configs (up to competitor assignment) to be generated.
max_worlds_per_config – The maximum number of worlds to run per config. If None, then all possible assignments of competitors within each config will be tried (all permutations).
n_runs_per_world – Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration.
n_agents_per_competitor – Number of agents per competitor
min_factories_per_level – Minimum number of factories for each production level
total_timeout – Total timeout for the complete process
tournament_path – Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs
parallelism – Type of parallelism. Can be ‘serial’ for serial, ‘parallel’ for parallel and ‘distributed’ for distributed
scheduler_port – Port of the dask scheduler if parallelism is dask, dist, or distributed
scheduler_ip – IP Address of the dask scheduler if parallelism is dask, dist, or distributed
world_progress_callback – A function to be called after everystep of every world run (only allowed for serial evaluation and should be used with cautious).
tournament_progress_callback – A function to be called with
WorldRunResults
after each world finished processingnon_competitors – A list of agent types that will not be competing in the sabotage competition but will exist in the world
non_competitor_params – parameters of non competitor agents
verbose – Verbosity
configs_only – If true, a config file for each
compact – If true, compact logs will be created and effort will be made to reduce the memory footprint
kwargs – Arguments to pass to the
world_generator
function
- Returns:
TournamentResults
The results of the tournament or aPathLike
giving the location where configs were saved
Remarks:
Default parameters will be used in the league with the exception of
parallelism
which may use distributed processing
- scml.scml2019.anac2019_std(competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]], competitor_params: Sequence[Dict[str, Any]] | None = None, agent_names_reveal_type=False, n_configs: int = 5, max_worlds_per_config: int | None = 1000, n_runs_per_world: int = 5, min_factories_per_level: int = 5, tournament_path: str = None, total_timeout: int | None = None, parallelism='parallel', scheduler_ip: str | None = None, scheduler_port: str | None = None, tournament_progress_callback: Callable[[negmas.tournaments.WorldRunResults | None], None] = None, world_progress_callback: Callable[[scml.scml2019.world.SCML2019World | None], None] = None, non_competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]] | None = None, non_competitor_params: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]] | None = None, name: str = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) negmas.tournaments.TournamentResults | os.PathLike [source]
The function used to run ANAC 2019 SCML tournament (standard track).
- Parameters:
name – Tournament name
competitors – A list of class names for the competitors
competitor_params – A list of competitor parameters (used to initialize the competitors).
agent_names_reveal_type – If true then the type of an agent should be readable in its name (most likely at its beginning).
n_configs – The number of different world configs (up to competitor assignment) to be generated.
max_worlds_per_config – The maximum number of worlds to run per config. If None, then all possible assignments of competitors within each config will be tried (all permutations).
n_runs_per_world – Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration.
min_factories_per_level – Minimum number of factories for each production level
total_timeout – Total timeout for the complete process
tournament_path – Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs
parallelism – Type of parallelism. Can be ‘serial’ for serial, ‘parallel’ for parallel and ‘distributed’ for distributed
scheduler_port – Port of the dask scheduler if parallelism is dask, dist, or distributed
scheduler_ip – IP Address of the dask scheduler if parallelism is dask, dist, or distributed
world_progress_callback – A function to be called after everystep of every world run (only allowed for serial evaluation and should be used with cautious).
tournament_progress_callback – A function to be called with
WorldRunResults
after each world finished processingnon_competitors – A list of agent types that will not be competing in the sabotage competition but will exist in the world
non_competitor_params – parameters of non competitor agents
verbose – Verbosity
configs_only – If true, a config file for each
compact – If true, compact logs will be created and effort will be made to reduce the memory footprint
kwargs – Arguments to pass to the
world_generator
function
- Returns:
TournamentResults
The results of the tournament or aPathLike
giving the location where configs were saved
Remarks:
Default parameters will be used in the league with the exception of
parallelism
which may use distributed processing
- scml.scml2019.balance_calculator(worlds: List[scml.scml2019.world.SCML2019World], scoring_context: Dict[str, Any], dry_run: bool, ignore_default=True) negmas.tournaments.WorldRunResults [source]
A scoring function that scores factory managers’ performance by the final balance only ignoring whatever still in their inventory.
- Parameters:
worlds – The world which is assumed to be run up to the point at which the scores are to be calculated.
scoring_context – A dict of context parameters passed by the world generator or assigner.
dry_run – A boolean specifying whether this is a dry_run. For dry runs, only names and types are expected in the returned
WorldRunResults
- Returns:
WorldRunResults giving the names, scores, and types of factory managers.
- scml.scml2019.anac2019_sabotage(competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]], competitor_params: Sequence[Dict[str, Any]] | None = None, agent_names_reveal_type=False, n_configs: int = 5, max_worlds_per_config: int | None = 1000, n_runs_per_world: int = 5, n_agents_per_competitor: int = 5, min_factories_per_level: int = 5, tournament_path: str | pathlib.Path | None = None, total_timeout: int | None = None, parallelism='parallel', scheduler_ip: str | None = None, scheduler_port: str | None = None, tournament_progress_callback: Callable[[negmas.tournaments.WorldRunResults | None], None] = None, world_progress_callback: Callable[[scml.scml2019.world.SCML2019World | None], None] = None, non_competitors: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]] | None = None, non_competitor_params: Sequence[str | Type[scml.scml2019.factory_managers.builtins.FactoryManager]] | None = None, name: str = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) negmas.tournaments.TournamentResults | os.PathLike [source]
The function used to run ANAC 2019 SCML tournament (collusion track).
- Parameters:
name – Tournament name
competitors – A list of class names for the competitors
competitor_params – A list of competitor parameters (used to initialize the competitors).
agent_names_reveal_type – If true then the type of an agent should be readable in its name (most likely at its beginning).
n_configs – The number of different world configs (up to competitor assignment) to be generated.
max_worlds_per_config – The maximum number of worlds to run per config. If None, then all possible assignments of competitors within each config will be tried (all permutations).
n_runs_per_world – Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration.
n_agents_per_competitor – Number of agents per competitor
min_factories_per_level – Minimum number of factories for each production level
total_timeout – Total timeout for the complete process
tournament_path – Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs
parallelism – Type of parallelism. Can be ‘serial’ for serial, ‘parallel’ for parallel and ‘distributed’ for distributed
scheduler_port – Port of the dask scheduler if parallelism is dask, dist, or distributed
scheduler_ip – IP Address of the dask scheduler if parallelism is dask, dist, or distributed
world_progress_callback – A function to be called after every step of every world run (only allowed for serial evaluation and should be used with cautious).
tournament_progress_callback – A function to be called with
WorldRunResults
after each world finished processingnon_competitors – A list of agent types that will not be competing in the sabotage competition but will exist in the world
non_competitor_params – parameters of non competitor agents
verbose – Verbosity
configs_only – If true, a config file for each
compact – If true, compact logs will be created and effort will be made to reduce the memory footprint
kwargs – Arguments to pass to the
world_generator
function
- Returns:
TournamentResults
The results of the tournament or aPathLike
giving the location where configs were saved
Remarks:
Default parameters will be used in the league with the exception of
parallelism
which may use distributed processing
- class scml.scml2019.DefaultGreedyManager(*args, reserved_value=0.0, negotiator_params=None, optimism=0.0, negotiator_type=DEFAULT_NEGOTIATOR, n_retrials=5, use_consumer=True, reactive=True, sign_only_guaranteed_contracts=False, riskiness=0.0, max_insurance_premium: float = float('inf'), **kwargs)[source]
Bases:
scml.scml2019.factory_managers.builtins.GreedyFactoryManager
The default factory manager that will be implemented by the committee of ANAC-SCML 2019
- class scml.scml2019.SCML2019World(products: Collection[scml.scml2019.common.Product], processes: Collection[scml.scml2019.common.Process], factories: List[scml.scml2019.common.Factory], consumers: List[scml.scml2019.consumers.Consumer], miners: List[scml.scml2019.miners.Miner], factory_managers: List[scml.scml2019.factory_managers.builtins.FactoryManager] | None = None, n_steps=100, time_limit=60 * 90, mechanisms: Dict[str, Dict[str, Any]] | None = None, neg_n_steps=20, neg_time_limit=2 * 60, neg_step_time_limit=60, negotiation_speed=21, no_bank=False, minimum_balance=0, interest_rate=0.1, interest_max=0.3, installment_interest=0.2, interest_time_increment=0.02, balance_at_max_interest=None, loan_installments=1, no_insurance=False, premium=0.03, premium_time_increment=0.03, premium_breach_increment=0.001, max_allowed_breach_level=None, breach_processing=BreachProcessing.VICTIM_THEN_PERPETRATOR, breach_penalty_society=0.1, breach_penalty_society_min=0.0, breach_penalty_victim=0.0, breach_move_max_product=True, initial_wallet_balances: int | None = None, money_resolution=0.5, default_signing_delay=0, transportation_delay: int = 0, transfer_delay: int = 0, start_negotiations_immediately=False, catalog_profit=0.15, avg_process_cost_is_public=True, catalog_prices_are_public=True, strip_annotations=True, financial_reports_period=10, ignore_negotiated_penalties=False, prevent_cfp_tampering=False, default_price_for_products_without_one=1, compensation_fraction=0.5, compact=False, log_folder=None, log_to_file: bool = False, log_to_screen: bool = False, log_file_level=logging.DEBUG, log_screen_level=logging.ERROR, log_file_name: str = 'log.txt', log_ufuns: bool = False, log_negotiations: bool = False, save_mechanism_state_in_contract=False, save_signed_contracts: bool = True, save_cancelled_contracts: bool = True, save_negotiations: bool = True, save_resolved_breaches: bool = True, save_unresolved_breaches: bool = True, ignore_agent_exceptions: bool = False, ignore_contract_execution_exceptions: bool = False, name: str | None = None, **kwargs)[source]
Bases:
negmas.situated.TimeInAgreementMixin
,negmas.situated.World
The
SCML2020World
class running a simulation of supply chain management.- compact = False
- prevent_cfp_tampering = False
- ignore_negotiated_penalties = False
- compensation_fraction = 0.5
- save_mechanism_state_in_contract = False
- default_price_for_products_without_one = 1
- agents: Dict[str, scml.scml2019.agent.SCML2019Agent]
- strip_annotations = True
- minimum_balance = 0
- money_resolution = 0.5
- transportation_delay = 0
- breach_penalty_society = 0.1
- breach_move_max_product = True
- breach_penalty_society_min = 0.0
- penalties = 0.0
- financial_reports_period = 10
- max_allowed_breach_level = None
- catalog_profit = 0.15
- loan_installments = 1
- breach_penalty_victim = 0.0
- avg_process_cost_is_public = True
- catalog_prices_are_public = True
- initial_wallet_balances = None
- products: List[scml.scml2019.common.Product] = []
- processes: List[scml.scml2019.common.Process] = []
- factory_managers: List[scml.scml2019.factory_managers.builtins.FactoryManager] = []
- miners: List[scml.scml2019.miners.Miner] = []
- consumers: List[scml.scml2019.consumers.Consumer] = []
- factories
- _report_receivers: Dict[str, Set[scml.scml2019.agent.SCML2019Agent]]
- f2a: Dict[str, scml.scml2019.agent.SCML2019Agent]
- a2f: Dict[str, scml.scml2019.common.Factory]
- __interested_agents: List[List[scml.scml2019.agent.SCML2019Agent]]
- n_new_cfps = 0
- __n_nullified = 0
- __n_bankrupt = 0
- _transport: Dict[int, List[Tuple[scml.scml2019.agent.SCML2019Agent, int, int]]]
- _transfer: Dict[int, List[Tuple[scml.scml2019.agent.SCML2019Agent, float]]]
- transfer_delay = 0
- _n_production_failures = 0
- bank
- insurance_company
- traders
- join(x: negmas.situated.Agent, simulation_priority: int = 0)[source]
Add an agent to the world.
- Parameters:
x – The agent to be registered
simulation_priority – The simulation priority. Entities with lower priorities will be stepped first during
Returns:
- save_config(file_name: str) None [source]
Saves the config of the world as a yaml file
- Parameters:
file_name – Name of file to save the config to
Returns:
- assign_managers(factory_managers=Iterable[Union[str, Type[FactoryManager], FactoryManager]], params: Iterable[Dict[str, Any]] | None = None) None [source]
Assigns existing factories to new factory managers created from the given types and parameters or manager objects.
- Parameters:
factory_managers – An iterable of
FactoryManager
objects type names orFactoryManager
types to assign toparams – parameters of the newly created managers
Remarks:
factories are assigned in the same order they exist in the local
factories
attribute cycling through the input managers or types/paramsIf a
FactoryManager
object is given instead of a type or a string in thefactory_managers
collection, and the number offactory_managers
is less than the number of factories in the world causing this object to cycle for more than one factory, it is assigned to the first such factory but then deep copies of it with new ids and names are assigned to the rest of the factories. That ensures that each manager has exactly one factory and that all factories are assigned exactly one unique manager.
- classmethod random_small(n_production_levels: int = 1, n_factories: int = 10, factory_kwargs: Dict[str, Any] = None, miner_kwargs: Dict[str, Any] = None, consumer_kwargs: Dict[str, Any] = None, **kwargs)[source]
- classmethod chain_world(n_intermediate_levels=0, n_miners=5, n_factories_per_level=5, n_consumers: int | Tuple[int, int] | List[int] = 5, n_steps=100, n_lines_per_factory=10, n_max_assignable_factories=None, log_file_name: str = None, agent_names_reveal_type: bool = False, negotiator_type: str = DEFAULT_NEGOTIATOR, miner_type: str | Type[scml.scml2019.miners.Miner] = ReactiveMiner, consumer_type: str | Type[scml.scml2019.consumers.Consumer] = JustInTimeConsumer, max_storage: int = sys.maxsize, default_manager_params: Dict[str, Any] = None, miner_kwargs: Dict[str, Any] = None, consumption: int | Tuple[int, int] = (0, 5), consumer_kwargs: Dict[str, Any] = None, negotiation_speed: int | None = 21, manager_types: Sequence[Type[scml.scml2019.factory_managers.builtins.FactoryManager]] = (GreedyFactoryManager,), manager_params: Sequence[Dict[str, Any]] | None = None, n_default_per_level: int = 0, default_factory_manager_type: Type[scml.scml2019.factory_managers.builtins.FactoryManager] = GreedyFactoryManager, randomize: bool = True, initial_wallet_balances=1000, process_cost: float | Tuple[float, float] = (1.0, 5.0), process_time: int | Tuple[int, int] = 1, interest_rate=float('inf'), interest_max=float('inf'), shared_profile_per_factory=False, **kwargs)[source]
Creates a very small world in which only one raw material and one final product. The production graph is a series with
n_intermediate_levels
intermediate levels between the single raw material and single final product- Parameters:
n_max_assignable_factories – The maximum number of factories assigned to managers other than the default
randomize – If true, the factory assignment is randomized
n_default_per_level – The number of
GreedyFactoryManager
objects guaranteed at every leveldefault_factory_manager_type – The
FactoryManager
type to use as the base for default_factory_managers. You can specify how many of this type exist at every level by specifyingn_default_per_level
. Ifn_default_per_level
is zero, this parameter has no effect.manager_types – A sequence of factory manager types to control the factories.
manager_params – An optional sequence of dictionaries giving the parameters to pass to
manager_types
.consumer_type – Consumer type to use for all consumers
miner_type – Miner type to use for all miners
consumption – Consumption schedule
n_intermediate_levels – The number of intermediate products
n_miners – number of miners of the single raw material
n_factories_per_level – number of factories at every production level
n_consumers – number of consumers of the final product
n_steps – number of simulation steps
n_lines_per_factory – number of lines in each factory
process_cost – The range of process costs. A uniform distribution will be used
process_time – The range of process times. A uniform distribution will be used
log_file_name – File name to store the logs
agent_names_reveal_type – If true, agent names will start with a snake_case version of their type name
negotiator_type – The negotiation factory used to create all negotiators
max_storage – maximum storage capacity for all factory managers If None then it is unlimited
default_manager_params – keyword arguments to be used for constructing factory managers
consumer_kwargs – keyword arguments to be used for constructing consumers
miner_kwargs – keyword arguments to be used for constructing miners
negotiation_speed – The number of negotiation steps per simulation step. None means infinite
interest_max – Maximum interest rate
interest_rate – Minimum interest rate
initial_wallet_balances – initial wallet balances for all factories
shared_profile_per_factory – If true, all lines in the same factory will have the same profile costs
kwargs – Any other parameters are just passed to the world constructor
- Returns:
SCML2019World ready to run
Remarks:
Every production level n has one process only that takes n steps to complete
- classmethod random(n_raw_materials: int | Tuple[int, int] = (5, 10), raw_material_price: float | Tuple[float, float] = (1.0, 30.0), n_final_products: int | Tuple[int, int] = (3, 5), n_production_levels: int | Tuple[int, int] = (3, 5), n_products_per_level: int | Tuple[int, int] = (3, 5), n_processes_per_level: int | Tuple[int, int] = (6, 10), n_inputs_per_process: int | Tuple[int, int] = (2, 5), bias_toward_last_level_products: float = 0.0, quantity_per_input: int | Tuple[int, int] = (1, 10), input_step: float | Tuple[float, float] = 0.0, quantity_per_output: int | Tuple[int, int] = (1, 1), output_step: float | Tuple[float, float] = 1.0, process_relative_cost: float | Tuple[float, float] = (0.05, 0.4), n_outputs_per_process: int | Tuple[int, int] = (1, 1), n_lines: int | Tuple[int, int] = (3, 5), lines_are_similar: bool = False, n_processes_per_line: int | Tuple[int, int] = None, cost_for_line: float | Tuple[float, float] = (5.0, 50.0), n_production_steps: int | Tuple[int, int] = (2, 10), max_storage: int | Tuple[int, int] = 2000, n_factories: int | Tuple[int, int] = 20, n_consumers: int | Tuple[int, int] = 5, n_products_per_consumer: int | Tuple[int, int] = None, n_miners: int | Tuple[int, int] = 5, n_products_per_miner: int | Tuple[int, int] | None = None, factory_manager_types: Type[scml.scml2019.factory_managers.builtins.FactoryManager] | List[Type[scml.scml2019.factory_managers.builtins.FactoryManager]] = GreedyFactoryManager, consumer_types: Type[scml.scml2019.consumers.Consumer] | List[Type[scml.scml2019.consumers.Consumer]] = JustInTimeConsumer, miner_types: Type[scml.scml2019.miners.Miner] | List[Type[scml.scml2019.miners.Miner]] = ReactiveMiner, negotiator_type=DEFAULT_NEGOTIATOR, initial_wallet_balance: float | Tuple[float, float] = 1000, factory_kwargs: Dict[str, Any] = None, miner_kwargs: Dict[str, Any] = None, consumer_kwargs: Dict[str, Any] = None, **kwargs)[source]
Creates a random SCML scenario with adjustable parameters.
- Parameters:
n_raw_materials – Number of raw materials. Can be a value or a range.
raw_material_price – Catalog prices for raw materials. Can be a value or a range.
n_final_products – Number of final products. Can be a value or a range.
n_production_levels – How deep is the production graph (number of intermediate products). Can be a value or
range. (miner. Can be a value or a)
n_products_per_level – How many intermediate products per intermediate level. Can be a value or a range.
n_processes_per_level – Number of processes in intermediate levels. Can be a value or a range.
n_inputs_per_process – Number of inputs per process. Can be a value or a range.
bias_toward_last_level_products – How biased are production processes toward using products from the last
them (level below)
quantity_per_input – How many items are needed for each input to a process. Can be a value or a range.
input_step – When are inputs consumed during the production process. Can be a value or a range. Default 0
quantity_per_output – How many items are produced per output. Can be a value or a range.
output_step – When are outputs created during the production process. Can be a value or a range. Default 1
process_relative_cost – Intrinsic relative cost of processes [Outputs will be produced
sum (at a cost of)
n_outputs_per_process – Number of outputs per process. Can be a value or a range.
n_lines – Number of lines per factory. Can be a value or a range.
lines_are_similar – If true then all lins of the same factory will have the same production processes.
n_processes_per_line – Number of processes that can be run on each line per factory. Can be a value or a
range.
cost_for_line – Cost for running a process on a line. Can be a value or a range.
n_production_steps – Number of production steps per line. Can be a value or a range.
max_storage – Maximum storage per factory. Can be a value or a range.
n_factories – Number of factories. Can be a value or a range.
n_consumers – Number of consumers. Can be a value or a range.
n_products_per_consumer – Number of products per miner. If None then all final products will be assigned to
range.
n_miners – Number of miners. Can be a value or a range.
n_products_per_miner – Number of products per miner. If None then all raw materials will be assigned to every
range.
factory_manager_types – A callable for creating factory managers for the factories
consumer_types – A callable for creating
Consumer
objectsminer_types – A callable for creating
Miner
objectsnegotiator_type – A string that can be `eval`uated to a negotiator.
initial_wallet_balance – The initial balance of all wallets
factory_kwargs – keyword arguments to be used for constructing factory managers
consumer_kwargs – keyword arguments to be used for constructing consumers
miner_kwargs – keyword arguments to be used for constructing miners
**kwargs
- Returns:
SCML2019World
The random world generated
Remarks:
Most parameters accept either a single value or a 2-valued tuple. In the later case, it will sample a value within the range specified by the tuple (low, high) inclusive. For example the number of lines (n_lines) follows this pattern
- _update_dynamic_product_process_info()[source]
Updates the catalog prices of all products based on the prices of their inputs
- set_consumers(consumers: List[scml.scml2019.consumers.Consumer])[source]
- set_miners(miners: List[scml.scml2019.miners.Miner])[source]
- set_factory_managers(factory_managers: List[scml.scml2019.factory_managers.builtins.FactoryManager] | None)[source]
- set_processes(processes: Collection[scml.scml2019.common.Process])[source]
- set_products(products: Collection[scml.scml2019.common.Product])[source]
- order_contracts_for_execution(contracts: Collection[negmas.situated.Contract])[source]
Orders the contracts in a specific time-step that are about to be executed
- execute_action(action: negmas.situated.Action, agent: negmas.situated.Agent, callback: Callable[[negmas.situated.Action, bool], Any] = None) bool [source]
Executes the given action by the given agent
- get_private_state(agent: negmas.situated.Agent) scml.scml2019.common.FactoryState [source]
Reads the private state of the given agent
- receive_financial_reports(agent: scml.scml2019.agent.SCML2019Agent, receive: bool, agents: List[str] | None)[source]
Registers interest/disinterest in receiving financial reports
- pre_step_stats()[source]
Called at the beginning of the simulation step to prepare stats or update them
Kept for backward compatibility and will be dropped. Override
update_stats
instead
- start_contract_execution(contract: negmas.situated.Contract) Set[negmas.situated.Breach] [source]
Tries to execute the contract
- Parameters:
contract
- Returns:
The set of breaches committed if any. If there are no breaches return an empty set
- Return type:
Set[Breach]
Remarks:
You must call super() implementation of this method before doing anything
It is possible to return None which indicates that the contract was nullified (i.e. not executed due to a reason other than an execution exeception).
- _move_product(buyer: scml.scml2019.agent.SCML2019Agent, seller: scml.scml2019.agent.SCML2019Agent, product_id: int, quantity: int, money: float)[source]
Moves as much product and money between the buyer and seller
- complete_contract_execution(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach], resolution: negmas.situated.Contract | None)[source]
The resolution can either be None or a contract with the following items:
The issues can be any or all of the following:
immediate_quantity: int immediate_unit_price: float later_quantity: int later_unit_price: int later_penalty: float later_time: int
- _move_product_force(buyer: scml.scml2019.agent.SCML2019Agent, seller: scml.scml2019.agent.SCML2019Agent, product_id: int, quantity: int, money: float)[source]
Moves as much product and money between the buyer and seller
- register_interest(agent: scml.scml2019.agent.SCML2019Agent, products: List[int]) None [source]
- unregister_interest(agent: scml.scml2019.agent.SCML2019Agent, products: List[int]) None [source]
- make_bankrupt(agent: scml.scml2019.agent.SCML2019Agent, amount: float, beneficiary: negmas.situated.Agent, contract: negmas.situated.Contract | None) None [source]
Marks the agent as bankrupt
- evaluate_insurance(contract: negmas.situated.Contract, agent: scml.scml2019.agent.SCML2019Agent, t: int = None) float | None [source]
Can be called to evaluate the premium for insuring the given contract against breachs committed by others
- Parameters:
agent – The agent buying the contract
contract – hypothetical contract
t – time at which the policy is to be bought. If None, it means current step
- buy_insurance(contract: negmas.situated.Contract, agent: scml.scml2019.agent.SCML2019Agent) bool [source]
Buys insurance for the contract by the premium calculated by the insurance company.
- Remarks:
The agent can call
evaluate_insurance
to find the premium that will be used.
- _process_annotation(annotation: Dict[str, Any] | None) Dict[str, Any] | None [source]
Processes an annotation stripping any extra information not allowed if necessary. Will return None if the annotation is suspecious
- run_negotiation(caller: negmas.situated.Agent, issues: Collection[negmas.outcomes.Issue], partners: Collection[negmas.situated.Agent], negotiator: negmas.Negotiator, ufun: negmas.UtilityFunction = None, caller_role: str = None, roles: Collection[str] = None, annotation: Dict[str, Any] | None = None, mechanism_name: str = None, mechanism_params: Dict[str, Any] = None) Tuple[negmas.situated.Contract, negmas.NegotiatorMechanismInterface] | None [source]
Runs a negotiation until completion
- Parameters:
caller – The agent requesting the negotiation
partners – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/
Agent
or as a list containing a single string/Agent
, then he caller will be added at the beginning of the list. This will only be done ifroles
was passed as None.negotiator – The negotiator to be used in the negotiation
preferences – The utility function. Only needed if the negotiator does not already know it
caller_role – The role of the caller in the negotiation
issues – Negotiation issues
annotation – Extra information to be passed to the
partners
when asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles – The roles of different partners. If None then each role for each partner will be None
mechanism_name – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the
None (must also be)
my_role (then roles and)
None
mechanism_params – A dict of parameters used to initialize the mechanism object
- Returns:
A Tuple of a contract and the nmi of the mechanism used to get it in case of success. None otherwise
- run_negotiations(caller: negmas.situated.Agent, issues: List[negmas.outcomes.Issue] | List[List[negmas.outcomes.Issue]], partners: List[List[negmas.situated.Agent]], negotiators: List[negmas.Negotiator], ufuns: List[negmas.UtilityFunction] = None, caller_roles: List[str] = None, roles: List[List[str] | None] | None = None, annotations: List[Dict[str, Any] | None] | None = None, mechanism_names: str | List[str] | None = None, mechanism_params: Dict[str, Any] | List[Dict[str, Any]] | None = None, all_or_none: bool = False) List[Tuple[negmas.situated.Contract, negmas.NegotiatorMechanismInterface]] [source]
Requests to run a set of negotiations simultaneously. Returns after all negotiations are run to completion
- Parameters:
caller – The agent requesting the negotiation
partners – A list of list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners[i] is passed as a single string/
Agent
or as a list containing a single string/Agent
, then he caller will be added at the beginning of the list. This will only be done ifroles
was passed as None.issues – Negotiation issues
negotiators – The negotiator to be used in the negotiation
ufuns – The utility function. Only needed if the negotiator does not already know it
caller_roles – The role of the caller in the negotiation
annotations – Extra information to be passed to the
partners
when asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles – The roles of different partners. If None then each role for each partner will be None
mechanism_names – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the
None (must also be)
my_role (then roles and)
None
mechanism_params – A dict of parameters used to initialize the mechanism object
all_of_none – If True, ALL partners must agree to negotiate to go through.
- Returns:
contract (None for failure) and nmi (The mechanism info [None if the partner refused the negotiation])
- Return type:
A list of tuples each with two values
- request_negotiation_about(req_id: str, caller: negmas.situated.Agent, issues: List[negmas.outcomes.Issue], partners: List[negmas.situated.Agent], roles: List[str] = None, annotation: Dict[str, Any] | None = None, mechanism_name: str = None, mechanism_params: Dict[str, Any] = None, group=None)[source]
Requests to start a negotiation with some other agents
- Parameters:
req_id – An ID For the request that is unique to the caller
caller – The agent requesting the negotiation
partners – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/
Agent
or as a list containing a single string/Agent
, then he caller will be added at the beginning of the list. This will only be done ifroles
was passed as None.issues – Negotiation issues
annotation – Extra information to be passed to the
partners
when asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles – The roles of different partners. If None then each role for each partner will be None
mechanism_name – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the
None (must also be)
my_role (then roles and)
None
mechanism_params – A dict of parameters used to initialize the mechanism object
group – An identifier for the group to which the negotiation belongs. This is not not used by the system.
- Returns:
None. The caller will be informed by a callback function
on_neg_request_accepted
oron_neg_request_rejected
about the status of the negotiation.
- property winners
The winners of this world (factory managers with maximum wallet balance
- on_event(event: negmas.events.Event, sender: negmas.events.EventSource) None [source]
Called whenever an event is raised for which the
SCML2020World
is registered asa listener- Parameters:
event – The event
sender – The sender
- Returns:
None
- contract_record(contract: negmas.situated.Contract) Dict[str, Any] [source]
Converts a contract to a record suitable for permanent storage
- 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.
- profiles: List[ManufacturingProfile] = []
A list of profiles used to initialize the factory
- _commands: numpy.ndarray
The production command currently running
- _line_schedules: numpy.ndarray
- _jobs: Dict[Tuple[int, int], Job]
The jobs waiting to be run on the factory indexed by (time, line) tuples
- _carried_updates: FactoryStatusUpdate
Carried updates from last executed command
- _world: negmas.situated.World = None
- property commands: numpy.ndarray
- property line_schedules: numpy.ndarray
- schedule(job: Job, override=False) None [source]
Schedules the given job at its
time
andline
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