scml ==== .. py:module:: scml Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/scml/__main__/index /autoapi/scml/cli/index /autoapi/scml/cliadv/index /autoapi/scml/common/index /autoapi/scml/experiment/index /autoapi/scml/oneshot/index /autoapi/scml/runner/index /autoapi/scml/scml2019/index /autoapi/scml/scml2020/index /autoapi/scml/std/index /autoapi/scml/utils/index /autoapi/scml/vendor/index Attributes ---------- .. autoapisummary:: scml.__author__ scml.__email__ scml.__version__ scml.__all__ scml.UNIT_PRICE scml.TIME scml.QUANTITY scml.INVALID_STEP scml.NO_PRODUCTION scml.DEFAULT_NEGOTIATOR scml.__all__ scml.SYSTEM_BUYER_ID scml.SYSTEM_SELLER_ID scml.COMPENSATION_ID scml.ANY_STEP scml.NO_COMMAND scml.ANY_LINE scml.INFINITE_COST scml.QUANTITY scml.TIME scml.UNIT_PRICE scml.__all__ scml.QUANTITY scml.UNIT_PRICE scml.TIME scml.INFINITE_COST scml.SYSTEM_BUYER_ID scml.SYSTEM_SELLER_ID scml.DefaultActionManager scml.RLState scml.RLAction scml.RLModel scml.DefaultObservationManager scml.PLACEHOLDER_AGENT_PREFIX scml.__all__ Classes ------- .. autoapisummary:: scml.SCML2019Agent scml.SCMLAWI scml.DefaultBank scml.Bank scml.Product scml.Process scml.InputOutput scml.RunningCommandInfo scml.ManufacturingProfile scml.ManufacturingProfileCompiled scml.ProductManufacturingInfo scml.FactoryStatusUpdate scml.Job scml.ProductionNeed scml.MissingInput scml.ProductionReport scml.ProductionFailure scml.FinancialReport scml.SCMLAgreement scml.SCMLAction scml.CFP scml.Loan scml.InsurancePolicy scml.Factory scml.FactoryState scml.Consumer scml.ConsumptionProfile scml.JustInTimeConsumer scml.FactoryManager scml.DoNothingFactoryManager scml.GreedyFactoryManager scml.DefaultInsuranceCompany scml.InsuranceCompany scml.Miner scml.MiningProfile scml.ReactiveMiner scml.ScheduleInfo scml.Scheduler scml.GreedyScheduler scml.FactorySimulator scml.SlowFactorySimulator scml.FastFactorySimulator scml.DefaultGreedyManager scml.SCML2019World scml.SCML2020Agent scml.OneShotAdapter scml.RandomAgent scml.DoNothingAgent scml.IndependentNegotiationsAgent scml.MarketAwareIndependentNegotiationsAgent scml.BuyCheapSellExpensiveAgent scml.MarketAwareBuyCheapSellExpensiveAgent scml.DecentralizingAgent scml.IndDecentralizingAgent scml.DecentralizingAgentWithLogging scml.MarketAwareDecentralizingAgent scml.MarketAwareIndDecentralizingAgent scml.ReactiveAgent scml.MarketAwareReactiveAgent scml.MovingRangeAgent scml.MarketAwareMovingRangeAgent scml.SatisficerAgent scml.AWI scml.FactoryState scml.FinancialReport scml.FactoryProfile scml.Failure scml.ExogenousContract scml.ProductionStrategy scml.SupplyDrivenProductionStrategy scml.DemandDrivenProductionStrategy scml.TradeDrivenProductionStrategy scml.TradePredictionStrategy scml.FixedTradePredictionStrategy scml.ExecutionRatePredictionStrategy scml.FixedERPStrategy scml.MeanERPStrategy scml.MarketAwareTradePredictionStrategy scml.SignAll scml.SignAllPossible scml.KeepOnlyGoodPrices scml.NegotiationManager scml.StepNegotiationManager scml.IndependentNegotiationsManager scml.MovingRangeNegotiationManager scml.Simulation scml.Factory scml.SCML2020World scml.SCML2021World scml.SCML2022World scml.SCML2023World scml.SCML2024World scml.OneShotAgent scml.OneShotSyncAgent scml.OneShotSingleAgreementAgent scml.OneShotIndNegotiatorsAgent scml.EndingNegotiator scml.SingleAgreementAspirationAgent scml.GreedyOneShotAgent scml.GreedySyncAgent scml.GreedySingleAgreementAgent scml.OneshotDoNothingAgent scml.Placeholder scml.RandomOneShotAgent scml.RandDistOneShotAgent scml.EqualDistOneShotAgent scml.SyncRandomOneShotAgent scml.SingleAgreementRandomAgent scml.OneShotAWI scml.OneShotState scml.OneShotExogenousContract scml.OneShotProfile scml.FinancialReport scml.Context scml.GeneralContext scml.ANACContext scml.LimitedPartnerNumbersContext scml.FixedPartnerNumbersContext scml.ANACOneShotContext scml.LimitedPartnerNumbersOneShotContext scml.FixedPartnerNumbersOneShotContext scml.SupplierContext scml.ConsumerContext scml.StrongSupplierContext scml.StrongConsumerContext scml.WeakSupplierContext scml.WeakConsumerContext scml.BalancedSupplierContext scml.BalancedConsumerContext scml.RepeatingContext scml.ContextParams scml.MonopolicContext scml.SingleAgentPerLevelSupplierContext scml.EutopiaContext scml.EutopiaConsumerContext scml.EutopiaSupplierContext scml.OneShotPolicy scml.ActionManager scml.FlexibleActionManager scml.OneShotRLAgent scml.OneShotEnv scml.ObservationManager scml.FlexibleObservationManager scml.RewardFunction scml.DefaultRewardFunction scml.DefaultOneShotAdapter scml._StdSystemAgent scml.OneShotUFun scml.UFunLimit scml.UtilityInfo scml.SCMLBaseWorld scml.OneShotWorld scml.SCML2020OneShotWorld scml.SCML2021OneShotWorld scml.SCML2022OneShotWorld scml.SCML2023OneShotWorld scml.SCML2024OneShotWorld Functions --------- .. autoapisummary:: scml.builtin_agent_types scml.pos_gauss scml._safe_max scml.zero_runs scml.transaction scml.temporary_transaction scml.anac2019_world scml.anac2019_tournament scml.anac2019_collusion scml.anac2019_std scml.balance_calculator scml.anac2019_sabotage scml.builtin_agent_types scml.is_system_agent scml.builtin_agent_types scml.is_system_agent scml.model_wrapper scml.random_action scml.random_policy scml.greedy_policy Package Contents ---------------- .. py:data:: __author__ :value: 'Yasser Mohammad' .. py:data:: __email__ :value: 'yasserfarouk@gmail.com' .. py:data:: __version__ :value: '0.7.7' .. py:function:: builtin_agent_types(as_str=False) Returns all built-in agents. :param as_str: If true, the full type name will be returned otherwise the type object itself. .. py:data:: __all__ .. py:class:: SCML2019Agent(name: Optional[str] = None, ufun: Optional[negmas.UtilityFunction] = None) Bases: :py:obj:`negmas.situated.Agent` The base for all SCM Agents .. py:attribute:: line_profiles :type: Dict[int, scml.scml2019.common.ManufacturingProfileCompiled] A mapping specifying for each `Line` index, all the profiles used to run it in the factory .. py:attribute:: process_profiles :type: Dict[int, scml.scml2019.common.ManufacturingProfileCompiled] A mapping specifying for each `Process` index, all the profiles used to run it in the factory .. py:attribute:: producing :type: Dict[int, List[scml.scml2019.common.ProductManufacturingInfo]] Mapping from a product to all manufacturing processes that can generate it .. py:attribute:: consuming :type: Dict[int, List[scml.scml2019.common.ProductManufacturingInfo]] Mapping from a product to all manufacturing processes that can consume it .. py:attribute:: compiled_profiles :type: List[scml.scml2019.common.ManufacturingProfileCompiled] :value: [] All the profiles to be used by the factory belonging to this agent compiled to use indices .. py:attribute:: immediate_negotiations :value: False Whether or not negotiations start immediately upon registration (default is to start on the next production step) .. py:attribute:: negotiation_speed_multiple :type: int :value: 1 The number of negotiation rounds (steps) conducted in a single production step .. py:attribute:: transportation_delay :type: int :value: 0 Transportation delay in the system. Default is zero .. py:attribute:: products :type: List[scml.scml2019.common.Product] :value: [] List of products in the system .. py:attribute:: processes :type: List[scml.scml2019.common.Process] :value: [] List of processes in the system .. py:property:: awi :type: 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. .. py:method:: reset() .. py:method:: is_clean() -> bool .. py:method:: init_() The initialization function called by the world directly. It does the following actions by default: 1. copies some of the static world settings to the agent to make them available without calling the AWI. 2. prepares production related properties like producing, consuming, line_profiles, compiled_profiles, etc. 3. registers interest in all products that the agent can produce or consume in its factory. 4. finally it calls any custom initialization logic implemented in `init`() .. seealso:: `init`, `step` .. py:method:: can_expect_agreement(cfp: scml.scml2019.common.CFP, margin: int) Checks if it is possible in principle to get an agreement on this CFP by the time it becomes executable :param margin: :param cfp: Returns: .. py:method:: _create_annotation(cfp: scml.scml2019.common.CFP, partner: str = None) Creates full annotation based on a cfp that the agent is receiving :param cfp: The call for proposal to create annotation about :param 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 .. py:method:: _respond_to_negotiation_request(initiator: str, partners: List[str], issues: List[negmas.outcomes.Issue], annotation: Dict[str, Any], mechanism: negmas.common.NegotiatorMechanismInterface, role: Optional[str], req_id: Optional[str]) -> Optional[negmas.negotiators.Negotiator] Called by the mechanism to ask for joining a negotiation. The agent can refuse by returning a None :param initiator: The ID of the agent that initiated the negotiation request :param partners: The partner list (will include this agent) :param issues: The list of issues :param annotation: Any annotation specific to this negotiation. :param mechanism: The mechanism that started the negotiation :param role: The role of this agent in the negotiation :param 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 .. py:method:: request_negotiation(cfp: scml.scml2019.common.CFP, negotiator: negmas.negotiators.Negotiator = None, ufun: negmas.UtilityFunction = None) -> bool Requests a negotiation from the AWI while keeping track of available negotiation requests :param cfp: :param negotiator: :param ufun: :returns: Whether the negotiation request was successful indicating that the partner accepted the negotiation .. py:method:: on_contract_executed(contract: negmas.situated.Contract) -> None :abstractmethod: Called after successful contract execution for which the agent is one of the partners. .. py:method:: on_contract_breached(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach], resolution: Optional[negmas.situated.Contract]) -> None :abstractmethod: Called after complete processing of a contract that involved a breach. :param contract: The contract :param breaches: All breaches committed (even if they were resolved) :param resolution: The resolution contract if re-negotiation was successful. None if not. .. py:method:: confirm_loan(loan: scml.scml2019.common.Loan, bankrupt_if_rejected: bool) -> bool :abstractmethod: called by the world manager to confirm a loan if needed by the buyer of a contract that is about to be breached .. py:method:: on_contract_nullified(contract: negmas.situated.Contract, bankrupt_partner: str, compensation: float) -> None :abstractmethod: Will be called whenever a contract the agent is involved in is nullified because another partner went bankrupt .. py:method:: on_agent_bankrupt(agent_id: str) -> None :abstractmethod: Will be called whenever any agent goes bankrupt :param agent_id: The ID of the agent that went bankrupt Remarks: - Agents can go bankrupt in two cases: 1. Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it. 2. Failing to pay a penalty on a sell contract they failed to honor (and refusing or being unable to get a loan to pay for it). - All built-in agents ignore this call and they use the bankruptcy list ONLY to decide whether or not to negotiate in their `on_new_cfp` and `respond_to_negotiation_request` callbacks by pulling the bulletin-board using the helper function `is_bankrupt` of their AWI. .. py:method:: confirm_partial_execution(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach]) -> bool :abstractmethod: Will be called whenever a contract cannot be fully executed due to breaches by the other partner. :param contract: The contract that was breached :param breaches: A list of all the breaches committed. Remarks: - Will not be called if both partners committed breaches. .. py:method:: confirm_contract_execution(contract: negmas.situated.Contract) -> bool :abstractmethod: Called before executing any agreement .. py:method:: respond_to_negotiation_request(cfp: scml.scml2019.common.CFP, partner: str) -> Optional[negmas.negotiators.Negotiator] :abstractmethod: Called when a prospective partner requests a negotiation to start .. py:method:: on_new_cfp(cfp: scml.scml2019.common.CFP) :abstractmethod: Called when a new CFP for a product for which the agent registered interest is published .. py:method:: on_remove_cfp(cfp: scml.scml2019.common.CFP) :abstractmethod: Called when a new CFP for a product for which the agent registered interest is removed .. py:method:: on_new_report(report: scml.scml2019.common.FinancialReport) :abstractmethod: Called whenever a financial report is published. :param 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 .. py:method:: on_inventory_change(product: int, quantity: int, cause: str) -> None :abstractmethod: Received whenever something moves in or out of the factory's storage :param product: Product index. :param quantity: Negative value for products moving out and positive value for products moving in :param 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). .. py:method:: on_cash_transfer(amount: float, cause: str) -> None :abstractmethod: Received whenever money is transferred to the factory or from it. :param amount: Amount of money (negative for transfers out of the factory, positive for transfers to it). :param 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). .. py:class:: SCMLAWI(world: negmas.situated.world.World, agent: negmas.situated.agent.Agent) Bases: :py:obj:`negmas.situated.AgentWorldInterface` A single contact point between SCML agents and the world simulation. The agent can access the world simulation in one of two ways: 1. Attributes and methods available in this Agent-SCML2020World-Interface 2. Attributes and methods in the `FactoryManager` object itself which provide handy shortcuts to the agent-world interface **Attributes** *Simulation settings* - `current_step` : Current simulation step - `default_signing_delay` : The grace period allowed between contract conclusion and signature by default (i.e. if not agreed upon during the negotiation) - `n_steps` : Total number of simulation steps. - `relative_time` : The fraction of total simulation time elapsed (it will be a number between 0 and 1) *Production Graph* - `products` : A list of `Product` objects giving all products defined in the world simulation - `processes` : A list of `Process` objects giving all products defined in the world simulation *Agent Related* - `state` : The current private state available to the agent. In SCML it is a `FactoryState` object. **Methods** *Production Control* - `schedule_job` : Schedules a `Job` for production sometime in the future - `schedule_production` : Schedules production using profile number instead of a `Job` object - `cancel_production` : Cancels already scheduled production (if it did not start yet) or stop a running production. - `execute` : A general function to execute any command on the factory. There is no need to directly call this function as the SCMLAWI provides convenient functions (e.g. `schedule_job` , `hide_funds` , etc) to achieve the same goal without having to worry about creating `Action` objects *Storage and Wallet Control* - `hide_funds` : Hides funds from the view of the simulator. Note that when bankruptcy is considered, hidden funds are visible to the simulator. - `hide_inventory` : Hides inventory from the view of the simulator. Note that when bankruptcy is considered, hidden funds are visible to the simulator. - `unhide_funds` : Un-hides funds hidden earlier with a call to `hide_funds` - `unhide_inventory` : Un-hides inventory hidden earlier with a call to `hide_inventory` *Negotiation and CFP Control* - `register_cfp` : Registers a Call-for-Proposals on the bulletin board. - `remove_cfp` : Removes a Call-for-Proposals from the bulletin board. - `request_negotiation` : Requests a negotiation based on the content of a CFP published on the bulletin-board. *It is recommended not to use this method directly and to request negotiations using the request_negotiation method of `FactoryManager` (i.e. use self.request_negotiation instead of self.awi.request_negotiation). This makes it possible for NegMAS to keep track of existing `requested_negotiations` and `running_negotiations` for you. *Notification Control* - `receive_financial_reports` : Register/unregisters interest in receiving financial reports for an agent, a set of agents or all agents. - `register_interest` : registers interest in receiving CFPs about a set of products. By default all `FactoryManager` objects are registered to receive all CFPs for any product they can produce or need to consumer according to their line-profiles. - `unregister_interest` : unregisters interest in receiving CFPs about a set of products. *Information about Other Agents* - `is_bankrupt` : Asks about the bankruptcy status of an agent - `receive_financial_reports` : Register/unregisters interest in receiving financial reports for an agent, a set of agents or all agents. - `reports_at` : reads *all* financial reports produced at a given time-step - `reports_for` : reads *all* financial reports of a given agent *Financial Control* - `evaluate_insurance` : Asks for the premium to be paid for insuring against partner breaches for a given contract - `buy_insurance` : Buys an insurance against partner breaches for a given contract *Bulletin-Board* The bulletin-board is a key-value store. These methods allows the agent to interact with it. *The `SCMLAWI` provides convenient functions for recording to the bulletin-board so you mostly need to use read/query functions*. - `bb_read` : Reads a complete section or a single value from the bulletin-board - `bb_query` : Returns all records in the given section/sections of the bulletin-board that satisfy a query - `bb_record` : Registers a record in the bulletin-board. - `bb_remove` : Removes a record from the bulletin-board. The following list of sections are available in the SCML Bulletin-Board (Use the exact string for the ``section`` parameter of any method starting with ``bb_``): - **cfps**: All CFPs currently on the board. The key is the CFP ID - **products**: A list of all products. The key is the product index/ID - **processes**: A list of all processes. The key is the product index/ID - **bankruptcy**: The bankruptcy list giving names of all bankrupt agents. - **reports_time**: Financial reports indexed by time. - **reports_agent**: Financial reports indexed by agent - **breaches**: Breach-list indexed by breach ID giving all breaches committed in the system - **settings**: Static settings of the simulation. The following settings are currently available: - *breach_penalty_society*: Penalty of breaches paid to society (as a fraction of contract value). This is always paid for every breach whether or not there is a negotiated breach. - *breach_penalty_victim*: Penalty of breaches paid to victim (as a fraction of contract value). This is always paid for every breach whether or not there is a negotiated breach. - *immediate_negotiations*: Whether negotiations start immediately when registered (the other possibility -- which is the default -- is for them to start at the next production step). - *negotiation_speed_multiple*: Number of negotiation steps that finish in a single production step. - *negotiation_n_steps*: Maximum allowed number of steps (rounds) in any negotiation - *negotiation_step_time_limit*: The maximum real-time allowed for each negotiation step (round) - *negotiation_time_limit*: The time limit for a complete negotiation. - *transportation_delay*: Transportation delay when products are moved between factories. Default is zero. - *transfer_delay*: The delay in transferring funds between factories when executing a contract. Default is zero. - *n_steps*: Number of simulation steps - *time_limit*: Time limit for the complete simulation - stats: Global statistics about the simulation. **Not available for SCML 2019 league**. *Logging* - `logerror` : Logs an error in the world simulation log file - `logwarning` : Logs a warning in the world simulation log file - `loginfo` : Logs information in the world simulation log file - `logdebug` : Logs debug information in the world simulation log file .. py:method:: register_cfp(cfp: scml.scml2019.common.CFP) -> None Registers a CFP .. py:method:: register_interest(products: List[int]) -> None registers interest in receiving callbacks about CFPs related to these products .. py:method:: unregister_interest(products: List[int]) -> None registers interest in receiving callbacks about CFPs related to these products .. py:method:: remove_cfp(cfp: scml.scml2019.common.CFP) -> bool Removes a CFP .. py:method:: evaluate_insurance(contract: negmas.situated.Contract, t: int = None) -> Optional[float] Can be called to evaluate the premium for insuring the given contract against breaches committed by others :param contract: hypothetical contract :param t: time at which the policy is to be bought. If None, it means current step .. py:method:: buy_insurance(contract: negmas.situated.Contract) -> bool 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. .. py:method:: _create_annotation(cfp: scml.scml2019.common.CFP, partner: str = None) Creates full annotation based on a cfp that the agent is receiving .. py:method:: 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 Requests a negotiation with the publisher of a given CFP :param cfp: The CFP to negotiate about :param req_id: A string that is passed back to the caller in all callbacks related to this negotiation :param roles: The roles of the CFP publisher and the agent (in that order). By default no roles are passed (None) :param mechanism_name: The mechanism type to use. If not given the default mechanism from the world will be used :param mechanism_params: Parameters of the mechanism :returns: Success of failure of the negotiation request Remarks: - The `SCML2019Agent` class implements another request_negotiation method that does not receive a `req_id`. This helper method is recommended as it generates the required req_id and passes it keeping track of requested negotiations (and later of running negotiations). Call this method direclty *only* if you do not intend to use the `requested_negotiations` and `running_negotiations` properties of the `SCML2019Agent` class .. py:method:: request_negotiation_about(issues: List[negmas.Issue], partners: List[str], req_id: str, roles: List[str] = None, annotation: Optional[Dict[str, Any]] = None, mechanism_name: str = None, mechanism_params: Dict[str, Any] = None) Overrides the method of the same name in the base class to disable it in SCM Worlds. **Do not call this method** .. py:method:: is_bankrupt(agent_id: str) -> bool Checks whether the given agent is bankrupt :param agent_id: Agent ID :returns: The bankruptcy state of the agent .. py:method:: reports_for(agent_id: str) -> List[scml.scml2019.common.FinancialReport] Gets all financial reports of an agent (in the order of their publication) :param agent_id: Agent ID Returns: .. py:method:: reports_at(step: int = None) -> Dict[str, scml.scml2019.common.FinancialReport] Gets all financial reports of all agents at a given step :param 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 .. py:method:: receive_financial_reports(receive: bool = True, agents: Optional[List[str]] = None) -> None Registers/unregisters interest in receiving financial reports :param receive: True to receive and False to stop receiving :param 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. .. py:property:: state :type: 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**. .. py:property:: products :type: List[scml.scml2019.common.Product] Products in the world .. py:property:: processes :type: List[scml.scml2019.common.Process] Processes in the world .. py:method:: schedule_production(profile: int, step: int, contract: Optional[negmas.situated.Contract] = None, override: bool = True) -> None Schedules production on the agent's factory :param profile: Index of the profile in the agent's `compiled_profiles` list :param step: The step to start production according to the given profile :param contract: The contract for which the production is scheduled (optional) :param override: Whether to override existing production jobs schedules at the same time. .. py:method:: stop_production(line: int, step: int, contract: Optional[negmas.situated.Contract], override: bool = True) Stops/cancels production scheduled at the given line at the given time. :param line: One of the factory lines (index) :param step: Step to stop/cancel production at :param contract: The contract for which the job is scheduled (optional) :param override: Whether to override existing production jobs schedules at the same time. .. py:attribute:: cancel_production Stops/cancels production scheduled at the given line at the given time. :param line: One of the factory lines (index) :param step: Step to stop/cancel production at .. py:method:: schedule_job(job: scml.scml2019.common.Job, contract: Optional[negmas.situated.Contract]) Schedules production using a `Job` object. This can be used to schedule any kind of job :param job: The job description :param 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. .. py:method:: hide_inventory(product: int, quantity: int) -> None Hides the given quantity of the given product so that it is not accessible by the simulator and does not appear in reports etc. :param product: product index :param 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 .. py:method:: hide_funds(amount: float) -> None Hides the given amount of money so that it is not accessible by the simulator and does not appear in reports etc. :param 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 .. py:method:: unhide_inventory(product: int, quantity: int) -> None 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. :param product: product index :param 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 .. py:method:: unhide_funds(amount: float) -> None Un-hides the given amount of money so that it is not accessible by the simulator and does not appear in reports etc. :param 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 .. py:class:: 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) Bases: :py:obj:`Bank` Represents a bank in the world .. py:method:: init() Called to initialize the agent **after** the world is initialized. the AWI is accessible at this point. .. py:method:: respond_to_negotiation_request(initiator: str, partners: list[str], issues: list[negmas.Issue], annotation: dict[str, Any], mechanism: negmas.Mechanism, role: Optional[str], req_id: str) -> Optional[negmas.Negotiator] .. py:attribute:: storage :type: dict[int, int] .. py:attribute:: wallet :type: float :value: 0.0 .. py:attribute:: disabled :value: False .. py:attribute:: loans :type: dict[scml.scml2019.agent.SCML2019Agent, list[scml.scml2019.common.Loan]] .. py:attribute:: minimum_balance .. py:attribute:: interest_rate .. py:attribute:: interest_max .. py:attribute:: installment_interest .. py:attribute:: time_increment .. py:attribute:: balance_at_max_interest .. py:attribute:: _credit_rating :type: dict[str, float] .. py:attribute:: a2f .. py:method:: set_renegotiation_agenda(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach]) -> Optional[negmas.situated.RenegotiationRequest] Received by partners in ascending order of their total breach levels in order to set the renegotiation agenda when contract execution fails :param contract: The contract being breached :param breaches: All breaches on `contract` :returns: Renegotiation agenda (issues to negotiate about to avoid reporting the breaches). .. py:method:: respond_to_renegotiation_request(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach], agenda: negmas.situated.RenegotiationRequest) -> Optional[negmas.Negotiator] Called to respond to a renegotiation request :param agenda: :param contract: :param breaches: Returns: .. py:method:: _evaluate_loan(agent: scml.scml2019.agent.SCML2019Agent, amount: float, n_installments: int, starts_at: int, installment_loan=False) -> Optional[scml.scml2019.common.Loan] Evaluates the interest that will be imposed on the agent to buy_loan that amount .. py:method:: evaluate_loan(agent: scml.scml2019.agent.SCML2019Agent, amount: float, start_at: int, n_installments: int) -> Optional[scml.scml2019.common.Loan] Evaluates the interest that will be imposed on the agent to buy_loan that amount .. py:method:: _buy_loan(agent: scml.scml2019.agent.SCML2019Agent, loan: scml.scml2019.common.Loan, beneficiary: negmas.situated.Agent, contract: Optional[negmas.situated.Contract], bankrupt_if_rejected=False) -> Optional[scml.scml2019.common.Loan] .. py:method:: buy_loan(agent: scml.scml2019.agent.SCML2019Agent, amount: float, n_installments: int, beneficiary: negmas.situated.Agent, contract: Optional[negmas.situated.Contract], force: bool = False) -> Optional[scml.scml2019.common.Loan] Gives a loan of amount to agent at the interest calculated using `evaluate_loan` .. py:method:: step() Takes payments from agents .. py:method:: _reduce_credit_rating(agent: negmas.situated.Agent, unavailable: float) Updates the credit rating when the agent fails to pay an installment .. py:method:: credit_rating(agent_id: str) -> float .. py:class:: Bank(*args, **kwargs) Bases: :py:obj:`negmas.situated.Agent`, :py:obj:`abc.ABC` Base class for all banks .. py:attribute:: _world :value: None .. py:method:: _respond_to_negotiation_request(initiator: str, partners: list[str], issues: list[negmas.Issue], annotation: dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, role: Optional[str], req_id: Optional[str]) -> Optional[negmas.Negotiator] Called by the mechanism to ask for joining a negotiation. The agent can refuse by returning a None :param initiator: The ID of the agent that initiated the negotiation request :param partners: The partner list (will include this agent) :param issues: The list of issues :param annotation: Any annotation specific to this negotiation. :param mechanism: The mechanism that started the negotiation :param role: The role of this agent in the negotiation :param 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 .. py:method:: on_neg_request_rejected(req_id: str, by: Optional[list[str]]) Called when a requested negotiation is rejected :param req_id: The request ID passed to _request_negotiation :param by: A list of agents that refused to participate or None if the failure was for another reason .. py:method:: on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface) Called when a requested negotiation is accepted .. py:method:: on_negotiation_failure(partners: list[str], annotation: dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, state: negmas.MechanismState) -> None Called whenever a negotiation ends without agreement .. py:method:: on_negotiation_success(contract: negmas.situated.Contract, mechanism: negmas.NegotiatorMechanismInterface) -> None Called whenever a negotiation ends with agreement .. py:method:: on_contract_signed(contract: negmas.situated.Contract) -> None Called whenever a contract is signed by all partners .. py:method:: on_contract_cancelled(contract: negmas.situated.Contract, rejectors: list[str]) -> None Called whenever at least a partner did not sign the contract .. py:method:: sign_contract(contract: negmas.situated.Contract) -> Optional[str] Called after the signing delay from contract conclusion to sign the contract. Contracts become binding only after they are signed. .. py:method:: respond_to_negotiation_request(initiator: str, partners: list[str], issues: list[negmas.Issue], annotation: dict[str, Any], mechanism: negmas.Mechanism, role: Optional[str], req_id: str) -> Optional[negmas.Negotiator] .. py:method:: on_contract_executed(contract: negmas.situated.Contract) -> None Called after successful contract execution for which the agent is one of the partners. .. py:method:: on_contract_breached(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach], resolution: Optional[negmas.situated.Contract]) -> None Called after complete processing of a contract that involved a breach. :param contract: The contract :param breaches: All breaches committed (even if they were resolved) :param resolution: The resolution contract if re-negotiation was successful. None if not. .. py:data:: UNIT_PRICE :value: 2 Index of unit price in negotiation issues .. py:data:: TIME :value: 1 Index of time in negotiation issues .. py:data:: QUANTITY :value: 0 Index of quantity in negotiation issues .. py:class:: Product .. py:attribute:: __slots__ :value: ['id', 'production_level', 'name', 'expires_in', 'catalog_price'] A product that can be transacted in. .. py:attribute:: id :type: int Product index. Must be set during construction and **MUST** be unique for products in the same world .. py:attribute:: production_level :type: int The level of this product in the production graph. .. py:attribute:: name :type: str Object name .. py:attribute:: expires_in :type: Optional[int] Number of steps within which the product must be consumed. None means never .. py:attribute:: catalog_price :type: Optional[float] Catalog price of the product. .. py:method:: __str__() String representation is simply the name .. py:method:: __post_init__() .. py:method:: __hash__() .. py:class:: Process .. py:attribute:: __slots__ :value: ['id', 'production_level', 'name', 'inputs', 'outputs', 'historical_cost'] .. py:attribute:: id :type: int A manufacturing process. .. py:attribute:: production_level :type: int The level of this process in the production graph .. py:attribute:: name :type: str Object name .. py:attribute:: inputs :type: 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) .. py:attribute:: outputs :type: 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) .. py:attribute:: historical_cost :type: Optional[float] Average cost for running this process in some world. Filled by the world .. py:method:: __str__() String representation is simply the name .. py:method:: __post_init__() .. py:method:: __hash__() The hash depends only on the name .. py:class:: InputOutput An input/output to a production process .. py:attribute:: __slots__ :value: ['product', 'quantity', 'step'] .. py:attribute:: product :type: int Index of the product used as input or output .. py:attribute:: quantity :type: int Quantity needed/produced .. py:attribute:: step :type: float Relative time within the production at which the input is needed (output is produced) .. py:class:: RunningCommandInfo .. py:attribute:: __slots__ :value: ['profile', 'beg', 'end', 'action', 'updates', 'step', 'paused'] .. py:attribute:: profile :type: ManufacturingProfile The manufacturing profile associated with this command. Most importantly, it gives the process and line .. py:attribute:: beg :type: int The time the command is to be executed .. py:attribute:: end :type: int The number of steps starting at `beg` for this command to end (it ends at end - 1) .. py:attribute:: step :type: int The time-step relative to `beg` at the factory is currently executing the `Process` indicated in `profile`. `step` will always go up by one every simulation step except if the command is paused where it does not change .. py:attribute:: paused :type: bool True if the command is paused .. py:attribute:: action :type: str The command type. For the current implementation it will always be run or none for no command .. py:attribute:: updates :type: Dict[int, FactoryStatusUpdate] The status updates implied by this command with their times relative to `beg` .. py:property:: n_steps :type: int .. py:method:: ended_before(t: int) .. py:method:: started_on_or_after(t: int) .. py:method:: __str__() .. py:property:: is_none .. py:method:: do_nothing() :classmethod: .. py:data:: INVALID_STEP :value: -1000 .. py:data:: NO_PRODUCTION :value: -1 .. py:class:: ManufacturingProfile The costs/time required for running a process on a line (with associated cancellation costs etc). This data-structure carries full information about the `Process` es instead of just its index as in `ManufacturingProfileCompiled`. It is intended to be used to construct factories .. seealso:: `Factory` .. py:attribute:: __slots__ :value: ['n_steps', 'cost', 'initial_pause_cost', 'running_pause_cost', 'resumption_cost',... .. py:attribute:: n_steps :type: int Number of steps needed to complete the manufacturing .. py:attribute:: cost :type: float Cost of manufacturing .. py:attribute:: initial_pause_cost :type: float Cost of pausing incurred only at the step a pause is started .. py:attribute:: running_pause_cost :type: float Running cost of pausing .. py:attribute:: resumption_cost :type: float Cost of resuming a process .. py:attribute:: cancellation_cost :type: float Cost of cancelling the process before the last step .. py:attribute:: line :type: int The line index .. py:attribute:: process :type: Process The `Process` associated with this profile .. py:class:: ManufacturingProfileCompiled The costs/time required for running a process on a line (with associated cancellation costs etc). .. seealso:: `Factory` .. py:attribute:: __slots__ :value: ['n_steps', 'cost', 'initial_pause_cost', 'running_pause_cost', 'resumption_cost',... .. py:attribute:: n_steps :type: int Number of steps needed to complete the manufacturing .. py:attribute:: cost :type: float Cost of manufacturing .. py:attribute:: initial_pause_cost :type: float Cost of pausing incurred only at the step a pause is started .. py:attribute:: running_pause_cost :type: float Running cost of pausing .. py:attribute:: resumption_cost :type: float Cost of resuming a process .. py:attribute:: cancellation_cost :type: float Cost of cancelling the process before the last step .. py:attribute:: line :type: int The line index .. py:attribute:: process :type: int The `Process` index .. py:method:: from_manufacturing_profile(profile: ManufacturingProfile, process2ind: Dict[Process, int]) :classmethod: .. py:class:: ProductManufacturingInfo Gives full information about a manufacturing process that can generate or consume a product. .. seealso:: `consuming` and `producing` of `Factory` .. py:attribute:: __slots__ :value: ['profile', 'quantity', 'step'] .. py:attribute:: profile :type: int The `ManufacturingProfile` index .. py:attribute:: quantity :type: int The quantity generated/consumed by running this manufacturing info .. py:attribute:: step :type: int The step from the beginning at which the `Product` is received/consumed .. py:class:: FactoryStatusUpdate .. py:attribute:: __slots__ :value: ['balance', 'storage'] .. py:attribute:: balance :type: float The update to the balance .. py:attribute:: storage :type: Dict[int, int] The updates to be applied to the storage after this step .. py:method:: __post_init__() .. py:method:: make_empty() -> None Makes the update an empty one. .. py:method:: combine(other: FactoryStatusUpdate) -> None Combines this status update with another one in place :param other: The other status update :returns: None .. py:method:: combine_sets(dst: Dict[int, FactoryStatusUpdate], src: Dict[int, FactoryStatusUpdate]) :classmethod: Combines a set of updates over time with another in place (overriding `first`) :param dst: First set of updates to be combined into :param src: second set of updates to be combined from Returns: .. py:property:: is_empty .. py:method:: empty() :classmethod: .. py:method:: __str__() .. py:class:: Job Describes a job to be run on one production line of a `Factory`. .. py:attribute:: __slots__ :value: ['profile', 'time', 'line', 'action', 'contract', 'override'] .. py:attribute:: profile :type: int The process for run commands .. py:attribute:: time :type: int The time the command is to be executed .. py:attribute:: line :type: int Index of the line on which the job is to be scheduled. Notice that it will be ignored for `run` actions. .. py:attribute:: action :type: str The command type. For the current implementation it can be run/pause/resume/stop/cancel with `cancel` cancelling any other command type. .. py:attribute:: contract :type: Optional[negmas.situated.Contract] The sell contract associated with the command .. py:attribute:: override :type: bool Whether to override existing commands when the job is to be executed. .. py:method:: __str__() .. py:method:: is_cancelling(job: Job) -> bool Determines if the given jobs cancels this one :param job: Returns: .. py:class:: ProductionNeed Describes some quantity of a product that is needed to honor a (sell) contract. .. py:attribute:: __slots__ :value: ['product', 'needed_for', 'quantity_to_buy', 'quantity_in_storage', 'step'] .. py:attribute:: product :type: int The product needed .. py:attribute:: needed_for :type: negmas.situated.Contract The contract for which the product is needed .. py:attribute:: quantity_to_buy :type: int The quantity need to be bought .. py:attribute:: quantity_in_storage :type: int The quantity already found in storage .. py:attribute:: step :type: int The time step at which the product is needed .. py:method:: __str__() String representation is simply the name .. py:class:: MissingInput .. py:attribute:: __slots__ :value: ['product', 'quantity'] .. py:attribute:: product :type: int .. py:attribute:: quantity :type: int .. py:method:: __str__() .. py:class:: ProductionReport .. py:attribute:: line :type: int ID of the line .. py:attribute:: started :type: Optional[RunningCommandInfo] Commands started .. py:attribute:: continuing :type: Optional[RunningCommandInfo] Command that is continuing .. py:attribute:: finished :type: Optional[RunningCommandInfo] Command finished .. py:attribute:: failure :type: Optional[ProductionFailure] Failures .. py:attribute:: updates :type: FactoryStatusUpdate Updates applied to the factory .. py:property:: failed .. py:property:: is_empty .. py:property:: no_production .. py:method:: __str__() .. py:class:: ProductionFailure .. py:attribute:: __slots__ :value: ['line', 'command', 'missing_inputs', 'missing_money', 'missing_space'] .. py:attribute:: line :type: int ID of the line that failed .. py:attribute:: command :type: RunningCommandInfo Information about the command that failed .. py:attribute:: missing_inputs :type: List[MissingInput] The missing inputs if any with their quantities .. py:attribute:: missing_money :type: float The amount of money needed for production that is not available .. py:attribute:: missing_space :type: int The amount space needed in storage but not found .. py:method:: __str__() .. py:class:: FinancialReport Reports that financial standing of an agent at a given time in the simulation .. py:attribute:: agent :type: str Agent ID .. py:attribute:: step :type: int Time of the report .. py:attribute:: cash :type: float Cash at hand .. py:attribute:: liabilities :type: float Total liabilities (loans) .. py:attribute:: inventory :type: float Value of everything in the inventory priced at catalog prices. .. py:attribute:: credit_rating :type: float The agent's credit rating as a fraction of the maximum credit rating (1 indicates highest credit rating). .. py: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. .. py:class:: SCMLAgreement .. py:attribute:: time :type: int delivery time .. py:attribute:: unit_price :type: float unit price .. py:attribute:: quantity :type: int quantity .. py:attribute:: penalty :type: Optional[float] :value: None penalty .. py:attribute:: signing_delay :type: int :value: -1 Delay between agreement conclusion and signing it to be binding .. py:method:: __getitem__(k) .. py:method:: get(k, default=None) .. py:method:: asdict() .. py:method:: to_dict() .. py:method:: keys() .. py:method:: values() .. py:method:: items() .. py:class:: SCMLAction .. py:attribute:: line :type: str Line to execute the action on (need not be given if the profile is given .. py:attribute:: profile :type: Optional[int] Index of the profile to execute .. py:attribute:: action :type: str The action which may be start, stop, pause, resume .. py:attribute:: time :type: int :value: 0 Time to execute the action at .. py:class:: CFP A Call for proposal upon which a negotiation can start .. py:attribute:: is_buy :type: bool If true, the author wants to buy otherwise to sell. Non-negotiable. .. py:attribute:: publisher :type: str the publisher name. Non-negotiable. .. py:attribute:: product :type: int product ID. Non-negotiable. .. py:attribute:: time :type: Union[int, Tuple[int, int], List[int]] delivery time. May be negotiable. .. py:attribute:: unit_price :type: Union[float, Tuple[float, float], List[float]] unit price. May be negotiable. .. py:attribute:: quantity :type: Union[int, Tuple[int, int], List[int]] quantity. May be negotiable. .. py:attribute:: penalty :type: Optional[Union[float, Tuple[float, float], List[float]]] :value: None penalty per missing item in case the seller cannot provide the required quantity. May be negotiable. .. py:attribute:: signing_delay :type: Optional[Union[int, Tuple[int, int], List[int]]] :value: None The grace period after which the agents are asked to confirm signing the contract .. py:attribute:: money_resolution :type: Optional[float] :value: None If not None then it is the minimum unit of money (e.g. 1 for dollar, 0.01 for cent, etc) .. py:attribute:: id :type: str :value: '' Unique CFP ID .. py:method:: __str__() .. py:method:: satisfies(query: Dict[str, Any]) -> bool Tests whether the CFP satisfies the conditions set by the query :param 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 .. py:property:: issues Returns the set of issues associated with this CFP. Notice that some of the issues may have a single value .. py:property:: outcomes .. py:property:: min_time .. py:property:: max_time .. py:property:: min_quantity .. py:property:: max_quantity .. py:property:: min_unit_price .. py:property:: max_unit_price .. py:property:: min_signing_delay .. py:property:: max_signing_delay .. py:property:: min_penalty .. py:property:: max_penalty .. py:method:: to_dict() .. py:method:: from_dict(idict: Dict[str, Any], class_name: Optional[str] = None) -> CFP :classmethod: .. py:class:: Loan .. py:attribute:: amount :type: float Loan amount .. py:attribute:: starts_at :type: int The time-step at which payment starts .. py:attribute:: total :type: float The total to be paid including the amount + interests .. py:attribute:: interest :type: float The interest rate per step .. py:attribute:: installment :type: float The amount to be paid in one installment .. py:attribute:: n_installments :type: int The number of installments .. py:method:: __str__() .. py:class:: InsurancePolicy .. py:attribute:: premium :type: float .. py:attribute:: contract :type: negmas.situated.Contract .. py:attribute:: at_time :type: int .. py:attribute:: against :type: scml.scml2019.agent.SCML2019Agent .. py:class:: Factory Represents a factory within an SCML world. It is only accessed by the SCML2020World so it need not be made public. .. py:attribute:: initial_storage :type: dataclasses.InitVar[Dict[int, int]] Initial storage .. py:attribute:: initial_wallet :type: dataclasses.InitVar[float] :value: 0.0 Initial Wallet .. py:attribute:: id :type: str :value: '' Object name .. py:attribute:: profiles :type: List[ManufacturingProfile] :value: [] A list of profiles used to initialize the factory .. py:attribute:: max_storage :type: int :value: 9223372036854775807 Maximum storage allowed in this factory .. py:attribute:: min_storage :type: int :value: 0 Minimum allowed storage per product .. py:attribute:: min_balance :type: int | float :value: 0 Minimum allowed balance .. py:attribute:: initial_balance :type: float :value: 0.0 Initial balance of the factory .. py:attribute:: _commands :type: numpy.ndarray The production command currently running .. py:attribute:: _line_schedules :type: numpy.ndarray .. py:attribute:: _storage :type: Dict[int, int] Mapping from product index to the amount available in the inventory .. py:attribute:: _total_storage :type: int :value: 0 Total storage .. py:attribute:: _wallet :type: float :value: 0 Money available for purchases .. py:attribute:: _hidden_money :type: float :value: 0 Amount of money hidden by the agent .. py:attribute:: _hidden_storage :type: Dict[int, int] Mapping from product index to the amount hidden by the agent .. py:attribute:: _loans :type: float :value: 0.0 The total money owned as loans .. py:attribute:: _n_lines :type: int The number of lines in the factory, will be set using the `profiles` input .. py:attribute:: _jobs :type: Dict[Tuple[int, int], Job] The jobs waiting to be run on the factory indexed by (time, line) tuples .. py:attribute:: _next_step :type: int :value: 0 Current simulation step .. py:attribute:: _carried_updates :type: FactoryStatusUpdate Carried updates from last executed command .. py:attribute:: _world :type: negmas.situated.World :value: None .. py:method:: attach_to_world(world) .. py:method:: __post_init__(initial_storage: Dict[int, int], initial_wallet=0.0) .. py:property:: hidden_money :type: float .. py:property:: hidden_storage :type: Dict[int, int] .. py:property:: n_lines :type: int .. py:property:: jobs :type: Dict[Tuple[int, int], Job] .. py:property:: commands :type: numpy.ndarray .. py:property:: line_schedules :type: numpy.ndarray .. py:property:: wallet :type: float .. py:property:: storage :type: Dict[int, int] .. py:property:: loans :type: float .. py:property:: total_storage :type: int .. py:property:: balance :type: float The total balance of the factory .. py:property:: total_balance :type: float total balance including hidden money .. py:property:: next_step :type: int .. py:method:: add_loan(total: float) -> None .. py:method:: receive(payment: float) -> None .. py:method:: pay(payment: float) -> None .. py:method:: transport_to(product: int, quantity: int) -> None .. py:method:: buy(product: int, quantity: int, price: float) -> None .. py:method:: sell(product: int, quantity: int, price: float) -> None .. py:method:: transport_from(product: int, quantity: int) -> None .. py:method:: hide_funds(amount: float) -> None .. py:method:: hide_product(product: int, quantity: int) -> None .. py:method:: unhide_funds(amount: float) -> None .. py:method:: unhide_product(product: int, quantity: int) -> None .. py:method:: schedule(job: Job, override=False) -> None Schedules the given job at its `time` and `line` optionally overriding whatever was already scheduled :param job: :param override: :returns: Success/failure .. py:method:: _apply_updates(updates: FactoryStatusUpdate) -> None .. py:method:: step() -> List[ProductionReport] .. py:method:: _run(profile: ManufacturingProfile, override=True) -> None running is executed at the beginning of the step t :param profile: the profile to start giving both the line and process :param 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 .. py:method:: _pause(line: int) -> None pausing is executed at the end of the step :param 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. :rtype: Optional[Dict[int, FactoryStatusUpdate]] Remarks: - Not implemented yet - pausing when nothing is running is not an error and will return an empty status update .. py:method:: _resume(line: int) -> None resumption is executed at the end of the step (starting next step count down) :param 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. :rtype: Optional[Dict[int, FactoryStatusUpdate]] Remarks: - Not implemented yet - resuming when nothing is paused is not an error and will return an empty status update .. py:method:: _stop(line: int) -> None stopping is executed at the beginning of the current step :param 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. :rtype: Optional[Dict[int, FactoryStatusUpdate]] Remarks: - stopping when nothing is running is not an error and will just return an empty schedule .. py:method:: _step_line(line: int) -> ProductionReport Steps the line to the time-step `t` assuming that it is already stepped to time-step t-1 given the storage :param line: the line to step :returns: ProductionReport .. py:class:: FactoryState Read Only State of a factory .. py:attribute:: max_storage :type: int Maximum storage allowed in this factory .. py:attribute:: line_schedules :type: numpy.ndarray An array of n_lines * n_steps giving the line schedules .. py:attribute:: storage :type: Dict[int, int] Mapping from product index to the amount available in the inventory .. py:attribute:: wallet :type: float Money available for purchases .. py:attribute:: hidden_money :type: float Amount of money hidden by the agent .. py:attribute:: hidden_storage :type: Dict[int, int] Mapping from product index to the amount hidden by the agent .. py:attribute:: loans :type: float The total money owned as loans .. py:attribute:: n_lines :type: int The number of lines in the factory, will be set using the `profiles` input .. py:attribute:: profiles :type: List[ManufacturingProfile] A list of profiles used to initialize the factory .. py:attribute:: next_step :type: int Next simulation step for this factory .. py:attribute:: commands :type: numpy.ndarray The production command currently running .. py:attribute:: jobs :type: Dict[Tuple[int, int], Job] The jobs waiting to be run on the factory indexed by (time, line) tuples .. py:data:: DEFAULT_NEGOTIATOR :value: 'negmas.sao.AspirationNegotiator' .. py:class:: Consumer(name: Optional[str] = None, ufun: Optional[negmas.UtilityFunction] = None) Bases: :py:obj:`scml.scml2019.agent.SCML2019Agent`, :py:obj:`abc.ABC` Base class of all consumer classes .. py:class:: ConsumptionProfile .. py:attribute:: schedule :type: Union[int, List[int]] :value: 0 .. py:attribute:: underconsumption :type: float :value: 0.1 .. py:attribute:: overconsumption :type: float :value: 0.01 .. py:attribute:: dynamicity :type: float :value: 0.0 .. py:attribute:: cv :type: float :value: 0.1 .. py:attribute:: alpha_q :type: float :value: 0.5 .. py:attribute:: alpha_u :type: float :value: 1.0 .. py:attribute:: beta_q :type: float :value: 10.0 .. py:attribute:: beta_u :type: float :value: 10.0 .. py:attribute:: tau_q :type: float :value: 2 .. py:attribute:: tau_u :type: float :value: 0.25 .. py:method:: random() :classmethod: .. py:method:: schedule_at(time: int) -> int .. py:method:: schedule_within(time: Union[int, List[int], Tuple[int, int]]) -> int .. py:method:: set_schedule_at(time: int, value: int, n_steps: int) -> None .. py:class:: JustInTimeConsumer(profiles: Dict[int, ConsumptionProfile] = None, negotiator_type=DEFAULT_NEGOTIATOR, consumption_horizon: Optional[int] = 20, immediate_cfp_update: bool = True, name=None) Bases: :py:obj:`Consumer` Consumer class .. py:method:: on_contract_executed(contract: negmas.situated.Contract) -> None Called after successful contract execution for which the agent is one of the partners. .. py:method:: on_contract_breached(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach], resolution: Optional[negmas.situated.Contract]) -> None Called after complete processing of a contract that involved a breach. :param contract: The contract :param breaches: All breaches committed (even if they were resolved) :param resolution: The resolution contract if re-negotiation was successful. None if not. .. py:method:: on_inventory_change(product: int, quantity: int, cause: str) -> None Received whenever something moves in or out of the factory's storage :param product: Product index. :param quantity: Negative value for products moving out and positive value for products moving in :param 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). .. py:method:: on_cash_transfer(amount: float, cause: str) -> None Received whenever money is transferred to the factory or from it. :param amount: Amount of money (negative for transfers out of the factory, positive for transfers to it). :param 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). .. py:method:: on_new_report(report: scml.scml2019.common.FinancialReport) Called whenever a financial report is published. :param 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 .. py:method:: on_neg_request_rejected(req_id: str, by: Optional[List[str]]) Called when a requested negotiation is rejected :param req_id: The request ID passed to _request_negotiation :param by: A list of agents that refused to participate or None if the failure was for another reason .. py:method:: on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface) Called when a requested negotiation is accepted .. py:method:: on_negotiation_failure(partners: List[str], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, state: negmas.MechanismState) -> None Called whenever a negotiation ends without agreement .. py:method:: on_negotiation_success(contract: negmas.situated.Contract, mechanism: negmas.NegotiatorMechanismInterface) -> None Called whenever a negotiation ends with agreement .. py:method:: on_contract_cancelled(contract: negmas.situated.Contract, rejectors: List[str]) -> None Called whenever at least a partner did not sign the contract .. py:method:: on_contract_nullified(contract: negmas.situated.Contract, bankrupt_partner: str, compensation: float) -> None Will be called whenever a contract the agent is involved in is nullified because another partner went bankrupt .. py:method:: on_agent_bankrupt(agent_id: str) -> None Will be called whenever any agent goes bankrupt :param agent_id: The ID of the agent that went bankrupt Remarks: - Agents can go bankrupt in two cases: 1. Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it. 2. Failing to pay a penalty on a sell contract they failed to honor (and refusing or being unable to get a loan to pay for it). - All built-in agents ignore this call and they use the bankruptcy list ONLY to decide whether or not to negotiate in their `on_new_cfp` and `respond_to_negotiation_request` callbacks by pulling the bulletin-board using the helper function `is_bankrupt` of their AWI. .. py:method:: confirm_partial_execution(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach]) -> bool Will be called whenever a contract cannot be fully executed due to breaches by the other partner. :param contract: The contract that was breached :param breaches: A list of all the breaches committed. Remarks: - Will not be called if both partners committed breaches. .. py:method:: on_remove_cfp(cfp: scml.scml2019.common.CFP) Called when a new CFP for a product for which the agent registered interest is removed .. py:attribute:: MAX_UNIT_PRICE :value: 100.0 .. py:attribute:: RELATIVE_MAX_PRICE :value: 1.5 .. py:attribute:: negotiator_type :value: 'negmas.sao.AspirationNegotiator' .. py:attribute:: profiles :type: Dict[int, ConsumptionProfile] .. py:attribute:: secured_quantities :type: Dict[int, int] .. py:attribute:: consumption_horizon :value: 20 .. py:attribute:: immediate_cfp_update :value: True .. py:method:: on_new_cfp(cfp: scml.scml2019.common.CFP) -> None Called when a new CFP for a product for which the agent registered interest is published .. py:method:: init() Called to initialize the agent **after** the world is initialized. the AWI is accessible at this point. .. py:method:: set_profiles(profiles: Dict[int, ConsumptionProfile]) .. py:method:: register_product_cfps(p: int, t: int, profile: ConsumptionProfile) .. py:method:: step() Called by the simulator at every simulation step .. py:method:: confirm_contract_execution(contract: negmas.situated.Contract) -> bool Called before executing any agreement .. py:method:: _qufun(outcome: Dict[str, Any], tau: float, profile: ConsumptionProfile) :staticmethod: The ufun value for quantity .. py:method:: respond_to_negotiation_request(cfp: scml.scml2019.common.CFP, partner: str) -> Optional[negmas.negotiators.Negotiator] Called when a prospective partner requests a negotiation to start .. py:method:: set_renegotiation_agenda(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach]) -> Optional[negmas.situated.RenegotiationRequest] Received by partners in ascending order of their total breach levels in order to set the renegotiation agenda when contract execution fails :param contract: The contract that was breached about which re-negotiation is offered :param 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. .. py:method:: respond_to_renegotiation_request(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach], agenda: negmas.situated.RenegotiationRequest) -> Optional[negmas.negotiators.Negotiator] Called to respond to a renegotiation request :param agenda: Renegotiation agenda (issues to renegotiate about). :param contract: The contract that was breached :param breaches: All breaches on that contract :returns: None to refuse to enter the negotiation, otherwise, a negotiator to use for this negotiation. .. py:method:: confirm_loan(loan: scml.scml2019.common.Loan, bankrupt_if_rejected: bool) -> bool called by the world manager to confirm a loan if needed by the buyer of a contract that is about to be breached .. py:method:: sign_contract(contract: negmas.situated.Contract) -> Optional[str] Called after the signing delay from contract conclusion to sign the contract. Contracts become binding only after they are signed. .. py:method:: on_contract_signed(contract: negmas.situated.Contract) Called whenever a contract is signed by all partners .. py:class:: FactoryManager(name=None, simulator_type: Union[str, Type[scml.scml2019.simulators.FactorySimulator]] = FastFactorySimulator) Bases: :py:obj:`scml.scml2019.agent.SCML2019Agent`, :py:obj:`abc.ABC` Base factory manager class that will be inherited by participant negmas in ANAC 2019. The agent can access the world simulation in one of two ways: 1. Attributes and methods available in the Agent-SCML2020World-Interface (See `SCMLAWI` documentation for those). 2. Attributes and methods in the `FactoryManager` object itself. All factory managers will have the following attributes and methods that simplify the interaction with the world simulation. Some of these attributes/methods are convenient ways to access functionality already available in the agent's internal `SCMLAWI`. **Attributes** *Agent information* - `id` : The unique ID assigned to this agent. This is unique system-wide and is what is used in contracts, CFPs, etc. - `name`: A name of the agent used for display purposes only. The simulator never accesses or uses this name except in printing and logging. - `uuid` : Another name of the `id` . - `type_name` : A string giving the type of the agent (as a fully qualified python class name). *Capabilities/Profiles* - `line_profiles` : A mapping specifying for each line index, all the profiles that can be run on it - `process_profiles` : A mapping specifying for each `Process` index, all the profiles used to run it in the factory - `producing` : Mapping from a product index to all manufacturing processes that can generate it - `consuming` : Mapping from a product index to all manufacturing processes that can consume it - `compiled_profiles` : All the profiles to be used by the factory belonging to this agent compiled to use process indices - `max_storage` : Maximum storage available to the agent. Zero, None or float('inf') all indicate unlimited storage. *Production Graph* (also accessible through *awi*) - `products` : List of products in the system - `processes` : List of processes in the system *Helper Objects* - `awi` : The `SCMLAWI` instance assigned to this agent. It can be used to interact with the simulation (See `SCMLAWI` documentation). - `simulator` : A `FactorySimulator` object that can be used to simulate what happens in the `Factory` assigned to this agent when given operations are conducted (e.g. production, paying money, etc). *Negotiations/Contracts* - `requested_negotiations` : A dynamic list of negotiations currently requested by the agent but not started. *Correct management of this list is only possible if the agent **always** uses `request_negotiation` method of this class (see methods later) rather than directly calling request_method on the `SCMLAWI` ( `awi` ) member. - `running_negotiations` : A dynamic list of negotiations currently running involving this agent. *Correct management of this list is only possible if the agent **always** uses `request_negotiation` method of this class (see methods later) rather than directly calling request_method on the `SCMLAWI` ( `awi` ) member. - `unsigned_contracts` : A dynamic list of negotiations contracts concluded involving this agent but not yet signed. *Correct management of this list is only possible if the agent **always** uses `request_negotiation` method of this class (see methods later) rather than directly calling request_method on the `SCMLAWI` ( `awi` ) member. *Simulation attributes* (also accessible through *awi*) - `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 step - `transportation_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 a `CFP` . *Scheduling and simulation helpers* - `can_expect_agreement` : Checks if it is possible in principle to get an agreement on this CFP by the time it becomes executable. **Callbacks** (Callable by the simulation) *Decision callbacks* (Called to make decisions) - Negotiation and Contracts - `respond_to_negotiation_request` : Decide whether or not to engage in a negotiation on a `CFP` that was published earlier by this factory manager. If accepted, the agent should return a `SAONegotiator` object. - `sign_contract` : Decide whether or not to sign the contract. If accepted, the agent should return its own ID. - `confirm_contract_execution` : Decide whether or not to go on with executing a contract that the agent already signed. If rejected (by returning `False` ), a refusal-to-execute breach will be recorded. - Breach related - `confirm_partial_execution` : Decide whether the agent agrees to partial execution. Called only when the the partner of this agent commits a partial breach (of level < 1) and this agent commits no breaches. - `set_renegotiation_agenda` : Decide what are the issues and ranges of acceptable values to re-negotiate about. Called only in case of breaches. - `respond_to_renegotiation_request` : Decide whether or not to engage in a re-negotiation. - Financial - `confirm_loan` : Decide whether or not to accept an offered loan. *In ANAC 2019 league, loans are not allowed and this callback will never be called by the simulator. *Time-dependent callbacks* (Information callback called at predefined times) - `init` : Called once before any production or negotiations to initiate the agent. - `step` : Called at every production step. *Information callbacks* (Called to inform the agent about events) - CFP related - `on_new_cfp` : Called whenever a `CFP` on a `Product` for which the agent has already registered interest (using `register_interest` method of its `awi`) is published. By default all agents register interest in the products they can consume or produce according to their profiles. - `on_remove_cfp` : Called whenever a `CFP` on a `Product` for which the agent has already registered interest (using `register_interest` method of its `awi`) is removed from the bulletin-board. - Negotiation related - `on_neg_request_accepted` : Called when a negotiation request of the agent is accepted - `on_neg_request_rejected` : Called when a negotiation request of the agent is rejected - `on_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 a `Contract` of which the agent is a party is cancelled because the other party refused to sign it. - `on_contract_signed` : Called whenever a `Contract` of which the agent is a party is signed by both patners. - `on_contract_nullified` : Called whenever a `Contract` of which the agent is a party is nullified by the simulator as a part of bankruptcy processing. - `on_contract_executed` : Called when a contract executes completely and successfully. - `on_contract_breached` : Called when a contract is breached after complete contract processing. - Production and factory related - `on_production_failure` : Called whenever a scheduled production (see `SCMLAWI` for production commands) fails - `on_inventory_change` : Called whenever there is a change in the inventory (something is moved in or out or out of storage due to an event other than production (e.g. contract execution). - `on_cash_transfer` : Called whenever cash is transferred to or from the factory's wallet. - About other agents - `on_agent_bankrupt` : Called whenever another agent goes bankrupt - `on_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's `awi` 's `receive_financial_reports` method. .. py:attribute:: transportation_delay :value: 0 Transportation delay in the world .. py:attribute:: simulator :type: Optional[scml.scml2019.simulators.FactorySimulator] :value: None The simulator used by this agent .. py:attribute:: simulator_type :type: Type[scml.scml2019.simulators.FactorySimulator] Simulator type (as a class) .. py:attribute:: current_step :value: 0 Current simulation step .. py:attribute:: max_storage :type: int :value: 0 Maximum storage available to the agent .. py:method:: init_() The initialization function called by the world directly. It does the following actions by default: 1. copies some of the static world settings to the agent to make them available without calling the AWI. 2. prepares production related properties like producing, consuming, line_profiles, compiled_profiles, etc. 3. registers interest in all products that the agent can produce or consume in its factory. 4. finally it calls any custom initialization logic implemented in `init`() .. seealso:: `init`, `step` .. py:method:: step_() Called at every time-step. This function is called directly by the world. .. py:method:: on_production_failure(failures: List[scml.scml2019.common.ProductionFailure]) -> None :abstractmethod: Called with a list of `ProductionFailure` records on production failure. .. py:method:: on_production_success(reports: List[scml.scml2019.common.ProductionReport]) -> None :abstractmethod: Called with a list of `ProductionReport` records on production success .. py:class:: DoNothingFactoryManager(name=None, simulator_type: Union[str, Type[scml.scml2019.simulators.FactorySimulator]] = FastFactorySimulator) Bases: :py:obj:`FactoryManager` The default factory manager that will be implemented by the committee of ANAC-SCML 2019 .. py:method:: init() Called to initialize the agent **after** the world is initialized. the AWI is accessible at this point. .. py:method:: step() Called by the simulator at every simulation step .. py:method:: on_neg_request_rejected(req_id: str, by: Optional[List[str]]) Called when a requested negotiation is rejected :param req_id: The request ID passed to _request_negotiation :param by: A list of agents that refused to participate or None if the failure was for another reason .. py:method:: on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface) Called when a requested negotiation is accepted .. py:method:: on_negotiation_failure(partners: List[str], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, state: negmas.MechanismState) -> None Called whenever a negotiation ends without agreement .. py:method:: on_negotiation_success(contract: negmas.Contract, mechanism: negmas.NegotiatorMechanismInterface) -> None Called whenever a negotiation ends with agreement .. py:method:: on_contract_signed(contract: negmas.Contract) -> None Called whenever a contract is signed by all partners .. py:method:: on_contract_cancelled(contract: negmas.Contract, rejectors: List[str]) -> None Called whenever at least a partner did not sign the contract .. py:method:: on_contract_executed(contract: negmas.Contract) -> None Called after successful contract execution for which the agent is one of the partners. .. py:method:: on_contract_breached(contract: negmas.Contract, breaches: List[negmas.Breach], resolution: Optional[negmas.Contract]) -> None Called after complete processing of a contract that involved a breach. :param contract: The contract :param breaches: All breaches committed (even if they were resolved) :param resolution: The resolution contract if re-negotiation was successful. None if not. .. py:method:: sign_contract(contract: negmas.Contract) -> Optional[str] Called after the signing delay from contract conclusion to sign the contract. Contracts become binding only after they are signed. .. py:method:: on_contract_nullified(contract: negmas.Contract, bankrupt_partner: str, compensation: float) -> None Will be called whenever a contract the agent is involved in is nullified because another partner went bankrupt .. py:method:: on_agent_bankrupt(agent_id: str) -> None Will be called whenever any agent goes bankrupt :param agent_id: The ID of the agent that went bankrupt Remarks: - Agents can go bankrupt in two cases: 1. Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it. 2. Failing to pay a penalty on a sell contract they failed to honor (and refusing or being unable to get a loan to pay for it). - All built-in agents ignore this call and they use the bankruptcy list ONLY to decide whether or not to negotiate in their `on_new_cfp` and `respond_to_negotiation_request` callbacks by pulling the bulletin-board using the helper function `is_bankrupt` of their AWI. .. py:method:: confirm_partial_execution(contract: negmas.Contract, breaches: List[negmas.Breach]) -> bool Will be called whenever a contract cannot be fully executed due to breaches by the other partner. :param contract: The contract that was breached :param breaches: A list of all the breaches committed. Remarks: - Will not be called if both partners committed breaches. .. py:method:: on_remove_cfp(cfp: scml.scml2019.common.CFP) -> None Called when a new CFP for a product for which the agent registered interest is removed .. py:method:: on_production_failure(failures: List[scml.scml2019.common.ProductionFailure]) -> None Called with a list of `ProductionFailure` records on production failure. .. py:method:: respond_to_negotiation_request(cfp: scml.scml2019.common.CFP, partner: str) -> Optional[negmas.Negotiator] Called when a prospective partner requests a negotiation to start .. py:method:: confirm_contract_execution(contract: negmas.Contract) -> bool Called before executing any agreement .. py:method:: set_renegotiation_agenda(contract: negmas.Contract, breaches: List[negmas.Breach]) -> Optional[negmas.RenegotiationRequest] Received by partners in ascending order of their total breach levels in order to set the renegotiation agenda when contract execution fails :param contract: The contract being breached :param breaches: All breaches on `contract` :returns: Renegotiation agenda (issues to negotiate about to avoid reporting the breaches). .. py:method:: respond_to_renegotiation_request(contract: negmas.Contract, breaches: List[negmas.Breach], agenda: negmas.RenegotiationRequest) -> Optional[negmas.Negotiator] Called to respond to a renegotiation request :param agenda: :param contract: :param breaches: Returns: .. py:method:: confirm_loan(loan: scml.scml2019.common.Loan, bankrupt_if_rejected: bool) -> bool called by the world manager to confirm a loan if needed by the buyer of a contract that is about to be breached .. py:method:: on_new_cfp(cfp: scml.scml2019.common.CFP) -> None Called when a new CFP for a product for which the agent registered interest is published .. py:method:: on_inventory_change(product: int, quantity: int, cause: str) -> None Received whenever something moves in or out of the factory's storage :param product: Product index. :param quantity: Negative value for products moving out and positive value for products moving in :param 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). .. py:method:: on_production_success(reports: List[scml.scml2019.common.ProductionReport]) -> None Called with a list of `ProductionReport` records on production success .. py:method:: on_cash_transfer(amount: float, cause: str) -> None Received whenever money is transferred to the factory or from it. :param amount: Amount of money (negative for transfers out of the factory, positive for transfers to it). :param 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). .. py:method:: on_new_report(report: scml.scml2019.common.FinancialReport) Called whenever a financial report is published. :param 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 .. py:class:: GreedyFactoryManager(name=None, simulator_type: Union[str, Type[scml.scml2019.simulators.FactorySimulator]] = FastFactorySimulator, scheduler_type: Union[str, Type[scml.scml2019.schedulers.Scheduler]] = GreedyScheduler, scheduler_params: Optional[Dict[str, Any]] = None, optimism: float = 0.0, negotiator_type: Union[str, Type[negmas.Negotiator]] = DEFAULT_NEGOTIATOR, negotiator_params: Optional[Dict[str, Any]] = 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')) Bases: :py:obj:`DoNothingFactoryManager` The default factory manager that will be implemented by the committee of ANAC-SCML 2019 .. py:method:: on_production_failure(failures: List[scml.scml2019.common.ProductionFailure]) -> None Called with a list of `ProductionFailure` records on production failure. .. py:method:: on_production_success(reports: List[scml.scml2019.common.ProductionReport]) -> None Called with a list of `ProductionReport` records on production success .. py:method:: confirm_loan(loan: scml.scml2019.common.Loan, bankrupt_if_rejected: bool) -> bool called by the world manager to confirm a loan if needed by the buyer of a contract that is about to be breached .. py:method:: confirm_contract_execution(contract: negmas.Contract) -> bool Called before executing any agreement .. py:method:: set_renegotiation_agenda(contract: negmas.Contract, breaches: List[negmas.Breach]) -> Optional[negmas.RenegotiationRequest] Received by partners in ascending order of their total breach levels in order to set the renegotiation agenda when contract execution fails :param contract: The contract being breached :param breaches: All breaches on `contract` :returns: Renegotiation agenda (issues to negotiate about to avoid reporting the breaches). .. py:method:: respond_to_renegotiation_request(contract: negmas.Contract, breaches: List[negmas.Breach], agenda: negmas.RenegotiationRequest) -> Optional[negmas.Negotiator] Called to respond to a renegotiation request :param agenda: :param contract: :param breaches: Returns: .. py:attribute:: negotiator_type :value: 'negmas.sao.AspirationNegotiator' .. py:attribute:: negotiator_params :value: None .. py:attribute:: optimism :value: 0.0 .. py:attribute:: ufun_factory :type: Union[Type[NegotiatorUtility], Callable[[Any, Any], NegotiatorUtility]] .. py:attribute:: __reserved_value .. py:attribute:: max_insurance_premium :value: 0.1 .. py:attribute:: n_retrials :value: 5 .. py:attribute:: n_neg_trials :type: Dict[str, int] .. py:attribute:: consumer :value: None .. py:attribute:: use_consumer :value: True .. py:attribute:: reactive :value: True .. py:attribute:: sign_only_guaranteed_contracts :value: False .. py:attribute:: contract_schedules :type: Dict[str, scml.scml2019.schedulers.ScheduleInfo] .. py:attribute:: riskiness :value: 0.0 .. py:attribute:: negotiation_margin .. py:attribute:: scheduler_type :type: Type[scml.scml2019.schedulers.Scheduler] .. py:attribute:: scheduler :type: scml.scml2019.schedulers.Scheduler :value: None .. py:attribute:: scheduler_params :type: Dict[str, Any] :value: None .. py:method:: total_utility(contracts: Collection[negmas.Contract] = ()) -> float Calculates the total utility for the agent of a collection of contracts .. py:method:: init() Called to initialize the agent **after** the world is initialized. the AWI is accessible at this point. .. py:method:: respond_to_negotiation_request(cfp: scml.scml2019.common.CFP, partner: str) -> Optional[negmas.Negotiator] Called when a prospective partner requests a negotiation to start .. py:method:: on_negotiation_success(contract: negmas.Contract, mechanism: negmas.NegotiatorMechanismInterface) Called whenever a negotiation ends with agreement .. py:method:: on_negotiation_failure(partners: List[str], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, state: negmas.MechanismState) -> None Called whenever a negotiation ends without agreement .. py:method:: _execute_schedule(schedule: scml.scml2019.schedulers.ScheduleInfo, contract: negmas.Contract) -> None .. py:method:: sign_contract(contract: negmas.Contract) Called after the signing delay from contract conclusion to sign the contract. Contracts become binding only after they are signed. .. py:method:: on_contract_signed(contract: negmas.Contract) Called whenever a contract is signed by all partners .. py:method:: _process_buy_cfp(cfp: scml.scml2019.common.CFP) -> None .. py:method:: _process_sell_cfp(cfp: scml.scml2019.common.CFP) .. py:method:: on_new_cfp(cfp: scml.scml2019.common.CFP) -> None Called when a new CFP for a product for which the agent registered interest is published .. py:method:: step() Called by the simulator at every simulation step .. py:method:: can_produce(cfp: scml.scml2019.common.CFP, assume_no_further_negotiations=False) -> bool Whether or not we can produce the required item in time .. py:method:: can_secure_needs(schedule: scml.scml2019.schedulers.ScheduleInfo, step: int) Finds if it is possible in principle to arrange these needs at the given time. :param schedule: :param step: Returns: .. py:function:: pos_gauss(mu, sigma) Returns a sample from a rectified gaussian .. py:function:: _safe_max(a, b) .. py:function:: zero_runs(a: numpy.array) -> numpy.array Finds all runs of zero in an array :param a: Input array (assumed to be 1D) :returns: A 2D array giving beginning and end (exclusive) of zero stretches in the input array. :rtype: np.array .. py:class:: DefaultInsuranceCompany(premium: float, premium_breach_increment: float, premium_time_increment: float, a2f: Dict[str, scml.scml2019.common.Factory], disabled=False, name: str = None) Bases: :py:obj:`InsuranceCompany` Represents an insurance company in the world .. py:attribute:: premium_breach_increment .. py:attribute:: premium .. py:attribute:: disabled :value: False .. py:attribute:: premium_time_increment .. py:attribute:: insured_contracts :type: Dict[Tuple[negmas.situated.Contract, str], scml.scml2019.common.InsurancePolicy] .. py:attribute:: storage :type: Dict[int, int] .. py:attribute:: wallet :type: float :value: 0.0 .. py:attribute:: a2f .. py:method:: init() Called to initialize the agent **after** the world is initialized. the AWI is accessible at this point. .. py:method:: set_renegotiation_agenda(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach]) -> Optional[negmas.situated.RenegotiationRequest] Received by partners in ascending order of their total breach levels in order to set the renegotiation agenda when contract execution fails :param contract: The contract being breached :param breaches: All breaches on `contract` :returns: Renegotiation agenda (issues to negotiate about to avoid reporting the breaches). .. py:method:: respond_to_renegotiation_request(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach], agenda: negmas.situated.RenegotiationRequest) -> Optional[negmas.negotiators.Negotiator] Called to respond to a renegotiation request :param agenda: :param contract: :param breaches: Returns: .. py:method:: evaluate_insurance(contract: negmas.situated.Contract, insured: scml.scml2019.agent.SCML2019Agent, against: scml.scml2019.agent.SCML2019Agent, t: int = None) -> Optional[float] Can be called to evaluate the premium for insuring the given contract against breaches committed by others :param against: The `SCML2019Agent` to insure against :param contract: hypothetical contract :param insured: The `SCML2019Agent` to buy the insurance :param t: time at which the policy is to be bought. If None, it means current step Remarks: - The premium returned is relative to the contract price. To actually calculate the cost of buying this insurance, you need to multiply this by the contract value (quantity * unit_price). .. py:method:: buy_insurance(contract: negmas.situated.Contract, insured: scml.scml2019.agent.SCML2019Agent, against: scml.scml2019.agent.SCML2019Agent) -> Optional[scml.scml2019.common.InsurancePolicy] 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. .. seealso:: `evaluate_premium` .. py:method:: is_insured(contract: negmas.situated.Contract, perpetrator: scml.scml2019.agent.SCML2019Agent) -> bool :param contract: :param perpetrator: Returns: .. py:method:: step() does nothing .. py:class:: InsuranceCompany(*args, **kwargs) Bases: :py:obj:`negmas.situated.Agent`, :py:obj:`abc.ABC` Base class for all insurance companies .. py:attribute:: _world :type: Optional[scml.scml2019.world.SCML2019World] :value: None .. py:method:: _respond_to_negotiation_request(initiator: str, partners: List[str], issues: List[negmas.outcomes.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, role: Optional[str], req_id: Optional[str]) -> Optional[negmas.negotiators.Negotiator] Called by the mechanism to ask for joining a negotiation. The agent can refuse by returning a None :param initiator: The ID of the agent that initiated the negotiation request :param partners: The partner list (will include this agent) :param issues: The list of issues :param annotation: Any annotation specific to this negotiation. :param mechanism: The mechanism that started the negotiation :param role: The role of this agent in the negotiation :param 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 .. py:method:: on_neg_request_rejected(req_id: str, by: Optional[List[str]]) Called when a requested negotiation is rejected :param req_id: The request ID passed to _request_negotiation :param by: A list of agents that refused to participate or None if the failure was for another reason .. py:method:: on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface) Called when a requested negotiation is accepted .. py:method:: on_negotiation_failure(partners: List[str], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, state: negmas.MechanismState) -> None Called whenever a negotiation ends without agreement .. py:method:: on_negotiation_success(contract: negmas.situated.Contract, mechanism: negmas.NegotiatorMechanismInterface) -> None Called whenever a negotiation ends with agreement .. py:method:: on_contract_signed(contract: negmas.situated.Contract) -> None Called whenever a contract is signed by all partners .. py:method:: on_contract_cancelled(contract: negmas.situated.Contract, rejectors: List[str]) -> None Called whenever at least a partner did not sign the contract .. py:method:: sign_contract(contract: negmas.situated.Contract) -> Optional[str] Called after the signing delay from contract conclusion to sign the contract. Contracts become binding only after they are signed. .. py:method:: respond_to_negotiation_request(initiator: str, partners: List[str], issues: List[negmas.outcomes.Issue], annotation: Dict[str, Any], mechanism: negmas.Mechanism, role: Optional[str], req_id: str) -> Optional[negmas.negotiators.Negotiator] .. py:method:: on_contract_breached(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach], resolution: Optional[negmas.situated.Contract]) -> None Called after complete processing of a contract that involved a breach. :param contract: The contract :param breaches: All breaches committed (even if they were resolved) :param resolution: The resolution contract if re-negotiation was successful. None if not. .. py:method:: on_contract_executed(contract: negmas.situated.Contract) -> None Called after successful contract execution for which the agent is one of the partners. .. py:class:: Miner(name: Optional[str] = None, ufun: Optional[negmas.UtilityFunction] = None) Bases: :py:obj:`scml.scml2019.agent.SCML2019Agent`, :py:obj:`abc.ABC` Base class of all miners .. py:class:: MiningProfile .. py:attribute:: cv :type: float :value: 0.05 .. py:attribute:: alpha_t :type: float :value: 1.0 .. py:attribute:: alpha_q :type: float :value: 1.0 .. py:attribute:: alpha_u :type: float :value: 1.0 .. py:attribute:: beta_t :type: float :value: 1.0 .. py:attribute:: beta_q :type: float :value: 100.0 .. py:attribute:: beta_u :type: float :value: 100.0 .. py:attribute:: tau_t :type: float :value: -0.25 .. py:attribute:: tau_q :type: float :value: 0.25 .. py:attribute:: tau_u :type: float :value: 1.0 .. py:method:: random() :classmethod: .. py:class:: ReactiveMiner(profiles: dict[int, MiningProfile] | None = None, negotiator_type=DEFAULT_NEGOTIATOR, n_retrials=0, reactive=True, name=None) Bases: :py:obj:`Miner` Raw Material Generator .. py:method:: on_contract_executed(contract: negmas.situated.Contract) -> None Called after successful contract execution for which the agent is one of the partners. .. py:method:: on_contract_breached(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach], resolution: Optional[negmas.situated.Contract]) -> None Called after complete processing of a contract that involved a breach. :param contract: The contract :param breaches: All breaches committed (even if they were resolved) :param resolution: The resolution contract if re-negotiation was successful. None if not. .. py:method:: on_inventory_change(product: int, quantity: int, cause: str) -> None Received whenever something moves in or out of the factory's storage :param product: Product index. :param quantity: Negative value for products moving out and positive value for products moving in :param 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). .. py:method:: on_cash_transfer(amount: float, cause: str) -> None Received whenever money is transferred to the factory or from it. :param amount: Amount of money (negative for transfers out of the factory, positive for transfers to it). :param 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). .. py:method:: on_new_report(report: scml.scml2019.common.FinancialReport) Called whenever a financial report is published. :param 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 .. py:method:: on_neg_request_rejected(req_id: str, by: Optional[list[str]]) Called when a requested negotiation is rejected :param req_id: The request ID passed to _request_negotiation :param by: A list of agents that refused to participate or None if the failure was for another reason .. py:method:: on_neg_request_accepted(req_id: str, mechanism: negmas.common.NegotiatorMechanismInterface) Called when a requested negotiation is accepted .. py:method:: on_negotiation_success(contract: negmas.situated.Contract, mechanism: negmas.common.NegotiatorMechanismInterface) -> None Called whenever a negotiation ends with agreement .. py:method:: on_contract_signed(contract: negmas.situated.Contract) -> None Called whenever a contract is signed by all partners .. py:method:: on_contract_cancelled(contract: negmas.situated.Contract, rejectors: list[str]) -> None Called whenever at least a partner did not sign the contract .. py:method:: sign_contract(contract: negmas.situated.Contract) -> Optional[str] Called after the signing delay from contract conclusion to sign the contract. Contracts become binding only after they are signed. .. py:method:: on_contract_nullified(contract: negmas.situated.Contract, bankrupt_partner: str, compensation: float) -> None Will be called whenever a contract the agent is involved in is nullified because another partner went bankrupt .. py:method:: on_agent_bankrupt(agent_id: str) -> None Will be called whenever any agent goes bankrupt :param agent_id: The ID of the agent that went bankrupt Remarks: - Agents can go bankrupt in two cases: 1. Failing to pay one installments of a loan they bought and refusing (or being unable to) get another loan to pay it. 2. Failing to pay a penalty on a sell contract they failed to honor (and refusing or being unable to get a loan to pay for it). - All built-in agents ignore this call and they use the bankruptcy list ONLY to decide whether or not to negotiate in their `on_new_cfp` and `respond_to_negotiation_request` callbacks by pulling the bulletin-board using the helper function `is_bankrupt` of their AWI. .. py:method:: confirm_partial_execution(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach]) -> bool Will be called whenever a contract cannot be fully executed due to breaches by the other partner. :param contract: The contract that was breached :param breaches: A list of all the breaches committed. Remarks: - Will not be called if both partners committed breaches. .. py:method:: on_remove_cfp(cfp: scml.scml2019.common.CFP) Called when a new CFP for a product for which the agent registered interest is removed .. py:attribute:: negotiator_type :value: 'negmas.sao.AspirationNegotiator' .. py:attribute:: profiles :type: dict[int, MiningProfile] .. py:attribute:: n_neg_trials :type: dict[str, int] .. py:attribute:: n_retrials :value: 0 .. py:attribute:: reactive :value: True .. py:method:: init() Called to initialize the agent **after** the world is initialized. the AWI is accessible at this point. .. py:method:: on_negotiation_failure(partners: list[str], annotation: dict[str, Any], mechanism: negmas.common.NegotiatorMechanismInterface, state: negmas.common.MechanismState) -> None Called whenever a negotiation ends without agreement .. py:method:: set_profiles(profiles: dict[int, MiningProfile]) .. py:method:: _process_cfp(cfp: scml.scml2019.common.CFP) .. py:method:: on_new_cfp(cfp: scml.scml2019.common.CFP) Called when a new CFP for a product for which the agent registered interest is published .. py:method:: step() Called by the simulator at every simulation step .. py:method:: confirm_contract_execution(contract: negmas.situated.Contract) -> bool Called before executing any agreement .. py:method:: respond_to_negotiation_request(cfp: scml.scml2019.common.CFP, partner: str) -> Optional[negmas.negotiators.Negotiator] Called when a prospective partner requests a negotiation to start .. py:method:: set_renegotiation_agenda(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach]) -> Optional[negmas.situated.RenegotiationRequest] Received by partners in ascending order of their total breach levels in order to set the renegotiation agenda when contract execution fails :param contract: The contract being breached :param breaches: All breaches on `contract` :returns: Renegotiation agenda (issues to negotiate about to avoid reporting the breaches). .. py:method:: respond_to_renegotiation_request(contract: negmas.situated.Contract, breaches: list[negmas.situated.Breach], agenda: negmas.situated.RenegotiationRequest) -> Optional[negmas.negotiators.Negotiator] Called to respond to a renegotiation request :param agenda: :param contract: :param breaches: Returns: .. py:method:: confirm_loan(loan: scml.scml2019.common.Loan, bankrupt_if_rejected: bool) -> bool called by the world manager to confirm a loan if needed by the buyer of a contract that is about to be breached .. py:class:: ScheduleInfo .. py:attribute:: final_balance :type: float balance at the end of the schedule .. py:attribute:: valid :type: bool :value: True Is this a valid schedule? .. py:attribute:: start :type: Optional[int] :value: None The starting step of this schedule .. py:attribute:: end :type: Optional[int] :value: None The step after the last step in this simulation .. py:attribute:: needs :type: List[scml.scml2019.common.ProductionNeed] :value: [] The products needed but not still in storage needed to complete this schedule. .. py:attribute:: jobs :type: List[scml.scml2019.common.Job] :value: [] The jobs that need to be scheduled .. py:attribute:: failed_contracts :type: List[negmas.situated.Contract] :value: [] A list of contracts that failed to be scheduled. .. py:attribute:: ignored_contracts :type: List[negmas.situated.Contract] :value: [] A list of contracts ignored for this schedule because they are in the past. .. py:method:: __str__() .. py:method:: combine(other: ScheduleInfo) -> None .. py:class:: Scheduler(manager_id: str, awi: scml.scml2019.awi.SCMLAWI, max_insurance_premium: float = float('inf'), horizon: Optional[int] = None) Bases: :py:obj:`abc.ABC` Base class for all schedulers .. py:attribute:: horizon :value: None .. py:attribute:: n_steps :value: 0 .. py:attribute:: n_lines :value: 0 .. py:attribute:: simulator :type: scml.scml2019.simulators.FactorySimulator | None :value: None .. py:attribute:: products :type: List[scml.scml2019.common.Product] :value: [] .. py:attribute:: processes :type: List[scml.scml2019.common.Process] :value: [] .. py:attribute:: profiles :type: List[scml.scml2019.common.ManufacturingProfileCompiled] :value: [] .. py:attribute:: producing :type: Dict[int, List[scml.scml2019.common.ProductManufacturingInfo]] .. py:attribute:: manager_id .. py:attribute:: awi .. py:attribute:: max_insurance_premium .. py:method:: bookmark() -> int Sets a bookmark to the current location :returns: bookmark ID .. py:method:: rollback(bookmark_id: int) -> bool Rolls back to the given bookmark ID :param bookmark_id The bookmark ID returned from bookmark: 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) .. py:method:: delete_bookmark(bookmark_id: int) -> bool Commits everything since the bookmark so it cannot be rolled back :param bookmark_id The bookmark ID returned from bookmark: 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) .. py:method:: 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]]) Called by the FactoryManager after it is initialized .. py:method:: schedule(contracts: Collection[negmas.situated.Contract] = (), assume_no_further_negotiations=False, ensure_storage_for: int = 0, start_at: int = 0) -> ScheduleInfo Schedules a set of contracts and returns either the search_for_schedule or None if infeasible :param whatever it has scheduled before. If the state is given: :param it is taken as the initial state for scheduling: :param contracts: The contracts to be scheduled :param assume_no_further_negotiations: whether to assume that more negotiations can take place (to secure :param production needs): :param ensure_storage_for: A minimum time to ensure that products are available in storage before contract delivery :param times: :type times: sell contracts :param 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. .. py:method:: 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 :abstractmethod: Schedules a set of contracts and returns either the search_for_schedule or None if infeasible :param start: :param end: :param contracts: :param assume_no_further_negotiations: :param ensure_storage_for: :param 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). .. py:class:: GreedyScheduler(manager_id: str, awi: scml.scml2019.awi.SCMLAWI, max_insurance_premium: float = float('inf'), horizon: Optional[int] = None, add_catalog_prices=True, strategy: str = 'latest', profile_sorter: str = 'total-cost>time') Bases: :py:obj:`Scheduler` Default scheduler used by the DefaultFactoryManager .. py:method:: __getstate__() .. py:method:: __setstate__(state) .. py:attribute:: add_catalog_prices :value: True .. py:attribute:: strategy :value: 'latest' .. py:attribute:: fields :type: List[Callable[[scml.scml2019.common.ProductManufacturingInfo], float]] .. py:attribute:: field_order :type: List[int] :value: [] .. py:attribute:: producing :type: Dict[int, List[scml.scml2019.common.ProductManufacturingInfo]] .. py:method:: 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]]) Called by the FactoryManager after it is initialized .. py:method:: _profile_sorter(info: scml.scml2019.common.ProductManufacturingInfo) -> Any .. py:method:: unit_time(info: scml.scml2019.common.ProductManufacturingInfo) -> float .. py:method:: total_cost(info: scml.scml2019.common.ProductManufacturingInfo) -> float .. py:method:: total_unit_cost(info: scml.scml2019.common.ProductManufacturingInfo) -> float .. py:method:: production_cost(info: scml.scml2019.common.ProductManufacturingInfo) -> float .. py:method:: production_unit_cost(info: scml.scml2019.common.ProductManufacturingInfo) -> float .. py:method:: input_cost(info: scml.scml2019.common.ProductManufacturingInfo) .. py:method:: input_unit_cost(info: scml.scml2019.common.ProductManufacturingInfo) -> float .. py:method:: schedule_contract(contract: negmas.situated.Contract, assume_no_further_negotiations=False, end: int = None, ensure_storage_for: int = 0, start_at: int = 0) -> ScheduleInfo Schedules this contract if possible and returns information about the resulting schedule :param contract: The contract being scheduled :param assume_no_further_negotiations: If true no further negotiations will be assumed possible :param end: The scheduling horizon (None for the default). :param ensure_storage_for: The number of steps all needs must be in storage before they are consumed in production :param start_at: No jobs will be scheduled before that time. :returns: Full schedule information including validity, line schedulers, production needs, etc (see `SchedulerInfo`). .. py:method:: 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 Schedules a set of contracts and returns the `ScheduleInfo`. :param contracts: Contracts to schedule :param assume_no_further_negotiations: If true, no further negotiations will be assumed to be possible :param end: The end of the simulation for the schedule (exclusive) :param ensure_storage_for: Ensure that the outcome will be at the storage for at least this time :param 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 .. py:method:: 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) Schedules a set of contracts and returns either the search_for_schedule or None if infeasible :param start: :param end: :param contracts: :param assume_no_further_negotiations: :param ensure_storage_for: :param 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). .. py:class:: FactorySimulator(initial_wallet: float, initial_storage: Dict[int, int], n_steps: int, n_products: int, profiles: List[scml.scml2019.common.ManufacturingProfile], max_storage: Optional[int] = None) Bases: :py:obj:`abc.ABC` Simulates a factory allowing for prediction of storage/balance in the future. :param initial_wallet: The initial amount of cash in the wallet :param initial_storage: initial inventory :param n_steps: number of simulation steps :param n_products: number of products in the world :param profiles: all profiles that the factory being simulated can run :param max_storage: maximum available storage space. .. py:attribute:: _n_steps .. py:attribute:: _max_storage :value: None .. py:attribute:: _initial_wallet .. py:attribute:: _initial_storage .. py:attribute:: _profiles .. py:attribute:: _n_products .. py:attribute:: _reserved_storage .. py:method:: _as_array(storage: Dict[int, int]) .. py:property:: max_storage :type: Optional[int] Maximum storage available .. py:property:: n_steps :type: int Number of steps to predict ahead. .. py:property:: initial_wallet :type: float Initial cash in wallet .. py:property:: initial_storage :type: numpy.array Initial inventory .. py:property:: n_lines :abstractmethod: Number of lines .. py:property:: final_balance :type: float :abstractmethod: Final balance given everything scheduled so-far .. py:method:: wallet_to(t: int) -> numpy.array :abstractmethod: Returns the cash in wallet up to and including time t. :param t: Time Returns: .. py:method:: wallet_at(t: int) -> float Returns the cash in wallet *at* a given timestep (given all simulated actions) :param t: Returns: .. py:method:: storage_to(t: int) -> numpy.array :abstractmethod: Returns the storage of all products *up to* time t :param t: Time :returns: An array of size `n_products` * `t` giving the quantity of each product in storage at every step up to `t`. .. py:method:: storage_at(t: int) -> numpy.array Returns the storage of all products *at* time t :param t: Time :returns: An array of size `n_products` giving the quantity of each product in storage at time-step `t`. .. seealso:: `storage_to` `wallet_at` .. py:method:: line_schedules_to(t: int) -> numpy.array :abstractmethod: Returns the schedule of each line up to a given timestep :param t: time :returns: An array of `n_lines` * `t` values giving the schedule up to `t`. Remarks: - A `NO_PRODUCTION` value means no production, otherwise the index of the process being run .. py:method:: line_schedules_at(t: int) -> numpy.array Returns the schedule of each line at a given timestep :param t: time :returns: An array of `n_lines` values giving the schedule up at `t`. Remarks: - A `NO_PRODUCTION` value means no production, otherwise the index of the process being run .. py:method:: total_storage_to(t: int) -> numpy.array The total storage *up to* a given time :param t: time :returns: an array of size `t` giving the total quantity of stored products in the inventory up to timestep `t` .. seealso:: `total_storage_at` `storage_to` .. py:method:: total_storage_at(t: int) -> int The total storage *at* a given time :param t: time :returns: an integer giving the total quantity of stored products in the inventory at timestep `t` .. seealso:: `total_storage_to` `storage_at` .. py:method:: reserved_storage_to(t: int) -> numpy.array Returns the *reserved* storage of all products *up to* time t :param t: Time :returns: An array of size `n_products` * `t` giving the quantity of each product reserved at every step up to `t`. Remarks: - Reserved storage *is counted* in calls to `storage_at` , `total_storage_at` , `storage_to` , `total_storage_to` - Reserving quantities of products is a tool that can be used to avoid double counting availability of given products in the inventory for multiple contracts. .. seealso:: `total_storage_at` `storage_at` `reserved_storage_at` .. py:method:: reserved_storage_at(t: int) -> numpy.array Returns the *reserved* storage of all products *at* time t :param t: Time :returns: An array of size `n_products` giving the quantity of each product reserved at time-step `t`. Remarks: - Reserved storage *is counted* in calls to `storage_at` , `total_storage_at` , `storage_to` , `total_storage_to` - Reserving quantities of products is a tool that can be used to avoid double counting availability of given products in the inventory for multiple contracts. .. seealso:: `total_storage_to` `storage_to` `reserved_storage_at` .. py:method:: available_storage_to(t: int) -> numpy.array Returns the *available* storage of all products *up to* time t. :param t: Time :returns: An array of size `n_products` * `t` giving the quantity of each product available at every step up to `t`. Remarks: - Available storage is defined as the difference between storage and reserved storage. - Reserved storage *is counted* in calls to `storage_at` , `total_storage_at` , `storage_to` , `total_storage_to` - Reserving quantities of products is a tool that can be used to avoid double counting availability of given products in the inventory for multiple contracts. .. seealso:: `total_storage_to` `storage_to` `reserved_storage_to` .. py:method:: available_storage_at(t: int) -> numpy.array Returns the *available* storage of all products *at* time t :param t: Time :returns: An array of size `n_products` giving the quantity of each product available at time-step `t`. Remarks: - Available storage is defined as the difference between storage and reserved storage. - Reserved storage *is counted* in calls to `storage_at` , `total_storage_at` , `storage_to` , `total_storage_to` - Reserving quantities of products is a tool that can be used to avoid double counting availability of given products in the inventory for multiple contracts. .. seealso:: `total_storage_to` `storage_to` `reserved_storage_at` .. py:method:: loans_to(t: int) -> numpy.array :abstractmethod: Returns loans up to time t :param t: time :returns: An array of `t` real numbers giving the loans registered at time-steps up to `t` .. py:method:: loans_at(t: int) -> float Returns loans at time t :param t: time .. py:method:: balance_at(t: int) -> float Returns the balance fo the factory at time t. :param t: time Remarks: - The balance is defined as the cash in wallet minus loans .. seealso:: `loans_at` `wallet_at` .. py:method:: balance_to(t: int) -> numpy.array Returns the balance fo the factory *up to* time t. :param t: time Remarks: - The balance is defined as the cash in wallet minus loans .. seealso:: `loans_to` `wallet_to` .. py:property:: fixed_before :abstractmethod: Gives the time before which the schedule is fixed. .. seealso:: `fix_before` .. py:method:: set_state(t: int, storage: numpy.array, wallet: float, loans: float, line_schedules: numpy.array) -> None :abstractmethod: Sets the current state at the given time-step. It implicitly causes a fix_before(t + 1) :param t: Time step to set the state at :param storage: quantity of every product (array of integers of size `n_products`) :param wallet: Cash in wallet :param loans: Loans :param line_schedules: Line schedules (array of process numbers/NO_PRODUCTION of size `n_lines`) .. py:method:: add_loan(total: float, t: int) -> bool :abstractmethod: Adds a loan at the given time :param total: Total amount of the loan :param 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. .. py:method:: receive(payment: float, t: int) -> bool Simulates receiving payment at time t :param payment: Amount received :param t: time :returns: Success or failure .. py:method:: pay(payment: float, t: int, ignore_money_shortage: bool = True) -> bool :abstractmethod: Simulate payment at time t :param payment: Amount payed :param t: time :param ignore_money_shortage: If True, shortage in money will be ignored and the wallet can go negative :returns: Success or failure .. py:method:: transport_to(product: int, quantity: int, t: int, ignore_inventory_shortage: bool = True, ignore_space_shortage: bool = True) -> bool :abstractmethod: Simulates transporting products to/from storage at time t :param product: product ID (index) :param quantity: quantity to transport :param t: time :param ignore_inventory_shortage: Ignore shortage in the `product` which may lead to negative storage[product] :param ignore_space_shortage: Ignore the limit on total storage which may lead to total_storage > max_storage :returns: Success or failure .. py:method:: buy(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_space_shortage: bool = True) -> bool :abstractmethod: Buy a given quantity of a product for a given price at some time t :param product: Product to buy (ID/index) :param quantity: quantity to buy :param price: unit price :param t: time :param ignore_money_shortage: If True, shortage in money will be ignored and the wallet can go negative :param 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 .. seealso:: `sell` .. py:method:: sell(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_inventory_shortage: bool = True) -> bool :abstractmethod: sell a given quantity of a product for a given price at some time t :param product: Index/ID of the product to be sold :param quantity: quantity to be sold :param price: unit price :param t: time :param ignore_money_shortage: If True, shortage in money will be ignored and the wallet can go negative :param 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 .. seealso:: `buy` .. py:method:: schedule(job: scml.scml2019.common.Job, ignore_inventory_shortage=True, ignore_money_shortage=True, ignore_space_shortage=True, override=True) -> bool :abstractmethod: Simulates scheduling the given job at its `time` and `line` optionally overriding whatever was already scheduled :param job: Production job :param ignore_inventory_shortage: If true shortages in inputs will be ignored :param ignore_money_shortage: If true, shortage in money will be ignored :param ignore_space_shortage: If true, shortage in space will be ignored :param override: Whether the job should override any already registered job at its time-step :returns: Success/failure .. py:method:: reserve(product: int, quantity: int, t: int) -> bool Simulates reserving the given quantity of the given product at times >= t. :param product: Index/ID of the product being reserved :param quantity: quantity being reserved :param t: time :returns: Success/failure Remarks: - Reserved products show in calls to `storage_at` , `total_storage_at` etc. - Reserving a product does nothing more than mark some quantity as reserved for calls to `reserved_storage_at` and `available_storage_at`. - This feature can be used to simulate inventory hiding commands in the real factory and to avoid double counting of inventory when calculating needs for future contracts. .. py:method:: fix_before(t: int) -> bool :abstractmethod: Fix the history before this point :param t: time :returns: Success/failure Remarks: - After this function is called at any time-step `t`, there is no way to change any component of the factory state at any timestep before `t`. - This function is useful for *fixing* any difference between the simulator and the real state (in conjunction with `set_state`). .. seealso:: `set_state` `fixed_before` .. py:method:: bookmark() -> int :abstractmethod: Sets a bookmark to the current location :returns: bookmark ID Remarks: - Bookmarks can be used to implement transactions. .. seealso:: `delete_bookmark` `rollback` `transaction` `temporary_transaction` .. py:method:: rollback(bookmark_id: int) -> bool :abstractmethod: Rolls back to the given bookmark ID :param bookmark_id The bookmark ID returned from bookmark: 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) .. seealso:: `delete_bookmark` `rollback` `transaction` `temporary_transaction` .. py:method:: delete_bookmark(bookmark_id: int) -> bool :abstractmethod: Commits everything since the bookmark so it cannot be rolled back :param bookmark_id The bookmark ID returned from bookmark: :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). .. seealso:: `delete_bookmark` `rollback` `transaction` `temporary_transaction` .. py:class:: SlowFactorySimulator(initial_wallet: float, initial_storage: Dict[int, int], n_steps: int, n_products: int, profiles: List[scml.scml2019.common.ManufacturingProfile], max_storage: Optional[int]) Bases: :py:obj:`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 .. py:method:: set_state(t: int, storage: numpy.array, wallet: float, loans: float, line_schedules: numpy.array) -> None Sets the current state at the given time-step. It implicitly causes a fix_before(t + 1) :param t: Time step to set the state at :param storage: quantity of every product (array of integers of size `n_products`) :param wallet: Cash in wallet :param loans: Loans :param line_schedules: Line schedules (array of process numbers/NO_PRODUCTION of size `n_lines`) .. py:method:: delete_bookmark(bookmark_id: int) -> bool Commits everything since the bookmark so it cannot be rolled back :param bookmark_id The bookmark ID returned from bookmark: :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). .. seealso:: `delete_bookmark` `rollback` `transaction` `temporary_transaction` .. py:method:: bookmark() -> int Sets a bookmark to the current location :returns: bookmark ID Remarks: - Bookmarks can be used to implement transactions. .. seealso:: `delete_bookmark` `rollback` `transaction` `temporary_transaction` .. py:method:: rollback(bookmark_id: int) -> bool Rolls back to the given bookmark ID :param bookmark_id The bookmark ID returned from bookmark: 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) .. seealso:: `delete_bookmark` `rollback` `transaction` `temporary_transaction` .. py:property:: final_balance :type: float Final balance given everything scheduled so-far .. py:property:: n_lines Number of lines .. py:method:: fix_before(t: int) -> bool Fix the history before this point :param t: time :returns: Success/failure Remarks: - After this function is called at any time-step `t`, there is no way to change any component of the factory state at any timestep before `t`. - This function is useful for *fixing* any difference between the simulator and the real state (in conjunction with `set_state`). .. seealso:: `set_state` `fixed_before` .. py:attribute:: _factory .. py:attribute:: _jobs :type: Dict[int, List[scml.scml2019.common.Job, bool, bool, bool, bool]] .. py:attribute:: _buy_contracts :type: Dict[int, List[int, int, float]] .. py:attribute:: _sell_contracts :type: Dict[int, List[int, int, float]] .. py:attribute:: _payment_updates :type: Dict[int, float] .. py:attribute:: _loans_updates :type: Dict[int, float] .. py:attribute:: _storage_updates :type: Dict[int, Dict[int, int]] .. py:attribute:: _wallet .. py:attribute:: _loans .. py:attribute:: _storage .. py:attribute:: _line_schedules .. py:attribute:: _fixed_before :value: 0 .. py:attribute:: _bookmarks :type: List[_Bookmark] :value: [] .. py:attribute:: _active_bookmark :type: Optional[_Bookmark] :value: None .. py:attribute:: _active_bookmarked_at :type: int :value: -1 .. py:attribute:: _bookmarked_at :type: List[int] :value: [] .. py:attribute:: _saved_states :type: Dict[int, List[_State]] .. py:method:: _update_state() -> None .. py:method:: reset_to(t: int) -> None .. py:method:: goto(t: int) -> None Steps the factory to the end of step t :param t: time Returns: .. py:method:: wallet_to(t: int) -> numpy.array Returns the cash in wallet up to and including time t. :param t: Time Returns: .. py:method:: line_schedules_to(t: int) -> numpy.array Returns the schedule of each line up to a given timestep :param t: time :returns: An array of `n_lines` * `t` values giving the schedule up to `t`. Remarks: - A `NO_PRODUCTION` value means no production, otherwise the index of the process being run .. py:method:: storage_to(t: int) -> numpy.array Returns the storage of all products *up to* time t :param t: Time :returns: An array of size `n_products` * `t` giving the quantity of each product in storage at every step up to `t`. .. py:method:: loans_to(t: int) -> float Returns loans up to time t :param t: time :returns: An array of `t` real numbers giving the loans registered at time-steps up to `t` .. py:method:: add_loan(total: float, t: int) -> bool Adds a loan at the given time :param total: Total amount of the loan :param 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. .. py:method:: pay(payment: float, t: int, ignore_money_shortage: bool = True) -> bool Simulate payment at time t :param payment: Amount payed :param t: time :param ignore_money_shortage: If True, shortage in money will be ignored and the wallet can go negative :returns: Success or failure .. py:method:: transport_to(product: int, quantity: int, t: int, ignore_inventory_shortage: bool = True, ignore_space_shortage: bool = True) -> bool Simulates transporting products to/from storage at time t :param product: product ID (index) :param quantity: quantity to transport :param t: time :param ignore_inventory_shortage: Ignore shortage in the `product` which may lead to negative storage[product] :param ignore_space_shortage: Ignore the limit on total storage which may lead to total_storage > max_storage :returns: Success or failure .. py:method:: schedule(job: scml.scml2019.common.Job, ignore_inventory_shortage=True, ignore_money_shortage=True, ignore_space_shortage=True, override=True) -> bool Simulates scheduling the given job at its `time` and `line` optionally overriding whatever was already scheduled :param job: Production job :param ignore_inventory_shortage: If true shortages in inputs will be ignored :param ignore_money_shortage: If true, shortage in money will be ignored :param ignore_space_shortage: If true, shortage in space will be ignored :param override: Whether the job should override any already registered job at its time-step :returns: Success/failure .. py:method:: buy(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_space_shortage: bool = True) -> bool Buy a given quantity of a product for a given price at some time t :param product: Product to buy (ID/index) :param quantity: quantity to buy :param price: unit price :param t: time :param ignore_money_shortage: If True, shortage in money will be ignored and the wallet can go negative :param 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 .. seealso:: `sell` .. py:method:: sell(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_inventory_shortage: bool = True) -> bool sell a given quantity of a product for a given price at some time t :param product: Index/ID of the product to be sold :param quantity: quantity to be sold :param price: unit price :param t: time :param ignore_money_shortage: If True, shortage in money will be ignored and the wallet can go negative :param 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 .. seealso:: `buy` .. py:property:: fixed_before Gives the time before which the schedule is fixed. .. seealso:: `fix_before` .. py:class:: FastFactorySimulator(initial_wallet: float, initial_storage: Dict[int, int], n_steps: int, n_products: int, profiles: List[scml.scml2019.common.ManufacturingProfile], max_storage: Optional[int]) Bases: :py:obj:`FactorySimulator` A faster implementation of the `FactorySimulator` interface (compared with `SlowFactorySimulator`. .. py:method:: _as_array(storage: Dict[int, int]) -> numpy.array .. py:attribute:: _wallet .. py:attribute:: _loans .. py:attribute:: _storage .. py:attribute:: _total_storage .. py:attribute:: _profiles :value: [] .. py:attribute:: _n_lines .. py:attribute:: _line_schedules .. py:attribute:: _has_jobs .. py:attribute:: _fixed_before :value: 0 .. py:attribute:: _bookmarks :type: List[_FullBookmark] :value: [] .. py:attribute:: _active_bookmark :type: Optional[_FullBookmark] :value: None .. py:method:: init(*args, **kwargs) .. py:property:: fixed_before Gives the time before which the schedule is fixed. .. seealso:: `fix_before` .. py:property:: n_lines Number of lines .. py:property:: final_balance :type: float Final balance given everything scheduled so-far .. py:method:: wallet_to(t: int) -> numpy.array Returns the cash in wallet up to and including time t. :param t: Time Returns: .. py:method:: storage_to(t: int) -> numpy.array Returns the storage of all products *up to* time t :param t: Time :returns: An array of size `n_products` * `t` giving the quantity of each product in storage at every step up to `t`. .. py:method:: line_schedules_to(t: int) -> numpy.array Returns the schedule of each line up to a given timestep :param t: time :returns: An array of `n_lines` * `t` values giving the schedule up to `t`. Remarks: - A `NO_PRODUCTION` value means no production, otherwise the index of the process being run .. py:method:: loans_to(t: int) -> numpy.array Returns loans up to time t :param t: time :returns: An array of `t` real numbers giving the loans registered at time-steps up to `t` .. py:method:: add_loan(total: float, t: int) -> bool Adds a loan at the given time :param total: Total amount of the loan :param 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. .. py:method:: pay(payment: float, t: int, ignore_money_shortage: bool = True) -> bool Simulate payment at time t :param payment: Amount payed :param t: time :param ignore_money_shortage: If True, shortage in money will be ignored and the wallet can go negative :returns: Success or failure .. py:method:: transport_to(product: int, quantity: int, t: int, ignore_inventory_shortage: bool = True, ignore_space_shortage: bool = True) -> bool Simulates transporting products to/from storage at time t :param product: product ID (index) :param quantity: quantity to transport :param t: time :param ignore_inventory_shortage: Ignore shortage in the `product` which may lead to negative storage[product] :param ignore_space_shortage: Ignore the limit on total storage which may lead to total_storage > max_storage :returns: Success or failure .. py:method:: buy(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_space_shortage: bool = True) -> bool Buy a given quantity of a product for a given price at some time t :param product: Product to buy (ID/index) :param quantity: quantity to buy :param price: unit price :param t: time :param ignore_money_shortage: If True, shortage in money will be ignored and the wallet can go negative :param 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 .. seealso:: `sell` .. py:method:: sell(product: int, quantity: int, price: int, t: int, ignore_money_shortage: bool = True, ignore_inventory_shortage: bool = True) -> bool sell a given quantity of a product for a given price at some time t :param product: Index/ID of the product to be sold :param quantity: quantity to be sold :param price: unit price :param t: time :param ignore_money_shortage: If True, shortage in money will be ignored and the wallet can go negative :param 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 .. seealso:: `buy` .. py:method:: schedule(job: scml.scml2019.common.Job, ignore_inventory_shortage=True, ignore_money_shortage=True, ignore_space_shortage=True, override=True) -> bool Simulates scheduling the given job at its `time` and `line` optionally overriding whatever was already scheduled :param job: Production job :param ignore_inventory_shortage: If true shortages in inputs will be ignored :param ignore_money_shortage: If true, shortage in money will be ignored :param ignore_space_shortage: If true, shortage in space will be ignored :param override: Whether the job should override any already registered job at its time-step :returns: Success/failure .. py:method:: fix_before(t: int) -> bool Fix the history before this point :param t: time :returns: Success/failure Remarks: - After this function is called at any time-step `t`, there is no way to change any component of the factory state at any timestep before `t`. - This function is useful for *fixing* any difference between the simulator and the real state (in conjunction with `set_state`). .. seealso:: `set_state` `fixed_before` .. py:method:: delete_bookmark(bookmark_id: int) -> bool Commits everything since the bookmark so it cannot be rolled back :param bookmark_id The bookmark ID returned from bookmark: :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). .. seealso:: `delete_bookmark` `rollback` `transaction` `temporary_transaction` .. py:method:: bookmark() -> int Sets a bookmark to the current location :returns: bookmark ID Remarks: - Bookmarks can be used to implement transactions. .. seealso:: `delete_bookmark` `rollback` `transaction` `temporary_transaction` .. py:method:: rollback(bookmark_id: int) -> bool Rolls back to the given bookmark ID :param bookmark_id The bookmark ID returned from bookmark: 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) .. seealso:: `delete_bookmark` `rollback` `transaction` `temporary_transaction` .. py:method:: set_state(t: int, storage: numpy.array, wallet: float, loans: float, line_schedules: numpy.array) -> None Sets the current state at the given time-step. It implicitly causes a fix_before(t + 1) :param t: Time step to set the state at :param storage: quantity of every product (array of integers of size `n_products`) :param wallet: Cash in wallet :param loans: Loans :param line_schedules: Line schedules (array of process numbers/NO_PRODUCTION of size `n_lines`) .. py:function:: transaction(simulator) Runs the simulated actions then confirms them if they are not rolled back .. py:function:: temporary_transaction(simulator) Runs the simulated actions then rolls them back .. py:function:: anac2019_world(competitors: Sequence[Union[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 Creates a world compatible with the ANAC 2019 competition. Note that :param n_agents_per_competitor: Number of instantiations of each competing type. :param name: SCML2020World name to use :param agent_names_reveal_type: If true, a snake_case version of the agent_type will prefix agent names :param randomize: If true, managers are assigned to factories randomly otherwise in the order :param they are giving: :type they are giving: cycling :param n_intermediate: :param n_default_per_level: :param competitors: A list of class names for the competitors :param params: A list of dictionaries giving parameters to pass to the competitors :param n_miners: number of miners of the single raw material :param n_factories_per_level: number of factories at every production level :param n_consumers: number of consumers of the final product :param n_steps: number of simulation steps :param n_lines_per_factory: number of lines in each factory :param negotiation_speed: The number of negotiation steps per simulation step. None means infinite :param default_signing_delay: The number of simulation between contract conclusion and signature :param neg_n_steps: The maximum number of steps of a single negotiation (that is double the number of rounds) :param neg_time_limit: The total time-limit of a single negotiation :param time_limit: The total time-limit of the simulation :param transportation_delay: The transportation delay :param n_retrials: The number of retrials the `Miner` and `GreedyFactoryManager` will try if negotiations fail :param max_insurance_premium: The maximum insurance premium accepted by `GreedyFactoryManager` (-1 to disable) :param use_consumer: If true, the `GreedyFactoryManager` will use an internal consumer for buying its needs :param guaranteed_contracts: If true, the `GreedyFactoryManager` will only sign contracts that it can guaratnee not to :param break.: :param consumption_horizon: The number of steps for which `Consumer` publishes `CFP` s :param consumption: The consumption schedule will be sampled from a uniform distribution with these limits inclusive :param log_file_name: File name to store the logs :param negotiator_type: The negotiation factory used to create all negotiators :param max_storage: maximum storage capacity for all factory managers If None then it is unlimited :param compact: If True, then compact logs will be created to reduce memory footprint :param 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 .. py:function:: anac2019_tournament(competitors: Sequence[Union[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: Optional[int] = None, parallelism='parallel', scheduler_ip: Optional[str] = None, scheduler_port: Optional[str] = None, tournament_progress_callback: Callable[[Optional[negmas.tournaments.WorldRunResults]], None] = None, world_progress_callback: Callable[[Optional[scml.scml2019.world.SCML2019World]], None] = None, name: str = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) -> Union[negmas.tournaments.TournamentResults, os.PathLike] The function used to run ANAC 2019 SCML tournament (collusion track). :param name: Tournament name :param competitors: A list of class names for the competitors :param agent_names_reveal_type: If true then the type of an agent should be readable in its name (most likely at its beginning). :param n_configs: The number of different world configs (up to competitor assignment) to be generated. :param 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). :param n_runs_per_world: Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration. :param n_agents_per_competitor: Number of agents per competitor :param total_timeout: Total timeout for the complete process :param tournament_path: Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs :param parallelism: Type of parallelism. Can be 'serial' for serial, 'parallel' for parallel and 'distributed' for distributed :param scheduler_port: Port of the dask scheduler if parallelism is dask, dist, or distributed :param scheduler_ip: IP Address of the dask scheduler if parallelism is dask, dist, or distributed :param 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). :param tournament_progress_callback: A function to be called with `WorldRunResults` after each world finished processing :param verbose: Verbosity :param configs_only: If true, a config file for each :param compact: If true, effort will be made to reduce memory footprint including disableing most logs :param kwargs: Arguments to pass to the `world_generator` function :returns: `TournamentResults` The results of the tournament or a `PathLike` giving the location where configs were saved Remarks: Default parameters will be used in the league with the exception of `parallelism` which may use distributed processing .. py:function:: anac2019_collusion(competitors: Sequence[Union[str, Type[scml.scml2019.factory_managers.builtins.FactoryManager]]], competitor_params: Optional[Sequence[Dict[str, Any]]] = None, agent_names_reveal_type=False, n_configs: int = 5, max_worlds_per_config: Optional[int] = 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: Optional[int] = None, parallelism='parallel', scheduler_ip: Optional[str] = None, scheduler_port: Optional[str] = None, tournament_progress_callback: Callable[[Optional[negmas.tournaments.WorldRunResults]], None] | None = None, world_progress_callback: Callable[[Optional[scml.scml2019.world.SCML2019World]], None] | None = None, non_competitors: Optional[Sequence[Union[str, Type[scml.scml2019.factory_managers.builtins.FactoryManager]]]] = None, non_competitor_params: Optional[Sequence[Dict[str, Any]]] = None, name: str | None = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) -> Union[negmas.tournaments.TournamentResults, os.PathLike] The function used to run ANAC 2019 SCML tournament (collusion track). :param name: Tournament name :param competitors: A list of class names for the competitors :param competitor_params: A list of competitor parameters (used to initialize the competitors). :param agent_names_reveal_type: If true then the type of an agent should be readable in its name (most likely at its beginning). :param n_configs: The number of different world configs (up to competitor assignment) to be generated. :param 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). :param n_runs_per_world: Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration. :param n_agents_per_competitor: Number of agents per competitor :param min_factories_per_level: Minimum number of factories for each production level :param total_timeout: Total timeout for the complete process :param tournament_path: Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs :param parallelism: Type of parallelism. Can be 'serial' for serial, 'parallel' for parallel and 'distributed' for distributed :param scheduler_port: Port of the dask scheduler if parallelism is dask, dist, or distributed :param scheduler_ip: IP Address of the dask scheduler if parallelism is dask, dist, or distributed :param 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). :param tournament_progress_callback: A function to be called with `WorldRunResults` after each world finished processing :param non_competitors: A list of agent types that will not be competing in the sabotage competition but will exist in the world :param non_competitor_params: parameters of non competitor agents :param verbose: Verbosity :param configs_only: If true, a config file for each :param compact: If true, compact logs will be created and effort will be made to reduce the memory footprint :param kwargs: Arguments to pass to the `world_generator` function :returns: `TournamentResults` The results of the tournament or a `PathLike` giving the location where configs were saved Remarks: Default parameters will be used in the league with the exception of `parallelism` which may use distributed processing .. py:function:: anac2019_std(competitors: Sequence[Union[str, Type[scml.scml2019.factory_managers.builtins.FactoryManager]]], competitor_params: Optional[Sequence[Dict[str, Any]]] = None, agent_names_reveal_type=False, n_configs: int = 5, max_worlds_per_config: Optional[int] = 1000, n_runs_per_world: int = 5, min_factories_per_level: int = 5, tournament_path: str = None, total_timeout: Optional[int] = None, parallelism='parallel', scheduler_ip: Optional[str] = None, scheduler_port: Optional[str] = None, tournament_progress_callback: Callable[[Optional[negmas.tournaments.WorldRunResults]], None] = None, world_progress_callback: Callable[[Optional[scml.scml2019.world.SCML2019World]], None] = None, non_competitors: Optional[Sequence[Union[str, Type[scml.scml2019.factory_managers.builtins.FactoryManager]]]] = None, non_competitor_params: Optional[Sequence[Union[str, Type[scml.scml2019.factory_managers.builtins.FactoryManager]]]] = None, name: str = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) -> Union[negmas.tournaments.TournamentResults, os.PathLike] The function used to run ANAC 2019 SCML tournament (standard track). :param name: Tournament name :param competitors: A list of class names for the competitors :param competitor_params: A list of competitor parameters (used to initialize the competitors). :param agent_names_reveal_type: If true then the type of an agent should be readable in its name (most likely at its beginning). :param n_configs: The number of different world configs (up to competitor assignment) to be generated. :param 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). :param n_runs_per_world: Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration. :param min_factories_per_level: Minimum number of factories for each production level :param total_timeout: Total timeout for the complete process :param tournament_path: Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs :param parallelism: Type of parallelism. Can be 'serial' for serial, 'parallel' for parallel and 'distributed' for distributed :param scheduler_port: Port of the dask scheduler if parallelism is dask, dist, or distributed :param scheduler_ip: IP Address of the dask scheduler if parallelism is dask, dist, or distributed :param 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). :param tournament_progress_callback: A function to be called with `WorldRunResults` after each world finished processing :param non_competitors: A list of agent types that will not be competing in the sabotage competition but will exist in the world :param non_competitor_params: parameters of non competitor agents :param verbose: Verbosity :param configs_only: If true, a config file for each :param compact: If true, compact logs will be created and effort will be made to reduce the memory footprint :param kwargs: Arguments to pass to the `world_generator` function :returns: `TournamentResults` The results of the tournament or a `PathLike` giving the location where configs were saved Remarks: Default parameters will be used in the league with the exception of `parallelism` which may use distributed processing .. py:function:: balance_calculator(worlds: List[scml.scml2019.world.SCML2019World], scoring_context: Dict[str, Any], dry_run: bool, ignore_default=True) -> negmas.tournaments.WorldRunResults A scoring function that scores factory managers' performance by the final balance only ignoring whatever still in their inventory. :param worlds: The world which is assumed to be run up to the point at which the scores are to be calculated. :param scoring_context: A dict of context parameters passed by the world generator or assigner. :param 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. .. py:function:: anac2019_sabotage(competitors: Sequence[Union[str, Type[scml.scml2019.factory_managers.builtins.FactoryManager]]], competitor_params: Optional[Sequence[Dict[str, Any]]] = None, agent_names_reveal_type=False, n_configs: int = 5, max_worlds_per_config: Optional[int] = 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: Optional[int] = None, parallelism='parallel', scheduler_ip: Optional[str] = None, scheduler_port: Optional[str] = None, tournament_progress_callback: Callable[[Optional[negmas.tournaments.WorldRunResults]], None] = None, world_progress_callback: Callable[[Optional[scml.scml2019.world.SCML2019World]], None] = None, non_competitors: Optional[Sequence[Union[str, Type[scml.scml2019.factory_managers.builtins.FactoryManager]]]] = None, non_competitor_params: Optional[Sequence[Union[str, Type[scml.scml2019.factory_managers.builtins.FactoryManager]]]] = None, name: str = None, verbose: bool = False, configs_only=False, compact=False, **kwargs) -> Union[negmas.tournaments.TournamentResults, os.PathLike] The function used to run ANAC 2019 SCML tournament (collusion track). :param name: Tournament name :param competitors: A list of class names for the competitors :param competitor_params: A list of competitor parameters (used to initialize the competitors). :param agent_names_reveal_type: If true then the type of an agent should be readable in its name (most likely at its beginning). :param n_configs: The number of different world configs (up to competitor assignment) to be generated. :param 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). :param n_runs_per_world: Number of runs per world. All of these world runs will have identical competitor assignment and identical world configuration. :param n_agents_per_competitor: Number of agents per competitor :param min_factories_per_level: Minimum number of factories for each production level :param total_timeout: Total timeout for the complete process :param tournament_path: Path at which to store all results. A scores.csv file will keep the scores and logs folder will keep detailed logs :param parallelism: Type of parallelism. Can be 'serial' for serial, 'parallel' for parallel and 'distributed' for distributed :param scheduler_port: Port of the dask scheduler if parallelism is dask, dist, or distributed :param scheduler_ip: IP Address of the dask scheduler if parallelism is dask, dist, or distributed :param 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). :param tournament_progress_callback: A function to be called with `WorldRunResults` after each world finished processing :param non_competitors: A list of agent types that will not be competing in the sabotage competition but will exist in the world :param non_competitor_params: parameters of non competitor agents :param verbose: Verbosity :param configs_only: If true, a config file for each :param compact: If true, compact logs will be created and effort will be made to reduce the memory footprint :param kwargs: Arguments to pass to the `world_generator` function :returns: `TournamentResults` The results of the tournament or a `PathLike` giving the location where configs were saved Remarks: Default parameters will be used in the league with the exception of `parallelism` which may use distributed processing .. py:class:: 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) Bases: :py:obj:`scml.scml2019.factory_managers.builtins.GreedyFactoryManager` The default factory manager that will be implemented by the committee of ANAC-SCML 2019 .. py:class:: 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: Optional[List[scml.scml2019.factory_managers.builtins.FactoryManager]] = None, n_steps=100, time_limit=60 * 90, mechanisms: Optional[Dict[str, Dict[str, Any]]] = 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: Optional[int] = 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) Bases: :py:obj:`negmas.situated.TimeInAgreementMixin`, :py:obj:`negmas.situated.World` The `SCML2020World` class running a simulation of supply chain management. .. py:attribute:: compact :value: False .. py:attribute:: prevent_cfp_tampering :value: False .. py:attribute:: ignore_negotiated_penalties :value: False .. py:attribute:: compensation_fraction :value: 0.5 .. py:attribute:: save_mechanism_state_in_contract :value: False .. py:attribute:: default_price_for_products_without_one :value: 1 .. py:attribute:: agents :type: Dict[str, scml.scml2019.agent.SCML2019Agent] .. py:attribute:: strip_annotations :value: True .. py:attribute:: minimum_balance :value: 0 .. py:attribute:: money_resolution :value: 0.5 .. py:attribute:: transportation_delay :value: 0 .. py:attribute:: breach_penalty_society :value: 0.1 .. py:attribute:: breach_move_max_product :value: True .. py:attribute:: breach_penalty_society_min :value: 0.0 .. py:attribute:: penalties :value: 0.0 .. py:attribute:: financial_reports_period :value: 10 .. py:attribute:: max_allowed_breach_level :value: None .. py:attribute:: catalog_profit :value: 0.15 .. py:attribute:: loan_installments :value: 1 .. py:attribute:: breach_penalty_victim :value: 0.0 .. py:attribute:: avg_process_cost_is_public :value: True .. py:attribute:: catalog_prices_are_public :value: True .. py:attribute:: initial_wallet_balances :value: None .. py:attribute:: products :type: List[scml.scml2019.common.Product] :value: [] .. py:attribute:: processes :type: List[scml.scml2019.common.Process] :value: [] .. py:attribute:: factory_managers :type: List[scml.scml2019.factory_managers.builtins.FactoryManager] :value: [] .. py:attribute:: miners :type: List[scml.scml2019.miners.Miner] :value: [] .. py:attribute:: consumers :type: List[scml.scml2019.consumers.Consumer] :value: [] .. py:attribute:: factories .. py:attribute:: _report_receivers :type: Dict[str, Set[scml.scml2019.agent.SCML2019Agent]] .. py:attribute:: f2a :type: Dict[str, scml.scml2019.agent.SCML2019Agent] .. py:attribute:: a2f :type: Dict[str, scml.scml2019.common.Factory] .. py:attribute:: __interested_agents :type: List[List[scml.scml2019.agent.SCML2019Agent]] .. py:attribute:: n_new_cfps :value: 0 .. py:attribute:: __n_nullified :value: 0 .. py:attribute:: __n_bankrupt :value: 0 .. py:attribute:: _transport :type: Dict[int, List[Tuple[scml.scml2019.agent.SCML2019Agent, int, int]]] .. py:attribute:: _transfer :type: Dict[int, List[Tuple[scml.scml2019.agent.SCML2019Agent, float]]] .. py:attribute:: transfer_delay :value: 0 .. py:attribute:: _n_production_failures :value: 0 .. py:attribute:: bank .. py:attribute:: insurance_company .. py:attribute:: traders .. py:method:: join(x: negmas.situated.Agent, simulation_priority: int = 0) Add an agent to the world. :param x: The agent to be registered :param simulation_priority: The simulation priority. Entities with lower priorities will be stepped first during Returns: .. py:method:: save_config(file_name: str) -> None Saves the config of the world as a yaml file :param file_name: Name of file to save the config to Returns: .. py:method:: assign_managers(factory_managers=Iterable[Union[str, Type[FactoryManager], FactoryManager]], params: Optional[Iterable[Dict[str, Any]]] = None) -> None Assigns existing factories to new factory managers created from the given types and parameters or manager objects. :param factory_managers: An iterable of `FactoryManager` objects type names or `FactoryManager` types to assign to :param params: parameters of the newly created managers Remarks: - factories are assigned in the same order they exist in the local `factories` attribute cycling through the input managers or types/params - If a `FactoryManager` object is given instead of a type or a string in the `factory_managers` collection, and the number of `factory_managers` is less than the number of factories in the world causing this object to cycle for more than one factory, it is assigned to the first such factory but then deep copies of it with new ids and names are assigned to the rest of the factories. That ensures that each manager has exactly one factory and that all factories are assigned exactly one unique manager. .. py:method:: 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) :classmethod: .. py:method:: chain_world(n_intermediate_levels=0, n_miners=5, n_factories_per_level=5, n_consumers: Union[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: Union[str, Type[scml.scml2019.miners.Miner]] = ReactiveMiner, consumer_type: Union[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: Union[int, Tuple[int, int]] = (0, 5), consumer_kwargs: Dict[str, Any] = None, negotiation_speed: Optional[int] = 21, manager_types: Sequence[Type[scml.scml2019.factory_managers.builtins.FactoryManager]] = (GreedyFactoryManager, ), manager_params: Optional[Sequence[Dict[str, Any]]] = 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: Union[float, Tuple[float, float]] = (1.0, 5.0), process_time: Union[int, Tuple[int, int]] = 1, interest_rate=float('inf'), interest_max=float('inf'), shared_profile_per_factory=False, **kwargs) :classmethod: 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 :param n_max_assignable_factories: The maximum number of factories assigned to managers other than the default :param randomize: If true, the factory assignment is randomized :param n_default_per_level: The number of `GreedyFactoryManager` objects guaranteed at every level :param default_factory_manager_type: The `FactoryManager` type to use as the base for default_factory_managers. You can specify how many of this type exist at every level by specifying `n_default_per_level`. If `n_default_per_level` is zero, this parameter has no effect. :param manager_types: A sequence of factory manager types to control the factories. :param manager_params: An optional sequence of dictionaries giving the parameters to pass to `manager_types`. :param consumer_type: Consumer type to use for all consumers :param miner_type: Miner type to use for all miners :param consumption: Consumption schedule :param n_intermediate_levels: The number of intermediate products :param n_miners: number of miners of the single raw material :param n_factories_per_level: number of factories at every production level :param n_consumers: number of consumers of the final product :param n_steps: number of simulation steps :param n_lines_per_factory: number of lines in each factory :param process_cost: The range of process costs. A uniform distribution will be used :param process_time: The range of process times. A uniform distribution will be used :param log_file_name: File name to store the logs :param agent_names_reveal_type: If true, agent names will start with a snake_case version of their type name :param negotiator_type: The negotiation factory used to create all negotiators :param max_storage: maximum storage capacity for all factory managers If None then it is unlimited :param default_manager_params: keyword arguments to be used for constructing factory managers :param consumer_kwargs: keyword arguments to be used for constructing consumers :param miner_kwargs: keyword arguments to be used for constructing miners :param negotiation_speed: The number of negotiation steps per simulation step. None means infinite :param interest_max: Maximum interest rate :param interest_rate: Minimum interest rate :param initial_wallet_balances: initial wallet balances for all factories :param shared_profile_per_factory: If true, all lines in the same factory will have the same profile costs :param 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 .. py:method:: random(n_raw_materials: Union[int, Tuple[int, int]] = (5, 10), raw_material_price: Union[float, Tuple[float, float]] = (1.0, 30.0), n_final_products: Union[int, Tuple[int, int]] = (3, 5), n_production_levels: Union[int, Tuple[int, int]] = (3, 5), n_products_per_level: Union[int, Tuple[int, int]] = (3, 5), n_processes_per_level: Union[int, Tuple[int, int]] = (6, 10), n_inputs_per_process: Union[int, Tuple[int, int]] = (2, 5), bias_toward_last_level_products: float = 0.0, quantity_per_input: Union[int, Tuple[int, int]] = (1, 10), input_step: Union[float, Tuple[float, float]] = 0.0, quantity_per_output: Union[int, Tuple[int, int]] = (1, 1), output_step: Union[float, Tuple[float, float]] = 1.0, process_relative_cost: Union[float, Tuple[float, float]] = (0.05, 0.4), n_outputs_per_process: Union[int, Tuple[int, int]] = (1, 1), n_lines: Union[int, Tuple[int, int]] = (3, 5), lines_are_similar: bool = False, n_processes_per_line: Union[int, Tuple[int, int]] = None, cost_for_line: Union[float, Tuple[float, float]] = (5.0, 50.0), n_production_steps: Union[int, Tuple[int, int]] = (2, 10), max_storage: Union[int, Tuple[int, int]] = 2000, n_factories: Union[int, Tuple[int, int]] = 20, n_consumers: Union[int, Tuple[int, int]] = 5, n_products_per_consumer: Union[int, Tuple[int, int]] = None, n_miners: Union[int, Tuple[int, int]] = 5, n_products_per_miner: Optional[Union[int, Tuple[int, int]]] = None, factory_manager_types: Union[Type[scml.scml2019.factory_managers.builtins.FactoryManager], List[Type[scml.scml2019.factory_managers.builtins.FactoryManager]]] = GreedyFactoryManager, consumer_types: Union[Type[scml.scml2019.consumers.Consumer], List[Type[scml.scml2019.consumers.Consumer]]] = JustInTimeConsumer, miner_types: Union[Type[scml.scml2019.miners.Miner], List[Type[scml.scml2019.miners.Miner]]] = ReactiveMiner, negotiator_type=DEFAULT_NEGOTIATOR, initial_wallet_balance: Union[float, Tuple[float, float]] = 1000, factory_kwargs: Dict[str, Any] = None, miner_kwargs: Dict[str, Any] = None, consumer_kwargs: Dict[str, Any] = None, **kwargs) :classmethod: Creates a random SCML scenario with adjustable parameters. :param n_raw_materials: Number of raw materials. Can be a value or a range. :param raw_material_price: Catalog prices for raw materials. Can be a value or a range. :param n_final_products: Number of final products. Can be a value or a range. :param n_production_levels: How deep is the production graph (number of intermediate products). Can be a value or :param a range.: :param n_products_per_level: How many intermediate products per intermediate level. Can be a value or a range. :param n_processes_per_level: Number of processes in intermediate levels. Can be a value or a range. :param n_inputs_per_process: Number of inputs per process. Can be a value or a range. :param bias_toward_last_level_products: How biased are production processes toward using products from the last :param level below them: :type level below them: 0 means not bias, 1 means only sample from this last level :param quantity_per_input: How many items are needed for each input to a process. Can be a value or a range. :param input_step: When are inputs consumed during the production process. Can be a value or a range. Default 0 :param quantity_per_output: How many items are produced per output. Can be a value or a range. :param output_step: When are outputs created during the production process. Can be a value or a range. Default 1 :param process_relative_cost: Intrinsic relative cost of processes [Outputs will be produced :param at a cost of sum: :type at a cost of sum: input costs) * (1 + process_relative_cost :param n_outputs_per_process: Number of outputs per process. Can be a value or a range. :param n_lines: Number of lines per factory. Can be a value or a range. :param lines_are_similar: If true then all lins of the same factory will have the same production processes. :param n_processes_per_line: Number of processes that can be run on each line per factory. Can be a value or a :param range.: :param cost_for_line: Cost for running a process on a line. Can be a value or a range. :param n_production_steps: Number of production steps per line. Can be a value or a range. :param max_storage: Maximum storage per factory. Can be a value or a range. :param n_factories: Number of factories. Can be a value or a range. :param n_consumers: Number of consumers. Can be a value or a range. :param n_products_per_consumer: Number of products per miner. If None then all final products will be assigned to :param every customer. Can be a value or a range.: :param n_miners: Number of miners. Can be a value or a range. :param n_products_per_miner: Number of products per miner. If None then all raw materials will be assigned to every :param miner. Can be a value or a range.: :param factory_manager_types: A callable for creating factory managers for the factories :param consumer_types: A callable for creating `Consumer` objects :param miner_types: A callable for creating `Miner` objects :param negotiator_type: A string that can be `eval`uated to a negotiator. :param initial_wallet_balance: The initial balance of all wallets :param factory_kwargs: keyword arguments to be used for constructing factory managers :param consumer_kwargs: keyword arguments to be used for constructing consumers :param miner_kwargs: keyword arguments to be used for constructing miners :param \*\*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 .. py:method:: _update_dynamic_product_process_info() Updates the catalog prices of all products based on the prices of their inputs .. py:method:: set_consumers(consumers: List[scml.scml2019.consumers.Consumer]) .. py:method:: set_miners(miners: List[scml.scml2019.miners.Miner]) .. py:method:: set_factory_managers(factory_managers: Optional[List[scml.scml2019.factory_managers.builtins.FactoryManager]]) .. py:method:: set_processes(processes: Collection[scml.scml2019.common.Process]) .. py:method:: set_products(products: Collection[scml.scml2019.common.Product]) .. py:method:: order_contracts_for_execution(contracts: Collection[negmas.situated.Contract]) Orders the contracts in a specific time-step that are about to be executed .. py:method:: execute_action(action: negmas.situated.Action, agent: negmas.situated.Agent, callback: Callable[[negmas.situated.Action, bool], Any] = None) -> bool Executes the given action by the given agent .. py:method:: get_private_state(agent: negmas.situated.Agent) -> scml.scml2019.common.FactoryState Reads the private state of the given agent .. py:method:: receive_financial_reports(agent: scml.scml2019.agent.SCML2019Agent, receive: bool, agents: Optional[List[str]]) Registers interest/disinterest in receiving financial reports .. py:method:: simulation_step(stage) A step of SCML simulation .. py:method:: pre_step_stats() Called at the beginning of the simulation step to prepare stats or update them Kept for backward compatibility and will be dropped. Override `update_stats` instead .. py:method:: post_step_stats() Saves relevant stats .. py:method:: start_contract_execution(contract: negmas.situated.Contract) -> Set[negmas.situated.Breach] Tries to execute the contract :param contract: :returns: The set of breaches committed if any. If there are no breaches return an empty set :rtype: 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). .. py:method:: _move_product(buyer: scml.scml2019.agent.SCML2019Agent, seller: scml.scml2019.agent.SCML2019Agent, product_id: int, quantity: int, money: float) Moves as much product and money between the buyer and seller .. py:method:: complete_contract_execution(contract: negmas.situated.Contract, breaches: List[negmas.situated.Breach], resolution: Optional[negmas.situated.Contract]) 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 .. py:method:: _move_product_force(buyer: scml.scml2019.agent.SCML2019Agent, seller: scml.scml2019.agent.SCML2019Agent, product_id: int, quantity: int, money: float) Moves as much product and money between the buyer and seller .. py:method:: register_interest(agent: scml.scml2019.agent.SCML2019Agent, products: List[int]) -> None .. py:method:: unregister_interest(agent: scml.scml2019.agent.SCML2019Agent, products: List[int]) -> None .. py:method:: make_bankrupt(agent: scml.scml2019.agent.SCML2019Agent, amount: float, beneficiary: negmas.situated.Agent, contract: Optional[negmas.situated.Contract]) -> None Marks the agent as bankrupt .. py:method:: nullify_contract(contract: negmas.situated.Contract) .. py:method:: evaluate_insurance(contract: negmas.situated.Contract, agent: scml.scml2019.agent.SCML2019Agent, t: int = None) -> Optional[float] Can be called to evaluate the premium for insuring the given contract against breachs committed by others :param agent: The agent buying the contract :param contract: hypothetical contract :param t: time at which the policy is to be bought. If None, it means current step .. py:method:: buy_insurance(contract: negmas.situated.Contract, agent: scml.scml2019.agent.SCML2019Agent) -> bool 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. .. py:method:: _process_annotation(annotation: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]] Processes an annotation stripping any extra information not allowed if necessary. Will return None if the annotation is suspecious .. py:method:: 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: Optional[Dict[str, Any]] = None, mechanism_name: str = None, mechanism_params: Dict[str, Any] = None) -> Optional[Tuple[negmas.situated.Contract, negmas.NegotiatorMechanismInterface]] Runs a negotiation until completion :param caller: The agent requesting the negotiation :param partners: A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/`Agent` or as a list containing a single string/`Agent`, then he caller will be added at the beginning of the list. This will only be done if `roles` was passed as None. :param negotiator: The negotiator to be used in the negotiation :param preferences: The utility function. Only needed if the negotiator does not already know it :param caller_role: The role of the caller in the negotiation :param issues: Negotiation issues :param annotation: Extra information to be passed to the `partners` when asking them to join the negotiation :param partners: A list of partners to participate in the negotiation :param roles: The roles of different partners. If None then each role for each partner will be None :param mechanism_name: Name of the mechanism to use. It must be one of the mechanism_names that are supported by the :param `World` or None which means that the `World` should select the mechanism. If None: :param then `roles` and `my_role`: :param must also be None: :param 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 .. py:method:: run_negotiations(caller: negmas.situated.Agent, issues: Union[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: Optional[List[Optional[List[str]]]] = None, annotations: Optional[List[Optional[Dict[str, Any]]]] = None, mechanism_names: Optional[Union[str, List[str]]] = None, mechanism_params: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None, all_or_none: bool = False) -> List[Tuple[negmas.situated.Contract, negmas.NegotiatorMechanismInterface]] Requests to run a set of negotiations simultaneously. Returns after all negotiations are run to completion :param caller: The agent requesting the negotiation :param partners: A list of list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners[i] is passed as a single string/`Agent` or as a list containing a single string/`Agent`, then he caller will be added at the beginning of the list. This will only be done if `roles` was passed as None. :param issues: Negotiation issues :param negotiators: The negotiator to be used in the negotiation :param ufuns: The utility function. Only needed if the negotiator does not already know it :param caller_roles: The role of the caller in the negotiation :param annotations: Extra information to be passed to the `partners` when asking them to join the negotiation :param partners: A list of partners to participate in the negotiation :param roles: The roles of different partners. If None then each role for each partner will be None :param mechanism_names: Name of the mechanism to use. It must be one of the mechanism_names that are supported by the :param `World` or None which means that the `World` should select the mechanism. If None: :param then `roles` and `my_role`: :param must also be None: :param mechanism_params: A dict of parameters used to initialize the mechanism object :param 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]) :rtype: A list of tuples each with two values .. py:method:: 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: Optional[Dict[str, Any]] = None, mechanism_name: str = None, mechanism_params: Dict[str, Any] = None, group=None) Requests to start a negotiation with some other agents :param req_id: An ID For the request that is unique to the caller :param caller: The agent requesting the negotiation :param partners: A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/`Agent` or as a list containing a single string/`Agent`, then he caller will be added at the beginning of the list. This will only be done if `roles` was passed as None. :param issues: Negotiation issues :param annotation: Extra information to be passed to the `partners` when asking them to join the negotiation :param partners: A list of partners to participate in the negotiation :param roles: The roles of different partners. If None then each role for each partner will be None :param mechanism_name: Name of the mechanism to use. It must be one of the mechanism_names that are supported by the :param `World` or None which means that the `World` should select the mechanism. If None: :param then `roles` and `my_role`: :param must also be None: :param mechanism_params: A dict of parameters used to initialize the mechanism object :param group: An identifier for the group to which the negotiation belongs. This is not not used by the system. :returns: None. The caller will be informed by a callback function `on_neg_request_accepted` or `on_neg_request_rejected` about the status of the negotiation. .. py:property:: winners The winners of this world (factory managers with maximum wallet balance .. py:method:: on_event(event: negmas.events.Event, sender: negmas.events.EventSource) -> None Called whenever an event is raised for which the `SCML2020World` is registered asa listener :param event: The event :param sender: The sender :returns: None .. py:method:: contract_record(contract: negmas.situated.Contract) -> Dict[str, Any] Converts a contract to a record suitable for permanent storage .. py:method:: breach_record(breach: negmas.situated.Breach) -> Dict[str, Any] Converts a breach to a record suitable for storage during the simulation .. py:method:: contract_size(contract: negmas.situated.Contract) -> float Returns an estimation of the **activity level** associated with this contract. Higher is better :param contract: Returns: .. py:function:: builtin_agent_types(as_str=False) Returns all built-in agents. :param as_str: If true, the full type name will be returned otherwise the type object itself. .. py:data:: __all__ .. py:class:: SCML2020Agent(name: str | None = None, type_postfix: str = '', preferences: negmas.preferences.Preferences | None = None, ufun: negmas.preferences.UtilityFunction | None = None) Bases: :py:obj:`negmas.Agent` Base class for all SCML2020 agents (factory managers) .. py:method:: reset() .. py:method:: is_clean() -> bool .. py:method:: init() Called to initialize the agent **after** the world is initialized. the AWI is accessible at this point. .. py:method:: before_step() .. py:method:: step_() Called at every time-step. This function is called directly by the world. .. py:method:: step() Called by the simulator at every simulation step .. py:method:: to_dict() .. py:method:: _respond_to_negotiation_request(initiator: str, partners: List[str], issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, role: Optional[str], req_id: Optional[str]) -> Optional[negmas.Negotiator] Called by the mechanism to ask for joining a negotiation. The agent can refuse by returning a None :param initiator: The ID of the agent that initiated the negotiation request :param partners: The partner list (will include this agent) :param issues: The list of issues :param annotation: Any annotation specific to this negotiation. :param mechanism: The mechanism that started the negotiation :param role: The role of this agent in the negotiation :param 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 .. py:method:: on_contract_breached(contract: negmas.Contract, breaches: List[negmas.Breach], resolution: Optional[negmas.Contract]) -> None Called after complete processing of a contract that involved a breach. :param contract: The contract :param breaches: All breaches committed (even if they were resolved) :param resolution: The resolution contract if re-negotiation was successful. None if not. .. py:method:: on_contract_executed(contract: negmas.Contract) -> None Called after successful contract execution for which the agent is one of the partners. .. py:method:: set_renegotiation_agenda(contract: negmas.Contract, breaches: List[negmas.Breach]) -> Optional[negmas.RenegotiationRequest] Received by partners in ascending order of their total breach levels in order to set the renegotiation agenda when contract execution fails :param contract: The contract being breached :param breaches: All breaches on `contract` :returns: Renegotiation agenda (issues to negotiate about to avoid reporting the breaches). .. py:method:: respond_to_renegotiation_request(contract: negmas.Contract, breaches: List[negmas.Breach], agenda: negmas.RenegotiationRequest) -> Optional[negmas.Negotiator] Called to respond to a renegotiation request :param agenda: :param contract: :param breaches: Returns: .. py:method:: on_neg_request_rejected(req_id: str, by: Optional[List[str]]) Called when a requested negotiation is rejected :param req_id: The request ID passed to _request_negotiation :param by: A list of agents that refused to participate or None if the failure was for another reason .. py:method:: on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface) Called when a requested negotiation is accepted .. py:property:: internal_state :type: Dict[str, Any] Returns the internal state of the agent for debugging purposes .. py:method:: on_negotiation_failure(partners: List[str], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, state: negmas.MechanismState) -> None Called whenever a negotiation ends without agreement .. py:method:: on_negotiation_success(contract: negmas.Contract, mechanism: negmas.NegotiatorMechanismInterface) -> None Called whenever a negotiation ends with agreement .. py:method:: on_agent_bankrupt(agent: str, contracts: List[negmas.Contract], quantities: List[int], compensation_money: int) -> None Called whenever a contract is nullified (because the partner is bankrupt) :param agent: The ID of the agent that went bankrupt. :param contracts: All future contracts between this agent and the bankrupt agent. :param quantities: The actual quantities that these contracts will be executed at. :param compensation_money: The compensation money that is already added to the agent's wallet (if ANY). Remarks: - compensation_money will be nonzero iff immediate_compensation is enabled for this world .. py:method:: on_failures(failures: List[scml.scml2020.common.Failure]) -> None Called whenever there are failures either in production or in execution of guaranteed transactions :param failures: A list of `Failure` s. .. py:method:: respond_to_negotiation_request(initiator: str, issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) -> Optional[negmas.Negotiator] Called whenever another agent requests a negotiation with this agent. :param initiator: The ID of the agent that requested this negotiation :param issues: Negotiation issues :param annotation: Annotation attached with this negotiation :param mechanism: The `NegotiatorMechanismInterface` interface to the mechanism to be used for this negotiation. :returns: None to reject the negotiation, otherwise a negotiator .. py:method:: confirm_production(commands: numpy.ndarray, balance: int, inventory) -> numpy.ndarray Called just before production starts at every time-step allowing the agent to change what is to be produced in its factory :param commands: an n_lines vector giving the process to be run at every line (NO_COMMAND indicates nothing to be processed :param balance: The current balance of the factory :param inventory: an n_products vector giving the number of items available in the inventory of every product type. :returns: an n_lines vector giving the process to be run at every line (NO_COMMAND indicates nothing to be processed Remarks: - Not called in SCML2020 competition. - The inventory will contain zero items of all products that the factory does not buy or sell - The default behavior is to just retrun commands confirming production of everything. .. py:method:: sign_all_contracts(contracts: List[negmas.Contract]) -> List[Optional[str]] Signs all contracts .. py:class:: OneShotAdapter(oneshot_type: Union[str, scml.oneshot.agent.OneShotAgent], oneshot_params: Dict[str, Any], obj: Optional[scml.oneshot.agent.OneShotAgent] = None, name=None, type_postfix='', ufun=None) Bases: :py:obj:`scml.scml2020.components.signing.SignAll`, :py:obj:`scml.scml2020.components.production.DemandDrivenProductionStrategy`, :py:obj:`scml.scml2020.components.trading.MarketAwareTradePredictionStrategy`, :py:obj:`SCML2020Agent`, :py:obj:`negmas.situated.Adapter`, :py:obj:`scml.oneshot.mixins.OneShotUFunCreatorMixin` An adapter allowing agents developed for SCML-OneShot to run in `SCML2020World` simulations. .. py:attribute:: _obj :type: SCML2020Agent .. py:method:: init() Called to initialize the agent **after** the world is initialized. the AWI is accessible at this point. .. py:property:: price_multiplier .. py:method:: _make_issues(product) .. py:method:: before_step() .. py:method:: step() Called by the simulator at every simulation step .. py:method:: make_ufun(add_exogenous: bool) .. py:method:: to_dict() .. py:method:: respond_to_negotiation_request(initiator, issues, annotation, mechanism) Called whenever another agent requests a negotiation with this agent. :param initiator: The ID of the agent that requested this negotiation :param issues: Negotiation issues :param annotation: Annotation attached with this negotiation :param mechanism: The `NegotiatorMechanismInterface` interface to the mechanism to be used for this negotiation. :returns: None to reject the negotiation, otherwise a negotiator .. py:method:: get_disposal_cost() -> float .. py:method:: get_shortfall_penalty_mean() .. py:method:: get_disposal_cost_mean() .. py:method:: get_shortfall_penalty_dev() .. py:method:: get_disposal_cost_dev() .. py:method:: get_storage_cost_mean() .. py:method:: get_storage_cost_dev() .. py:method:: get_profile() .. py:method:: get_shortfall_penalty() .. py:method:: get_current_balance() .. py:method:: get_exogenous_output() -> Tuple[int, int] .. py:method:: get_exogenous_input() -> Tuple[int, int] .. py:property:: is_perishable :type: bool Are all products perishable (original design of OneShot) .. py:property:: current_disposal_cost :type: float Cost of storing one unit (penalizes buying too much/ selling too little) .. py:property:: current_storage_cost :type: float Cost of storing one unit (penalizes buying too much/ selling too little) .. py:property:: current_shortfall_penalty :type: float Cost of failure to deliver one unit (penalizes buying too little / selling too much) .. py:property:: allow_zero_quantity :type: bool Does negotiations allow zero quantity? .. py:class:: RandomAgent(*args, **kwargs) Bases: :py:obj:`scml.scml2020.agents.indneg.IndependentNegotiationsAgent` An agent that negotiates randomly. .. py:method:: create_ufun(is_seller: bool, issues=None, outcomes=None) Creates a utility function .. py:class:: DoNothingAgent(name: str | None = None, type_postfix: str = '', preferences: negmas.preferences.Preferences | None = None, ufun: negmas.preferences.UtilityFunction | None = None) Bases: :py:obj:`scml.scml2020.agent.SCML2020Agent` An agent that does nothing for the whole length of the simulation .. py:method:: respond_to_negotiation_request(initiator: str, issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) -> Optional[negmas.Negotiator] Called whenever another agent requests a negotiation with this agent. :param initiator: The ID of the agent that requested this negotiation :param issues: Negotiation issues :param annotation: Annotation attached with this negotiation :param mechanism: The `NegotiatorMechanismInterface` interface to the mechanism to be used for this negotiation. :returns: None to reject the negotiation, otherwise a negotiator .. py:method:: sign_all_contracts(contracts: List[negmas.Contract]) -> List[Optional[str]] Signs all contracts .. py:method:: on_contracts_finalized(signed: List[negmas.Contract], cancelled: List[negmas.Contract], rejectors: List[List[str]]) -> None Called for all contracts in a single step to inform the agent about which were finally signed and which were rejected by any agents (including itself) :param signed: A list of signed contracts. These are binding :param cancelled: A list of cancelled contracts. These are not binding :param rejectors: A list of lists where each of the internal lists gives the rejectors of one of the cancelled contracts. Notice that it is possible that this list is empty which means that the contract other than being rejected by any agents (if that was possible in the specific world). Remarks: The default implementation is to call `on_contract_signed` for singed contracts and `on_contract_cancelled` for cancelled contracts .. py:method:: step() Called by the simulator at every simulation step .. py:method:: init() Called to initialize the agent **after** the world is initialized. the AWI is accessible at this point. .. py:method:: on_agent_bankrupt(agent: str, contracts: List[negmas.Contract], quantities: List[int], compensation_money: int) -> None Called whenever a contract is nullified (because the partner is bankrupt) :param agent: The ID of the agent that went bankrupt. :param contracts: All future contracts between this agent and the bankrupt agent. :param quantities: The actual quantities that these contracts will be executed at. :param compensation_money: The compensation money that is already added to the agent's wallet (if ANY). Remarks: - compensation_money will be nonzero iff immediate_compensation is enabled for this world .. py:method:: on_failures(failures: List[scml.scml2020.common.Failure]) -> None Called whenever there are failures either in production or in execution of guaranteed transactions :param failures: A list of `Failure` s. .. py:method:: on_negotiation_failure(partners: List[str], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, state: negmas.MechanismState) -> None Called whenever a negotiation ends without agreement .. py:method:: on_negotiation_success(contract: negmas.Contract, mechanism: negmas.NegotiatorMechanismInterface) -> None Called whenever a negotiation ends with agreement .. py:method:: on_contract_cancelled(contract: negmas.Contract, rejectors: List[str]) -> None Called whenever at least a partner did not sign the contract .. py:method:: on_contract_executed(contract: negmas.Contract) -> None Called after successful contract execution for which the agent is one of the partners. .. py:method:: on_contract_breached(contract: negmas.Contract, breaches: List[negmas.Breach], resolution: Optional[negmas.Contract]) -> None Called after complete processing of a contract that involved a breach. :param contract: The contract :param breaches: All breaches committed (even if they were resolved) :param resolution: The resolution contract if re-negotiation was successful. None if not. .. py:class:: IndependentNegotiationsAgent(*args, **kwargs) Bases: :py:obj:`scml.scml2020.components.negotiation.IndependentNegotiationsManager`, :py:obj:`scml.scml2020.components.prediction.FixedTradePredictionStrategy`, :py:obj:`scml.scml2020.components.trading.ReactiveTradingStrategy`, :py:obj:`scml.scml2020.world.SCML2020Agent` Implements the base class for agents that negotiate independently with different partners. These agents do not take production capacity, availability of materials or any other aspects of the simulation into account. They are to serve only as baselines. Remarks: - `IndependentNegotiationsAgent` agents assume that each production process has one input type with the same index as itself and one output type with one added to the index (i.e. process $i$ takes product $i$ as input and creates product $i+1$ as output. - It does not assume that all lines have the same production cost (it uses the average cost though). - It does not assume that the agent has a single production process. .. py:method:: acceptable_unit_price(step: int, sell: bool) -> int Returns the maximum/minimum acceptable unit price for buying/selling at the given time-step :param step: Simulation step :param sell: Sell or buy .. py:method:: target_quantity(step: int, sell: bool) -> int Returns the target quantity to sell/buy at a given time-step :param step: Simulation step :param sell: Sell or buy .. py:class:: MarketAwareIndependentNegotiationsAgent(*args, buying_margin=None, selling_margin=None, min_price_margin=0.5, max_price_margin=0.5, **kwargs) Bases: :py:obj:`scml.scml2020.components.signing.KeepOnlyGoodPrices`, :py:obj:`IndependentNegotiationsAgent` Implements the base class for agents that negotiate independently with different partners using trading/catalog prices to control signing These agents do not take production capacity, availability of materials or any other aspects of the simulation into account. They are to serve only as baselines. Remarks: - `IndependentNegotiationsAgent` agents assume that each production process has one input type with the same index as itself and one output type with one added to the index (i.e. process $i$ takes product $i$ as input and creates product $i+1$ as output. - It does not assume that all lines have the same production cost (it uses the average cost though). - It does not assume that the agent has a single production process. .. py:class:: BuyCheapSellExpensiveAgent(*args, **kwargs) Bases: :py:obj:`scml.scml2020.agents.indneg.IndependentNegotiationsAgent` An agent that tries to buy cheap and sell expensive but does not care about production scheduling. .. py:method:: create_ufun(is_seller: bool, issues=None, outcomes=None) Creates a utility function .. py:class:: MarketAwareBuyCheapSellExpensiveAgent(*args, buying_margin=None, selling_margin=None, min_price_margin=0.5, max_price_margin=0.5, **kwargs) Bases: :py:obj:`scml.scml2020.agents.indneg.MarketAwareIndependentNegotiationsAgent`, :py:obj:`BuyCheapSellExpensiveAgent` An agent that tries to buy cheap and sell expensive but does not care about production scheduling. .. py:class:: DecentralizingAgent(*args, negotiator_type: Union[negmas.SAONegotiator, str] = AspirationNegotiator, negotiator_params: Optional[Dict[str, Any]] = None, **kwargs) Bases: :py:obj:`_NegotiationCallbacks`, :py:obj:`scml.scml2020.components.StepNegotiationManager`, :py:obj:`scml.scml2020.components.trading.PredictionBasedTradingStrategy`, :py:obj:`scml.scml2020.components.SupplyDrivenProductionStrategy`, :py:obj:`scml.scml2020.world.SCML2020Agent` A negotiation manager that controls a controller and another for selling for every timestep :param negotiator_type: The negotiator type to use to manage all negotiations :param negotiator_params: Paramters of the negotiator Provides: - `all_negotiations_concluded` Requires: - `acceptable_unit_price` - `target_quantity` - OPTIONALLY `target_quantities` Hooks Into: - `init` - `respond_to_negotiation_request` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:class:: IndDecentralizingAgent(*args, negotiator_type: Union[negmas.SAONegotiator, str] = AspirationNegotiator, negotiator_params: Optional[Dict[str, Any]] = None, **kwargs) Bases: :py:obj:`_NegotiationCallbacks`, :py:obj:`scml.scml2020.components.IndependentNegotiationsManager`, :py:obj:`scml.scml2020.components.trading.PredictionBasedTradingStrategy`, :py:obj:`scml.scml2020.components.SupplyDrivenProductionStrategy`, :py:obj:`scml.scml2020.world.SCML2020Agent` A negotiation manager that manages independent negotiators that do not share any information once created :param negotiator_type: The negotiator type to use to manage all negotiations :param negotiator_params: Parameters of the negotiator Requires: - `create_ufun` - `acceptable_unit_price` - `target_quantity` - OPTIONALLY `target_quantities` Hooks Into: - `respond_to_negotiation_request` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:method:: create_ufun(is_seller: bool, issues=None, outcomes=None) Creates a utility function .. py:class:: DecentralizingAgentWithLogging(*args, **kwargs) Bases: :py:obj:`_NegotiationCallbacks`, :py:obj:`scml.scml2020.components.StepNegotiationManager`, :py:obj:`scml.scml2020.components.trading.PredictionBasedTradingStrategy`, :py:obj:`scml.scml2020.components.SupplyDrivenProductionStrategy`, :py:obj:`scml.scml2020.world.SCML2020Agent` A negotiation manager that controls a controller and another for selling for every timestep :param negotiator_type: The negotiator type to use to manage all negotiations :param negotiator_params: Paramters of the negotiator Provides: - `all_negotiations_concluded` Requires: - `acceptable_unit_price` - `target_quantity` - OPTIONALLY `target_quantities` Hooks Into: - `init` - `respond_to_negotiation_request` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:class:: MarketAwareDecentralizingAgent(*args, buying_margin=None, selling_margin=None, min_price_margin=0.5, max_price_margin=0.5, **kwargs) Bases: :py:obj:`scml.scml2020.components.prediction.MarketAwareTradePredictionStrategy`, :py:obj:`_NegotiationCallbacks`, :py:obj:`scml.scml2020.components.MovingRangeNegotiationManager`, :py:obj:`scml.scml2020.components.trading.PredictionBasedTradingStrategy`, :py:obj:`scml.scml2020.components.signing.KeepOnlyGoodPrices`, :py:obj:`scml.scml2020.components.SupplyDrivenProductionStrategy`, :py:obj:`scml.scml2020.world.SCML2020Agent` Predicts an amount based on publicly available market information. Falls back to fixed prediction if no information is available Hooks Into: - `internal_state` - `on_contracts_finalized` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:class:: MarketAwareIndDecentralizingAgent(*args, buying_margin=None, selling_margin=None, min_price_margin=0.5, max_price_margin=0.5, **kwargs) Bases: :py:obj:`scml.scml2020.components.signing.KeepOnlyGoodPrices`, :py:obj:`scml.scml2020.components.prediction.MarketAwareTradePredictionStrategy`, :py:obj:`IndDecentralizingAgent` Signs all contracts that have good prices Overrides: - `sign_all_contracts` .. attribute:: - buying_margin The margin from the catalog price to allow for buying. The agent will never buy at a price higher than the catalog price by more than this margin (relative to catalog price). .. attribute:: - selling_margin The margin from the catalog price to allow for selling. The agent will never sell at a price lower than the catalog price by more than this margin (relative to catalog price). Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:class:: ReactiveAgent(*args, negotiator_type: Union[negmas.SAONegotiator, str] = AspirationNegotiator, negotiator_params: Optional[Dict[str, Any]] = None, **kwargs) Bases: :py:obj:`scml.scml2020.components.StepNegotiationManager`, :py:obj:`scml.scml2020.components.trading.ReactiveTradingStrategy`, :py:obj:`scml.scml2020.components.production.TradeDrivenProductionStrategy`, :py:obj:`scml.scml2020.components.FixedTradePredictionStrategy`, :py:obj:`scml.scml2020.world.SCML2020Agent` A negotiation manager that controls a controller and another for selling for every timestep :param negotiator_type: The negotiator type to use to manage all negotiations :param negotiator_params: Paramters of the negotiator Provides: - `all_negotiations_concluded` Requires: - `acceptable_unit_price` - `target_quantity` - OPTIONALLY `target_quantities` Hooks Into: - `init` - `respond_to_negotiation_request` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:method:: acceptable_unit_price(step: int, sell: bool) -> int Returns the maximum/minimum acceptable unit price for buying/selling at the given time-step :param step: Simulation step :param sell: Sell or buy .. py:method:: target_quantity(step: int, sell: bool) -> int Returns the target quantity to sell/buy at a given time-step :param step: Simulation step :param sell: Sell or buy .. py:method:: target_quantities(steps: Tuple[int, int], sell: bool) -> numpy.ndarray Implemented for speed but not really required .. py:class:: MarketAwareReactiveAgent(*args, buying_margin=None, selling_margin=None, min_price_margin=0.5, max_price_margin=0.5, **kwargs) Bases: :py:obj:`scml.scml2020.components.signing.KeepOnlyGoodPrices`, :py:obj:`ReactiveAgent` Signs all contracts that have good prices Overrides: - `sign_all_contracts` .. attribute:: - buying_margin The margin from the catalog price to allow for buying. The agent will never buy at a price higher than the catalog price by more than this margin (relative to catalog price). .. attribute:: - selling_margin The margin from the catalog price to allow for selling. The agent will never sell at a price lower than the catalog price by more than this margin (relative to catalog price). Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:class:: MovingRangeAgent(*args, price_weight=0.7, utility_threshold=0.9, time_threshold=0.9, time_horizon=0.1, min_price_margin=0.5, max_price_margin=0.5, **kwargs) Bases: :py:obj:`scml.scml2020.components.MovingRangeNegotiationManager`, :py:obj:`scml.scml2020.components.trading.PredictionBasedTradingStrategy`, :py:obj:`scml.scml2020.components.SupplyDrivenProductionStrategy`, :py:obj:`scml.scml2020.world.SCML2020Agent` My negotiation strategy :param price_weight: The relative importance of price in the utility calculation. :param utility_threshold: The fraction of maximum utility above which all offers will be accepted. :param time_threshold: The fraction of the negotiation time after which any valid offers will be accepted. :param time_range: The time-range for each controller as a fraction of the number of simulation steps Hooks Into: - `init` - `step` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:class:: MarketAwareMovingRangeAgent(*args, min_price_margin=0.5, max_price_margin=0.5, **kwargs) Bases: :py:obj:`scml.scml2020.components.prediction.MarketAwareTradePredictionStrategy`, :py:obj:`MovingRangeAgent` Predicts an amount based on publicly available market information. Falls back to fixed prediction if no information is available Hooks Into: - `internal_state` - `on_contracts_finalized` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:class:: SatisficerAgent(*args, target_productivity=1.0, satisfying_profit=0.15, acceptable_loss=0.02, price_range=0.4, concession_rate_price=1.0, concession_rate_quantity=1.0, concession_rate_time=1.0, market_share=1, horizon=5, **kwargs) Bases: :py:obj:`scml.scml2020.agent.SCML2020Agent` A simple monolithic agent that tries to *carefully* make small profit every step. :param target_productivity: The productivity level targeted by the agent defined as the fraction of its lines to be active per step. :param satisfying_profit: A profit amount considered satisfactory. Used when deciding negotiation agenda and signing to decide if a price is a good price (see `_good_price()`). A fraction of the trading price. :param acceptable_loss: A fraction of trading price that the seller/buyer is willing to go under/over the current trading price during negotiation. :param price_range: The total range around the trading price for negotiation agendas. :param concession_rate_price: The exponent of the consession curve for price. :param concession_rate_quantity: The exponent of the consession curve for quantity. :param concession_rate_time: The exponent of the consession curve for time. :param market_share: An integer specifying the expected share of the agent in the market. The agent will assume that it can get up to (market_share / (n_competitors + market_share -1)) of all sales and supplies where `n_competitors` is the number of agents at the same production level. Setting it to 1 means that the agent assumes it will get the same amount of trade as all other agents. Setting it to infinity means that the agent will assume it will take all the trade in the market :param horizon: Time horizon for negotiations. If None, the exogenous_contracts_revelation horizon will be used .. py:attribute:: horizon :value: 5 .. py:attribute:: satisfying_profit :value: 0.15 .. py:attribute:: target_productivity :value: 1.0 .. py:attribute:: price_range :value: 0.4 .. py:attribute:: ep :value: 1.0 .. py:attribute:: eq :value: 1.0 .. py:attribute:: et :value: 1.0 .. py:attribute:: acceptable_loss :value: 0.02 .. py:attribute:: last_q .. py:attribute:: last_t .. py:attribute:: market_share :value: 1 .. py:method:: init() Called once .. py:method:: before_step() Called at at the BEGINNING of every production step (day) .. py:method:: step() Called at the end of the day. Will request all negotiations .. py:method:: respond_to_negotiation_request(initiator, issues, annotation, mechanism) Called whenever another agent requests a negotiation with this agent. :param initiator: The ID of the agent that requested this negotiation :param issues: Negotiation issues :param annotation: Annotation attached with this negotiation :param mechanism: The `NegotiatorMechanismInterface` interface to the mechanism to be used for this negotiation. :returns: None to reject the negotiation, otherwise a negotiator .. py:method:: sign_all_contracts(contracts) Signs all contracts .. py:method:: on_contracts_finalized(signed, cancelled, rejectors) Called for all contracts in a single step to inform the agent about which were finally signed and which were rejected by any agents (including itself) :param signed: A list of signed contracts. These are binding :param cancelled: A list of cancelled contracts. These are not binding :param rejectors: A list of lists where each of the internal lists gives the rejectors of one of the cancelled contracts. Notice that it is possible that this list is empty which means that the contract other than being rejected by any agents (if that was possible in the specific world). Remarks: The default implementation is to call `on_contract_signed` for singed contracts and `on_contract_cancelled` for cancelled contracts .. py:method:: do_production() -> int .. py:method:: propose(state: negmas.sao.SAOState, ami: negmas.sao.SAONMI, is_selling: bool, is_requested: bool) Used to propose to the opponent :param state: mechanism state including current round :param ami: Agent-mechanism-interface for accessing the negotiation mechanism :param offer: The offer proposed by the partner :param is_selling: Whether the agent is selling to this partner :param is_requested: Whether the agent requested this negotiation .. py:method:: respond(state, ami, is_selling, is_requested) Responds to an offer from one partner. :param state: mechanism state including current round :param ami: Agent-mechanism-interface for accessing the negotiation mechanism :param offer: The offer proposed by the partner :param is_selling: Whether the agent is selling to this partner :param is_requested: Whether the agent requested this negotiation Remarks: - The main idea is to accept offers that are within the quantity limits for the delivery day if its price is good enough for the current stage of the negotiation. - During negotiation, the agent starts accepting highest/lowest prices for selling/buying and gradually conceeds to the minimally acceptable price (`good_price`) defined as being `acceptable_loss` above/below the trading price for buying/selling. .. py:method:: on_negotiation_failure(partners, annotation, mechanism, state) Called when a negotiation fails .. py:method:: on_negotiation_success(contract, mechanism) Called when a negotiation fails .. py:method:: _remove_tentative_offer(selling, partner) Removes my last offer from the tentative offers .. py:method:: _is_good_price(is_selling: bool, u: float, slack: float = 0.0) Checks whether a price is good relative to current trading prices, and satisfying profit (with possible slack). .. py:class:: AWI(world: negmas.situated.world.World, agent: negmas.situated.agent.Agent) Bases: :py:obj:`negmas.AgentWorldInterface` The Agent SCML2020World Interface for SCML2020 world. This class contains all the methods needed to access the simulation to extract information which are divided into 5 groups: Static World Information: Information about the world and the agent that does not change over time. These include: A. Market Information: - *n_products*: Number of products in the production chain. - *n_processes*: Number of processes in the production chain. - *n_competitors*: Number of other factories on the same production level. - *all_suppliers*: A list of all suppliers by product. - *all_consumers*: A list of all consumers by product. - *catalog_prices*: A list of the catalog prices (by product). - *inputs*: Inputs to every manufacturing process. - *outputs*: Outputs to every manufacturing process. - *is_system*: Is the given system ID corresponding to a system agent? - *is_bankrupt*: Is the given agent bankrupt (None asks about self)? - *current_step*: Current simulation step (inherited from `negmas.situated.AgentWorldInterface` ). - *n_steps*: Number of simulation steps (inherited from `negmas.situated.AgentWorldInterface` ). - *relative_time*: fraction of the simulation completed (inherited from `negmas.situated.AgentWorldInterface`). - *settings*: The system settings (inherited from `negmas.situated.AgentWorldInterface` ). B. Agent Information: - *profile*: Gives the agent profile including its production cost, number of production lines, input product index, mean of its delivery penalties, mean of its disposal costs, standard deviation of its shortfall penalties and standard deviation of its disposal costs. See `OneShotProfile` for full description. This information is private information and no other agent knows it. - *n_lines*: the number of production lines in the factory (private information). - *is_first_level*: Is the agent in the first production level (i.e. it is an input agent that buys the raw material). - *is_last_level*: Is the agent in the last production level (i.e. it is an output agent that sells the final product). - *is_middle_level*: Is the agent neither a first level nor a last level agent - *my_input_product*: The input product to the factory controlled by the agent. - *my_output_product*: The output product from the factory controlled by the agent. - *my_input_products*: All input products of a factory controlled by the agent. Currently, it is always a list of one item. For future compatibility. - *my_output_products*: All output products of a factory controlled by the agent. Currently, it is always a list of one item. For future compatibility. - *available_for_production*: Returns the line-step slots available for production. - *level*: The production level which is numerically the same as the input product. - *my_suppliers*: A list of IDs for all suppliers to the agent (i.e. agents that can sell the input product of the agent). - *my_consumers*: A list of IDs for all consumers to the agent (i.e. agents that can buy the output product of the agent). - *penalties_scale*: The scale at which to calculate disposal cost/delivery penalties. "trading" and "catalog" mean trading and catalog prices. "unit" means the contract's unit price while "none" means that disposal cost/shortfall penalty are absolute. - *n_input_negotiations*: Number of negotiations with suppliers. - *n_output_negotiations*: Number of negotiations with consumers. - *state*: The full state of the agent ( `FactoryState` ). - *current_balance*: The current balance of the agent - *current_inventory*: The current inventory of the agent (quantity per product) Dynamic World Information: Information about the world and the agent that changes over time. A. Market Information: - *trading_prices*: The trading prices of all products. This information is only available if `publish_trading_prices` is set in the world. - *exogenous_contract_summary*: A list of n_products tuples each giving the total quantity and average price of exogenous contracts for a product. This information is only available if `publish_exogenous_summary` is set in the world. B. Other Agents' Information: - *reports_of_agent*: Gives all past financial reports of a given agent. See `FinancialReport` for details. - *reports_at_step*: Gives all reports of all agents at a given step. See `FinancialReport` for details. C. Current Negotiations Information: - *current_input_issues*: The current issues for all negotiations to buy the input product of the agent. If the agent is at level zero, this will be empty. - *current_output_issues*: The current issues for all negotiations to buy the output product of the agent. If the agent is at level n_products - 1, this will be empty. D. Agent Information: - *spot_market_quantity*: The quantity the agent bought from the spot market at a given step - *spot_market_loss*: The spot market loss for the agent. Actions: A. Negotiation Control: - *request_negotiations*: Requests a set of negotiations controlled by a single controller. - *request_negotiation*: Requests a negotiation controlled by a single negotiator. B. Production Control: - *schedule_production*: Schedules production using one of the predefined scheduling strategies. - *order_production*: Orders production directly for the current step. - *set_commands*: Sets production commands directly on the factory. - *cancel_production*: Cancels a scheduled production command. Services (All inherited from `negmas.situated.AgentWorldInterface`): - *logdebug/loginfo/logwarning/logerror*: Logs to the world log at the given log level. - *logdebug_agent/loginf_agnet/...*: Logs to the agent specific log at the given log level. - *bb_query*: Queries the bulletin-board. - *bb_read*: Read a section of the bulletin-board. .. py:method:: request_negotiations(is_buy: bool, product: int, quantity: Union[int, Tuple[int, int]], unit_price: Union[int, Tuple[int, int]], time: Union[int, Tuple[int, int]], controller: Optional[negmas.SAOController] = None, negotiators: List[negmas.Negotiator] = None, partners: List[str] = None, extra: Dict[str, Any] = None, copy_partner_id=True) -> bool Requests a negotiation :param is_buy: If True the negotiation is about buying otherwise selling. :param product: The product to negotiate about :param quantity: The minimum and maximum quantities. Passing a single value q is equivalent to passing (q,q) :param unit_price: The minimum and maximum unit prices. Passing a single value u is equivalent to passing (u,u) :param time: The minimum and maximum delivery step. Passing a single value t is equivalent to passing (t,t) :param controller: The controller to manage the complete set of negotiations :param negotiators: An optional list of negotiators to use for negotiating with the given partners (in the same order). :param partners: ID of all the partners to negotiate with. :param extra: Extra information accessible through the negotiation annotation to the caller :param copy_partner_id: If true, the partner ID will be copied to the negotiator ID :returns: `True` if the partner accepted and the negotiation is ready to start Remarks: - You can either use controller or negotiators. One of them must be None. - All negotiations will use the following issues **in order**: quantity, time, unit_price - Negotiations with bankrupt agents or on invalid products (see next point) will be automatically rejected - Valid products for a factory are the following (any other products are not valid): 1. Buying an input product (i.e. product $\in$ `my_input_products` ) and an output product if the world settings allows it (see `allow_buying_output`) 1. Selling an output product (i.e. product $\in$ `my_output_products` ) and an input product if the world settings allows it (see `allow_selling_input`) .. py:method:: request_negotiation(is_buy: bool, product: int, quantity: Union[int, Tuple[int, int]], unit_price: Union[int, Tuple[int, int]], time: Union[int, Tuple[int, int]], partner: str, negotiator: negmas.SAONegotiator, extra: Dict[str, Any] = None) -> bool Requests a negotiation :param is_buy: If True the negotiation is about buying otherwise selling. :param product: The product to negotiate about :param quantity: The minimum and maximum quantities. Passing a single value q is equivalent to passing (q,q) :param unit_price: The minimum and maximum unit prices. Passing a single value u is equivalent to passing (u,u) :param time: The minimum and maximum delivery step. Passing a single value t is equivalent to passing (t,t) :param partner: ID of the partner to negotiate with. :param negotiator: The negotiator to use for this negotiation (if the partner accepted to negotiate) :param extra: Extra information accessible through the negotiation annotation to the caller :returns: `True` if the partner accepted and the negotiation is ready to start Remarks: - All negotiations will use the following issues **in order**: quantity, time, unit_price - Negotiations with bankrupt agents or on invalid products (see next point) will be automatically rejected - Valid products for a factory are the following (any other products are not valid): 1. Buying an input product (i.e. product $\in$ `my_input_products` ) and an output product if the world settings allows it (see `allow_buying_output`) 1. Selling an output product (i.e. product $\in$ `my_output_products` ) and an input product if the world settings allows it (see `allow_selling_input`) .. py:method:: schedule_production(process: int, repeats: int, step: Union[int, Tuple[int, int]] = ANY_STEP, line: int = ANY_LINE, override: bool = True, method: str = 'latest', partial_ok: bool = False) -> Tuple[numpy.ndarray, numpy.ndarray] Orders the factory to run the given process at the given line at the given step :param process: The process to run :param repeats: How many times to repeat the process :param step: The simulation step or a range of steps. The special value ANY_STEP gives the factory the freedom to schedule production at any step in the present or future. :param line: The production line. The special value ANY_LINE gives the factory the freedom to use any line :param override: Whether to override existing production commands or not :param method: When to schedule the command if step was set to a range. Options are latest, earliest :param partial_ok: If true, allows partial scheduling :returns: Tuple[int, int] giving the steps and lines at which production is scheduled. Remarks: - The step cannot be in the past. Production can only be ordered for current and future steps - ordering production of process -1 is equivalent of `cancel_production` only if both step and line are given .. py:method:: order_production(process: int, steps: numpy.ndarray, lines: numpy.ndarray) -> None Orders production of the given process :param process: The process to run :param steps: The time steps to run the process at as an np.ndarray :param lines: The corresponding lines to run the process at Remarks: - len(steps) must equal len(lines) - No checks are done in this function. It is expected to be used after calling `available_for_production` .. py:method:: available_for_production(repeats: int, step: Union[int, Tuple[int, int]] = ANY_STEP, line: int = ANY_LINE, override: bool = True, method: str = 'latest') -> Tuple[numpy.ndarray, numpy.ndarray] Finds available times and lines for scheduling production. :param repeats: How many times to repeat the process :param step: The simulation step or a range of steps. The special value ANY_STEP gives the factory the freedom to schedule production at any step in the present or future. :param line: The production line. The special value ANY_LINE gives the factory the freedom to use any line :param override: Whether to override any existing commands at that line at that time. :param method: When to schedule the command if step was set to a range. Options are latest, earliest, all :returns: Tuple[np.ndarray, np.ndarray] The steps and lines at which production is scheduled. Remarks: - You cannot order production in the past or in the current step - Ordering production, will automatically update inventory and balance for all simulation steps assuming that this production will be carried out. At the indicated `step` if production was not possible (due to insufficient funds or insufficient inventory of the input product), the predictions for the future will be corrected. .. py:method:: set_commands(commands: numpy.ndarray, step: int = -1) -> None Sets the production commands for all lines in the given step :param commands: n_lines vector of commands. A command is either a process number to run or `NO_COMMAND` to keep the line idle :param step: The step to set the commands at. If < 0, it means current step .. py:method:: cancel_production(step: int, line: int) -> bool Cancels any production commands on that line at this step :param step: The step to cancel production at (must be in the future). :param line: The production line :returns: success/failure Remarks: - The step cannot be in the past or the current step. Cancellation can only be ordered for future steps .. py:property:: trading_prices :type: numpy.ndarray Returns the current trading prices of all products .. py:property:: exogenous_contract_summary :type: List[Tuple[int, int]] The exogenous contracts in the current step for all products :returns: A list of tuples giving the total quantity and total price of all revealed exogenous contracts of all products at the current step. .. py:property:: allow_zero_quantity :type: bool Does negotiations allow zero quantity? .. py:property:: state :type: scml.scml2020.common.FactoryState Receives the factory state .. py:property:: current_balance Current balance of the agent .. py:property:: current_inventory Current inventory of the agent .. py:method:: reports_of_agent(aid: str) -> Dict[int, scml.scml2020.common.FinancialReport] Returns a dictionary mapping time-steps to financial reports of the given agent .. py:method:: reports_at_step(step: int) -> Dict[str, scml.scml2020.common.FinancialReport] Returns a dictionary mapping agent ID to its financial report for the given time-step .. py:property:: profile :type: scml.scml2020.common.FactoryProfile Gets the profile (static private information) associated with the agent .. py:property:: all_suppliers :type: List[List[str]] Returns a list of agent IDs for all suppliers for every product .. py:property:: all_consumers :type: List[List[str]] Returns a list of agent IDs for all consumers for every product .. py:property:: inputs :type: numpy.ndarray Returns the number of inputs to every production process .. py:property:: outputs :type: numpy.ndarray Returns the number of outputs to every production process .. py:property:: n_competitors :type: int Returns the number of factories/agents in the same production level .. py:property:: my_input_product :type: int Returns a list of products that are inputs to at least one process the agent can run .. py:property:: my_output_product :type: int Returns a list of products that are outputs to at least one process the agent can run .. py:property:: my_input_products :type: numpy.ndarray Returns a list of products that are inputs to at least one process the agent can run .. py:property:: my_output_products :type: numpy.ndarray Returns a list of products that are outputs to at least one process the agent can run .. py:property:: my_suppliers :type: List[str] Returns a list of IDs for all of the agent's suppliers (agents that can supply at least one product it may need). Remarks: - If the agent have multiple input products, suppliers of a specific product $p$ can be found using: **self.all_suppliers[p]**. .. py:property:: my_consumers :type: List[str] Returns a list of IDs for all the agent's consumers (agents that can consume at least one product it may produce). Remarks: - If the agent have multiple output products, consumers of a specific product $p$ can be found using: **self.all_consumers[p]**. .. py:property:: n_lines :type: int The number of lines in the corresponding factory. You can read `state` to get this among other information .. py:property:: catalog_prices :type: numpy.ndarray Returns the catalog prices of all products .. py:property:: n_products :type: int Number of products in the world .. py:property:: n_processes :type: int Returns the number of processes in the system .. py:property:: is_first_level Whether this agent is in the first production level .. py:property:: is_last_level Whether this agent is in the last production level .. py:property:: level The production level which is the index of the process for this factory (or the index of its input product) .. py:property:: is_middle_level Whether this agent is in neither in the first nor in the last level .. py:method:: is_system(aid: str) -> bool Checks whether an agent is a system agent or not :param aid: Agent ID .. py:method:: is_bankrupt(aid: Optional[str] = None) -> bool Checks whether the agent is bankrupt :param aid: Agent ID (None means self) .. py:method:: spot_market_quantity(step: Optional[int]) -> int The quantity bought by the agent from the spot market at the given step. :param step: The simulation step (day) Remarks: If step is `None`, the current step will be used .. py:method:: spot_market_loss(step: Optional[int]) -> int The spot market loss of the agent at the given step. :param step: The simulation step (day) Remarks: If step is `None`, the current step will be used .. py:data:: SYSTEM_BUYER_ID :value: 'BUYER' ID of the system buyer agent .. py:data:: SYSTEM_SELLER_ID :value: 'SELLER' ID of the system seller agent .. py:data:: COMPENSATION_ID :value: 'COMPENSATOR' ID of the takeover agent .. py:data:: ANY_STEP :value: -1 Used to indicate any time-step .. py:data:: NO_COMMAND :value: -1 A constant indicating no command is scheduled on a factory line .. py:data:: ANY_LINE :value: -1 Used to indicate any line .. py:data:: INFINITE_COST :value: 4611686018427387903 A constant indicating an invalid cost for lines incapable of running some process .. py:data:: QUANTITY :value: 0 Index of quantity in negotiation issues .. py:data:: TIME :value: 1 Index of time in negotiation issues .. py:data:: UNIT_PRICE :value: 2 Index of unit price in negotiation issues .. py:function:: is_system_agent(aid: str) -> bool Checks whether an agent is a system agent or not :param aid: Agent ID :returns: True if the ID is for a system agent. .. py:class:: FactoryState .. py:attribute:: inventory :type: numpy.ndarray An n_products vector giving current quantity of every product in storage .. py:attribute:: balance :type: int Current balance in the wallet .. py:attribute:: commands :type: numpy.ndarray n_steps * n_lines array giving the process scheduled on each line at every step for the whole simulation .. py:attribute:: inventory_changes :type: numpy.ndarray Changes in the inventory in the last step .. py:attribute:: balance_change :type: int Change in the balance in the last step .. py:attribute:: contracts :type: list[list[ContractInfo]] The An n_steps list of lists containing the contracts of this agent by time-step .. py:property:: n_lines :type: int .. py:property:: n_steps :type: int .. py:property:: n_products :type: int .. py:property:: n_processes :type: int .. py:class:: FinancialReport A report published periodically by the system showing the financial standing of an agent .. py:attribute:: __slots__ :value: ['agent_id', 'step', 'cash', 'assets', 'breach_prob', 'breach_level', 'is_bankrupt', 'agent_name'] .. py:attribute:: agent_id :type: str Agent ID .. py:attribute:: step :type: int Simulation step at the beginning of which the report was published. .. py:attribute:: cash :type: int Cash in the agent's wallet. Negative numbers indicate liabilities. .. py:attribute:: assets :type: int Value of the products in the agent's inventory @ catalog prices. .. py:attribute:: breach_prob :type: float Number of times the agent breached a contract over the total number of contracts it signed. .. py:attribute:: breach_level :type: float Sum of the agent's breach levels so far divided by the number of contracts it signed. .. py:attribute:: is_bankrupt :type: bool Whether the agent is already bankrupt (i.e. incapable of doing any more transactions). .. py:attribute:: agent_name :type: str Agent name for printing purposes .. py:method:: __str__() .. py:class:: FactoryProfile Defines all private information of a factory .. py:attribute:: __slots__ :value: ['costs'] .. py:attribute:: costs :type: numpy.ndarray An n_lines * n_processes array giving the cost of executing any process (INVALID_COST indicates infinity) .. py:property:: n_lines .. py:property:: n_products .. py:property:: n_processes .. py:property:: processes :type: numpy.ndarray The processes that have valid costs .. py:property:: input_products :type: numpy.ndarray The input products to all processes runnable (See `processes` ) .. py:property:: output_products :type: numpy.ndarray The output products to all processes runnable (See `processes` ) .. py:class:: Failure A production failure .. py:attribute:: __slots__ :value: ['is_inventory', 'line', 'step', 'process'] .. py:attribute:: is_inventory :type: bool True if the cause of failure was insufficient inventory. If False, the cause was insufficient funds. Note that if both conditions were true, only insufficient funds (is_inventory=False) will be reported. .. py:attribute:: line :type: int The line at which the failure happened .. py:attribute:: step :type: int The step at which the failure happened .. py:attribute:: process :type: int The process that failed to execute .. py:class:: ExogenousContract Represents a contract to be revealed at revelation_time to buyer and seller between them that is not agreed upon through negotiation but is endogenously given .. py:attribute:: product :type: int Product .. py:attribute:: quantity :type: int Quantity .. py:attribute:: unit_price :type: int Unit price .. py:attribute:: time :type: int Delivery time .. py:attribute:: revelation_time :type: int Time at which to reveal the contract to both buyer and seller .. py:attribute:: seller :type: int :value: -1 Seller index in the agents array (-1 means "system") .. py:attribute:: buyer :type: int :value: -1 Buyer index in the agents array (-1 means "system") .. py:class:: ProductionStrategy(*args, **kwargs) Represents a strategy for controlling production. Provides: - `schedule_range` : A mapping from contract ID to a tuple of the first and last steps at which some lines are occupied to produce the quantity specified by the contract and whether it is a sell contract - `can_be_produced` : Given a contract, it returns whether or not it is possible to produce the quantity entailed by it (which means that there is enough vacant production line slots before/after the contracts delivery time for sell/buy contracts). Hooks Into: - `on_contract_breached` - `on_contract_executed` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:attribute:: schedule_range :type: dict[str, tuple[int, int, bool]] Gives the range of steps at which the production needed for a given contract are scheduled .. py:method:: can_be_produced(contract_id: str) Returns True if the SELL contract given can be honored in principle given the production capacity of the agent (n. lines). It does not check for the availability of inputs or enough money to run the production process. Remarks: - Cannot be called before calling on_contracts_finalized .. py:method:: on_contract_executed(contract: negmas.Contract) -> None .. py:method:: on_contract_breached(contract: negmas.Contract, breaches, resolution) -> None .. py:class:: SupplyDrivenProductionStrategy(*args, **kwargs) Bases: :py:obj:`ProductionStrategy` A production strategy that converts all inputs to outputs Hooks Into: - `step` - `on_contracts_finalized` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:method:: step() .. py:method:: on_contracts_finalized(signed: list[negmas.Contract], cancelled: list[negmas.Contract], rejectors: list[list[str]]) -> None .. py:class:: DemandDrivenProductionStrategy(*args, **kwargs) Bases: :py:obj:`ProductionStrategy` A production strategy that produces ONLY when a contract is secured Hooks Into: - `on_contract_finalized` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:method:: on_contracts_finalized(signed: list[negmas.Contract], cancelled: list[negmas.Contract], rejectors: list[list[str]]) -> None .. py:class:: TradeDrivenProductionStrategy(*args, **kwargs) Bases: :py:obj:`ProductionStrategy` A production strategy that produces ONLY for contracts that the agent did not initiate. Hooks Into: - `on_contract_finalized` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:method:: on_contracts_finalized(signed: list[negmas.Contract], cancelled: list[negmas.Contract], rejectors: list[list[str]]) -> None .. py:class:: TradePredictionStrategy(*args, predicted_outputs: Union[int, numpy.ndarray] = None, predicted_inputs: Union[int, numpy.ndarray] = None, add_trade=False, **kwargs) A prediction strategy for expected inputs and outputs at every step :param - `predicted_inputs`: None for default, a number of an n_steps numbers giving predicted inputs :param - `predicted_outputs`: None for default, a number of an n_steps numbers giving predicted outputs Provides: - `expected_inputs` : n_steps vector giving the predicted inputs at every time-step. It defaults to the number of lines. - `expected_outputs` : n_steps vector giving the predicted outputs at every time-step. It defaults to the number of lines. - `input_cost` : n_steps vector giving the predicted input cost at every time-step. It defaults to catalog price. - `output_price` : n_steps vector giving the predicted output price at every time-step. It defaults to catalog price. Hooks Into: - `init` - `before_step` - `step` Abstract: - `trade_prediction_init`: Called during init() to initialize the trade prediction. - `trade_prediction_step`: Called during step() to update the trade prediction. Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:attribute:: expected_outputs :value: None Expected output quantity every step .. py:attribute:: expected_inputs :value: None Expected input quantity every step .. py:attribute:: input_cost :type: numpy.ndarray :value: None Expected unit price of the input .. py:attribute:: output_price :type: numpy.ndarray :value: None Expected unit price of the output .. py:attribute:: _add_trade :value: False .. py:method:: trade_prediction_init() -> None :abstractmethod: Will be called to update expected_outputs, expected_inputs, input_cost, output_cost during init() .. py:method:: trade_prediction_before_step() -> None Will be called at the beginning of every step to update the prediction .. py:method:: trade_prediction_step() -> None Will be called at the end of every step to update the prediction .. py:method:: init() .. py:method:: before_step() .. py:method:: step() .. py:class:: FixedTradePredictionStrategy(*args, add_trade=True, **kwargs) Bases: :py:obj:`TradePredictionStrategy` Predicts a fixed amount of trade both for the input and output products. Hooks Into: - `internal_state` - `on_contracts_finalized` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:attribute:: _add_trade :value: True .. py:method:: trade_prediction_init() Will be called to update expected_outputs, expected_inputs, input_cost, output_cost during init() .. py:property:: internal_state .. py:method:: on_contracts_finalized(signed: List[negmas.Contract], cancelled: List[negmas.Contract], rejectors: List[List[str]]) -> None .. py:class:: ExecutionRatePredictionStrategy A prediction strategy for expected inputs and outputs at every step Provides: - `predict_quantity` : A method for predicting the quantity that will actually be executed from a contract Abstract: - `predict_quantity` : A method for predicting the quantity that will actually be executed from a contract Hooks Into: - `internal_state` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:method:: predict_quantity(contract: negmas.Contract) :abstractmethod: .. py:class:: FixedERPStrategy(*args, execution_fraction=0.95, **kwargs) Bases: :py:obj:`ExecutionRatePredictionStrategy` Predicts that the there is a fixed execution rate that does not change for all partners :param execution_fraction: The expected fraction of any contract's quantity to be executed Provides: - `predict_quantity` : A method for predicting the quantity that will actually be executed from a contract Hooks Into: - `internal_state` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:attribute:: _execution_fraction :value: 0.95 .. py:method:: predict_quantity(contract: negmas.Contract) .. py:class:: MeanERPStrategy(*args, execution_fraction=0.95, **kwargs) Bases: :py:obj:`ExecutionRatePredictionStrategy` Predicts the mean execution fraction for each partner :param execution_fraction: The expected fraction of any contract's quantity to be executed Provides: - `predict_quantity` : A method for predicting the quantity that will actually be executed from a contract Hooks Into: - `internal_state` - `init` - `on_contract_executed` - `on_contract_breached` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:attribute:: _execution_fraction :value: 0.95 .. py:attribute:: _total_quantity :value: None .. py:method:: predict_quantity(contract: negmas.Contract) .. py:method:: init() .. py:property:: internal_state .. py:method:: on_contract_executed(contract: negmas.Contract) -> None .. py:method:: on_contract_breached(contract: negmas.Contract, breaches: List[negmas.Breach], resolution: Optional[negmas.Contract]) -> None .. py:class:: MarketAwareTradePredictionStrategy(*args, predicted_outputs: Union[int, numpy.ndarray] = None, predicted_inputs: Union[int, numpy.ndarray] = None, add_trade=False, **kwargs) Bases: :py:obj:`TradePredictionStrategy` Predicts an amount based on publicly available market information. Falls back to fixed prediction if no information is available Hooks Into: - `internal_state` - `on_contracts_finalized` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:method:: init() .. py:method:: trade_prediction_init() Will be called to update expected_outputs, expected_inputs, input_cost, output_cost during init() .. py:method:: __update() .. py:method:: trade_prediction_step() Will be called at the end of every step to update the prediction .. py:method:: trade_prediction_before_step() Will be called at the beginning of every step to update the prediction .. py:property:: internal_state .. py:class:: SignAll Signs all contracts no matter what. Overrides: - `sign_all_contracts` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:method:: sign_all_contracts(contracts: List[negmas.Contract]) -> List[Optional[str]] .. py:class:: SignAllPossible Signs all contracts that can in principle be honored. The only check made by this strategy is that for sell contracts there is enough production capacity Overrides: - `sign_all_contracts` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:method:: sign_all_contracts(contracts: List[negmas.Contract]) -> List[Optional[str]] .. py:class:: KeepOnlyGoodPrices(*args, buying_margin=0.5, selling_margin=0.5, **kwargs) Signs all contracts that have good prices Overrides: - `sign_all_contracts` .. attribute:: - buying_margin The margin from the catalog price to allow for buying. The agent will never buy at a price higher than the catalog price by more than this margin (relative to catalog price). .. attribute:: - selling_margin The margin from the catalog price to allow for selling. The agent will never sell at a price lower than the catalog price by more than this margin (relative to catalog price). Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:method:: sign_all_contracts(contracts: List[negmas.Contract]) -> List[Optional[str]] .. py:class:: NegotiationManager(*args, horizon=5, negotiate_on_signing=True, logdebug=False, use_trading_prices=True, min_price_margin=0.5, max_price_margin=0.5, **kwargs) A negotiation manager is a component that provides negotiation control functionality to an agent :param horizon: The number of steps in the future to consider for selling outputs. Provides: - `start_negotiations` An easy to use method to start a set of buy/sell negotiations Requires: - `acceptable_unit_price` - `target_quantity` - OPTIONALLY `target_quantities` Abstract: - `respond_to_negotiation_request` Hooks Into: - `init` - `step` - `on_contracts_finalized` - `respond_to_negotiation_request` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:attribute:: _horizon :value: 5 .. py:attribute:: _negotiate_on_signing :value: True .. py:attribute:: _log :value: False .. py:attribute:: _use_trading :value: True .. py:attribute:: _min_margin :value: 0.5 .. py:attribute:: _max_margin :value: 1.5 .. py:property:: use_trading .. py:method:: init() .. py:method:: start_negotiations(product: int, quantity: int, unit_price: int, step: int, partners: List[str] = None) -> None Starts a set of negotiations to buy/sell the product with the given limits :param product: product type. If it is an input product, negotiations to buy it will be started otherweise to sell. :param quantity: The maximum quantity to negotiate about :param unit_price: The maximum/minimum unit price for buy/sell :param step: The maximum/minimum time for buy/sell :param partners: A list of partners to negotiate with Remarks: - This method assumes that product is either my_input_product or my_output_product .. py:method:: step() Generates buy and sell negotiations as needed .. py:method:: on_contracts_finalized(signed: List[negmas.Contract], cancelled: List[negmas.Contract], rejectors: List[List[str]]) -> None .. py:method:: _generate_negotiations(step: int, sell: bool) -> None Generates all the required negotiations for selling/buying for the given step .. py:method:: _urange(step, is_seller, time_range) .. py:method:: _trange(step, is_seller) .. py:method:: target_quantities(steps: Tuple[int, int], sell: bool) -> numpy.ndarray Returns the target quantity to negotiate about for each step in the range given (beginning included and ending excluded) for buying/selling :param steps: Simulation step :param sell: Sell or buy .. py:method:: _start_negotiations(product: int, sell: bool, step: int, qvalues: Tuple[int, int], uvalues: Tuple[int, int], tvalues: Tuple[int, int], partners: List[str]) -> None :abstractmethod: Actually start negotiations with the given agenda :param product: The product to negotiate about. :param sell: If true, this is a sell negotiation :param step: The step :param qvalues: the range of quantities :param uvalues: the range of unit prices :param tvalues: the range of times :param partners: partners .. py:method:: target_quantity(step: int, sell: bool) -> int :abstractmethod: Returns the target quantity to sell/buy at a given time-step :param step: Simulation step :param sell: Sell or buy .. py:method:: acceptable_unit_price(step: int, sell: bool) -> int :abstractmethod: Returns the maximum/minimum acceptable unit price for buying/selling at the given time-step :param step: Simulation step :param sell: Sell or buy .. py:method:: respond_to_negotiation_request(initiator: str, issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) -> Optional[negmas.Negotiator] :abstractmethod: .. py:class:: StepNegotiationManager(*args, negotiator_type: Union[negmas.SAONegotiator, str] = AspirationNegotiator, negotiator_params: Optional[Dict[str, Any]] = None, **kwargs) Bases: :py:obj:`scml.scml2020.components.prediction.MeanERPStrategy`, :py:obj:`NegotiationManager` A negotiation manager that controls a controller and another for selling for every timestep :param negotiator_type: The negotiator type to use to manage all negotiations :param negotiator_params: Paramters of the negotiator Provides: - `all_negotiations_concluded` Requires: - `acceptable_unit_price` - `target_quantity` - OPTIONALLY `target_quantities` Hooks Into: - `init` - `respond_to_negotiation_request` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:attribute:: negotiator_type .. py:attribute:: negotiator_params :value: None .. py:method:: init() .. py:method:: _start_negotiations(product: int, sell: bool, step: int, qvalues: Tuple[int, int], uvalues: Tuple[int, int], tvalues: Tuple[int, int], partners: List[str]) -> None Actually start negotiations with the given agenda :param product: The product to negotiate about. :param sell: If true, this is a sell negotiation :param step: The step :param qvalues: the range of quantities :param uvalues: the range of unit prices :param tvalues: the range of times :param partners: partners .. py:method:: respond_to_negotiation_request(initiator: str, issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) -> Optional[negmas.Negotiator] .. py:method:: all_negotiations_concluded(controller_index: int, is_seller: bool) -> None Called by the `StepController` to affirm that it is done negotiating for some time-step .. py:method:: add_controller(is_seller: bool, target, urange: Tuple[int, int], expected_quantity: int, step: int) -> scml.scml2020.services.controllers.StepController .. py:method:: insert_controller(controller: scml.scml2020.services.controllers.StepController, is_seller: bool, target, urange: Tuple[int, int], expected_quantity: int, step: int = None) -> scml.scml2020.services.controllers.StepController .. py:method:: create_controller(is_seller: bool, target, urange: Tuple[int, int], expected_quantity: int, step: int) -> scml.scml2020.services.controllers.StepController .. py:method:: _get_controller(mechanism) -> scml.scml2020.services.controllers.StepController .. py:class:: IndependentNegotiationsManager(*args, negotiator_type: Union[negmas.SAONegotiator, str] = AspirationNegotiator, negotiator_params: Optional[Dict[str, Any]] = None, **kwargs) Bases: :py:obj:`NegotiationManager` A negotiation manager that manages independent negotiators that do not share any information once created :param negotiator_type: The negotiator type to use to manage all negotiations :param negotiator_params: Parameters of the negotiator Requires: - `create_ufun` - `acceptable_unit_price` - `target_quantity` - OPTIONALLY `target_quantities` Hooks Into: - `respond_to_negotiation_request` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:attribute:: negotiator_type .. py:attribute:: negotiator_params :value: None .. py:method:: _start_negotiations(product: int, sell: bool, step: int, qvalues: Tuple[int, int], uvalues: Tuple[int, int], tvalues: Tuple[int, int], partners: List[str]) -> None Actually start negotiations with the given agenda :param product: The product to negotiate about. :param sell: If true, this is a sell negotiation :param step: The step :param qvalues: the range of quantities :param uvalues: the range of unit prices :param tvalues: the range of times :param partners: partners .. py:method:: respond_to_negotiation_request(initiator: str, issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) -> Optional[negmas.Negotiator] .. py:method:: create_ufun(is_seller: bool, issues=None, outcomes=None) -> negmas.UtilityFunction Creates a utility function .. py:method:: negotiator(is_seller: bool, issues=None, outcomes=None, partner=None) -> negmas.SAONegotiator Creates a negotiator .. py:class:: MovingRangeNegotiationManager(*args, price_weight=0.7, utility_threshold=0.9, time_threshold=0.9, time_horizon=0.1, min_price_margin=0.5, max_price_margin=0.5, **kwargs) My negotiation strategy :param price_weight: The relative importance of price in the utility calculation. :param utility_threshold: The fraction of maximum utility above which all offers will be accepted. :param time_threshold: The fraction of the negotiation time after which any valid offers will be accepted. :param time_range: The time-range for each controller as a fraction of the number of simulation steps Hooks Into: - `init` - `step` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:attribute:: index :type: List[int] :value: None .. py:attribute:: time_horizon :value: 0.1 .. py:attribute:: _time_threshold :value: 0.9 .. py:attribute:: _price_weight :value: 0.7 .. py:attribute:: _utility_threshold :value: 0.9 .. py:attribute:: _min_margin :value: 0.5 .. py:attribute:: _max_margin :value: 1.5 .. py:attribute:: controllers :type: Dict[bool, scml.scml2020.services.controllers.SyncController] .. py:attribute:: _current_end :value: -1 .. py:attribute:: _current_start :value: -1 .. py:method:: step() .. py:method:: respond_to_negotiation_request(initiator: str, issues: List[negmas.Issue], annotation: Dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) -> Optional[negmas.Negotiator] .. py:class:: Simulation(*args, **kwargs) Provides a simulator to the agent. Provides: - `simulator` (FactorySimulator): A simulator that can be used to simulate the effect of contracts on the future of the factory Hooks Into: - `init` - `step` Remarks: - `Attributes` section describes the attributes that can be used to construct the component (passed to its `__init__` method). - `Provides` section describes the attributes (methods, properties, data-members) made available by this component directly. Note that everything provided by the bases of this components are also available to the agent (Check the `Bases` section above for all the bases of this component). - `Requires` section describes any requirements from the agent using this component. It defines a set of methods or properties/data-members that must exist in the agent that uses this component. These requirement are usually implemented as abstract methods in the component - `Abstract` section describes abstract methods that MUST be implemented by any descendant of this component. - `Hooks Into` section describes the methods this component overrides calling `super` () which allows other components to hook into the same method (by overriding it). Usually callbacks starting with `on_` are hooked into this way. - `Overrides` section describes the methods this component overrides without calling `super` effectively disallowing any other components after it in the MRO to call this method. Usually methods that do some action (i.e. not starting with `on_`) are overridden this way. .. py:attribute:: simulator :type: scml.scml2020.services.FactorySimulator :value: None .. py:method:: init() .. py:method:: step() .. py:class:: Factory(profile: scml.scml2020.common.FactoryProfile, initial_balance: int, inputs: numpy.ndarray, outputs: numpy.ndarray, catalog_prices: numpy.ndarray, world: scml.scml2020.world.SCML2020World, compensate_before_past_debt: bool, buy_missing_products: bool, production_buy_missing: bool, production_penalty: float, production_no_bankruptcy: bool, production_no_borrow: bool, agent_id: str, agent_name: Optional[str] = None, confirm_production: bool = True, initial_inventory: Optional[numpy.ndarray] = None, disallow_concurrent_negs_with_same_partners=False) A simulated factory .. py:attribute:: confirm_production :value: True .. py:attribute:: production_buy_missing .. py:attribute:: compensate_before_past_debt .. py:attribute:: buy_missing_products .. py:attribute:: production_penalty .. py:attribute:: production_no_bankruptcy .. py:attribute:: production_no_borrow .. py:attribute:: catalog_prices .. py:attribute:: initial_balance .. py:attribute:: __profile .. py:attribute:: world .. py:attribute:: profile .. py:attribute:: _disallow_concurrent_negs_with_same_partners :value: False The readonly factory profile (See `FactoryProfile` ) .. py:attribute:: commands An n_steps * n_lines array giving the process scheduled for each line at every step. -1 indicates an empty line. .. py:attribute:: _balance Current balance .. py:attribute:: _inventory Current inventory .. py:attribute:: agent_id A unique ID for the agent owning the factory .. py:attribute:: inputs An n_process array giving the number of inputs needed for each process (of the product with the same index) .. py:attribute:: outputs An n_process array giving the number of outputs produced by each process (of the product with the next index) .. py:attribute:: inventory_changes Changes in the inventory in the last step .. py:attribute:: balance_change :value: 0 Change in the balance in the last step .. py:attribute:: min_balance The minimum balance possible .. py:attribute:: is_bankrupt :value: False Will be true when the factory is bankrupt .. py:attribute:: agent_name SCML2020Agent names used for logging purposes .. py:attribute:: contracts :type: List[List[scml.scml2020.common.ContractInfo]] A list of lists of contracts per time-step (len == n_steps) .. py:property:: state :type: scml.scml2020.common.FactoryState .. py:property:: current_inventory :type: numpy.ndarray Current inventory contents .. py:property:: current_balance :type: int Current wallet balance .. py:method:: schedule_production(process: int, repeats: int, step: Union[int, Tuple[int, int]] = ANY_STEP, line: int = ANY_LINE, override: bool = True, method: str = 'latest', partial_ok: bool = False) -> Tuple[numpy.ndarray, numpy.ndarray] Orders production of the given process on the given step and line. :param process: The process index :param repeats: How many times to repeat the process :param step: The simulation step or a range of steps. The special value ANY_STEP gives the factory the freedom to schedule production at any step in the present or future. :param line: The production line. The special value ANY_LINE gives the factory the freedom to use any line :param override: Whether to override any existing commands at that line at that time. :param method: When to schedule the command if step was set to a range. Options are latest, earliest, all :param partial_ok: If true, it is OK to produce only a subset of repeats :returns: Tuple[np.ndarray, np.ndarray] The steps and lines at which production is scheduled. Remarks: - You cannot order production in the past or in the current step - Ordering production, will automatically update inventory and balance for all simulation steps assuming that this production will be carried out. At the indicated `step` if production was not possible (due to insufficient funds or insufficient inventory of the input product), the predictions for the future will be corrected. .. py:method:: order_production(process: int, steps: numpy.ndarray, lines: numpy.ndarray) -> None Orders production of the given process :param process: The process to run :param steps: The time steps to run the process at as an np.ndarray :param lines: The corresponding lines to run the process at Remarks: - len(steps) must equal len(lines) - No checks are done in this function. It is expected to be used after calling `available_for_production` .. py:method:: available_for_production(repeats: int, step: Union[int, Tuple[int, int]] = ANY_STEP, line: int = ANY_LINE, override: bool = True, method: str = 'latest') -> Tuple[numpy.ndarray, numpy.ndarray] Finds available times and lines for scheduling production. :param repeats: How many times to repeat the process :param step: The simulation step or a range of steps. The special value ANY_STEP gives the factory the freedom to schedule production at any step in the present or future. :param line: The production line. The special value ANY_LINE gives the factory the freedom to use any line :param override: Whether to override any existing commands at that line at that time. :param method: When to schedule the command if step was set to a range. Options are latest, earliest, all :returns: Tuple[np.ndarray, np.ndarray] The steps and lines at which production is scheduled. Remarks: - You cannot order production in the past or in the current step - Ordering production, will automatically update inventory and balance for all simulation steps assuming that this production will be carried out. At the indicated `step` if production was not possible (due to insufficient funds or insufficient inventory of the input product), the predictions for the future will be corrected. .. py:method:: cancel_production(step: int, line: int) -> bool Cancels pre-ordered production given that it did not start yet. :param step: Step to cancel at :param line: Line to cancel at :returns: True if step >= self.current_step Remarks: - Cannot cancel a process in the past or present. .. py:method:: step() -> List[scml.scml2020.common.Failure] Override this method to modify stepping logic. .. py:method:: spot_price(product: int, spot_loss: float) -> int Get the current spot price for buying the given product on the spot market :param product: Product :param spot_loss: Spot loss specific to that agent :returns: The unit price .. py:method:: store(product: int, quantity: int, buy_missing: bool, spot_price: float, no_bankruptcy: bool = False, no_borrowing: bool = False) -> int Stores the given amount of product (signed) to the factory. :param product: Product :param quantity: quantity to store/take out (-ve means take out) :param buy_missing: If the quantity is negative and not enough product exists in the market, it buys the product from the spot-market at an increased price of penalty :param spot_price: The fraction of unit_price added because we are buying from the spot market. Only effective if quantity is negative and not enough of the product exists in the inventory :param no_bankruptcy: Never bankrupt the agent on this transaction :param no_borrowing: Never borrow for this transaction :returns: The quantity actually stored or taken out (always positive) .. py:method:: buy(product: int, quantity: int, unit_price: int, buy_missing: bool, penalty: float, no_bankruptcy: bool = False, no_borrowing: bool = False) -> Tuple[int, int] Executes a transaction to buy/sell involving adding quantity and paying price (both are signed) :param product: The product transacted on :param quantity: The quantity (added) :param unit_price: The unit price (paid) :param buy_missing: If true, attempt buying missing products from the spot market :param penalty: The penalty as a fraction to be paid for breaches :param no_bankruptcy: If true, this transaction can never lead to bankruptcy :param no_borrowing: If true, this transaction can never lead to borrowing :returns: Tuple[int, int] The actual quantities bought and the total cost .. py:method:: pay(money: int, no_bankruptcy: bool = False, no_borrowing: bool = False, unit: int = 0) -> int Pays money :param money: amount to pay :param no_bankruptcy: If true, this transaction can never lead to bankruptcy :param no_borrowing: If true, this transaction can never lead to borrowing :param unit: If nonzero then an integer multiple of unit will be paid :returns: The amount actually paid .. py:method:: bankrupt(required: int) -> int Bankruptcy processing for the given agent :param required: The money required after the bankruptcy is processed :returns: The amount of money to pay back to the entity that should have been paid `money` .. py:class:: SCML2020World(process_inputs: numpy.ndarray, process_outputs: numpy.ndarray, catalog_prices: numpy.ndarray, profiles: list[scml.scml2020.common.FactoryProfile], agent_types: list[type[scml.scml2020.agent.SCML2020Agent]], agent_params: list[dict[str, Any]] | None = None, exogenous_contracts: Collection[scml.scml2020.common.ExogenousContract] = (), initial_balance: numpy.ndarray | tuple[int, int] | int = 1000, allow_buying_output=False, allow_selling_input=False, catalog_quantities: int | numpy.ndarray = 50, buy_missing_products=True, borrow_on_breach=True, bankruptcy_limit=0.0, liquidation_rate=1.0, spot_market_global_loss=0.3, interest_rate=0.05, financial_report_period: int = 5, compensation_fraction: float = 1.0, compensate_immediately=False, compensate_before_past_debt=True, exogenous_horizon: int | None = None, exogenous_force_max: bool = False, production_confirm=False, production_buy_missing=False, production_no_borrow=True, production_no_bankruptcy=False, production_penalty=0.15, compact=False, no_logs=False, n_steps=1000, time_limit=60 * 90, neg_n_steps=20, neg_time_limit=2 * 60, neg_step_time_limit=60, negotiation_speed=21, negotiation_quota_per_step=None, negotiation_quota_per_simulation=float('inf'), n_concurrent_negs_between_partners=float('inf'), shuffle_negotiations=False, end_negotiation_on_refusal_to_propose=True, trading_price_discount=0.9, spot_discount=0.9, spot_multiplier=0.05, signing_delay=0, force_signing=False, batch_signing=True, name: str = None, publish_exogenous_summary=True, publish_trading_prices=True, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_trading: float = 0.5, inventory_valuation_catalog: float = 0.0, **kwargs) Bases: :py:obj:`negmas.situated.TimeInAgreementMixin`, :py:obj:`negmas.situated.World` A Supply Chain SCML2020World simulation as described for the SCML league of ANAC @ IJCAI 2020. :param process_inputs: An n_processes vector specifying the number of inputs from each product needed to execute each process. :param process_outputs: An n_processes vector specifying the number of inputs from each product generated by executing each process. :param catalog_prices: An n_products vector (i.e. n_processes+1 vector) giving the catalog price of all products :param profiles: An n_agents list of `FactoryProfile` objects specifying the private profile of the factory associated with each agent. :param agent_types: An n_agents list of strings/ `SCML2020Agent` classes specifying the type of each agent :param agent_params: An n_agents dictionaries giving the parameters of each agent :param initial_balance: The initial balance in each agent's wallet. All agents will start with this same value. :param allow_selling_input: Allows agents to sell their input product(s) through negotiation :param allow_buying_output: Allows agents to buy their output product(s) through negotiation :param catalog_quantities: The quantities in the past for which catalog_prices are the average unit prices. This is used when updating the trading prices. If set to zero then the trading price will follow the market price and will not use the catalog_price (except for products that are never sold in the market for which the trading price will take the default value of the catalog price). If set to a large value (e.g. 10000), the price at which a product is sold will not affect the trading price :param spot_market_global_loss: Buying from the spot market will cost trading-price * (1+`spot_market_global_loss) and selling to it will cost trading-price / (1+ spot_market_global_loss) for agents with unit spot-market-loss-multiplier :param financial_report_period: The number of steps between financial reports. If < 1, it is a fraction of n_steps :param borrow_on_breach: If true, agents will be forced to borrow money on breach as much as possible to honor the contract :param interest_rate: The interest at which loans grow over time (it only affect a factory when its balance is negative) :param bankruptcy_limit: The maximum amount that be be borrowed (including interest). The balance of any factory cannot go lower than - borrow_limit or the agent will go bankrupt immediately :param liquidation_rate: The rate at which future contracts get liquidated when an agent gets bankrupt. It should be between zero and one. :param compensation_fraction: Fraction of a contract to be compensated (at most) if a partner goes bankrupt. Notice that this fraction is not guaranteed because the bankrupt agent may not have enough assets to pay all of its standing contracts to this level of compensation. In such cases, a smaller fraction will be used. :param compensate_immediately: If true, compensation will happen immediately when an agent goes bankrupt and in in money. This means that agents with contracts involving the bankrupt agent will just have these contracts be nullified and receive monetary compensation immediately . If false, compensation will not happen immediately but at the contract execution time. In this case, agents with contracts involving the bankrupt agent will be informed of the compensation fraction (instead of the compensation money) at the time of bankruptcy and will receive the compensation in kind (money if they are sellers and products if they are buyers) at the normal execution time of the contract. In the special case of no-compensation (i.e. `compensation_fraction` is zero or the bankrupt agent has no assets), the two options will behave similarity. :param compensate_before_past_debt: If true, then compensations will be paid before past debt is considered, otherwise, the money from liquidating bankrupt agents will first be used to pay past debt then whatever remains will be used for compensation. Notice that in all cases, the trigger of bankruptcy will be paid before compensation and past debts. :param exogenous_horizon: The horizon for revealing external contracts :param exogenous_force_max: If true, exogenous contracts are forced to be signed independent of the setting of `force_signing` :param production_no_borrow: If true, agents will not borrow if they fail to satisfy its production need to execute a scheduled production command :param production_no_bankruptcy: If true, agents will not go bankrupt because of an production related transaction. :param production_penalty: The penalty paid when buying from spot-market to satisfy production needs :param production_confirm: If true, the factory will confirm running processes at every time-step just before running them by calling `confirm_production` on the agent controlling it. :param compact: If True, no logs will be kept and the whole simulation will use a smaller memory footprint :param n_steps: Number of simulation steps (can be considered as days). :param time_limit: Total time allowed for the complete simulation in seconds. :param neg_n_steps: Number of negotiation steps allowed for all negotiations. :param neg_time_limit: Total time allowed for a complete negotiation in seconds. :param neg_step_time_limit: Total time allowed for a single step of a negotiation. in seconds. :param negotiation_speed: The number of negotiation steps that pass in every simulation step. If 0, negotiations will be guaranteed to finish within a single simulation step :param signing_delay: The number of simulation steps to pass between a contract is concluded and signed :param name: The name of the simulations :param \*\*kwargs: Other parameters that are passed directly to `SCML2020World` constructor. .. py:attribute:: publish_exogenous_summary :value: True .. py:attribute:: publish_trading_prices :value: True .. py:attribute:: allow_buying_output :value: False .. py:attribute:: allow_selling_input :value: False .. py:attribute:: exogenous_horizon :value: None .. py:attribute:: buy_missing_products :value: True .. py:attribute:: production_buy_missing :value: False .. py:attribute:: liquidation_rate :value: 1.0 .. py:attribute:: trading_price_discount :value: 0.9 .. py:attribute:: spot_discount :value: 0.9 .. py:attribute:: spot_multiplier :value: 0.05 .. py:attribute:: catalog_quantities :value: 50 .. py:attribute:: inventory_valuation_trading :value: 0.5 .. py:attribute:: inventory_valuation_catalog :value: 0.0 .. py:attribute:: n_concurrent_negs_between_partners .. py:attribute:: compact :value: False .. py:attribute:: spot_market_global_loss :value: 0.3 .. py:attribute:: production_no_borrow :value: True .. py:attribute:: production_no_bankruptcy :value: False .. py:attribute:: production_penalty :value: 0.15 .. py:attribute:: compensation_fraction :value: 1.0 .. py:attribute:: profiles .. py:attribute:: catalog_prices .. py:attribute:: process_inputs .. py:attribute:: process_outputs .. py:attribute:: n_products .. py:attribute:: n_processes .. py:attribute:: borrow_on_breach :value: True .. py:attribute:: interest_rate :value: 0.05 .. py:attribute:: exogenous_force_max :value: False .. py:attribute:: compensate_before_past_debt :value: True .. py:attribute:: confirm_production :value: False .. py:attribute:: financial_reports_period :value: 5 .. py:attribute:: compensate_immediately :value: False .. py:attribute:: bankruptcy_limit :value: -0.0 .. py:attribute:: agent_types .. py:attribute:: agent_params .. py:attribute:: agent_unique_types .. py:attribute:: factories .. py:attribute:: a2f .. py:attribute:: afp .. py:attribute:: i2a :value: [] .. py:attribute:: i2f .. py:attribute:: breach_prob .. py:attribute:: _breach_level .. py:attribute:: agent_n_contracts .. py:attribute:: suppliers :type: list[list[str]] .. py:attribute:: consumers :type: list[list[str]] .. py:attribute:: agent_processes :type: dict[str, list[int]] .. py:attribute:: agent_inputs :type: dict[str, list[int]] .. py:attribute:: agent_outputs :type: dict[str, list[int]] .. py:attribute:: agent_consumers :type: dict[str, list[str]] .. py:attribute:: agent_suppliers :type: dict[str, list[str]] .. py:attribute:: agent_profiles :type: dict[str, Any] .. py:attribute:: initial_balances :type: dict[str, Any] .. py:attribute:: _n_production_failures :value: 0 .. py:attribute:: __n_nullified :value: 0 .. py:attribute:: __n_bankrupt :value: 0 .. py:attribute:: penalties :value: 0 .. py:attribute:: compensation_balance :value: 0 .. py:attribute:: compensation_records :type: dict[str, list[CompensationRecord]] .. py:attribute:: exogenous_contracts :type: dict[int:list[Contract]] .. py:attribute:: compensation_factory .. py:attribute:: _agent_output .. py:attribute:: _agent_input .. py:attribute:: _traded_quantity .. py:attribute:: _real_price .. py:attribute:: _sold_quantity .. py:attribute:: _trading_price .. py:attribute:: _betas .. py:attribute:: _betas_sum .. py:attribute:: _spot_quantity .. py:attribute:: _alphas .. py:attribute:: _agent_spot_loss .. py:attribute:: _agent_spot_quantity .. py:attribute:: _registered_negs :type: dict[tuple[str], int] .. py:attribute:: exogenous_contracts_summary :value: None .. py:method:: generate(agent_types: list[type[scml.scml2020.agent.SCML2020Agent] | str], agent_params: list[dict[str, Any]] | None = None, agent_processes: list[int] | None = None, n_steps: tuple[int, int] | int = (50, 200), n_processes: tuple[int, int] | int = (2, 4), n_lines: numpy.ndarray | tuple[int, int] | int = 10, n_agents_per_process: numpy.ndarray | tuple[int, int] | int = (2, 4), process_inputs: numpy.ndarray | tuple[int, int] | int = 1, process_outputs: numpy.ndarray | tuple[int, int] | int = 1, production_costs: numpy.ndarray | tuple[int, int] | int = (1, 4), profit_means: numpy.ndarray | tuple[float, float] | float = (0.15, 0.2), profit_stddevs: numpy.ndarray | tuple[float, float] | float = 0.001, max_productivity: numpy.ndarray | tuple[float, float] | float = 1.0, initial_balance: numpy.ndarray | tuple[int, int] | int | None = None, cost_increases_with_level=True, equal_exogenous_supply=False, equal_exogenous_sales=False, exogenous_supply_predictability: tuple[float, float] | float = (0.6, 0.9), exogenous_sales_predictability: tuple[float, float] | float = (0.6, 0.9), exogenous_control: tuple[float, float] | float = (0.2, 0.8), cash_availability: tuple[float, float] | float = (1.5, 2.5), force_signing=False, profit_basis=np.max, horizon: tuple[float, float] | float = (0.2, 0.5), inventory_valuation_trading: numpy.ndarray | tuple[float, float] | float = 0.5, inventory_valuation_catalog: numpy.ndarray | tuple[float, float] | float = 0.0, random_agent_types: bool = False, cost_relativity: float = 1.0, exogenous_generation_method='profitable', exogenous_supply_surplus: tuple[float, float] | float = 0.0, exogenous_sales_surplus: tuple[float, float] | float = 0.0, run_extra_checks: bool = True, **kwargs) -> dict[str, Any] :classmethod: Generates the configuration for a world :param agent_types: All agent types :param agent_params: Agent parameters used to initialize them :param n_steps: Number of simulation steps :param n_processes: Number of processes in the production chain :param n_lines: Number of lines per factory :param process_inputs: Number of input units per process :param process_outputs: Number of output units per process :param production_costs: Production cost per factory :param profit_means: Mean profitability per production level (i.e. process). :param profit_stddevs: Std. Dev. of the profitability of every level (i.e. process). :param inventory_valuation_catalog: The fraction of catalog price to value items at the end. :param inventory_valuation_trading: The fraction of trading price to value items at the end. :param max_productivity: Maximum possible productivity per level (i.e. process). :param initial_balance: The initial balance of all agents :param n_agents_per_process: Number of agents per process :param agent_processes: The process for each agent. If not `None` , it will override `n_agents_per_process` and must be a list/tuple of the same length as `agent_types` . Morevoer, `random_agent_types` must be False in this case :param cost_increases_with_level: If true, production cost will be higher for processes nearer to the final product. :param profit_basis: The statistic used when controlling catalog prices by profit arguments. It can be np.mean, np.median, np.min, np.max or any Callable[[list[float]], float] and is used to summarize production costs at every level. :param horizon: The horizon used for revealing external supply/sales as a fraction of n_steps :param equal_exogenous_supply: If true, external supply will be distributed equally among all agents in the first layer :param equal_exogenous_sales: If true, external sales will be distributed equally among all agents in the last layer :param exogenous_supply_predictability: How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random :param exogenous_sales_predictability: How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random :param cash_availability: The fraction of the total money needs of the agent to work at maximum capacity that is available as `initial_balance` . This is only effective if `initial_balance` is set to `None` . :param force_signing: Whether to force contract signatures (exogenous contracts are treated in the same way). :param exogenous_control: How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True :param random_agent_types: If True, the final agent types used by the generato wil always be sampled from the given types. If False, this random sampling will only happin if len(agent_types) != n_agents. :param cost_relativity: The exponent of production cost used to distribute contracts during generation :param method: The method used for world generation. Available methods are "profitable" and "guaranteed_profit" :param exogenous_supply_surplus: The surpolus exogenous supply contract quantity to add to the system as a fraction of the a fraction of the contracts generated by the given method. :param exogenous_sales_surplus: The surpolus exogenous sales contract quantity to add to the system as a fraction of the a fraction of the contracts generated by the given method. :param run_extra_checks: If given, the world generation method will check whether the genrated world "makes sense" given its internal criteria. May slow down world generation :param \*\*kwargs: :returns: world configuration as a dict[str, Any]. A world can be generated from this dict by calling SCML2020World(**d) Remarks: - There are two general ways to use this generator: 1. Pass `random_agent_types = True`, and pass `agent_types`, `agent_processes` to control placement of each agent in each level of the production graph. 2. Pass `random_agent_types = False` and pass `agent_types`, `n_agents_per_process` to make the system randomly place the specified number of agents in each production level - Most parameters (i.e. `process_inputs` , `process_outputs` , `n_agents_per_process` , `costs` ) can take a single value, a tuple of two values, or a list of values. If it has a single value, it is repeated for all processes/factories as appropriate. If it is a tuple of two numbers $(i, j)$, each process will take a number sampled from a uniform distribution supported on $[i, j]$ inclusive. If it is a list of values, of the length `n_processes` , it is used as it is otherwise, it is used to sample values for each process. .. py:method:: generate_guaranteed_profit(n_steps: int, n_lines: int, n_agents_per_process: int, process_of_agent: list[int], first_agent: list[int], last_agent: list[int], production_costs: list[int], exogenous_control: float, cash_availability: float, force_signing: bool, horizon: int, exogenous_supplies: list[int], max_productivity_process: list[float], max_productivity_agent: list[float], equal_exogenous_sales: bool, process_inputs: list[int], process_outputs: list[int], exogenous_sales_predictability: float, costs: numpy.ndarray, profit_stddevs_agent=list[float], profit_means_agent=list[float], initial_balance: numpy.ndarray | tuple[int, int] | int | None = None, cost_relativity: float = 1.0, profit_basis=np.max, inventory_valuation_trading: float = 0.5, inventory_valuation_catalog: float = 0.0, run_extra_checks=True) -> tuple[list[scml.scml2020.common.ExogenousContract], list[int], list[scml.scml2020.common.FactoryProfile], list[float], dict[str, Any]] :classmethod: Generates prices, contracts and profiles ensuring that all agents can profit and returning a set of explict contracts that can achieve this profit .. py:method:: generate_profitable(n_steps: int, n_lines: int, n_agents_per_process: int, process_of_agent: list[int], first_agent: list[int], last_agent: list[int], production_costs: list[int], exogenous_control: float, cash_availability: float, force_signing: bool, horizon: int, exogenous_supplies: list[int], max_productivity_process: list[float], max_productivity_agent: list[float], equal_exogenous_sales: bool, process_inputs: list[int], process_outputs: list[int], exogenous_sales_predictability: float, costs: numpy.ndarray, profit_stddevs_agent=list[float], profit_means_agent=list[float], initial_balance: numpy.ndarray | tuple[int, int] | int | None = None, cost_relativity: float = 1.0, profit_basis=np.max, inventory_valuation_trading: float = 0.5, inventory_valuation_catalog: float = 0.0, run_extra_checks: bool = True) -> tuple[list[scml.scml2020.common.ExogenousContract], list[int], list[scml.scml2020.common.FactoryProfile], list[float], dict[str, Any]] :classmethod: Generates the prices, contracts and profiles ensuring there is some possibility of profit in the market .. py:method:: get_private_state(agent: scml.scml2020.agent.SCML2020Agent) -> dict Reads the private state of the given agent .. py:method:: add_financial_report(agent: scml.scml2020.agent.SCML2020Agent, factory: scml.scml2020.factory.Factory, reports_agent, reports_time) -> None Records a financial report for the given agent in the agent indexed reports and time indexed reports :param agent: The agent :param factory: Its factory :param reports_agent: A dictionary of financial reports indexed by agent id :param reports_time: A dictionary of financial reports indexed by time Returns: .. py:method:: negs_between(a1, a2) .. py:method:: current_balance(agent_id: str) .. py:method:: can_negotiate(a1, a2) .. py:method:: simulation_step(stage) A single step of the simulation. :param stage: How many times so far was this method called within the current simulation step Remarks: - Using the stage parameter, it is possible to have `Operations` . `SimulationStep` several times with the list of operations while differentiating between these calls. .. py:method:: contract_size(contract: negmas.Contract) -> float Returns an estimation of the **activity level** associated with this contract. Higher is better :param contract: Returns: .. py:method:: contract_record(contract: negmas.Contract) -> dict[str, Any] Converts a contract to a record suitable for permanent storage .. py:method:: breach_record(breach: negmas.Breach) -> dict[str, Any] Converts a breach to a record suitable for storage during the simulation .. py:method:: execute_action(action: negmas.Action, agent: scml.scml2020.agent.SCML2020Agent, callback: Callable = None) -> bool Executes the given action by the given agent .. py:method:: post_step_stats() Called at the end of the simulation step to update all stats Kept for backward compatibility and will be dropped. Override `update_stats` ins .. py:method:: pre_step_stats() Called at the beginning of the simulation step to prepare stats or update them Kept for backward compatibility and will be dropped. Override `update_stats` instead .. py:property:: productivity :type: float Fraction of production lines occupied during the simulation .. py:method:: welfare(include_bankrupt: bool = False) -> float Total welfare of all agents .. py:method:: relative_welfare(include_bankrupt: bool = False) -> float | None Total welfare relative to expected value. Returns None if no expectation is found in self.info .. py:property:: relative_productivity :type: float | None Productivity relative to the expected value. Will return None if self.info does not have the expected productivity .. py:property:: bankruptcy_rate :type: float The fraction of factories that went bankrupt .. py:property:: num_bankrupt :type: float The fraction of factories that went bankrupt .. py:method:: order_contracts_for_execution(contracts: Collection[negmas.Contract]) -> Collection[negmas.Contract] Orders the contracts in a specific time-step that are about to be executed .. py:method:: _execute(product: int, q: int, p: int, u: int, buyer_factory: scml.scml2020.factory.Factory, seller_factory: scml.scml2020.factory.Factory, has_breaches: bool) Executes the contract .. py:method:: __register_contract(agent_id: str, level: float) -> None Registers execution of the contract in the agent's stats .. py:method:: record_bankrupt(factory: scml.scml2020.factory.Factory) -> None Records agent bankruptcy .. py:method:: on_contract_concluded(contract: negmas.Contract, to_be_signed_at: int) -> None Called to add a contract to the existing set of unsigned contract after it is concluded :param contract: The contract to add :param to_be_signed_at: The timestep at which the contract is to be signed Remarks: - By default this function just adds the contract to the set of contracts maintaned by the world. - You should ALWAYS call this function when overriding it. .. py:method:: is_valid_contact(contract: negmas.Contract) -> bool Checks whether a signed contract is valid .. py:method:: on_contract_signed(contract: negmas.Contract) -> bool Called to add a contract to the existing set of contract after it is signed :param contract: The contract to add :returns: True if everything went OK and False otherwise Remarks: - By default this function just adds the contract to the set of contracts maintaned by the world. - You should ALWAYS call this function when overriding it. .. py:method:: nullify_contract(contract: negmas.Contract, new_quantity: int) .. py:method:: __register_breach(agent_id: str, level: float, contract_total: float, factory: scml.scml2020.factory.Factory) -> int Registers a breach of the given level on the given agent. Assume that the contract is already added to the agent_contracts :param agent_id: The perpetrator of the breach :param level: The breach level :param contract_total: The total of the contract breached (quantity * unit_price) :param factory: The factory corresponding to the perpetrator :returns: If nonzero, the agent should go bankrupt and this amount taken from them .. py:method:: _spot_loss(aid: str) -> float .. py:method:: start_contract_execution(contract: negmas.Contract) -> set[negmas.Breach] | None Tries to execute the contract :param contract: :returns: The set of breaches committed if any. If there are no breaches return an empty set :rtype: 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). .. py:method:: complete_contract_execution(contract: negmas.Contract, breaches: list[negmas.Breach], resolution: negmas.Contract) -> None Called after breach resolution is completed for contracts for which some potential breaches occurred. :param contract: The contract considered. :param breaches: The list of potential breaches that was generated by `_execute_contract`. :param resolution: The agreed upon resolution Returns: .. py:method:: compensate(available: int, factory: scml.scml2020.factory.Factory) -> dict[str, list[tuple[negmas.Contract, int, int]]] Called by a factory when it is going bankrupt after liquidation :param available: The amount available from liquidation :param factory: The factory being bankrupted :returns: A mapping from agent ID to nullified contracts, the new quantity for them and compensation_money .. py:method:: scores(assets_multiplier_trading: float | None = None, assets_multiplier_catalog: float | None = None, assets_multiplier: float | None = None) -> dict[str, float] scores of all agents given the asset multiplier. :param assets_multiplier: a multiplier to multiply the assets with. .. py:property:: winners The winners of this world (factory managers with maximum wallet balance .. py:method:: trading_prices_for(discount: float = 1.0, condition='executed') -> numpy.ndarray Calculates the prices at which all products traded using an optional discount factor :param discount: A discount factor to treat older prices less importantly (exponential discounting). :param condition: The condition for contracts to consider. Possible values are executed, signed, concluded, nullified :returns: an n_products vector of trading prices .. py:property:: trading_prices .. py:property:: stats_df :type: pandas.DataFrame Returns a pandas data frame with the stats .. py:property:: contracts_df :type: pandas.DataFrame Returns a pandas data frame with the contracts .. py:property:: system_agents :type: list[scml.scml2020.agent.SCML2020Agent] Returns the two system agents .. py:property:: system_agent_names :type: list[str] Returns the names two system agents .. py:property:: non_system_agents :type: list[scml.scml2020.agent.SCML2020Agent] Returns all agents except system agents .. py:property:: non_system_agent_names :type: list[str] Returns names of all agents except system agents .. py:property:: agreement_fraction :type: float Fraction of negotiations ending in agreement and leading to signed contracts .. py:attribute:: system_agent_ids .. py:attribute:: non_system_agent_ids .. py:method:: draw(steps: tuple[int, int] | int | None = None, what: Collection[str] = DEFAULT_EDGE_TYPES, who: Callable[[negmas.Agent], bool] = None, where: Callable[[negmas.Agent], int | tuple[float, float]] = None, together: bool = True, axs: Collection[matplotlib.axis.Axis] = None, ncols: int = 4, figsize: tuple[int, int] = (15, 15), **kwargs) -> tuple[matplotlib.axis.Axis, networkx.Graph] | tuple[list[matplotlib.axis.Axis], list[networkx.Graph]] .. py:class:: SCML2021World(*args, **kwargs) Bases: :py:obj:`SCML2020World` A Supply Chain SCML2020World simulation as described for the SCML league of ANAC @ IJCAI 2020. :param process_inputs: An n_processes vector specifying the number of inputs from each product needed to execute each process. :param process_outputs: An n_processes vector specifying the number of inputs from each product generated by executing each process. :param catalog_prices: An n_products vector (i.e. n_processes+1 vector) giving the catalog price of all products :param profiles: An n_agents list of `FactoryProfile` objects specifying the private profile of the factory associated with each agent. :param agent_types: An n_agents list of strings/ `SCML2020Agent` classes specifying the type of each agent :param agent_params: An n_agents dictionaries giving the parameters of each agent :param initial_balance: The initial balance in each agent's wallet. All agents will start with this same value. :param allow_selling_input: Allows agents to sell their input product(s) through negotiation :param allow_buying_output: Allows agents to buy their output product(s) through negotiation :param catalog_quantities: The quantities in the past for which catalog_prices are the average unit prices. This is used when updating the trading prices. If set to zero then the trading price will follow the market price and will not use the catalog_price (except for products that are never sold in the market for which the trading price will take the default value of the catalog price). If set to a large value (e.g. 10000), the price at which a product is sold will not affect the trading price :param spot_market_global_loss: Buying from the spot market will cost trading-price * (1+`spot_market_global_loss) and selling to it will cost trading-price / (1+ spot_market_global_loss) for agents with unit spot-market-loss-multiplier :param financial_report_period: The number of steps between financial reports. If < 1, it is a fraction of n_steps :param borrow_on_breach: If true, agents will be forced to borrow money on breach as much as possible to honor the contract :param interest_rate: The interest at which loans grow over time (it only affect a factory when its balance is negative) :param bankruptcy_limit: The maximum amount that be be borrowed (including interest). The balance of any factory cannot go lower than - borrow_limit or the agent will go bankrupt immediately :param liquidation_rate: The rate at which future contracts get liquidated when an agent gets bankrupt. It should be between zero and one. :param compensation_fraction: Fraction of a contract to be compensated (at most) if a partner goes bankrupt. Notice that this fraction is not guaranteed because the bankrupt agent may not have enough assets to pay all of its standing contracts to this level of compensation. In such cases, a smaller fraction will be used. :param compensate_immediately: If true, compensation will happen immediately when an agent goes bankrupt and in in money. This means that agents with contracts involving the bankrupt agent will just have these contracts be nullified and receive monetary compensation immediately . If false, compensation will not happen immediately but at the contract execution time. In this case, agents with contracts involving the bankrupt agent will be informed of the compensation fraction (instead of the compensation money) at the time of bankruptcy and will receive the compensation in kind (money if they are sellers and products if they are buyers) at the normal execution time of the contract. In the special case of no-compensation (i.e. `compensation_fraction` is zero or the bankrupt agent has no assets), the two options will behave similarity. :param compensate_before_past_debt: If true, then compensations will be paid before past debt is considered, otherwise, the money from liquidating bankrupt agents will first be used to pay past debt then whatever remains will be used for compensation. Notice that in all cases, the trigger of bankruptcy will be paid before compensation and past debts. :param exogenous_horizon: The horizon for revealing external contracts :param exogenous_force_max: If true, exogenous contracts are forced to be signed independent of the setting of `force_signing` :param production_no_borrow: If true, agents will not borrow if they fail to satisfy its production need to execute a scheduled production command :param production_no_bankruptcy: If true, agents will not go bankrupt because of an production related transaction. :param production_penalty: The penalty paid when buying from spot-market to satisfy production needs :param production_confirm: If true, the factory will confirm running processes at every time-step just before running them by calling `confirm_production` on the agent controlling it. :param compact: If True, no logs will be kept and the whole simulation will use a smaller memory footprint :param n_steps: Number of simulation steps (can be considered as days). :param time_limit: Total time allowed for the complete simulation in seconds. :param neg_n_steps: Number of negotiation steps allowed for all negotiations. :param neg_time_limit: Total time allowed for a complete negotiation in seconds. :param neg_step_time_limit: Total time allowed for a single step of a negotiation. in seconds. :param negotiation_speed: The number of negotiation steps that pass in every simulation step. If 0, negotiations will be guaranteed to finish within a single simulation step :param signing_delay: The number of simulation steps to pass between a contract is concluded and signed :param name: The name of the simulations :param \*\*kwargs: Other parameters that are passed directly to `SCML2020World` constructor. .. py:method:: generate(*args, inventory_valuation_trading: numpy.ndarray | tuple[float, float] | float = (0.0, 0.5), horizon: tuple[float, float] | float = (0.2, 0.5), **kwargs) -> dict[str, Any] :classmethod: Generates the configuration for a world :param agent_types: All agent types :param agent_params: Agent parameters used to initialize them :param n_steps: Number of simulation steps :param n_processes: Number of processes in the production chain :param n_lines: Number of lines per factory :param process_inputs: Number of input units per process :param process_outputs: Number of output units per process :param production_costs: Production cost per factory :param profit_means: Mean profitability per production level (i.e. process). :param profit_stddevs: Std. Dev. of the profitability of every level (i.e. process). :param inventory_valuation_catalog: The fraction of catalog price to value items at the end. :param inventory_valuation_trading: The fraction of trading price to value items at the end. :param max_productivity: Maximum possible productivity per level (i.e. process). :param initial_balance: The initial balance of all agents :param n_agents_per_process: Number of agents per process :param agent_processes: The process for each agent. If not `None` , it will override `n_agents_per_process` and must be a list/tuple of the same length as `agent_types` . Morevoer, `random_agent_types` must be False in this case :param cost_increases_with_level: If true, production cost will be higher for processes nearer to the final product. :param profit_basis: The statistic used when controlling catalog prices by profit arguments. It can be np.mean, np.median, np.min, np.max or any Callable[[list[float]], float] and is used to summarize production costs at every level. :param horizon: The horizon used for revealing external supply/sales as a fraction of n_steps :param equal_exogenous_supply: If true, external supply will be distributed equally among all agents in the first layer :param equal_exogenous_sales: If true, external sales will be distributed equally among all agents in the last layer :param exogenous_supply_predictability: How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random :param exogenous_sales_predictability: How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random :param cash_availability: The fraction of the total money needs of the agent to work at maximum capacity that is available as `initial_balance` . This is only effective if `initial_balance` is set to `None` . :param force_signing: Whether to force contract signatures (exogenous contracts are treated in the same way). :param exogenous_control: How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True :param random_agent_types: If True, the final agent types used by the generato wil always be sampled from the given types. If False, this random sampling will only happin if len(agent_types) != n_agents. :param cost_relativity: The exponent of production cost used to distribute contracts during generation :param method: The method used for world generation. Available methods are "profitable" and "guaranteed_profit" :param exogenous_supply_surplus: The surpolus exogenous supply contract quantity to add to the system as a fraction of the a fraction of the contracts generated by the given method. :param exogenous_sales_surplus: The surpolus exogenous sales contract quantity to add to the system as a fraction of the a fraction of the contracts generated by the given method. :param run_extra_checks: If given, the world generation method will check whether the genrated world "makes sense" given its internal criteria. May slow down world generation :param \*\*kwargs: :returns: world configuration as a dict[str, Any]. A world can be generated from this dict by calling SCML2020World(**d) Remarks: - There are two general ways to use this generator: 1. Pass `random_agent_types = True`, and pass `agent_types`, `agent_processes` to control placement of each agent in each level of the production graph. 2. Pass `random_agent_types = False` and pass `agent_types`, `n_agents_per_process` to make the system randomly place the specified number of agents in each production level - Most parameters (i.e. `process_inputs` , `process_outputs` , `n_agents_per_process` , `costs` ) can take a single value, a tuple of two values, or a list of values. If it has a single value, it is repeated for all processes/factories as appropriate. If it is a tuple of two numbers $(i, j)$, each process will take a number sampled from a uniform distribution supported on $[i, j]$ inclusive. If it is a list of values, of the length `n_processes` , it is used as it is otherwise, it is used to sample values for each process. .. py:class:: SCML2022World(*args, **kwargs) Bases: :py:obj:`SCML2021World` A Supply Chain SCML2020World simulation as described for the SCML league of ANAC @ IJCAI 2020. :param process_inputs: An n_processes vector specifying the number of inputs from each product needed to execute each process. :param process_outputs: An n_processes vector specifying the number of inputs from each product generated by executing each process. :param catalog_prices: An n_products vector (i.e. n_processes+1 vector) giving the catalog price of all products :param profiles: An n_agents list of `FactoryProfile` objects specifying the private profile of the factory associated with each agent. :param agent_types: An n_agents list of strings/ `SCML2020Agent` classes specifying the type of each agent :param agent_params: An n_agents dictionaries giving the parameters of each agent :param initial_balance: The initial balance in each agent's wallet. All agents will start with this same value. :param allow_selling_input: Allows agents to sell their input product(s) through negotiation :param allow_buying_output: Allows agents to buy their output product(s) through negotiation :param catalog_quantities: The quantities in the past for which catalog_prices are the average unit prices. This is used when updating the trading prices. If set to zero then the trading price will follow the market price and will not use the catalog_price (except for products that are never sold in the market for which the trading price will take the default value of the catalog price). If set to a large value (e.g. 10000), the price at which a product is sold will not affect the trading price :param spot_market_global_loss: Buying from the spot market will cost trading-price * (1+`spot_market_global_loss) and selling to it will cost trading-price / (1+ spot_market_global_loss) for agents with unit spot-market-loss-multiplier :param financial_report_period: The number of steps between financial reports. If < 1, it is a fraction of n_steps :param borrow_on_breach: If true, agents will be forced to borrow money on breach as much as possible to honor the contract :param interest_rate: The interest at which loans grow over time (it only affect a factory when its balance is negative) :param bankruptcy_limit: The maximum amount that be be borrowed (including interest). The balance of any factory cannot go lower than - borrow_limit or the agent will go bankrupt immediately :param liquidation_rate: The rate at which future contracts get liquidated when an agent gets bankrupt. It should be between zero and one. :param compensation_fraction: Fraction of a contract to be compensated (at most) if a partner goes bankrupt. Notice that this fraction is not guaranteed because the bankrupt agent may not have enough assets to pay all of its standing contracts to this level of compensation. In such cases, a smaller fraction will be used. :param compensate_immediately: If true, compensation will happen immediately when an agent goes bankrupt and in in money. This means that agents with contracts involving the bankrupt agent will just have these contracts be nullified and receive monetary compensation immediately . If false, compensation will not happen immediately but at the contract execution time. In this case, agents with contracts involving the bankrupt agent will be informed of the compensation fraction (instead of the compensation money) at the time of bankruptcy and will receive the compensation in kind (money if they are sellers and products if they are buyers) at the normal execution time of the contract. In the special case of no-compensation (i.e. `compensation_fraction` is zero or the bankrupt agent has no assets), the two options will behave similarity. :param compensate_before_past_debt: If true, then compensations will be paid before past debt is considered, otherwise, the money from liquidating bankrupt agents will first be used to pay past debt then whatever remains will be used for compensation. Notice that in all cases, the trigger of bankruptcy will be paid before compensation and past debts. :param exogenous_horizon: The horizon for revealing external contracts :param exogenous_force_max: If true, exogenous contracts are forced to be signed independent of the setting of `force_signing` :param production_no_borrow: If true, agents will not borrow if they fail to satisfy its production need to execute a scheduled production command :param production_no_bankruptcy: If true, agents will not go bankrupt because of an production related transaction. :param production_penalty: The penalty paid when buying from spot-market to satisfy production needs :param production_confirm: If true, the factory will confirm running processes at every time-step just before running them by calling `confirm_production` on the agent controlling it. :param compact: If True, no logs will be kept and the whole simulation will use a smaller memory footprint :param n_steps: Number of simulation steps (can be considered as days). :param time_limit: Total time allowed for the complete simulation in seconds. :param neg_n_steps: Number of negotiation steps allowed for all negotiations. :param neg_time_limit: Total time allowed for a complete negotiation in seconds. :param neg_step_time_limit: Total time allowed for a single step of a negotiation. in seconds. :param negotiation_speed: The number of negotiation steps that pass in every simulation step. If 0, negotiations will be guaranteed to finish within a single simulation step :param signing_delay: The number of simulation steps to pass between a contract is concluded and signed :param name: The name of the simulations :param \*\*kwargs: Other parameters that are passed directly to `SCML2020World` constructor. .. py:class:: SCML2023World(*args, **kwargs) Bases: :py:obj:`SCML2022World` A Supply Chain SCML2020World simulation as described for the SCML league of ANAC @ IJCAI 2020. :param process_inputs: An n_processes vector specifying the number of inputs from each product needed to execute each process. :param process_outputs: An n_processes vector specifying the number of inputs from each product generated by executing each process. :param catalog_prices: An n_products vector (i.e. n_processes+1 vector) giving the catalog price of all products :param profiles: An n_agents list of `FactoryProfile` objects specifying the private profile of the factory associated with each agent. :param agent_types: An n_agents list of strings/ `SCML2020Agent` classes specifying the type of each agent :param agent_params: An n_agents dictionaries giving the parameters of each agent :param initial_balance: The initial balance in each agent's wallet. All agents will start with this same value. :param allow_selling_input: Allows agents to sell their input product(s) through negotiation :param allow_buying_output: Allows agents to buy their output product(s) through negotiation :param catalog_quantities: The quantities in the past for which catalog_prices are the average unit prices. This is used when updating the trading prices. If set to zero then the trading price will follow the market price and will not use the catalog_price (except for products that are never sold in the market for which the trading price will take the default value of the catalog price). If set to a large value (e.g. 10000), the price at which a product is sold will not affect the trading price :param spot_market_global_loss: Buying from the spot market will cost trading-price * (1+`spot_market_global_loss) and selling to it will cost trading-price / (1+ spot_market_global_loss) for agents with unit spot-market-loss-multiplier :param financial_report_period: The number of steps between financial reports. If < 1, it is a fraction of n_steps :param borrow_on_breach: If true, agents will be forced to borrow money on breach as much as possible to honor the contract :param interest_rate: The interest at which loans grow over time (it only affect a factory when its balance is negative) :param bankruptcy_limit: The maximum amount that be be borrowed (including interest). The balance of any factory cannot go lower than - borrow_limit or the agent will go bankrupt immediately :param liquidation_rate: The rate at which future contracts get liquidated when an agent gets bankrupt. It should be between zero and one. :param compensation_fraction: Fraction of a contract to be compensated (at most) if a partner goes bankrupt. Notice that this fraction is not guaranteed because the bankrupt agent may not have enough assets to pay all of its standing contracts to this level of compensation. In such cases, a smaller fraction will be used. :param compensate_immediately: If true, compensation will happen immediately when an agent goes bankrupt and in in money. This means that agents with contracts involving the bankrupt agent will just have these contracts be nullified and receive monetary compensation immediately . If false, compensation will not happen immediately but at the contract execution time. In this case, agents with contracts involving the bankrupt agent will be informed of the compensation fraction (instead of the compensation money) at the time of bankruptcy and will receive the compensation in kind (money if they are sellers and products if they are buyers) at the normal execution time of the contract. In the special case of no-compensation (i.e. `compensation_fraction` is zero or the bankrupt agent has no assets), the two options will behave similarity. :param compensate_before_past_debt: If true, then compensations will be paid before past debt is considered, otherwise, the money from liquidating bankrupt agents will first be used to pay past debt then whatever remains will be used for compensation. Notice that in all cases, the trigger of bankruptcy will be paid before compensation and past debts. :param exogenous_horizon: The horizon for revealing external contracts :param exogenous_force_max: If true, exogenous contracts are forced to be signed independent of the setting of `force_signing` :param production_no_borrow: If true, agents will not borrow if they fail to satisfy its production need to execute a scheduled production command :param production_no_bankruptcy: If true, agents will not go bankrupt because of an production related transaction. :param production_penalty: The penalty paid when buying from spot-market to satisfy production needs :param production_confirm: If true, the factory will confirm running processes at every time-step just before running them by calling `confirm_production` on the agent controlling it. :param compact: If True, no logs will be kept and the whole simulation will use a smaller memory footprint :param n_steps: Number of simulation steps (can be considered as days). :param time_limit: Total time allowed for the complete simulation in seconds. :param neg_n_steps: Number of negotiation steps allowed for all negotiations. :param neg_time_limit: Total time allowed for a complete negotiation in seconds. :param neg_step_time_limit: Total time allowed for a single step of a negotiation. in seconds. :param negotiation_speed: The number of negotiation steps that pass in every simulation step. If 0, negotiations will be guaranteed to finish within a single simulation step :param signing_delay: The number of simulation steps to pass between a contract is concluded and signed :param name: The name of the simulations :param \*\*kwargs: Other parameters that are passed directly to `SCML2020World` constructor. .. py:class:: SCML2024World(*args, **kwargs) Bases: :py:obj:`SCML2022World` A Supply Chain SCML2020World simulation as described for the SCML league of ANAC @ IJCAI 2020. :param process_inputs: An n_processes vector specifying the number of inputs from each product needed to execute each process. :param process_outputs: An n_processes vector specifying the number of inputs from each product generated by executing each process. :param catalog_prices: An n_products vector (i.e. n_processes+1 vector) giving the catalog price of all products :param profiles: An n_agents list of `FactoryProfile` objects specifying the private profile of the factory associated with each agent. :param agent_types: An n_agents list of strings/ `SCML2020Agent` classes specifying the type of each agent :param agent_params: An n_agents dictionaries giving the parameters of each agent :param initial_balance: The initial balance in each agent's wallet. All agents will start with this same value. :param allow_selling_input: Allows agents to sell their input product(s) through negotiation :param allow_buying_output: Allows agents to buy their output product(s) through negotiation :param catalog_quantities: The quantities in the past for which catalog_prices are the average unit prices. This is used when updating the trading prices. If set to zero then the trading price will follow the market price and will not use the catalog_price (except for products that are never sold in the market for which the trading price will take the default value of the catalog price). If set to a large value (e.g. 10000), the price at which a product is sold will not affect the trading price :param spot_market_global_loss: Buying from the spot market will cost trading-price * (1+`spot_market_global_loss) and selling to it will cost trading-price / (1+ spot_market_global_loss) for agents with unit spot-market-loss-multiplier :param financial_report_period: The number of steps between financial reports. If < 1, it is a fraction of n_steps :param borrow_on_breach: If true, agents will be forced to borrow money on breach as much as possible to honor the contract :param interest_rate: The interest at which loans grow over time (it only affect a factory when its balance is negative) :param bankruptcy_limit: The maximum amount that be be borrowed (including interest). The balance of any factory cannot go lower than - borrow_limit or the agent will go bankrupt immediately :param liquidation_rate: The rate at which future contracts get liquidated when an agent gets bankrupt. It should be between zero and one. :param compensation_fraction: Fraction of a contract to be compensated (at most) if a partner goes bankrupt. Notice that this fraction is not guaranteed because the bankrupt agent may not have enough assets to pay all of its standing contracts to this level of compensation. In such cases, a smaller fraction will be used. :param compensate_immediately: If true, compensation will happen immediately when an agent goes bankrupt and in in money. This means that agents with contracts involving the bankrupt agent will just have these contracts be nullified and receive monetary compensation immediately . If false, compensation will not happen immediately but at the contract execution time. In this case, agents with contracts involving the bankrupt agent will be informed of the compensation fraction (instead of the compensation money) at the time of bankruptcy and will receive the compensation in kind (money if they are sellers and products if they are buyers) at the normal execution time of the contract. In the special case of no-compensation (i.e. `compensation_fraction` is zero or the bankrupt agent has no assets), the two options will behave similarity. :param compensate_before_past_debt: If true, then compensations will be paid before past debt is considered, otherwise, the money from liquidating bankrupt agents will first be used to pay past debt then whatever remains will be used for compensation. Notice that in all cases, the trigger of bankruptcy will be paid before compensation and past debts. :param exogenous_horizon: The horizon for revealing external contracts :param exogenous_force_max: If true, exogenous contracts are forced to be signed independent of the setting of `force_signing` :param production_no_borrow: If true, agents will not borrow if they fail to satisfy its production need to execute a scheduled production command :param production_no_bankruptcy: If true, agents will not go bankrupt because of an production related transaction. :param production_penalty: The penalty paid when buying from spot-market to satisfy production needs :param production_confirm: If true, the factory will confirm running processes at every time-step just before running them by calling `confirm_production` on the agent controlling it. :param compact: If True, no logs will be kept and the whole simulation will use a smaller memory footprint :param n_steps: Number of simulation steps (can be considered as days). :param time_limit: Total time allowed for the complete simulation in seconds. :param neg_n_steps: Number of negotiation steps allowed for all negotiations. :param neg_time_limit: Total time allowed for a complete negotiation in seconds. :param neg_step_time_limit: Total time allowed for a single step of a negotiation. in seconds. :param negotiation_speed: The number of negotiation steps that pass in every simulation step. If 0, negotiations will be guaranteed to finish within a single simulation step :param signing_delay: The number of simulation steps to pass between a contract is concluded and signed :param name: The name of the simulations :param \*\*kwargs: Other parameters that are passed directly to `SCML2020World` constructor. .. py:function:: builtin_agent_types(as_str=False) Returns all built-in agents. :param as_str: If true, the full type name will be returned otherwise the type object itself. .. py:data:: __all__ .. py:class:: OneShotAgent(owner=None, ufun: scml.oneshot.OneShotUFun | None = None, name=None) Bases: :py:obj:`negmas.SAOController`, :py:obj:`negmas.Entity`, :py:obj:`abc.ABC` Base class for all agents in the One-Shot game. Remarks: - You can access all of the negotiators associated with the agent using `self.negotiators` which is a dictionary mapping the `negotiator_id` to a tuple of two values: The `SAONegotiator` object and a key-value context dictionary. In 2021, the context will always be empty. - The `negotiator_id` associated with a negotiation with some partner will be the same as the agent ID of that partner. This means that all negotiators engaged with some partner over all simulation steps will have the same ID which is useful if you are keeping information about past negotiations and partner behavior. .. py:attribute:: _awi :value: None .. py:attribute:: _owner :value: None .. py:property:: awi :type: scml.oneshot.OneShotAWI Returns a `OneShotAWI` object for accessing the simulation. .. py:property:: running_negotiations :type: list[negmas.situated.RunningNegotiationInfo] The negotiations currently requested by the agent. :returns: A list of negotiation information objects (`RunningNegotiationInfo`) .. py:property:: unsigned_contracts :type: list[negmas.Contract] All contracts that are not yet signed. .. py:method:: init() Called once after the AWI is set. Remarks: - Use this for any proactive initialization code. .. py:method:: make_ufun(add_exogenous=False) Creates a utility function for the agent. :param add_exogenous: If `True` then the exogenous contracts of the agent will be automatically added whenever the ufun is evaluated for any set of contracts, offers or otherwise. Remarks: - You can always as assume that self.ufun returns the ufun for your. You will not need to directly use this method in most cases. .. py:method:: before_step() Called at the beginning of every step. Remarks: - Use this for any proactive code that needs to be done every simulation step. .. py:method:: step() Called at the end of every step. Remarks: - Use this for any proactive code that needs to be done every simulation step. .. py:method:: connect_to_oneshot_adapter(owner) Connects the agent to its adapter (used internally) .. py:method:: connect_to_2021_adapter(owner) Connects the agent to its adapter (used internally) .. py:method:: propose(negotiator_id: str, state: negmas.SAOState) -> negmas.Outcome | None :abstractmethod: Proposes an offer to one of the partners. :param negotiator_id: ID of the negotiator (and partner) :param state: Mechanism state including current step :returns: an outcome to offer. .. py:method:: respond(negotiator_id: str, state: negmas.SAOState, source=None) -> negmas.ResponseType Responds to an offer from one of the partners. :param negotiator_id: ID of the negotiator (and partner) :param state: Mechanism state including current step :returns: A response type which can either be reject, accept, or end negotiation. Remarks: default behavior is to accept only if the current offer is the same or has a higher utility compared with what the agent would have proposed in the given state and reject otherwise .. py:property:: internal_state :type: dict[str, Any] Returns the internal state of the agent for debugging purposes. Remarks: - In your agent, you can add any key-value pair to this dict and then use agent_log_* methods to log this information at any point. .. py:method:: on_negotiation_failure(partners: list[str], annotation: dict[str, Any], mechanism: negmas.sao.SAONMI, state: negmas.SAOState) -> None Called whenever a negotiation ends without agreement. :param partners: List of the partner IDs consisting from self and the opponent. :param annotation: The annotation of the negotiation including the seller ID, buyer ID, and the product. :param mechanism: The `NegotiatorMechanismInterface` instance containing all information about the negotiation. :param state: The final state of the negotiation of the type `SAOState` including the agreement if any. .. py:method:: on_negotiation_success(contract: negmas.Contract, mechanism: negmas.sao.SAONMI) -> None Called whenever a negotiation ends with agreement. :param contract: The `Contract` agreed upon. :param mechanism: The `NegotiatorMechanismInterface` instance containing all information about the negotiation that led to the `Contract` if any. .. py:method:: sign_all_contracts(contracts: list[negmas.Contract]) -> list[str | None] Signs all contracts (used internally) .. py:method:: on_contract_executed(contract) -> None .. py:method:: on_contract_breached(contract, breaches, resolution) -> None .. py:method:: get_negotiator(partner_id: str) -> negmas.sao.SAONegotiator Returns the negotiator corresponding to the given partner ID. Remarks: - Note that the negotiator ID and the partner ID are always the same. .. py:method:: get_ami(partner_id: str) -> negmas.sao.SAONMI Returns the `SAONMI` (Agent Mechanism Interface) connecting the agent to the negotiation mechanism for the given partner. .. py:method:: get_nmi(partner_id: str) -> negmas.sao.SAONMI Returns the `SAONMI` (Agent Mechanism Interface) connecting the agent to the negotiation mechanism for the given partner. .. py:class:: OneShotSyncAgent(*args, **kwargs) Bases: :py:obj:`negmas.SAOSyncController`, :py:obj:`OneShotAgent`, :py:obj:`abc.ABC` An agent that automatically accumulate offers from opponents and allows you to control all negotiations centrally in the `counter_all` method. .. py:method:: counter_all(offers: dict[str, negmas.Outcome | None], states: dict[str, negmas.SAOState]) -> dict[str, negmas.SAOResponse] :abstractmethod: Calculate a response to all offers from all negotiators (negotiator ID is the key). :param offers: Maps negotiator IDs to offers :param states: Maps negotiator IDs to offers AT the time the offers were made. :returns: A dictionary mapping negotiator ID to an `SAOResponse`. The response per agent consist of a tuple. In case of acceptance or ending the negotiation the second item of the tuple should be None. In case of rejection, the second item should be the counter offer. Remarks: - The response type CANNOT be WAIT. - If the system determines that a loop is formed, the agent may receive this call for a subset of negotiations not all of them. .. py:method:: first_proposals() -> dict[str, negmas.Outcome | None] :abstractmethod: Gets a set of proposals to use for initializing the negotiation. :returns: A dictionary mapping each negotiator (in self.negotiators dict) to an outcome to be used as the first proposal if the agent is to start a negotiation. .. py:method:: sign_all_contracts(contracts: list[negmas.Contract]) -> list[str | None] Signs all contracts (used internally) .. py:class:: OneShotSingleAgreementAgent(*args, strict: bool = False, **kwargs) Bases: :py:obj:`negmas.SAOSingleAgreementController`, :py:obj:`OneShotSyncAgent` A synchronized agent that tries to get no more than one agreement. This controller manages a set of negotiations from which only a single one -- at most -- is likely to result in an agreement. To guarantee a single agreement, pass `strict=True` The general algorithm for this controller is something like this: - Receive offers from all partners. - Find the best offer among them by calling the abstract `best_offer` method. - Check if this best offer is acceptable using the abstract `is_acceptable` method. - If the best offer is acceptable, accept it and end all other negotiations. - If the best offer is still not acceptable, then all offers are rejected and with the partner who sent it receiving the result of `best_outcome` while the rest of the partners receive the result of `make_outcome`. - The default behavior of `best_outcome` is to return the outcome with maximum utility. - The default behavior of `make_outcome` is to return the best offer received in this round if it is valid for the respective negotiation and the result of `best_outcome` otherwise. :param strict: If True the controller is **guaranteed** to get a single agreement but it will have to send no-response repeatedly so there is a higher chance of never getting an agreement when two of those controllers negotiate with each other .. py:method:: is_acceptable(offer: negmas.Outcome, source: str, state: negmas.SAOState) -> bool :abstractmethod: Should decide if the given offer is acceptable :param offer: The offer being tested :param source: The ID of the negotiator that received this offer :param state: The state of the negotiation handled by that negotiator Remarks: - If True is returned, this offer will be accepted and all other negotiations will be ended. .. py:method:: best_offer(offers: dict[str, negmas.Outcome]) -> str | None :abstractmethod: Return the ID of the negotiator with the best offer :param offers: A mapping from negotiator ID to the offer it received :returns: The ID of the negotiator with best offer. Ties should be broken. Return None only if there is no way to calculate the best offer. .. py:method:: is_better(a: negmas.Outcome | None, b: negmas.Outcome | None, negotiator: str, state: negmas.SAOState) -> bool :abstractmethod: Compares two outcomes of the same negotiation :param a: "Outcome" :param b: "Outcome" :param negotiator: The negotiator for which the comparison is to be made :param state: Current state of the negotiation :returns: True if utility(a) > utility(b) .. py:class:: OneShotIndNegotiatorsAgent(*args, default_negotiator_type='negmas.sao.AspirationNegotiator', default_negotiator_params=None, normalize_ufuns=False, set_reservation=False, **kwargs) Bases: :py:obj:`OneShotAgent` A one-shot agent that deligates all of its decisions to a set of independent negotiators (one per partner per day). :param default_negotiator_type: An `SAONegotiator` descendent to be used for creating all negotiators. It can be passed either as a class object or a string with the full class name (e.g. "negmas.sao.AspirationNegotiator"). :param default_negotiator_type: A dict specifying the paratmers used to create negotiators. :param normalize_ufuns: If true, all utility functions will be normalized to have a maximum of 1.0 (the minimum value may be negative). :param set_reservation: If given, the reserved value of all ufuns will be guaranteed to be between the minimum and maximum of the ufun. This is needed to avoid failures of some GeniusNegotiators. Remarks: - To use this class, you need to override `generate_ufuns`. If you want to change the negotiator type used depending on the partner, you can also override `generate_negotiator`. - If you are using a `GeniusNegotiator` you must guarantee the following: - All ufuns are of the type `LinearAdditiveUtilityFunction`. - All ufuns are normalized with a maximum value of 1.0. You can use `normalize_ufuns=True` to gruarantee that. - All ufuns have a finite reserved value and at least one outcome is above it. You can guarantee that by using `set_reservation=True`. - All weights of the `LinearAdditiveUtilityFunction` must be between zero and one and the weights must sum to one. .. py:attribute:: _default_negotiator_type :value: 'negmas.sao.AspirationNegotiator' .. py:attribute:: _default_negotiator_params .. py:attribute:: _ufuns .. py:attribute:: _normalize :value: False .. py:attribute:: _set_reservation :value: False .. py:method:: generate_ufuns() -> dict[str, negmas.preferences.UtilityFunction] :abstractmethod: Returns a utility function for each partner. All ufuns **MUST** be of type `LinearAdditiveUtilityFunction` if a genius negotiator is used. .. py:method:: generate_negotiator(partner_id: str) -> negmas.sao.SAONegotiator Returns a negotiator to be used with some partner. Remarks: The default implementation will use the `default_negotiator_type` and `default_negotiator_params`. .. py:method:: _urange(u: negmas.preferences.UtilityFunction, issues: tuple[negmas.Issue, Ellipsis]) .. py:method:: _unorm(u: negmas.preferences.UtilityFunction, mn, mx) .. py:method:: _get_ufuns() Internal method that makes sure the reservation value is set to a meaningful value and that the ufun is normalized if needed .. py:method:: init() Called once after the AWI is set. Remarks: - Use this for any proactive initialization code. .. py:method:: step() Called at the end of every step. Remarks: - Use this for any proactive code that needs to be done every simulation step. .. py:method:: make_negotiator(negotiator_type=None, name: str | None = None, **kwargs) -> negmas.ControlledSAONegotiator Creates a negotiator but does not add it to the controller. Call `add_negotiator` to add it. :param negotiator_type: Type of the negotiator to be created. :param name: negotiator name :param \*\*kwargs: any key-value pairs to be passed to the negotiator constructor :returns: The negotiator to be controlled. None for failure Remarks: If you would like not to negotiate, just return `EndingNegotiator()` instead of None. The value None should only be returned if an exception is to be thrown. .. py:method:: propose(negotiator_id, state) Proposes an offer to one of the partners. :param negotiator_id: ID of the negotiator (and partner) :param state: Mechanism state including current step :returns: an outcome to offer. .. py:class:: EndingNegotiator(preferences: negmas.preferences.preferences.Preferences | None = None, ufun: negmas.preferences.base_ufun.BaseUtilityFunction | None = None, name: str | None = None, parent: negmas.negotiators.Controller | None = None, owner: negmas.situated.Agent | None = None, id: str | None = None, type_name: str | None = None, can_propose: bool = True, **kwargs) Bases: :py:obj:`negmas.sao.SAONegotiator`, :py:obj:`negmas.ControlledNegotiator` Base class for all SAO negotiators. Implemented by implementing propose() and respond() methods. :param name: Negotiator name :param parent: Parent controller if any :param preferences: The preferences of the negotiator :param ufun: The utility function of the negotiator (overrides preferences if given) :param owner: The `Agent` that owns the negotiator. Remarks: - The only method that **must** be implemented by any SAONegotiator is `propose`. - The default `respond` method, accepts offers with a utility value no less than whatever `propose` returns with the same mechanism state. - A default implementation of respond() is provided which simply accepts any offer better than the last offer I gave or the next one I would have given in the current state. .. seealso:: `SAOCallNegotiator` .. py:method:: propose(state) Propose an offer or None to refuse. :param state: `GBState` giving current state of the negotiation. :returns: The outcome being proposed or None to refuse to propose Remarks: - This function guarantees that no agents can propose something with a utility value .. py:method:: respond(state, source=None) Called to respond to an offer. This is the method that should be overriden to provide an acceptance strategy. :param state: a `SAOState` giving current state of the negotiation. :param source: The ID of the negotiator that gave this offer :returns: The response to the offer :rtype: ResponseType Remarks: - The default implementation never ends the negotiation - The default implementation asks the negotiator to `propose`() and accepts the `offer` if its utility was at least as good as the offer that it would have proposed (and above the reserved value). - The current offer to respond to can be accessed through `state.current_offer` .. py:class:: SingleAgreementAspirationAgent(*args, **kwargs) Bases: :py:obj:`scml.oneshot.agent.OneShotSyncAgent` Uses a time-based strategy to accept a single agreement from the set it is considering. .. py:method:: before_step() Called at the beginning of every step. Remarks: - Use this for any proactive code that needs to be done every simulation step. .. py:method:: counter_all(offers, states) Calculate a response to all offers from all negotiators (negotiator ID is the key). :param offers: Maps negotiator IDs to offers :param states: Maps negotiator IDs to offers AT the time the offers were made. :returns: A dictionary mapping negotiator ID to an `SAOResponse`. The response per agent consist of a tuple. In case of acceptance or ending the negotiation the second item of the tuple should be None. In case of rejection, the second item should be the counter offer. Remarks: - The response type CANNOT be WAIT. - If the system determines that a loop is formed, the agent may receive this call for a subset of negotiations not all of them. .. py:method:: choose_agents(offers, outcome) Selects an appropriate way to distribute this outcome to agents with given IDs. .. py:method:: first_proposals() -> Dict[str, negmas.Outcome | None] Gets a set of proposals to use for initializing the negotiation. :returns: A dictionary mapping each negotiator (in self.negotiators dict) to an outcome to be used as the first proposal if the agent is to start a negotiation. .. py:class:: GreedyOneShotAgent(*args, concession_exponent=None, acc_price_slack=float('inf'), step_price_slack=None, opp_price_slack=None, opp_acc_price_slack=None, range_slack=None, **kwargs) Bases: :py:obj:`scml.oneshot.agent.OneShotAgent` A greedy agent based on OneShotAgent :param concession_exponent: A real number controlling how fast does the agent concede on price. :param acc_price_slack: The allowed slack in price limits compared with best prices I got so far :param step_price_slack: The allowed slack in price limits compared with best prices I got this step :param opp_price_slack: The allowed slack in price limits compared with best prices I got so far from a given opponent in this step :param opp_acc_price_slack: The allowed slack in price limits compared with best prices I got so far from a given opponent so far :param range_slack: Always consider prices above (1-`range_slack`) of the best possible prices *good enough*. Remarks: - A `concession_exponent` greater than one makes the agent concede super linearly and vice versa .. py:attribute:: _e :value: None .. py:attribute:: _acc_price_slack .. py:attribute:: _step_price_slack :value: None .. py:attribute:: _opp_price_slack :value: None .. py:attribute:: _opp_acc_price_slack :value: None .. py:attribute:: _range_slack :value: None .. py:method:: init() Initialize the quantities and best prices received so far .. py:method:: before_step() Initialize the quantities and best prices received for next step .. py:method:: on_negotiation_success(contract, mechanism) Record sales/supplies secured .. py:method:: propose(negotiator_id: str, state, source=None) -> negmas.Outcome | None Proposes an offer to one of the partners. :param negotiator_id: ID of the negotiator (and partner) :param state: Mechanism state including current step :returns: an outcome to offer. .. py:method:: respond(negotiator_id, state, source=None) -> negmas.ResponseType Responds to an offer from one of the partners. :param negotiator_id: ID of the negotiator (and partner) :param state: Mechanism state including current step :returns: A response type which can either be reject, accept, or end negotiation. Remarks: default behavior is to accept only if the current offer is the same or has a higher utility compared with what the agent would have proposed in the given state and reject otherwise .. py:method:: best_offer(negotiator_id) .. py:method:: _needed(negotiator_id) .. py:method:: _is_selling(nmi) .. py:method:: _is_good_price(nmi, state, price) Checks if a given price is good enough at this stage .. py:method:: _find_good_price(nmi, state) Finds a good-enough price conceding linearly over time .. py:method:: _price_range(nmi) Limits the price by the best price received .. py:method:: _th(step, n_steps) calculates a descending threshold (0 <= th <= 1) .. py:class:: GreedySyncAgent(*args, threshold=None, **kwargs) Bases: :py:obj:`scml.oneshot.agent.OneShotSyncAgent`, :py:obj:`GreedyOneShotAgent` A greedy agent based on OneShotSyncAgent .. py:attribute:: _threshold :value: None .. py:attribute:: ufun :type: scml.oneshot.ufun.OneShotUFun Returns the preferences if it is a `BaseUtilityFunction` else None .. py:method:: before_step() Called at the beginning of every step. Remarks: - Use this for any proactive code that needs to be done every simulation step. .. py:method:: first_proposals() Decide a first proposal on every negotiation. Returning None for a negotiation means ending it. .. py:method:: counter_all(offers, states) -> dict Respond to a set of offers given the negotiation state of each. .. py:method:: _needs() Returns both input and output needs .. py:method:: propose(negotiator_id, state) Proposes an offer to one of the partners. :param negotiator_id: ID of the negotiator (and partner) :param state: Mechanism state including current step :returns: an outcome to offer. .. py:method:: respond(negotiator_id, state, source='') Responds to an offer from one of the partners. :param negotiator_id: ID of the negotiator (and partner) :param state: Mechanism state including current step :returns: A response type which can either be reject, accept, or end negotiation. Remarks: default behavior is to accept only if the current offer is the same or has a higher utility compared with what the agent would have proposed in the given state and reject otherwise .. py:class:: GreedySingleAgreementAgent(*args, **kwargs) Bases: :py:obj:`scml.oneshot.agent.OneShotSingleAgreementAgent` A greedy agent based on `OneShotSingleAgreementAgent` .. py:attribute:: ufun :type: scml.oneshot.ufun.OneShotUFun Returns the preferences if it is a `BaseUtilityFunction` else None .. py:method:: before_step() Called at the beginning of every step. Remarks: - Use this for any proactive code that needs to be done every simulation step. .. py:method:: is_acceptable(offer, source, state) -> bool Should decide if the given offer is acceptable :param offer: The offer being tested :param source: The ID of the negotiator that received this offer :param state: The state of the negotiation handled by that negotiator Remarks: - If True is returned, this offer will be accepted and all other negotiations will be ended. .. py:method:: best_offer(offers) Return the ID of the negotiator with the best offer :param offers: A mapping from negotiator ID to the offer it received :returns: The ID of the negotiator with best offer. Ties should be broken. Return None only if there is no way to calculate the best offer. .. py:method:: is_better(a, b, negotiator, state) Compares two outcomes of the same negotiation :param a: "Outcome" :param b: "Outcome" :param negotiator: The negotiator for which the comparison is to be made :param state: Current state of the negotiation :returns: True if utility(a) > utility(b) .. py:class:: OneshotDoNothingAgent(owner=None, ufun: scml.oneshot.OneShotUFun | None = None, name=None) Bases: :py:obj:`scml.oneshot.agent.OneShotAgent` An agent that does nothing. Remarks: Note that this agent will lose money whenever it is at the edges (i.e. it is an input or an output agent trading in raw material or final product). .. py:method:: propose(negotiator_id, state) Proposes an offer to one of the partners. :param negotiator_id: ID of the negotiator (and partner) :param state: Mechanism state including current step :returns: an outcome to offer. .. py:method:: respond(negotiator_id, state, source=None) Responds to an offer from one of the partners. :param negotiator_id: ID of the negotiator (and partner) :param state: Mechanism state including current step :returns: A response type which can either be reject, accept, or end negotiation. Remarks: default behavior is to accept only if the current offer is the same or has a higher utility compared with what the agent would have proposed in the given state and reject otherwise .. py:class:: Placeholder(*args, **kwargs) Bases: :py:obj:`scml.oneshot.policy.OneShotPolicy` An agent that always raises an exception if called to negotiate. It is useful as a placeholder (for example for RL and MARL exposition) .. py:method:: act(state) The main policy. Generates an action given a state .. py:class:: RandomOneShotAgent(*args, p_accept=PROB_ACCEPTANCE, p_end=PROB_END, **kwargs) Bases: :py:obj:`scml.oneshot.agent.OneShotAgent` An agent that randomly leaves the negotiation, accepts or counters with random outcomes .. py:method:: _random_offer(negotiator_id: str) .. py:method:: propose(negotiator_id, state) -> negmas.outcomes.Outcome | None Proposes an offer to one of the partners. :param negotiator_id: ID of the negotiator (and partner) :param state: Mechanism state including current step :returns: an outcome to offer. .. py:method:: respond(negotiator_id, state, source=None) -> negmas.ResponseType Responds to an offer from one of the partners. :param negotiator_id: ID of the negotiator (and partner) :param state: Mechanism state including current step :returns: A response type which can either be reject, accept, or end negotiation. Remarks: default behavior is to accept only if the current offer is the same or has a higher utility compared with what the agent would have proposed in the given state and reject otherwise .. py:class:: RandDistOneShotAgent(*args, **kwargs) Bases: :py:obj:`SyncRandomOneShotAgent` An agent that distributes its needs over its partners randomly. :param equal: If given, it tries to equally distribute its needs over as many of its suppliers/consumers as possible :param overordering_max: Maximum fraction of needs to over-order. For example, it the agent needs 5 items and this is 0.2, it will order 6 in the first negotiation step. :param overordering_min: Minimum fraction of needs to over-order. Used in the last negotiation step. :param overordering_exp: Controls how fast does the over-ordering quantity go from max to min. :param concession_exp: Controls how fast does the agent concedes on matching its needs exactly. :param mismatch_max: Maximum mismtach in quantity allowed between needs and accepted offers. If a fraction, it is will be this fraction of the production capacity (n_lines). .. py:class:: EqualDistOneShotAgent(*args, **kwargs) Bases: :py:obj:`SyncRandomOneShotAgent` Same as RandDistOneShotAgent but defaulting to equal distribution of needs :param equal: If given, it tries to equally distribute its needs over as many of its suppliers/consumers as possible :param overordering_max: Maximum fraction of needs to over-order. For example, it the agent needs 5 items and this is 0.2, it will order 6 in the first negotiation step. :param overordering_min: Minimum fraction of needs to over-order. Used in the last negotiation step. :param overordering_exp: Controls how fast does the over-ordering quantity go from max to min. :param concession_exp: Controls how fast does the agent concedes on matching its needs exactly. :param mismatch_max: Maximum mismtach in quantity allowed between needs and accepted offers. If a fraction, it is will be this fraction of the production capacity (n_lines). .. py:class:: SyncRandomOneShotAgent(*args, equal: bool = False, overordering_max: float = 0.2, overordering_min: float = 0.0, overordering_exp: float = 0.4, mismatch_exp: float = 4.0, mismatch_max: float = 0.3, **kwargs) Bases: :py:obj:`scml.oneshot.agent.OneShotSyncAgent` An agent that distributes its needs over its partners randomly. :param equal: If given, it tries to equally distribute its needs over as many of its suppliers/consumers as possible :param overordering_max: Maximum fraction of needs to over-order. For example, it the agent needs 5 items and this is 0.2, it will order 6 in the first negotiation step. :param overordering_min: Minimum fraction of needs to over-order. Used in the last negotiation step. :param overordering_exp: Controls how fast does the over-ordering quantity go from max to min. :param concession_exp: Controls how fast does the agent concedes on matching its needs exactly. :param mismatch_max: Maximum mismtach in quantity allowed between needs and accepted offers. If a fraction, it is will be this fraction of the production capacity (n_lines). .. py:attribute:: equal_distribution :value: False .. py:attribute:: overordering_max :value: 0.2 .. py:attribute:: overordering_min :value: 0.0 .. py:attribute:: overordering_exp :value: 0.4 .. py:attribute:: mismatch_exp :value: 4.0 .. py:attribute:: mismatch_max :value: 0.3 .. py:method:: init() Called once after the AWI is set. Remarks: - Use this for any proactive initialization code. .. py:method:: distribute_needs(t: float) -> dict[str, int] Distributes my needs randomly over all my partners .. py:method:: first_proposals() Gets a set of proposals to use for initializing the negotiation. :returns: A dictionary mapping each negotiator (in self.negotiators dict) to an outcome to be used as the first proposal if the agent is to start a negotiation. .. py:method:: counter_all(offers, states) Calculate a response to all offers from all negotiators (negotiator ID is the key). :param offers: Maps negotiator IDs to offers :param states: Maps negotiator IDs to offers AT the time the offers were made. :returns: A dictionary mapping negotiator ID to an `SAOResponse`. The response per agent consist of a tuple. In case of acceptance or ending the negotiation the second item of the tuple should be None. In case of rejection, the second item should be the counter offer. Remarks: - The response type CANNOT be WAIT. - If the system determines that a loop is formed, the agent may receive this call for a subset of negotiations not all of them. .. py:method:: _allowed_mismatch(r: float) .. py:method:: _overordering_fraction(t: float) .. py:method:: _step_and_price(best_price=False) Returns current step and a random (or max) price .. py:class:: SingleAgreementRandomAgent(*args, p_accept: float = PROB_ACCEPTANCE, **kwargs) Bases: :py:obj:`scml.oneshot.agent.OneShotSingleAgreementAgent` A controller that agrees randomly to one offer .. py:attribute:: _p_accept :value: 0.1 .. py:method:: is_acceptable(offer: negmas.outcomes.Outcome, source: str, state: negmas.sao.SAOState) -> bool Should decide if the given offer is acceptable :param offer: The offer being tested :param source: The ID of the negotiator that received this offer :param state: The state of the negotiation handled by that negotiator Remarks: - If True is returned, this offer will be accepted and all other negotiations will be ended. .. py:method:: best_offer(offers: dict[str, negmas.outcomes.Outcome]) -> str | None Return the ID of the negotiator with the best offer :param offers: A mapping from negotiator ID to the offer it received :returns: The ID of the negotiator with best offer. Ties should be broken. Return None only if there is no way to calculate the best offer. .. py:method:: is_better(a: negmas.outcomes.Outcome | None, b: negmas.outcomes.Outcome | None, negotiator: str, state: negmas.sao.SAOState) -> bool Compares two outcomes of the same negotiation :param a: "Outcome" :param b: "Outcome" :param negotiator: The negotiator for which the comparison is to be made :param state: Current state of the negotiation :returns: True if utility(a) > utility(b) .. py:class:: OneShotAWI(world: scml.oneshot.world.SCMLBaseWorld, agent: scml.oneshot.agent.OneShotAgent) Bases: :py:obj:`negmas.situated.AgentWorldInterface` The agent world interface for the one-shot game. This class contains all the methods needed to access the simulation to extract information which are divided into 4 groups: Static World Information: Information about the world and the agent that does not change over time. These include: A. Market Information: - **n_products**: Number of products in the production chain. - **n_processes**: Number of processes in the production chain. - **n_competitors**: Number of other factories on the same production level. - **all_suppliers**: A list of all suppliers by product. - **all_consumers**: A list of all consumers by product. - **proudction_capacities**: The total production capacity (i.e. number of lines) for each production level (i.e. manufacturing process). - **is_system**: Is the given system ID corresponding to a system agent? - **is_bankrupt**: Is the given agent bankrupt? None asks about self - **catalog_prices**: A list of the catalog prices (by product). - **price_multiplier**: The multiplier multiplied by the trading/catalog price when the negotiation agendas are created to decide the maximum and lower quantities. - **is_exogenous_forced**: Are exogenous contracts always forced or can the agent decide not to sign them. - **current_step**: Current simulation step (inherited from `negmas.situated.AgentWorldInterface` ). - **n_steps**: Number of simulation steps (inherited from `negmas.situated.AgentWorldInterface` ). - **relative_time**: fraction of the simulation completed (inherited from `negmas.situated.AgentWorldInterface`). - **state**: The full state of the agent ( `OneShotState` ). - **settings* The system settings (inherited from `negmas.situated.AgentWorldInterface` ). - **quantity_range* The maximum quantity in all negotiation agendas (new in 0.6.1) - **price_range* The maximum number of different prices in any negotiation agenda (new in 0.6.1) B. Agent Information: - **profile**: Gives the agent profile including its production cost, number of production lines, input product index, mean of its delivery penalties, mean of its disposal costs, standard deviation of its shortfall penalties and standard deviation of its disposal costs. See `OneShotProfile` for full description. This information is private information and no other agent knows it. - **n_lines**: the number of production lines in the factory (private information). - **is_first_level**: Is the agent in the first production level (i.e. it is an input agent that buys the raw material). - **is_last_level**: Is the agent in the last production level (i.e. it is an output agent that sells the final product). - **is_middle_level**: Is the agent neither a first level nor a last level agent - **my_input_product**: The input product to the factory controlled by the agent. - **my_output_product**: The output product from the factory controlled by the agent. - **level**: The production level which is numerically the same as the input product. - **my_suppliers**: A list of IDs for all suppliers to the agent (i.e. agents that can sell the input product of the agent). - **my_consumers**: A list of IDs for all consumers to the agent (i.e. agents that can buy the output product of the agent). - **penalties_scale**: The scale at which to calculate disposal cost/delivery penalties. "trading" and "catalog" mean trading and catalog prices. "unit" means the contract's unit price while "none" means that disposal cost/shortfall penalty are absolute. - **n_input_negotiations**: Number of negotiations with suppliers. - **n_output_negotiations**: Number of negotiations with consumers. Dynamic World Information: Information about the world and the agent that changes over time. A. Market Information: - **trading_prices**: The trading prices of all products. This information is only available if `publish_trading_prices` is set in the world. - **exogenous_contract_summary**: A list of n_products tuples each giving the total quantity and average price of exogenous contracts for a product. This information is only available if `publish_exogenous_summary` is set in the world. - **is_perishable**: Are all products perishable? B. Other Agents' Information: - **reports_of_agent**: Gives all past financial reports of a given agent. See `FinancialReport` for details. - **reports_at_step**: Gives all reports of all agents at a given step. See `FinancialReport` for details. C. Current Negotiations Information: - **current_input_outcome_space**: The current outcome-space for all negotiations to buy the input product of the agent. If the agent is at level zero, this will have no issues. - **current_output_outcome_space**: The current outcome-space for all negotiations to buy the output product of the agent. If the agent is at level n_products - 1, this will have no issues. - **current_negotiation_details**: Details on all current negotiations separated into "buy" and "sell" dictionaries. Useful helpers about current negotiations: - **current_input_issues**: The current issues for all negotiations to buy the input product of the agent. If the agent is at level zero, this will be empty. This is exactly the same as current_input_outcome_space.issues - **current_output_issues**: The current issues for all negotiations to buy the output product of the agent. If the agent is at level n_products - 1, this will be empty. This is exactly the same as current_output_outcome_space.issues - **current_buy_nmis**: All NMIs for current buy negotiations. - **current_sell_nmis**: All NMIs for current sell negotiations. - **current_nmis**: All states for current negotiations. - **current_buy_states**: All states for current buy negotiations. - **current_sell_states**: All states for current sell negotiations. - **current_states**: All states for current negotiations. - **current_buy_offers**: All offers for current buy negotiations. - **current_sell_offers**: All offers for current sell negotiations. - **current_offers**: All offers for current negotiations. - **running_buy_nmis**: All NMIs for running buy negotiations. - **running_sell_nmis**: All NMIs for running sell negotiations. - **running_nmis**: All states for running negotiations. - **running_buy_states**: All states for running buy negotiations. - **running_sell_states**: All states for running sell negotiations. - **running_states**: All states for running negotiations. D. Agent Information: - **current_exogenous_input_quantity**: The total quantity the agent have in its input exogenous contract. - **current_exogenous_input_price**: The total price of the agent's input exogenous contract. - **current_exogenous_output_quantity**: The total quantity the agent have in its output exogenous contract. - **current_exogenous_output_price**: The total price of the agent's output exogenous contract - **current_disposal_cost**: The disposal cost per unit item in the current step. - **current_shortfall_penalty**: The shortfall penalty per unit item in the current step. - **current_balance**: The current balance of the agent - **current_score**: The current score (balance / initial balance) of the agent - **current_inventory_input**: The total quantity remaining in the inventory of the input product - **current_inventory_output**: The total quantity remaining in the inventory of the output product - **current_inventory**: The total quantity remaining in the inventory of the input and output product E. Sales and Supplies (quantities) for today: - **sales**: Today's sales per customer so far. - **supplies**: Today's supplies per supplier so far. - **total_sales**: Today's total sales so far. - **total_supplies**: Today's total supplies so far. - **needed_sales**: Today's needed sales as of now (exogenous input + total supplies - exogenous output - total sales so far). - **needed_supplies**: Today's needed supplies as of now (exogenous output + total sales - exogenous input - total supplies so far). Services (All inherited from `negmas.situated.AgentWorldInterface`): - **logdebug/loginfo/logwarning/logerror**: Logs to the world log at the given log level. - **logdebug_agent/loginf_agnet/...**: Logs to the agent specific log at the given log level. - **bb_query**: Queries the bulletin-board. - **bb_read**: Read a section of the bulletin-board. .. py:attribute:: _world .. py:attribute:: agent .. py:attribute:: _future_sales :type: dict[int, dict[str, int]] .. py:attribute:: _future_supplies :type: dict[int, dict[str, int]] .. py:attribute:: _future_sales_cost :type: dict[int, dict[str, int]] .. py:attribute:: _future_supplies_cost :type: dict[int, dict[str, int]] .. py:property:: max_n_lines :type: int Maximum number of lines in the whole system .. py:property:: quantity_range :type: int The maximum cardinality of the quantity issue in all negotiations .. py:property:: price_range :type: int The maximum cardinality of the quantity issue in all negotiations .. py:property:: n_products :type: int Returns the number of products in the system .. py:property:: n_competitors :type: int Returns the number of factories/agents in the same production level .. py:property:: n_processes :type: int Returns the number of processes in the system .. py:property:: all_suppliers :type: list[list[str]] Returns a list of agent IDs for all suppliers for every product .. py:property:: production_capacities :type: list[int] Returns the total production capacity in the market for each process .. py:property:: all_consumers :type: list[list[str]] Returns a list of agent IDs for all consumers for every product .. py:method:: is_system(aid: str) -> bool Checks whether an agent is a system agent or not :param aid: Agent ID .. py:method:: is_bankrupt(aid: str | None = None) -> bool Checks whether an agent is a system agent or not :param aid: Agent ID .. py:property:: horizon :type: int Horizon for negotiations .. py:property:: catalog_prices :type: numpy.ndarray Returns the catalog prices of all products .. py:property:: price_multiplier :type: float Controls the minimum and maximum prices in the negotiation agendas Remarks: - The base price is either the catalog price if trading price information is not public or the trading price. - The minimum unit price in any negotiation agenda is the base price of the previous product in the chain ***divided* by the multiplier. If that is less than 1, the minimum unit price becomes 1. - The maximum unit price in any negotiation agenda is the base price of the previous product in the chain ***multiplied* by the multiplier. If that is less than 1, the minimum unit price becomes 1. .. py:property:: is_exogenous_forced :type: bool Are exogenous contracts forced in the sense that the agent cannot decide not to sign them? .. py:property:: allow_zero_quantity :type: bool Does negotiations allow zero quantity? .. py:property:: profile :type: scml.oneshot.common.OneShotProfile Gets the profile (static private information) associated with the agent .. py:property:: n_lines :type: int The number of lines in the corresponding factory. You can read `state` to get this among other information .. py:property:: n_input_negotiations :type: int Number of negotiations with suppliers at every step .. py:property:: n_output_negotiations :type: int Number of negotiations with consumers at every step .. py:property:: is_first_level Whether this agent is in the first production level .. py:property:: is_last_level Whether this agent is in the last production level .. py:property:: level The production level which is the index of the process for this factory (or the index of its input product) .. py:property:: is_middle_level Whether this agent is in neither in the first nor in the last level .. py:property:: my_input_product :type: int the product I need to buy .. py:property:: my_output_product :type: int the product I need to sell .. py:property:: my_competitors :type: list[str] Returns the names of all factories in the same level as me .. py:property:: my_suppliers :type: list[str] Returns a list of IDs for all of the agent's suppliers (agents that can supply the product I need). .. py:property:: my_consumers :type: list[str] Returns a list of IDs for all the agent's consumers (agents that can consume at least one product it may produce). .. py:property:: my_partners :type: list[str] Returns a list of IDs for all of the agent's partners starting with suppliers .. py:property:: penalties_scale :type: Literal['trading', 'catalog', 'unit', 'none'] .. py:property:: state :type: scml.oneshot.common.OneShotState Returns the private state of the agent in that world .. py:property:: current_balance .. py:property:: current_score :type: float Returns the current score (profit) of the agent .. py:property:: current_inventory :type: tuple[int, int] Current input and output inventory quantity .. py:property:: current_inventory_input :type: int Current input inventory quantity .. py:property:: current_inventory_output :type: int Current output inventory quantity .. py:property:: current_exogenous_input_quantity :type: int The exogenous contracts for the input (this step) .. py:property:: current_exogenous_input_price :type: int The exogenous contracts for the input (this step) .. py:property:: current_exogenous_output_quantity :type: int The exogenous contracts for the input (this step) .. py:property:: current_exogenous_output_price :type: int The exogenous contracts for the input (this step) .. py:method:: penalty_multiplier(is_input: bool, unit_price: float | None) -> float Returns the penalty multiplier for a contract with the give unit price. Remarks: - The unit price is only needed if the penalties_scale is unit. For all other options (trading, catalog, none), the penalty scale does not depend on the unit price. .. py:property:: is_perishable :type: bool Are all products perishable (original design of OneShot) .. py:property:: current_disposal_cost :type: float Cost of storing one unit (penalizes buying too much/ selling too little) .. py:property:: current_storage_cost :type: float Cost of storing one unit (penalizes buying too much/ selling too little) .. py:property:: current_shortfall_penalty :type: float Cost of failure to deliver one unit (penalizes buying too little / selling too much) .. py:property:: trading_prices :type: numpy.ndarray Returns the current trading prices of all products .. py:property:: exogenous_contract_summary :type: list[tuple[int, int]] The exogenous contracts in the current step for all products :returns: A list of tuples giving the total quantity and total price of all revealed exogenous contracts of all products at the current step. Will be empty if the world has "publish_exogenous_summary==False" .. py:method:: reports_of_agent(aid: str) -> dict[int, scml.oneshot.common.FinancialReport] Returns a dictionary mapping time-steps to financial reports of the given agent .. py:method:: reports_at_step(step: int) -> dict[str, scml.oneshot.common.FinancialReport] Returns a dictionary mapping agent ID to its financial report for the given time-step .. py:property:: current_input_issues :type: list[negmas.ContiguousIssue] .. py:property:: current_output_issues :type: list[negmas.ContiguousIssue] .. py:property:: current_input_outcome_space :type: negmas.outcomes.DiscreteCartesianOutcomeSpace .. py:property:: current_output_outcome_space :type: negmas.outcomes.DiscreteCartesianOutcomeSpace .. py:property:: current_negotiation_details :type: dict[str, dict[str, scml.oneshot.common.NegotiationDetails]] Details of current negotiations separated as two dicts for buying and selling. Remarks: - current_negotiation_details["buy"] gives details on all negotiations for buying - current_negotiation_details["sell"] gives details on all negotiations for selling .. py:property:: current_buy_states :type: dict[str, negmas.sao.SAOState] All running buy negotiations as a mapping from partner ID to current negotiation state .. py:property:: current_sell_states :type: dict[str, negmas.sao.SAOState] All running sell negotiations as a mapping from partner ID to current negotiation state .. py:property:: current_states :type: dict[str, negmas.sao.SAOState] All running negotiations as a mapping from partner ID to current negotiation state .. py:property:: current_buy_nmis :type: dict[str, negmas.sao.SAONMI] All running buy negotiations as a mapping from partner ID to current negotiation nmi .. py:property:: current_sell_nmis :type: dict[str, negmas.sao.SAONMI] All running negotiations as a mapping from partner ID to current negotiation state .. py:property:: current_nmis :type: dict[str, negmas.sao.SAONMI] All running negotiations as a mapping from partner ID to current negotiation nmi .. py:property:: current_buy_offers :type: dict[str, negmas.outcomes.Outcome] All current buy negotiations as a mapping from partner ID to current offer .. py:property:: current_sell_offers :type: dict[str, negmas.outcomes.Outcome] All current sell negotiations as a mapping from partner ID to current offer .. py:property:: current_offers :type: dict[str, negmas.outcomes.Outcome] All current negotiations as a mapping from partner ID to current offer .. py:property:: running_buy_states :type: dict[str, negmas.sao.SAOState] All running buy negotiations as a mapping from partner ID to current negotiation state .. py:property:: running_sell_states :type: dict[str, negmas.sao.SAOState] All running sell negotiations as a mapping from partner ID to current negotiation state .. py:property:: running_states :type: dict[str, negmas.sao.SAOState] All running negotiations as a mapping from partner ID to current negotiation state .. py:property:: running_sell_nmis :type: dict[str, negmas.sao.SAONMI] All running sell negotiations as a mapping from partner ID to current negotiation nmi .. py:property:: running_buy_nmis :type: dict[str, negmas.sao.SAONMI] All running buy negotiations as a mapping from partner ID to current negotiation nmi .. py:property:: running_nmis :type: dict[str, negmas.sao.SAONMI] All running negotiations as a mapping from partner ID to current negotiation nmi .. py:property:: sales :type: dict[str, int] Sales (quantity) per customer so far (this day) .. py:property:: supplies :type: dict[str, int] Supplies (quantity) per supplier so far (this day) .. py:property:: sales_cost :type: dict[str, int] Sales (total price) per customer so far (this day) .. py:property:: supplies_cost :type: dict[str, int] Supplies (total price) per supplier so far (this day) .. py:property:: future_sales :type: dict[int, dict[str, int]] Future sales (quantity) per customer so far (excluding this day) .. py:property:: future_supplies :type: dict[int, dict[str, int]] Future supplies (quantity) per supplier so far (excluding this day) .. py:property:: future_sales_cost :type: dict[int, dict[str, int]] Future sales (total price) per customer so far (excluding this day) .. py:property:: future_supplies_cost :type: dict[int, dict[str, int]] Future supplies (total price) per supplier so far (excluding this day) .. py:property:: total_sales :type: int Total sales so far (this day) .. py:property:: total_supplies :type: int Total supplies so far (this day) .. py:property:: total_future_sales :type: int Total sales so far (this day) .. py:method:: total_sales_from(start: int) -> int Total sales starting at start and ending at end (inclusive). Past days are ignored .. py:method:: total_supplies_from(start: int) -> int Total supplies starting at start and ending at end (inclusive). Past days are ignored .. py:method:: total_sales_between(start: int, end: int) -> int Total sales starting at start and ending at end (inclusive). Past days are ignored .. py:method:: total_supplies_between(start: int, end: int) -> int Total supplies starting at start and ending at end (inclusive). Past days are ignored .. py:method:: total_supplies_until(step: int) -> int Total supplies starting today until the given step (inclusive). Past days are ignored .. py:method:: total_sales_until(step: int) -> int Total sales starting today until the given step (inclusive). Past days are ignored .. py:method:: total_sales_at(step: int) -> int Total sales already signed at a future step .. py:method:: total_supplies_at(step: int) -> int Total supplies already signed at a future step .. py:property:: total_future_supplies :type: int Total supplies so far (this day) .. py:property:: needed_sales :type: int Sales that need to be secured (exogenous input + total supplies - exogenous output - total sales so far) .. py:property:: needed_supplies :type: int Supplies that need to be secured (exogenous output + total sales - exogenous input - total supplies so far) .. py:method:: _register_sale(customer: str, quantity: int, unit_price: int, step: int) -> None .. py:method:: _register_supply(supplier: str, quantity: int, unit_price: int, step: int) -> None .. py:method:: _reset_sales_and_supplies() -> None .. py:data:: QUANTITY :value: 0 Index of quantity in negotiation issues .. py:data:: UNIT_PRICE :value: 2 Index of unit price in negotiation issues .. py:data:: TIME :value: 1 Index of time in negotiation issues .. py:class:: OneShotState State of a one-shot agent .. py:attribute:: exogenous_input_quantity :type: int Exogenous input quantity for the current step .. py:attribute:: exogenous_input_price :type: int Exogenous input unit price for the current step .. py:attribute:: exogenous_output_quantity :type: int Exogenous output quantity for the current step .. py:attribute:: exogenous_output_price :type: int Exogenous output unit price for the current step .. py:attribute:: disposal_cost :type: float Current unit disposal cost .. py:attribute:: shortfall_penalty :type: float Current unit shortfall penalty .. py:attribute:: current_balance :type: int Current balance of the agent. .. py:attribute:: total_sales :type: int Total quantity registered as sales today using `awi.register_sale`. .. py:attribute:: total_supplies :type: int Total quantity registered as supplies today using `awi.register_supply`. .. py:attribute:: total_future_sales :type: int Total quantity registered as sales in the future using `awi.register_sale`. .. py:attribute:: total_future_supplies :type: int Total quantity registered as supplies in the future using `awi.register_supply`. .. py:attribute:: n_products :type: int Number of products in the production chain. .. py:attribute:: n_processes :type: int Number of processes in the production chain. .. py:attribute:: n_competitors :type: int Number of other factories on the same production level. .. py:attribute:: all_suppliers :type: list[list[str]] A list of all suppliers by product. .. py:attribute:: all_consumers :type: list[list[str]] A list of all consumers by product. .. py:attribute:: production_capacities :type: list[int] A list of total production capacity per production level. .. py:attribute:: bankrupt_agents :type: list[str] list of bankrupt agents .. py:attribute:: catalog_prices :type: list[float] A list of the catalog prices (by product). .. py:attribute:: price_multiplier :type: float The multiplier multiplied by the trading/catalog price when the negotiation agendas are created to decide the maximum and lower quantities. .. py:attribute:: is_exogenous_forced :type: bool exogenous contracts always forced or can the agent decide not to sign them. .. py:attribute:: current_step :type: int Current simulation step (inherited from `negmas.situated.AgentWorldInterface` ). .. py:attribute:: n_steps :type: int Number of simulation steps (inherited from `negmas.situated.AgentWorldInterface` ). .. py:attribute:: relative_simulation_time :type: float Fraction of the simulation completed (inherited from `negmas.situated.AgentWorldInterface`). .. py:attribute:: profile :type: OneShotProfile Gives the agent profile including its production cost, number of production lines, input product index, mean of its delivery penalties, mean of its disposal costs, standard deviation of its shortfall penalties and standard deviation of its disposal costs. See `OneShotProfile` for full description. This information is private information and no other agent knows it. .. py:attribute:: n_lines :type: int The number of production lines in the factory (private information). .. py:attribute:: is_first_level :type: bool Is the agent in the first production level (i.e. it is an input agent that buys the raw material). .. py:attribute:: is_last_level :type: bool Is the agent in the last production level (i.e. it is an output agent that sells the final product). .. py:attribute:: is_middle_level :type: bool Is the agent neither a first level nor a last level agent .. py:attribute:: my_input_product :type: int The input product to the factory controlled by the agent. .. py:attribute:: my_output_product :type: int The output product from the factory controlled by the agent. .. py:attribute:: level :type: int The production level which is numerically the same as the input product. .. py:attribute:: my_suppliers :type: list[str] A list of IDs for all suppliers to the agent (i.e. agents that can sell the input product of the agent). .. py:attribute:: my_consumers :type: list[str] A list of IDs for all consumers to the agent (i.e. agents that can buy the output product of the agent). .. py:attribute:: my_partners :type: list[str] A list of IDs for all negotiation partners of the agent (in the order suppliers then consumers). .. py:attribute:: penalties_scale :type: Literal['trading', 'catalog', 'unit', 'none'] The scale at which to calculate disposal cost/delivery penalties. "trading" and "catalog" mean trading and catalog prices. "unit" means the contract's unit price while "none" means that disposal cost/shortfall penalty are absolute. .. py:attribute:: n_input_negotiations :type: int Number of negotiations with suppliers. .. py:attribute:: n_output_negotiations :type: int Number of negotiations with consumers. .. py:attribute:: trading_prices :type: list[float] The trading prices of all products. This information is only available if `publish_trading_prices` is set in the world. .. py:attribute:: exogenous_contract_summary :type: list[tuple[int, int]] A list of n_products lists each giving the total quantity and average price of exogenous contracts for a product. This information is only available if `publish_exogenous_summary` is set in the world. .. py:attribute:: reports_of_agents :type: dict[str, dict[int, FinancialReport]] Gives all past financial reports of a given agent. See `FinancialReport` for details. .. py:attribute:: current_input_outcome_space :type: negmas.outcomes.DiscreteCartesianOutcomeSpace The current issues for all negotiations to buy the input product of the agent. If the agent is at level zero, this will be empty. This is exactly the same as current_input_outcome_space.issues .. py:attribute:: current_output_outcome_space :type: negmas.outcomes.DiscreteCartesianOutcomeSpace The current issues for all negotiations to buy the output product of the agent. If the agent is at level n_products - 1, this will be empty. This is exactly the same as current_output_outcome_space.issues .. py:attribute:: current_negotiation_details :type: dict[str, dict[str, NegotiationDetails]] Details on all current negotiations separated into "buy" and "sell" dictionaries. .. py:attribute:: sales :type: dict[str, int] Today's sales per customer so far. .. py:attribute:: supplies :type: dict[str, int] Today supplies per supplier so far. .. py:attribute:: needed_sales :type: int Today's needed sales as of now (exogenous input - exogenous output - total sales so far). .. py:attribute:: needed_supplies :type: int Today needed supplies as of now (exogenous output - exogenous input - total supplies). .. py:attribute:: perishable :type: bool :value: True Is this a perishable domain (oneshot) of not (std) .. py:attribute:: allow_zero_quantity :type: bool :value: False Does this world allow zero quantity in negotiated offers .. py:attribute:: storage_cost :type: float :value: 0.0 Current unit storage cost. Only used in standard worlds where products are not perishable .. py:property:: running_buy_states :type: dict[str, negmas.sao.common.SAOState] All running buy negotiations as a mapping from partner ID to current negotiation state .. py:property:: current_sell_states :type: dict[str, negmas.sao.common.SAOState] All running sell negotiations as a mapping from partner ID to current negotiation state .. py:property:: current_states :type: dict[str, negmas.sao.common.SAOState] All running negotiations as a mapping from partner ID to current negotiation state .. py:property:: current_buy_nmis :type: dict[str, negmas.sao.SAONMI] All running buy negotiations as a mapping from partner ID to current negotiation nmi .. py:property:: current_sell_nmis :type: dict[str, negmas.sao.SAONMI] All running sell negotiations as a mapping from partner ID to current negotiation nmi .. py:property:: current_nmis :type: dict[str, negmas.sao.SAONMI] All running negotiations as a mapping from partner ID to current negotiation state .. py:property:: current_buy_offers :type: dict[str, negmas.outcomes.Outcome] All current buy negotiations as a mapping from partner ID to current offer .. py:property:: current_sell_offers :type: dict[str, negmas.outcomes.Outcome] All current sell negotiations as a mapping from partner ID to current offer .. py:property:: current_offers :type: dict[str, negmas.outcomes.Outcome] All current negotiations as a mapping from partner ID to current offer .. py:method:: random(oneshot: bool | None = None) -> OneShotState :classmethod: .. py:class:: OneShotExogenousContract Exogenous contract information .. py:attribute:: __slots__ :value: ['quantity', 'unit_price', 'product', 'seller', 'buyer', 'time', 'revelation_time'] .. py:attribute:: quantity :type: int Contract quantity .. py:attribute:: unit_price :type: int Contract unit price .. py:attribute:: product :type: int Product index .. py:attribute:: seller :type: str Seller ID (when passing contrtacts to the constructor of SCML2020OneShotWorld, you can also pass an interged index referring to the agent's index in the `agent_types` list) .. py:attribute:: buyer :type: str Buyer ID (when passing contrtacts to the constructor of SCML2020OneShotWorld, you can also pass an interged index referring to the agent's index in the `agent_types` list) .. py:attribute:: time :type: int Simulation step at which the contract is exceucted .. py:attribute:: revelation_time :type: int Simulation step at which the contract is revealed to its owner. Should not exceed `time` and the default `generate()` method sets it to time .. py:class:: OneShotProfile Defines all private information of a factory .. py:attribute:: cost :type: float The cost of production .. py:attribute:: input_product :type: int The index of the input product (x for $L_x$ factories) .. py:attribute:: n_lines :type: int Number of lines for this factory .. py:attribute:: shortfall_penalty_mean :type: float A positive number specifying the average penalty for selling too much. .. py:attribute:: disposal_cost_mean :type: float A positive number specifying the average penalty buying too much. .. py:attribute:: shortfall_penalty_dev :type: float A positive number specifying the std. dev. of penalty for selling too much. .. py:attribute:: disposal_cost_dev :type: float A positive number specifying the std. dev. penalty buying too much. .. py:attribute:: storage_cost_mean :type: float A positive number specifying the average cost for keeping inventory for one step. This is only used if the products are not `perishable`. .. py:attribute:: storage_cost_dev :type: float A positive number specifying the std. dev. cost for keeping inventory for one step. This is only used if the products are not `perishable`. .. py:property:: level .. py:property:: output_product .. py:property:: process .. py:method:: random(input_product: int, oneshot: bool) -> OneShotProfile :classmethod: .. py:class:: FinancialReport A report published periodically by the system showing the financial standing of an agent .. py:attribute:: __slots__ :value: ['agent_id', 'step', 'cash', 'assets', 'breach_prob', 'breach_level', 'is_bankrupt', 'agent_name'] .. py:attribute:: agent_id :type: str Agent ID .. py:attribute:: step :type: int Simulation step at the beginning of which the report was published. .. py:attribute:: cash :type: int Cash in the agent's wallet. Negative numbers indicate liabilities. .. py:attribute:: assets :type: int Value of the products in the agent's inventory @ catalog prices. .. py:attribute:: breach_prob :type: float Number of times the agent breached a contract over the total number of contracts it signed. .. py:attribute:: breach_level :type: float Sum of the agent's breach levels so far divided by the number of contracts it signed. .. py:attribute:: is_bankrupt :type: bool Whether the agent is already bankrupt (i.e. incapable of doing any more transactions). .. py:attribute:: agent_name :type: str Agent name for printing purposes .. py:method:: __str__() .. py:function:: is_system_agent(aid: str) -> bool Checks whether an agent is a system agent or not :param aid: Agent ID :returns: True if the ID is for a system agent. .. py:data:: INFINITE_COST :value: 4611686018427387903 A constant indicating an invalid cost for lines incapable of running some process .. py:data:: SYSTEM_BUYER_ID :value: 'BUYER' ID of the system buyer agent .. py:data:: SYSTEM_SELLER_ID :value: 'SELLER' ID of the system seller agent .. py:class:: Context Bases: :py:obj:`abc.ABC` A context used for generating worlds satisfying predefined conditions and testing for them .. py:method:: __call__(*args, **kwargs) .. py:method:: generate(types: tuple[type[scml.oneshot.agent.OneShotAgent], Ellipsis] | None = None, params: tuple[dict[str, Any], Ellipsis] | None = None, name: str | None = None) -> tuple[scml.oneshot.world.SCMLBaseWorld, tuple[scml.oneshot.agent.OneShotAgent]] :abstractmethod: Generates a world with one or more agents to be controlled externally and returns both :param agent_types: The types of a list of agents to be guaranteed to exist in the world :param agent_params: The parameters to pass to the constructors of these agents. None means no parameters for any agents :param name: The name of the worlds to generate. Uses a random name if not given :returns: The constructed world and a tuple of the agents created corresponding (in order) to the given agent types/params .. py:method:: is_valid_world(world: scml.oneshot.world.SCMLBaseWorld) -> bool :abstractmethod: Checks that the given world could have been generated from this context .. py:method:: is_valid_awi(awi: scml.oneshot.awi.OneShotAWI) -> bool :abstractmethod: Checks that the given AWI is connected to a world that could have been generated from this context .. py:method:: contains_context(context: Context) -> bool :abstractmethod: Checks that the any world generated from the given `context` could have been generated from this context .. py:method:: __contains__(other: Union[SCMLBaseWorld, OneShotAWI, Context]) -> bool .. py:class:: GeneralContext Bases: :py:obj:`BaseContext` A context that generates oneshot worlds with agents of a given `types` with predetermined structure and settings .. py:attribute:: perishable :type: bool :value: True .. py:attribute:: price_multiplier :type: numpy.ndarray | tuple[float, float] | float :value: (1.5, 2.0) .. py:attribute:: force_signing :value: True .. py:attribute:: n_steps :type: tuple[int, int] | int :value: (20, 200) .. py:attribute:: n_processes :type: tuple[int, int] | int :value: 2 .. py:attribute:: n_lines :type: tuple[int, int] | int :value: 10 .. py:attribute:: n_agents_per_process :type: numpy.ndarray | list[int] | tuple[int, int] | int .. py:attribute:: production_costs :type: numpy.ndarray | tuple[int, int] | int :value: (1, 4) .. py:attribute:: cash_availability :type: tuple[float, float] | float :value: (1.5, 2.5) .. py:attribute:: shortfall_penalty :type: tuple[float, float] | float :value: (0.2, 1.0) .. py:attribute:: shortfall_penalty_dev :type: tuple[float, float] | float :value: (0.0, 0.1) .. py:attribute:: disposal_cost :type: tuple[float, float] | float :value: (0.0, 0.2) .. py:attribute:: disposal_cost_dev :type: tuple[float, float] | float :value: (0.0, 0.02) .. py:attribute:: storage_cost :type: tuple[float, float] | float :value: (0.0, 0.02) .. py:attribute:: storage_cost_dev :type: tuple[float, float] | float :value: 0 .. py:attribute:: cost_increases_with_level :value: True .. py:attribute:: penalties_scale :type: str | list[str] :value: 'trading' .. py:attribute:: process_inputs :type: tuple[int, int] | int :value: 1 .. py:attribute:: process_outputs :type: numpy.ndarray | tuple[int, int] | int :value: 1 .. py:attribute:: exogenous_generation_method :value: 'profitable' .. py:attribute:: profit_means :type: numpy.ndarray | tuple[float, float] | float :value: (0.1, 0.2) .. py:attribute:: profit_stddevs :type: numpy.ndarray | tuple[float, float] | float :value: 0.05 .. py:attribute:: max_productivity :type: numpy.ndarray | tuple[float, float] | float :value: (0.8, 1.0) .. py:attribute:: initial_balance :type: numpy.ndarray | tuple[int, int] | int | None :value: None .. py:attribute:: exogenous_supply_predictability :type: tuple[float, float] | float :value: (0.6, 0.9) .. py:attribute:: exogenous_sales_predictability :type: tuple[float, float] | float :value: (0.6, 0.9) .. py:attribute:: exogenous_control :type: tuple[float, float] | float :value: -1 .. py:attribute:: exogenous_price_dev :type: tuple[float, float] | float :value: (0.1, 0.2) .. py:attribute:: equal_exogenous_supply :value: False .. py:attribute:: equal_exogenous_sales :value: False .. py:attribute:: cap_exogenous_quantities :type: bool :value: True .. py:method:: __attrs_post_init__() .. py:method:: extract_context_params(min_values: bool, level: int | None = None) -> ContextParams .. py:method:: make_predefined_config(agent_types: list[type[scml.oneshot.agent.OneShotAgent]], agent_processes: list[int], agent_params: list[dict[str, Any]], n_agents_per_process: list[int]) -> dict[str, Any] Generates a config for a world .. py:method:: contains_context(context: Context, raise_on_failure: bool = False, warn_on_failure: bool = False, n_tests: int = NTESTS) -> bool Checks that the any world generated from the given `context` could have been generated from this context .. py:method:: _assign_types(n_processes, types, params, levels, n_agents_per_process) .. py:method:: _distribute_agents(n_types) .. py:method:: make_config() -> dict[str, Any] Generates a config for a world .. py:method:: is_valid_world(world: scml.oneshot.world.SCMLBaseWorld, raise_on_failure: bool = False, warn_on_failure: bool = False, types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | None = None) -> bool Checks that the given world could have been generated from this context .. py:method:: contains_general_context(context: GeneralContext) -> bool Checks that the any world generated from the given `context` could have been generated from this context .. py:class:: ANACContext Bases: :py:obj:`GeneralContext` Generates a oneshot world with no constraints except compatibility with a specific ANAC competition year. .. py:attribute:: year :type: int :value: 2024 .. py:method:: __attrs_post_init__() .. py:class:: LimitedPartnerNumbersContext Bases: :py:obj:`GeneralContext` Generates a world limiting the range of the agent level, production capacity and the number of suppliers, consumers, and optionally same-level competitors. .. py:attribute:: level :type: int :value: 0 .. py:attribute:: n_consumers :type: tuple[int, int] :value: (4, 8) .. py:attribute:: n_suppliers :type: tuple[int, int] :value: (0, 0) .. py:attribute:: n_competitors :type: tuple[int, int] .. py:attribute:: buying_strength :type: Strength | None :value: None .. py:attribute:: selling_strength :type: Strength | None :value: None .. py:method:: __attrs_post_init__() .. py:method:: extract_context_params(min_values: bool, level: int | None = None) -> ContextParams .. py:method:: make_config() -> dict[str, Any] Generates a config .. py:method:: find_test_agents(world: scml.oneshot.world.SCMLBaseWorld, types: tuple[type[scml.oneshot.agent.OneShotAgent], Ellipsis] | None = None) -> list[str] .. py:method:: is_valid_world(world: scml.oneshot.world.SCMLBaseWorld, types: tuple[type[scml.oneshot.agent.OneShotAgent], Ellipsis] | None = None, raise_on_failure: bool = False, warn_on_failure: bool = False) -> bool Checks that the given world could have been generated from this context .. py:method:: contains_limited_partner_context(context: LimitedPartnerNumbersContext, raise_on_failure: bool = False, warn_on_failure: bool = False) -> bool .. py:method:: contains_context(context: Context, raise_on_failure: bool = False, warn_on_failure: bool = False, n_tests: int = NTESTS) -> bool Checks that the any world generated from the given `context` could have been generated from this context .. py:class:: FixedPartnerNumbersContext Bases: :py:obj:`LimitedPartnerNumbersContext` Generates a world limiting the range of the agent level, production capacity and the number of suppliers, consumers, and optionally same-level competitors. .. py:attribute:: level :type: int :value: 0 .. py:attribute:: n_consumers :type: int :value: 4 .. py:attribute:: n_suppliers :type: int :value: 0 .. py:attribute:: n_competitors :type: int :value: 3 .. py:method:: __attrs_post_init__() .. py:method:: extract_context_params(min_values: bool, level: int | None = None) -> ContextParams .. py:class:: ANACOneShotContext Bases: :py:obj:`ANACContext` Generates a oneshot world with no constraints except compatibility with a specific ANAC competition year. .. py:method:: __attrs_post_init__() .. py:class:: LimitedPartnerNumbersOneShotContext Bases: :py:obj:`LimitedPartnerNumbersContext` Generates a oneshot world limiting the range of the agent level, production capacity and the number of suppliers, consumers, and optionally same-level competitors. .. py:attribute:: year :type: int :value: 2024 .. py:method:: __attrs_post_init__() .. py:class:: FixedPartnerNumbersOneShotContext Bases: :py:obj:`FixedPartnerNumbersContext` Generates a world limiting the range of the agent level, production capacity and the number of suppliers, consumers, and optionally same-level competitors. .. py:class:: SupplierContext(*args, **kwargs) Bases: :py:obj:`LimitedPartnerNumbersOneShotContext` A world context that can generate any world compatible with the observation manager .. py:class:: ConsumerContext(*args, **kwargs) Bases: :py:obj:`LimitedPartnerNumbersOneShotContext` A world context that can generate any world compatible with the observation manager .. py:class:: StrongSupplierContext(*args, **kwargs) Bases: :py:obj:`SupplierContext` A supplier with almost many consumers relative to competitors .. py:class:: StrongConsumerContext(*args, **kwargs) Bases: :py:obj:`ConsumerContext` A consumer with almost many suppliers relative to competitors .. py:class:: WeakSupplierContext(*args, **kwargs) Bases: :py:obj:`SupplierContext` A supplier with few consumers relative to competitors .. py:class:: WeakConsumerContext(*args, **kwargs) Bases: :py:obj:`ConsumerContext` A consumer with few suppliers relative to competitors .. py:class:: BalancedSupplierContext(*args, **kwargs) Bases: :py:obj:`SupplierContext` A supplier with almost same number of consumers as competitors .. py:class:: BalancedConsumerContext(*args, **kwargs) Bases: :py:obj:`ConsumerContext` A consumer with almost same number of suppliers as competitors .. py:class:: RepeatingContext Bases: :py:obj:`BaseContext` Encapsulates one or more configs and switches between them when asked to generate or make something. .. py:attribute:: configs :type: tuple[dict[str, Any], Ellipsis] .. py:attribute:: randomize :type: bool :value: True .. py:attribute:: rename :type: bool :value: True .. py:attribute:: _next :type: int .. py:method:: __attrs_post_init__() .. py:method:: extract_context_params(min_values: bool, level: int | None = None) -> ContextParams .. py:method:: make_config(types: tuple[type[scml.oneshot.agent.OneShotAgent], Ellipsis] = DEFAULT_PLACEHOLDER_AGENT_TYPES, params: tuple[dict[str, Any], Ellipsis] | None = None) -> dict[str, Any] Generates a config for a world .. py:method:: from_context(context: BaseContext, n: int = 1, types: tuple[type[scml.oneshot.agent.OneShotAgent]] = DEFAULT_PLACEHOLDER_AGENT_TYPES, rename: bool = False, randomize: bool = False) :classmethod: .. py:method:: contains_repeating_context(context: RepeatingContext, raise_on_failure: bool = False, warn_on_failure: bool = False) .. py:method:: is_valid_world(world: scml.oneshot.world.SCMLBaseWorld, raise_on_failure=RAISE_ON_FAILURE, warn_on_failure=WARN_ON_FAILURE, types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | None = None) -> bool Checks that the given world could have been generated from this context .. py:method:: contains_context(context: Context, raise_on_failure: bool = False, warn_on_failure: bool = False, n_tests: int = NTESTS) -> bool Checks that the any world generated from the given `context` could have been generated from this context .. py:class:: ContextParams Basic Parameters you can assume about a context. Returned by `extract_context_params` .. py:attribute:: perishable :type: bool .. py:attribute:: nlines :type: int .. py:attribute:: nsuppliers :type: int .. py:attribute:: nconsumers :type: int .. py:class:: MonopolicContext Bases: :py:obj:`LimitedPartnerNumbersContext` An agent that has no competitors in the same level as themselves .. py:attribute:: n_competitors :type: tuple[int, int] :value: (0, 0) .. py:attribute:: n_agents_per_process :type: numpy.ndarray | list[int] | tuple[int, int] | int .. py:method:: __attrs_post_init__() .. py:class:: SingleAgentPerLevelSupplierContext Bases: :py:obj:`MonopolicContext` A world in which every level has exactly one factory and the agent is a supplier .. py:attribute:: level :type: int :value: 0 .. py:attribute:: n_consumers :type: tuple[int, int] :value: (1, 1) .. py:attribute:: n_suppliers :type: tuple[int, int] :value: (0, 0) .. py:attribute:: n_agents_per_process :type: numpy.ndarray | list[int] | tuple[int, int] | int .. py:class:: EutopiaContext Bases: :py:obj:`MonopolicContext` An unrealistic context in which the agent is the only one in its level and all other agents are nice. .. py:attribute:: non_competitors :type: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] .. py:class:: EutopiaConsumerContext Bases: :py:obj:`EutopiaContext` An unrealistic context in which the agent is the only consumer and all suppliers are nice. .. py:attribute:: level :type: int .. py:attribute:: n_consumers :type: tuple[int, int] :value: (0, 0) .. py:attribute:: n_suppliers :type: tuple[int, int] :value: (4, 8) .. py:class:: EutopiaSupplierContext Bases: :py:obj:`EutopiaContext` An unrealistic context in which the agent is the only supplier and all consumers are nice. .. py:attribute:: level :type: int .. py:attribute:: n_consumers :type: tuple[int, int] :value: (4, 8) .. py:attribute:: n_suppliers :type: tuple[int, int] :value: (0, 0) .. py:class:: OneShotPolicy(*args, **kwargs) Bases: :py:obj:`scml.oneshot.agent.OneShotSyncAgent`, :py:obj:`abc.ABC` A oneshot agent structured in three components, state encoder, policy (action) and action decoder. The agent is divided into three components: 1. State encoder (encode_state()) which takes the current state of all negotiation mechanisms, access the awi as needed, and generates a **state** which can be of any type to be passed to the next component. 2. Policy (act()) which takes the state generated from the state encoder and returns an action which may be encoded as any type to be passed to the next component. *The policy (i.e. `act` () method) is not supposed to access the AWI or any other members of the class. It is preferred to be a pure function*. This makes it easy to test the policy at predefined conditions (i.e. states) without having to construct a simulation. 3. Action decoder (decode_action()) which takes the action generated from the policy and generates the appropriate set of responses to all partners. Remarks: - The simplest form of state encoder which is implemented by default is to return the `state` member of the AWI. - The simplest form of action encoding is to simply return the responses as a `dict[str, SAOResponse]` from `act` which is then passed as it is by `decode_action` . This is the default implementation of `decode_action` .. py:method:: encode_state(mechanism_states: dict[str, negmas.sao.common.SAOState]) -> Any Called to generate a state to be passed to the act() method. The default is all of `awi` of type `OneShotState` .. py:method:: act(state: Any) -> Any :abstractmethod: The main policy. Generates an action given a state .. py:method:: decode_action(action: Any) -> dict[str, negmas.sao.common.SAOResponse] Generates offers to all partners from an encoded action. Default is to return the action as it is assuming it is a `dict[str, SAOResponse]` .. py:method:: encode_action(responses: dict[str, negmas.sao.common.SAOResponse]) -> dict[str, negmas.sao.common.SAOResponse] Receives offers for all partners and generates the corresponding action. Used mostly for debugging and testing. .. py:method:: __call__(state) A policy is a callable that receives a state and generates an action .. py:method:: counter_all(offers: dict[str, negmas.outcomes.Outcome | None], states: dict[str, negmas.sao.common.SAOState]) -> dict[str, negmas.sao.common.SAOResponse] Calculate a response to all offers from all negotiators (negotiator ID is the key). :param offers: Maps negotiator IDs to offers :param states: Maps negotiator IDs to offers AT the time the offers were made. :returns: A dictionary mapping negotiator ID to an `SAOResponse`. The response per agent consist of a tuple. In case of acceptance or ending the negotiation the second item of the tuple should be None. In case of rejection, the second item should be the counter offer. Remarks: - The response type CANNOT be WAIT. - If the system determines that a loop is formed, the agent may receive this call for a subset of negotiations not all of them. .. py:method:: first_proposals() -> dict[str, negmas.outcomes.Outcome | None] Gets a set of proposals to use for initializing the negotiation. :returns: A dictionary mapping each negotiator (in self.negotiators dict) to an outcome to be used as the first proposal if the agent is to start a negotiation. .. py:class:: ActionManager Bases: :py:obj:`abc.ABC` Manges actions of an agent in an RL environment. .. py:attribute:: context :type: scml.oneshot.context.BaseContext .. py:attribute:: continuous :type: bool :value: False .. py:attribute:: n_suppliers :type: int .. py:attribute:: n_consumers :type: int .. py:attribute:: n_partners :type: int .. py:method:: make_space() -> gymnasium.Space :abstractmethod: Creates the action space .. py:method:: decode(awi: scml.oneshot.awi.OneShotAWI, action: numpy.ndarray) -> dict[str, negmas.sao.common.SAOResponse] :abstractmethod: Decodes an action from an array to a `PurchaseOrder` and a `CounterMessage`. .. py:method:: encode(awi: scml.oneshot.awi.OneShotAWI, responses: dict[str, negmas.sao.common.SAOResponse]) -> numpy.ndarray Encodes an action as an array. This is only used for testing so it is optional .. py:class:: FlexibleActionManager Bases: :py:obj:`ActionManager` An action manager that matches any context. :param n_prices: Number of distinct prices allowed in the action. :param max_quantity: Maximum allowed quantity to offer in any negotiation. The number of quantities is one plus that because zero is allowed to model ending negotiation. :param n_partners: Maximum of partners allowed in the action. Remarks: - This action manager will always generate offers that are within the price and quantity limits given in its parameters. Wen decoding them, it will scale them up so that the maximum corresponds to the actual value in the world it finds itself. For example, if `n_prices` is 10 and the world has only two prices currently in the price issue, it will use any value less than 5 as the minimum price and any value above 5 as the maximum price. If on the other hand the current price issue has 20 values, then it will scale by multiplying the number given in the encoded action (ranging from 0 to 9) by 19/9 which makes it range from 0 to 19 which is what is expected by the world. - This action manager will adjust offers for different number of partners as follows: - If the true number of partners is larger than `n_partners` used by this action manager, it will simply use `n_partners` of them and always end negotiations with the rest of them. - If the true number of partners is smaller than `n_partners`, it will use the first `n_partners` values in the encoded action and increase the quantities of any counter offers (i.e. ones in which the response is REJECT_OFFER) by the amount missing from the ignored partners in the encoded action up to the maximum quantities allowed by the current negotiation context. For example, if `n_partneers` is 4 and we have only 2 partners in reality, and the received quantities from partners were [4, 3] while the maximum quantity allowed is 10 and the encoded action was [2, *, 3, *, 2, *, 1, *] (where we ignored prices), then the encoded action will be converted to [(Reject, 5, *), (Accept, 3, *)] where the 3 extra units that were supposed to be offered to the last two partners are moved to the first partner. If the maximum quantity allowed was 4 in that example, the result will be [(Reject, 4, *), (Accept, 3, *)]. .. py:attribute:: capacity_multiplier :type: int :value: 1 .. py:attribute:: n_prices :type: int :value: 2 .. py:attribute:: max_group_size :type: int :value: 2 .. py:attribute:: reduce_space_size :type: bool :value: True .. py:attribute:: extra_checks :type: bool :value: False .. py:attribute:: max_quantity :type: int .. py:method:: __attrs_post_init__() .. py:method:: make_space() -> gymnasium.spaces.MultiDiscrete | gymnasium.spaces.Box Creates the action space .. py:method:: decode(awi: scml.oneshot.awi.OneShotAWI, action: numpy.ndarray) -> dict[str, negmas.sao.common.SAOResponse] Generates offers to all partners from an encoded action. Default is to return the action as it is assuming it is a `dict[str, SAOResponse]` .. py:method:: encode(awi: scml.oneshot.awi.OneShotAWI, responses: dict[str, negmas.sao.common.SAOResponse]) -> numpy.ndarray Receives offers for all partners and generates the corresponding action. Used mostly for debugging and testing. .. py:data:: DefaultActionManager The default action manager .. py:class:: OneShotRLAgent(*args, models: list[scml.oneshot.rl.common.RLModel] | tuple[scml.oneshot.rl.common.RLModel, Ellipsis] = tuple(), observation_managers: list[scml.oneshot.rl.observation.ObservationManager] | tuple[scml.oneshot.rl.observation.ObservationManager, Ellipsis] = tuple(), action_managers: list[scml.oneshot.rl.action.ActionManager] | tuple[scml.oneshot.rl.action.ActionManager, Ellipsis] | None = None, fallback_type: type[scml.oneshot.agent.OneShotAgent] | None = GreedyOneShotAgent, fallback_params: dict[str, Any] | None = None, dynamic_context_switching: bool = False, randomize_test_order: bool = False, **kwargs) Bases: :py:obj:`scml.oneshot.policy.OneShotPolicy` A oneshot agent that can execute trained RL models in appropriate worlds. It falls back to the given agent type otherwise :param models: List of models to choose from. :param observation_managers: List of observation managers. Must be the same length as `models` :param action_managers: List of action managers of the same length as `models` or `None` to use the default action manager. :param fallback_type: A `OneShotAgent` type to use as a fall-back if the current world is not compatible with any observation/action managers :param fallback_params: Parameters of the `fallback_type` :param dynamic_context_switching: If `True`, the world is tested each step (instead of only at init) to find the appropriate model :param randomize_test_order: If `True`, the order at which the observation/action managers are checked for compatibility with the current world is randomized. :param \*\*kwargs: Any other OneShotPolicy parameters .. py:attribute:: _models :value: () .. py:attribute:: _action_managers :value: None .. py:attribute:: _obs_managers :value: () .. py:attribute:: _fallback_type .. py:attribute:: _dynamic_context_switching :value: False .. py:attribute:: _randomize_test_order :value: False .. py:attribute:: _fallback_params :value: None .. py:attribute:: _valid_context :type: scml.oneshot.context.Context :value: None .. py:attribute:: _valid_action_manager :type: scml.oneshot.rl.action.ActionManager :value: None .. py:attribute:: _valid_obs_manager :type: scml.oneshot.rl.observation.ObservationManager :value: None .. py:attribute:: _valid_index :type: int :value: -1 .. py:attribute:: _fallback_agent :type: scml.oneshot.agent.OneShotAgent :value: None .. py:method:: setup_fallback() .. py:method:: has_no_valid_model() .. py:method:: context_switch() .. py:method:: init() Called once after the AWI is set. Remarks: - Use this for any proactive initialization code. .. py:method:: encode_state(mechanism_states: dict[str, negmas.sao.common.SAOState]) -> scml.oneshot.rl.common.RLState Called to generate a state to be passed to the act() method. The default is all of `awi` of type `OneShotState` .. py:method:: decode_action(action: scml.oneshot.rl.common.RLAction) -> dict[str, negmas.sao.common.SAOResponse] Generates offers to all partners from an encoded action. Default is to return the action as it is assuming it is a `dict[str, SAOResponse]` .. py:method:: act(state: scml.oneshot.rl.common.RLState) -> scml.oneshot.rl.common.RLAction The main policy. Generates an action given a state .. py:method:: propose(*args, **kwargs) -> negmas.outcomes.Outcome | None Called when the agent is asking to propose in one negotiation .. py:method:: respond(*args, **kwargs) -> negmas.gb.common.ResponseType Called when the agent is asked to respond to an offer .. py:method:: before_step() Called at at the BEGINNING of every production step (day) .. py:method:: step() Called at at the END of every production step (day) .. py:method:: on_negotiation_failure(*args, **kwargs) -> None Called when a negotiation the agent is a party of ends without agreement .. py:method:: on_negotiation_success(*args, **kwargs) -> None Called when a negotiation the agent is a party of ends with agreement .. py:data:: RLState We assume that RL states are numpy arrays .. py:data:: RLAction We assume that RL actions are numpy arrays .. py:data:: RLModel A policy is a callable that receives a state and returns an action .. py:function:: model_wrapper(model, deterministic: bool = False) -> RLModel Wraps a stable_baselines3 model as an RL model .. py:class:: OneShotEnv(action_manager: scml.oneshot.rl.action.ActionManager, observation_manager: scml.oneshot.rl.observation.ObservationManager, reward_function: scml.oneshot.rl.reward.RewardFunction = DefaultRewardFunction(), context: scml.oneshot.context.BaseContext = FixedPartnerNumbersOneShotContext(), agent_type: type[scml.oneshot.agent.OneShotAgent] = Placeholder, agent_params: dict[str, Any] | None = None, extra_checks: bool = True, skip_after_negotiations: bool = True, render_mode=None, debug=False) Bases: :py:obj:`gymnasium.Env` The main Gymnasium class for implementing Reinforcement Learning Agents environments. The class encapsulates an environment with arbitrary behind-the-scenes dynamics through the :meth:`step` and :meth:`reset` functions. An environment can be partially or fully observed by single agents. For multi-agent environments, see PettingZoo. The main API methods that users of this class need to know are: - :meth:`step` - Updates an environment with actions returning the next agent observation, the reward for taking that actions, if the environment has terminated or truncated due to the latest action and information from the environment about the step, i.e. metrics, debug info. - :meth:`reset` - Resets the environment to an initial state, required before calling step. Returns the first agent observation for an episode and information, i.e. metrics, debug info. - :meth:`render` - Renders the environments to help visualise what the agent see, examples modes are "human", "rgb_array", "ansi" for text. - :meth:`close` - Closes the environment, important when external software is used, i.e. pygame for rendering, databases Environments have additional attributes for users to understand the implementation - :attr:`action_space` - The Space object corresponding to valid actions, all valid actions should be contained within the space. - :attr:`observation_space` - The Space object corresponding to valid observations, all valid observations should be contained within the space. - :attr:`spec` - An environment spec that contains the information used to initialize the environment from :meth:`gymnasium.make` - :attr:`metadata` - The metadata of the environment, e.g. `{"render_modes": ["rgb_array", "human"], "render_fps": 30}`. For Jax or Torch, this can be indicated to users with `"jax"=True` or `"torch"=True`. - :attr:`np_random` - The random number generator for the environment. This is automatically assigned during ``super().reset(seed=seed)`` and when assessing :attr:`np_random`. .. seealso:: For modifying or extending environments use the :class:`gymnasium.Wrapper` class .. note:: To get reproducible sampling of actions, a seed can be set with ``env.action_space.seed(123)``. .. note:: For strict type checking (e.g. mypy or pyright), :class:`Env` is a generic class with two parameterized types: ``ObsType`` and ``ActType``. The ``ObsType`` and ``ActType`` are the expected types of the observations and actions used in :meth:`reset` and :meth:`step`. The environment's :attr:`observation_space` and :attr:`action_space` should have type ``Space[ObsType]`` and ``Space[ActType]``, see a space's implementation to find its parameterized type. .. py:attribute:: _skip_after_negotiations :value: True .. py:attribute:: _extra_checks :value: True .. py:attribute:: _reward_function .. py:attribute:: _world :type: scml.oneshot.world.SCMLBaseWorld :value: None .. py:attribute:: _agent_type .. py:attribute:: _agent_params :value: None .. py:attribute:: _agent_id :type: str :value: '' .. py:attribute:: _agent :type: scml.oneshot.agent.OneShotAgent :value: None .. py:attribute:: _obs_manager .. py:attribute:: _action_manager .. py:attribute:: _context .. py:attribute:: action_space .. py:attribute:: observation_space .. py:attribute:: render_mode :value: None .. py:method:: _get_obs() .. py:method:: calc_info() Calculates info to be returned from `step()`. .. py:method:: _render_frame() Used for rendering. Override with your rendering code .. py:method:: close() After the user has finished using the environment, close contains the code necessary to "clean up" the environment. This is critical for closing rendering windows, database or HTTP connections. Calling ``close`` on an already closed environment has no effect and won't raise an error. .. py:method:: render() Compute the render frames as specified by :attr:`render_mode` during the initialization of the environment. The environment's :attr:`metadata` render modes (`env.metadata["render_modes"]`) should contain the possible ways to implement the render modes. In addition, list versions for most render modes is achieved through `gymnasium.make` which automatically applies a wrapper to collect rendered frames. .. note:: As the :attr:`render_mode` is known during ``__init__``, the objects used to render the environment state should be initialised in ``__init__``. By convention, if the :attr:`render_mode` is: - None (default): no render is computed. - "human": The environment is continuously rendered in the current display or terminal, usually for human consumption. This rendering should occur during :meth:`step` and :meth:`render` doesn't need to be called. Returns ``None``. - "rgb_array": Return a single frame representing the current state of the environment. A frame is a ``np.ndarray`` with shape ``(x, y, 3)`` representing RGB values for an x-by-y pixel image. - "ansi": Return a strings (``str``) or ``StringIO.StringIO`` containing a terminal-style text representation for each time step. The text can include newlines and ANSI escape sequences (e.g. for colors). - "rgb_array_list" and "ansi_list": List based version of render modes are possible (except Human) through the wrapper, :py:class:`gymnasium.wrappers.RenderCollection` that is automatically applied during ``gymnasium.make(..., render_mode="rgb_array_list")``. The frames collected are popped after :meth:`render` is called or :meth:`reset`. .. note:: Make sure that your class's :attr:`metadata` ``"render_modes"`` key includes the list of supported modes. .. versionchanged:: 0.25.0 The render function was changed to no longer accept parameters, rather these parameters should be specified in the environment initialised, i.e., ``gymnasium.make("CartPole-v1", render_mode="human")`` .. py:method:: reset(*, seed: int | None = None, options: dict[str, Any] | None = None) -> tuple[Any, dict[str, Any]] Resets the environment to an initial internal state, returning an initial observation and info. This method generates a new starting state often with some randomness to ensure that the agent explores the state space and learns a generalised policy about the environment. This randomness can be controlled with the ``seed`` parameter otherwise if the environment already has a random number generator and :meth:`reset` is called with ``seed=None``, the RNG is not reset. Therefore, :meth:`reset` should (in the typical use case) be called with a seed right after initialization and then never again. For Custom environments, the first line of :meth:`reset` should be ``super().reset(seed=seed)`` which implements the seeding correctly. .. versionchanged:: v0.25 The ``return_info`` parameter was removed and now info is expected to be returned. :param seed: The seed that is used to initialize the environment's PRNG (`np_random`) and the read-only attribute `np_random_seed`. If the environment does not already have a PRNG and ``seed=None`` (the default option) is passed, a seed will be chosen from some source of entropy (e.g. timestamp or /dev/urandom). However, if the environment already has a PRNG and ``seed=None`` is passed, the PRNG will *not* be reset and the env's :attr:`np_random_seed` will *not* be altered. If you pass an integer, the PRNG will be reset even if it already exists. Usually, you want to pass an integer *right after the environment has been initialized and then never again*. Please refer to the minimal example above to see this paradigm in action. :type seed: optional int :param options: Additional information to specify how the environment is reset (optional, depending on the specific environment) :type options: optional dict :returns: Observation of the initial state. This will be an element of :attr:`observation_space` (typically a numpy array) and is analogous to the observation returned by :meth:`step`. info (dictionary): This dictionary contains auxiliary information complementing ``observation``. It should be analogous to the ``info`` returned by :meth:`step`. :rtype: observation (ObsType) .. py:method:: step(action) Run one timestep of the environment's dynamics using the agent actions. When the end of an episode is reached (``terminated or truncated``), it is necessary to call :meth:`reset` to reset this environment's state for the next episode. .. versionchanged:: 0.26 The Step API was changed removing ``done`` in favor of ``terminated`` and ``truncated`` to make it clearer to users when the environment had terminated or truncated which is critical for reinforcement learning bootstrapping algorithms. :param action: an action provided by the agent to update the environment state. :type action: ActType :returns: An element of the environment's :attr:`observation_space` as the next observation due to the agent actions. An example is a numpy array containing the positions and velocities of the pole in CartPole. reward (SupportsFloat): The reward as a result of taking the action. terminated (bool): Whether the agent reaches the terminal state (as defined under the MDP of the task) which can be positive or negative. An example is reaching the goal state or moving into the lava from the Sutton and Barto Gridworld. If true, the user needs to call :meth:`reset`. truncated (bool): Whether the truncation condition outside the scope of the MDP is satisfied. Typically, this is a timelimit, but could also be used to indicate an agent physically going out of bounds. Can be used to end the episode prematurely before a terminal state is reached. If true, the user needs to call :meth:`reset`. info (dict): Contains auxiliary diagnostic information (helpful for debugging, learning, and logging). This might, for instance, contain: metrics that describe the agent's performance state, variables that are hidden from observations, or individual reward terms that are combined to produce the total reward. In OpenAI Gym gymnasium.spaces.Space Creates the observation space .. py:method:: encode(awi: scml.oneshot.awi.OneShotAWI) -> numpy.ndarray Encodes an observation from the agent's awi .. py:method:: make_first_observation(awi: scml.oneshot.awi.OneShotAWI) -> numpy.ndarray Creates the initial observation (returned from gym's reset()) .. py:method:: get_offers(awi: scml.oneshot.awi.OneShotAWI, encoded: numpy.ndarray) -> dict[str, negmas.outcomes.Outcome | None] Gets the offers from an encoded awi .. py:class:: FlexibleObservationManager Bases: :py:obj:`BaseObservationManager` An observation manager that can be used with any SCML world. :param capacity_multiplier: A factor to multiply by the number of lines to give the maximum quantity allowed in offers :param exogenous_multiplier: A factor to multiply maximum production capacity with when encoding exogenous quantities :param continuous: If given the observation space will be a Box otherwise it will be a MultiDiscrete :param n_prices: The number of prices to use for encoding the unit price (if not `continuous`) :param max_production_cost: The limit for production cost. Anything above that will be mapped to this max :param max_group_size: Maximum size used for grouping observations from multiple partners. This will be used in the number of partners in the simulation is larger than the number used for training. :param n_past_received_offers: Number of past received offers to add to the observation. :param n_bins: N. bins to use for discretization (if not `continuous`) :param n_sigmas: The number of sigmas used for limiting the range of randomly distributed variables :param extra_checks: If given, extra checks are applied to make sure encoding and decoding make sense Remarks: ... .. py:attribute:: capacity_multiplier :type: int :value: 1 .. py:attribute:: n_prices :type: int :value: 2 .. py:attribute:: max_group_size :type: int :value: 2 .. py:attribute:: reduce_space_size :type: bool :value: True .. py:attribute:: n_past_received_offers :type: int :value: 1 .. py:attribute:: extra_checks :type: bool :value: False .. py:attribute:: n_bins :type: int :value: 40 .. py:attribute:: n_sigmas :type: int :value: 2 .. py:attribute:: max_production_cost :type: int :value: 10 .. py:attribute:: exogenous_multiplier :type: int :value: 1 .. py:attribute:: max_quantity :type: int .. py:attribute:: _chosen_partner_indices :type: list[int] | None .. py:attribute:: _previous_offers :type: collections.deque .. py:attribute:: _dims :type: list[int] | None .. py:method:: __attrs_post_init__() .. py:method:: get_dims() -> list[int] Get the sizes of all dimensions in the observation space. Used if not continuous. .. py:method:: make_space() -> gymnasium.spaces.MultiDiscrete | gymnasium.spaces.Box Creates the action space .. py:method:: make_first_observation(awi: scml.oneshot.awi.OneShotAWI) -> numpy.ndarray Creates the initial observation (returned from gym's reset()) .. py:method:: encode(awi: scml.oneshot.awi.OneShotAWI) -> numpy.ndarray Encodes the awi as an array .. py:method:: extra_obs(awi: scml.oneshot.awi.OneShotAWI) -> list[tuple[float, int] | float] The observation values other than offers and previous offers. :returns: A list of tuples. Each is some observation variable as a real number between zero and one and a number of bins to use for discrediting this variable. If a single value, the number of bins will be self.n_bin .. py:method:: get_offers(awi: scml.oneshot.awi.OneShotAWI, encoded: numpy.ndarray) -> dict[str, negmas.outcomes.Outcome | None] Gets offers from an encoded awi. .. py:data:: DefaultObservationManager The default observation manager .. py:function:: random_action(obs: numpy.ndarray, env: scml.oneshot.rl.env.OneShotEnv) -> numpy.ndarray Samples a random action from the action space of the .. py:function:: random_policy(obs: numpy.ndarray, env: scml.oneshot.rl.env.OneShotEnv, pend: float = 0.05, paccept: float = 0.15) -> numpy.ndarray Ends the negotiation or accepts with a predefined probability or samples a random response. .. py:function:: greedy_policy(obs: numpy.ndarray, awi: scml.oneshot.awi.OneShotAWI, obs_manager: scml.oneshot.rl.observation.ObservationManager, action_manager: scml.oneshot.rl.action.ActionManager = FlexibleActionManager(ANACOneShotContext()), debug=False, distributor: Callable[[int, int], list[int]] = all_but_concentrated) -> numpy.ndarray A simple greedy policy. :param obs: The current observation :param awi: The AWI of the agent running the policy :param obs_manager: The observation manager used to encode the observation :param action_manager: The action manager to be used to encode the action :param debug: If True, extra assertions are tested :param distributor: A callable that receives a total quantity to be distributed over n partners and returns a list of n values that sum to this total quantity Remarks: - Accepts the subset of offers with maximum total quantity under current needs. - The remaining quantity is distributed over the remaining partners using the distributor function - Prices are set to the worst for the agent if the price range is small else they are set randomly .. py:class:: RewardFunction Bases: :py:obj:`Protocol` Represents a reward function. Remarks: - `before_action` is called before the action is executed for initialization and should return info to be passed to the call - `__call__` is called with the awi (to get the state), action and info and should return the reward .. py:method:: before_action(awi: scml.oneshot.awi.OneShotAWI) -> Any Called before executing the action from the RL agent to save any required information for calculating the reward in its return Remarks: The returned value will be passed as `info` to `__call__()` when it is time to calculate the reward. .. py:method:: __call__(awi: scml.oneshot.awi.OneShotAWI, action: dict[str, negmas.SAOResponse], info: Any) -> float Called to calculate the reward to be given to the agent at the end of a step. :param awi: `OneShotAWI` to access the agent's state :param action: The action (decoded) as a mapping from partner ID to responses to their last offer. :param info: Information generated from `before_action()`. You an use this to store baselines for calculating the reward :returns: The reward (a number) to be given to the agent at the end of the step. .. py:class:: DefaultRewardFunction Bases: :py:obj:`RewardFunction` The default reward function of SCML Remarks: - The reward is the difference between the balance before the action and after it. .. py:method:: before_action(awi: scml.oneshot.awi.OneShotAWI) -> float Called before executing the action from the RL agent to save any required information for calculating the reward in its return Remarks: The returned value will be passed as `info` to `__call__()` when it is time to calculate the reward. .. py:method:: __call__(awi: scml.oneshot.awi.OneShotAWI, action: dict[str, negmas.SAOResponse], info: float) Called to calculate the reward to be given to the agent at the end of a step. :param awi: `OneShotAWI` to access the agent's state :param action: The action (decoded) as a mapping from partner ID to responses to their last offer. :param info: Information generated from `before_action()`. You an use this to store baselines for calculating the reward :returns: The reward (a number) to be given to the agent at the end of the step. .. py:class:: DefaultOneShotAdapter(*args, **kwargs) Bases: :py:obj:`negmas.Adapter`, :py:obj:`scml.oneshot.mixins.OneShotUFunCreatorMixin` The base class of all agents running in OneShot based on OneShotAgent. Remarks: - It inherits from `Adapter` allowing it to just pass any calls not defined explicity in it to the internal `_obj` object representing the OneShotAgent. .. py:attribute:: _obj :type: scml.oneshot.agent.OneShotAgent .. py:method:: make_ufun(add_exogenous: bool, in_adapter=False) .. py:method:: on_negotiation_failure(partners, annotation, mechanism, state) Called whenever a negotiation ends without agreement .. py:method:: on_negotiation_success(contract: negmas.Contract, mechanism) Called whenever a negotiation ends with agreement .. py:method:: on_contract_executed(contract: negmas.Contract) -> None Called after successful contract execution for which the agent is one of the partners. .. py:method:: on_contract_breached(contract: negmas.Contract, breaches: list[negmas.Breach], resolution: Optional[negmas.Contract]) -> None Called after complete processing of a contract that involved a breach. :param contract: The contract :param breaches: All breaches committed (even if they were resolved) :param resolution: The resolution contract if re-negotiation was successful. None if not. .. py:method:: init_() Called to initialize the agent **after** the world is initialized. the AWI is accessible at this point. .. py:method:: init() Override this method to modify initialization logic .. py:method:: reset() .. py:method:: is_clean() -> bool .. py:method:: before_step() .. py:method:: step() Override this method to modify stepping logic .. py:method:: to_dict() .. py:method:: _respond_to_negotiation_request(initiator: str, partners: list[str], issues: list[negmas.Issue], annotation: dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, role: Optional[str], req_id: Optional[str]) -> Optional[negmas.Negotiator] Called by the mechanism to ask for joining a negotiation. The agent can refuse by returning a None :param initiator: The ID of the agent that initiated the negotiation request :param partners: The partner list (will include this agent) :param issues: The list of issues :param annotation: Any annotation specific to this negotiation. :param mechanism: The mechanism that started the negotiation :param role: The role of this agent in the negotiation :param 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 .. py:method:: set_renegotiation_agenda(contract: negmas.Contract, breaches: list[negmas.Breach]) -> Optional[negmas.RenegotiationRequest] Received by partners in ascending order of their total breach levels in order to set the renegotiation agenda when contract execution fails :param contract: The contract being breached :param breaches: All breaches on `contract` :returns: Renegotiation agenda (issues to negotiate about to avoid reporting the breaches). .. py:method:: respond_to_renegotiation_request(contract: negmas.Contract, breaches: list[negmas.Breach], agenda: negmas.RenegotiationRequest) -> Optional[negmas.Negotiator] Called to respond to a renegotiation request :param agenda: :param contract: :param breaches: Returns: .. py:method:: on_neg_request_rejected(req_id: str, by: Optional[list[str]]) Called when a requested negotiation is rejected :param req_id: The request ID passed to _request_negotiation :param by: A list of agents that refused to participate or None if the failure was for another reason .. py:method:: on_neg_request_accepted(req_id: str, mechanism: negmas.NegotiatorMechanismInterface) Called when a requested negotiation is accepted .. py:property:: awi :type: scml.oneshot.awi.OneShotAWI Gets the Agent-world interface. .. py:property:: short_type_name Returns a short name of the type of this entity .. py:class:: _StdSystemAgent(*args, role, **kwargs) Bases: :py:obj:`DefaultOneShotAdapter` Implements an agent for handling system operations .. py:attribute:: id The unique ID of this entity .. py:attribute:: name A convenient name of the entity (intended primarily for printing/logging/debugging). .. py:attribute:: profile :value: None .. py:property:: type_name Returns a short name of the type of this entity .. py:property:: short_type_name Returns a short name of the type of this entity .. py:method:: respond_to_negotiation_request(initiator: str, issues: list[negmas.Issue], annotation: dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface) -> Optional[negmas.Negotiator] .. py:method:: before_step() .. py:method:: step() Override this method to modify stepping logic .. py:method:: init() Override this method to modify initialization logic .. py:method:: on_negotiation_failure(partners: list[str], annotation: dict[str, Any], mechanism: negmas.NegotiatorMechanismInterface, state: negmas.MechanismState) -> None Called whenever a negotiation ends without agreement .. py:method:: on_negotiation_success(contract: negmas.Contract, mechanism: negmas.NegotiatorMechanismInterface) -> None Called whenever a negotiation ends with agreement .. py:method:: sign_all_contracts(contracts: list[negmas.Contract]) -> list[Optional[str]] Signs all contracts .. py:class:: OneShotUFun(ex_pin: int, ex_qin: int, ex_pout: int, ex_qout: int, input_product: int, input_agent: bool, output_agent: bool, production_cost: float, disposal_cost: float, storage_cost: float, shortfall_penalty: float, input_penalty_scale: float | None, output_penalty_scale: float | None, storage_penalty_scale: float | None, n_input_negs: int, n_output_negs: int, current_step: int, agent_id: str | None, time_range: tuple[int, int], inventory_in: int = 0, inventory_out: int = 0, input_qrange: tuple[int, int] = (0, 0), input_prange: tuple[int, int] = (0, 0), output_qrange: tuple[int, int] = (0, 0), output_prange: tuple[int, int] = (0, 0), force_exogenous: bool = True, n_lines: int = 10, normalized: bool = False, current_balance: int | float = float('inf'), suppliers: set[str] = set(), consumers: set[str] = set(), perishable=True, **kwargs) Bases: :py:obj:`negmas.preferences.StationaryMixin`, :py:obj:`negmas.preferences.UtilityFunction` Calculates the utility function of a list of contracts or offers. :param force_exogenous: Is the agent forced to accept exogenous contracts given through `ex_*` arguments? :param ex_pin: total price of exogenous inputs for this agent :param ex_qin: total quantity of exogenous inputs for this agent :param ex_pout: total price of exogenous outputs for this agent :param ex_qout: total quantity of exogenous outputs for this agent. :param cost: production cost of the agent. :param disposal_cost: disposal cost per unit of input/output. :param shortfall_penalty: penalty for failure to deliver one unit of output. :param input_agent: Is the agent an input agent which means that its input product is the raw material :param output_agent: Is the agent an output agent which means that its output product is the final product :param n_lines: Number of production lines. If None, will be read through the AWI. :param input_product: Index of the input product. If None, will be read through the AWI :param input_qrange: A 2-int tuple giving the range of input quantities negotiated. If not given will be read through the AWI :param input_prange: A 2-int tuple giving the range of input unit prices negotiated. If not given will be read through the AWI :param output_qrange: A 2-int tuple giving the range of output quantities negotiated. If not given will be read through the AWI :param output_prange: A 2-int tuple giving the range of output unit prices negotiated. If not given will be read through the AWI :param n_input_negs: How many input negotiations are allowed. If not given, it will be the number of suppliers as given by the AWI :param n_output_negs: How many output negotiations are allowed. If not given, it will be the number of consumers as given by the AWI :param current_step: Current simulation step. Needed only for `ufun_range` when returning best outcomes :param normalized: If given the values returned by `from_*`, `utility_range` and `__call__` will all be normalized between zero and one. Remarks: - The utility function assumes that the agent will have to pay for all its input products but will receive money only for the output products it could generate and sell. - The utility function respects production capacity (n. lines). The agent cannot produce more than the number of lines it has. - disposal cost is paid for items bought but not produced only. Items consumed in production (i.e. sold) are not counted. .. py:attribute:: agent_id .. py:attribute:: time_range .. py:attribute:: suppliers .. py:attribute:: consumers .. py:attribute:: current_balance .. py:attribute:: normalized :value: False .. py:attribute:: input_penalty_scale .. py:attribute:: storage_penalty_scale .. py:attribute:: output_penalty_scale .. py:attribute:: current_step .. py:attribute:: inventory_in :value: 0 .. py:attribute:: inventory_out :value: 0 .. py:attribute:: n_input_negs .. py:attribute:: perishable :value: True .. py:attribute:: n_output_negs .. py:attribute:: force_exogenous :value: True .. py:attribute:: n_lines :value: 10 .. py:attribute:: input_product .. py:attribute:: reserved_value .. py:attribute:: _signed_agreements :type: list[tuple[int, int, int]] :value: [] .. py:attribute:: _signed_is_output :type: list[bool] :value: [] .. py:attribute:: _registered_sale_failures :type: set[str] .. py:attribute:: _registered_supply_failures :type: set[str] .. py:property:: best_option :type: UFunLimit Best possible options .. py:property:: worst_option :type: UFunLimit Best possible options .. py:method:: register_supply_failure(supplier_id: str) .. py:method:: register_sale_failure(consumer_id: str) .. py:method:: register_sale(q: int, p: int, t: int) Registers a sale to be considered when calculating utilities .. py:method:: register_supply(q: int, p: int, t: int) Registers a supply to be considered when calculating utilities .. py:method:: xml(issues) -> str :abstractmethod: .. py:method:: eval(offer: tuple[int, int, int] | None) -> float Calculates the utility function given a single contract. Remarks: - This method calculates the utility value of a single offer assuming all other negotiations end in failure. - It can only be called for agents that exist in the first or last layer of the production graph. .. py:method:: from_contracts(contracts: Iterable[negmas.Contract], return_info: Literal[False] = False, ignore_exogenous=True) -> float from_contracts(contracts: Iterable[negmas.Contract], return_info: Literal[True], ignore_exogenous=True) -> UtilityInfo Calculates the utility function given a list of contracts :param contracts: A list/tuple of contracts :param ignore_exogenous: If given, any contracts with a system agent will be ignored. Remarks: - This method ignores any unsigned contracts passed to it. - We do not consider time at all so it is implicitly assumed that all contracts have the same delivery time value. - The reason for having the `ignore_exogenous` parameter is to avoid double counting exogenous contracts if their information is passed during construction of the ufun and they also exist in the list of `contracts` passed here. .. py:method:: outcome_as_tuple(offer) :staticmethod: .. py:method:: from_offers(offers: tuple[tuple[int, int, int | float] | None, Ellipsis] | dict[str, tuple[int, int, int] | None], outputs: tuple[bool, Ellipsis] | None = None, return_info: Literal[False] = False, ignore_signed_contracts: bool = True) -> float from_offers(offers: tuple[tuple[int, int, int | float] | None, Ellipsis] | dict[str, tuple[int, int, int] | None], outputs: tuple[bool, Ellipsis] | None, return_info: Literal[True], ignore_signed_contracts: bool = True) -> UtilityInfo Calculates the utility value given a list of offers and whether each offer is for output or not (= input). :param offers: An iterable (e.g. list) of tuples each with three values: (quantity, time, unit price) IN THAT ORDER. Time is ignored and can be set to any value. :param outputs: An iterable of the same length as offers of booleans specifying for each offer whether it is an offer for buying the agent's output product. :param return_info: If true, detailed utility information is returned as Utility Info :param ignore_signed_contracts: If true, ignores the registered signed contracts. This means that only exogenous contracts and offers will be used in evaluating the utility. Remarks: - This method takes into account the exogenous contract information passed when constructing the ufun. - You can pass a dictionary mapping partner ID to an offer and the system will use the correct value for the corresponding outputs array. .. py:method:: from_aggregates(qin: int, qout_signed: int, qout_sold: int, pin: int, pout: int, input_penalty: float, output_penalty: float, storage_penalty: float) -> float Calculates the utility from aggregates of input/output quantity/prices :param qin: Input quantity (total including all exogenous contracts). :param qout_signed: Output quantity (total including all exogenous contracts) that the agent agreed to sell. :param qout_sold: Output quantity (total including all exogenous contracts) that the agent will actually sell. :param pin: Input total price (i.e. unit price * qin). :param pout: Output total price (i.e. unit price * qin). :param input_penalty: total disposal cost :param output_penalty: total shortfall penalty :param storage_penalty: total storage penalty Remarks: - Most likely, you do not need to directly call this method. Consider `from_offers` and `from_contracts` that take current balance and exogenous contract information (passed during ufun construction) into account. - The method respects production capacity (n. lines). The agent cannot produce more than the number of lines it has. - This method does not take exogenous contracts or current balance into account. - The method assumes that the agent CAN pay for all input and production. .. py:method:: breach_level(qin: int = 0, qout: int = 0) Calculates the breach level that would result from a given quantities .. py:method:: is_breach(qin: int = 0, qout: int = 0) Whether the given quantities would lead to a breach. .. py:property:: max_utility The maximum possible utility value .. py:property:: min_utility The minimum possible utility value .. py:method:: minmax(*args, **kwargs) -> tuple[float, float] Finds the range of the given utility function for the given outcomes :param self: The utility function :param issues: List of issues (optional) :param outcomes: A collection of outcomes (optional) :param max_cardinality: the maximum number of outcomes to try sampling (if sampling is used and outcomes are not given) :param above_reserve: If given, the minimum and maximum will be set to reserved value if they were less than it. :returns: (lowest, highest) utilities in that order .. py:method:: extreme_outcomes(outcome_space: negmas.outcomes.OutcomeSpace | None = None, issues: Iterable[negmas.outcomes.Issue] | None = None, outcomes: Iterable[negmas.outcomes.Outcome] | None = None, max_cardinality=1000) -> tuple[negmas.outcomes.Outcome, negmas.outcomes.Outcome] .. py:method:: utility_range(outcome_space: negmas.outcomes.OutcomeSpace | None = None, issues: list[negmas.outcomes.Issue] | None = None, outcomes: list[negmas.outcomes.Outcome] | None = None, return_outcomes=False, max_n_outcomes=1000) -> tuple[float, float] | tuple[float, float, negmas.outcomes.Outcome, negmas.outcomes.Outcome] Finds the utility range and optionally returns the corresponding outcomes from a given issue space or in a single negotiation. :param issues: The set of issues of the negotiation. If not given it will be read from the AWI. Note that you cannot specify these issues except for agent in the first or last layer of the production graph (because otherwise, the agent cannot know whether this negotiation is for buying of selling). :param outcomes: A list of outcomes to consider. Using outcomes is much slower than using issues and you should never pass both. :param infeasible_cutoff: A utility value under which we consider the outcome infeasible. :param return_outcomes: If given the worst and best outcomes (in that order) will be returned. :param max_n_outcomes: Maximum number of outcomes to try. Not used. :returns: A tuple of worst and best utility values if `return_outcomes` is `False`. otherwise, the worst and best outcomes are appended to the returned utilities leading to a 4-items tuple instead of two. Remarks: - You will get a warning if you use a list of outcomes here because it is too slow. - You should only pass `issues` if you know that the agent is either an input agent or an output agent. Agents in the middle of the production graph cannot know whether these issues are for buying of for selling. To find the utility range for these agents, you can use `worst` and `best` that allow specifying input and output issues separately. - It is always assumed that the range required is for a single negotiation not a set of negotiations and under the assumption that all other negotiations if any will end in failure .. py:method:: _is_midlevel() .. py:method:: find_limit(best: bool, n_input_negs=None, n_output_negs=None, secured_input_quantity=0, secured_input_unit_price=0.0, secured_output_quantity=0, secured_output_unit_price=0.0, ignore_signed_contracts: bool = True) -> UFunLimit Finds either the maximum or the minimum of the ufun. :param best: Best(max) or worst (min) ufun value? :param n_input_negs: How many input negs are we to consider? None means all :param n_output_negs: How many output negs are we to consider? None means all :param secured_input_quantity: A quantity that MUST be bought :param secured_input_unit_price: The (average) unit price of the quantity that MUST be bought. :param secured_output_quantity: A quantity that MUST be sold. :param secured_output_unit_price: The (average) unit price of the quantity that MUST be sold. :param ignore_signed_contracts: If True all signed contracts will be ignored. Use secured_* to pass this information if you need to in this case. Remarks: - You can use the `secured_*` arguments and control over the number of negotiations to consider to find the utility limits **given** some already concluded and signed contracts .. py:method:: best() -> negmas.outcomes.Outcome .. py:method:: worst() -> negmas.outcomes.Outcome .. py:method:: find_limit_brute_force(best, n_input_negs=None, n_output_negs=None, secured_input_quantity=0, secured_input_unit_price=0.0, secured_output_quantity=0, secured_output_unit_price=0.0, ignore_signed_contracts=True) -> UFunLimit Finds either the maximum and the minimum of the ufun. :param best: Best(max) or worst (min) ufun value? :param n_input_negs: How many input negs are we to consider? None means all :param n_output_negs: How many output negs are we to consider? None means all :param secured_input_quantity: A quantity that MUST be bought :param secured_input_unit_price: The (average) unit price of the quantity that MUST be bought. :param secured_output_quantity: A quantity that MUST be sold. :param secured_output_unit_price: The (average) unit price of the quantity that MUST be sold. Remarks: - You can use the `secured_*` arguments and control over the number of negotiations to consider to find the utility limits **given** some already concluded and signed contracts - Note that this function CANNOT take into account the sales or supplies already signed (and registered via `register_sale` and/or `register_supply`). You MUST pass the quantities and prices for signed contracts through the secured_* parameters. :returns: worst and best outcome information in the form of `UFunLimit` tuple. .. py:method:: ok_to_buy_at(unit_price: float) -> bool Checks if the unit price can -- even in principle -- be acceptable for buying Remarks: - This method is **very** optimistic. If it returns `False`, an agent should **never** buy at this price. If it returns `True`, it may *still be a bad idea* to buy at this price. - If we **buy** at this price, the **best** case scenario is that we pay it and pay production cost then receive the unit price of one output. - If we do **not** buy at this price, the **worst** case scenario is that we will pay shortfall penalty for one item - We should **NOT** buy if the best case scenario when buying is worse than the worst case scenario when not buying. - If called for agents not at the end of the production chain, it will always return `True` because in these cases we do not know what the the unit price for the output so there is nothing to compare with. .. py:method:: ok_to_sell_at(unit_price: float) -> bool Checks if the unit price can -- even in principle -- be acceptable for selling Remarks: - This method is **very** optimistic. If it returns `False`, an agent should **never** sell at this price. If it returns `True`, it may *still be a bad idea* to sell at this price. - Sales decisions does not affect in any way the amount we pay for input materials. It only affects the amount we produce, the amout we get paid in sales and the amount we pay as disposal cost and shortfall penalty. - If we agree to sell an item at this price, the best case scenario is that we can actually produce this item and sell it. We pay production cost and receive the given unit price. - If we do **not** sell at this price, the worst case scenario is that we really needed that sale. In this case, we will pay disposal cost for one item. - We should **NOT** sell if the best case scenario when selling is worse than the worst case scenario when not selling. - If called for agents not at the beginning of the production chain, it will always return `True` because in these cases we do not know what the the unit price for the input so there is nothing to compare with. .. py:class:: UFunLimit Bases: :py:obj:`tuple` .. py:attribute:: utility .. py:attribute:: input_quantity .. py:attribute:: input_price .. py:attribute:: output_quantity .. py:attribute:: output_price .. py:attribute:: exogenous_input_quantity .. py:attribute:: exogenous_input_price .. py:attribute:: exogenous_output_quantity .. py:attribute:: exogenous_output_price .. py:attribute:: inventory_input .. py:attribute:: inventory_output .. py:attribute:: producible .. py:class:: UtilityInfo .. py:attribute:: producible :type: int .. py:attribute:: total_input :type: int .. py:attribute:: total_output :type: int .. py:attribute:: shortfall_quantity :type: int .. py:attribute:: shortfall_penalty :type: float .. py:attribute:: remaining_quantity :type: int .. py:attribute:: disposal_cost :type: float .. py:attribute:: storage_cost :type: float .. py:attribute:: utility :type: float .. py:class:: SCMLBaseWorld(catalog_prices: numpy.ndarray, profiles: list[scml.oneshot.common.OneShotProfile], agent_types: list[type[scml.oneshot.agent.OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | numpy.ndarray = 50, financial_report_period=5, bankruptcy_limit=0.0, penalize_bankrupt_for_future_contracts=True, penalties_scale: Literal['trading', 'catalog', 'unit', 'none'] = 'trading', exogenous_contracts: Collection[scml.oneshot.common.OneShotExogenousContract] = tuple(), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: numpy.ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=60 * 15, sync_calls=False, neg_n_steps=20, neg_time_limit=None, neg_hidden_time_limit=60, neg_step_time_limit=20, negotiation_speed=None, shuffle_negotiations=False, one_offer_per_step=False, publish_exogenous_summary=True, publish_trading_prices=True, publish_assets=False, publish_production_capacity=True, price_multiplier=0.0, price_range_fraction=0.0, wide_price_range=False, allow_zero_quantity: bool = False, trading_price_discount=0.9, signing_delay=0, force_signing=False, batch_signing=True, name: str | None = None, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_catalog=0, inventory_valuation_trading=0, perishable=True, horizon=0, one_time_per_negotiation=True, quantity_multiplier: float = 1.0, nullify_bankrupt_contracts: bool = False, debug: bool = False, verbose: bool = False, **kwargs) Bases: :py:obj:`negmas.TimeInAgreementMixin`, :py:obj:`negmas.World`\ [\ :py:obj:`scml.oneshot.awi.OneShotAWI`\ , :py:obj:`scml.oneshot.sysagents.DefaultOneShotAdapter`\ ] Implements the a generalized form of SCML-OneShot game which supports both oneshot and standard simulations :param catalog_prices: An n_products vector (i.e. n_processes+1 vector) giving the catalog price of all products :param profiles: An n_agents list of `OneShotFactoryProfile` objects specifying the private profile of the factory associated with each agent. :param agent_types: An n_agents list of strings/ `OneShotAgent` classes specifying the type of each agent :param agent_params: An n_agents dictionaries giving the parameters of each agent :param catalog_quantities: The quantities in the past for which catalog_prices are the average unit prices. This is used when updating the trading prices. If set to zero then the trading price will follow the market price and will not use the catalog_price (except for products that are never sold in the market for which the trading price will take the default value of the catalog price). If set to a large value (e.g. 10000), the price at which a product is sold will not affect the trading price :param financial_report_period: The number of steps between financial reports. If < 1, it is a fraction of n_steps :param exogenous_force_max: If true, exogenous contracts are forced to be signed independent of the setting of `force_signing` :param compact: If True, no logs will be kept and the whole simulation will use a smaller memory footprint :param n_steps: Number of simulation steps (can be considered as days). :param time_limit: Total time allowed for the complete simulation in seconds. :param neg_n_steps: Number of negotiation steps allowed for all negotiations. :param neg_time_limit: Total time allowed for a complete negotiation in seconds. :param neg_step_time_limit: Total time allowed for a single step of a negotiation. in seconds. :param negotiation_speed: The number of negotiation steps that pass in every simulation step. If 0, negotiations will be guaranteed to finish within a single simulation step :param signing_delay: The number of simulation steps to pass between a contract is concluded and signed :param name: The name of the simulations :param \*\*kwargs: Other parameters that are passed directly to `SCML2020World` constructor. .. py:attribute:: _verbose :value: False .. py:attribute:: _debug :value: False .. py:attribute:: agents :type: dict[str, scml.oneshot.sysagents.DefaultOneShotAdapter] .. py:attribute:: publish_assets :value: False .. py:attribute:: publish_production_capacity :value: True .. py:attribute:: perishable :value: True .. py:attribute:: horizon :value: 0 .. py:attribute:: price_range_fraction :value: 0.0 .. py:attribute:: nullify_bankrupt_contracts :value: False .. py:attribute:: inventory_valuation_catalog :value: 0 .. py:attribute:: inventory_valuation_trading :value: 0 .. py:attribute:: allow_zero_quantity :value: False .. py:attribute:: _profits :type: dict[str, list[float]] .. py:attribute:: _breach_levels :type: dict[str, list[float]] .. py:attribute:: _breaches_of :type: dict[str, list[bool]] .. py:attribute:: _inventory_input :type: dict[str, int] .. py:attribute:: _inventory_output :type: dict[str, int] .. py:attribute:: _productivity :type: dict[str, float] .. py:attribute:: _shortfall_quantity :type: dict[str, int] .. py:attribute:: _shortfall_penalty :type: dict[str, float] .. py:attribute:: _storage_cost :type: dict[str, float] .. py:attribute:: _disposal_cost :type: dict[str, float] .. py:attribute:: _penalized_quantity :type: dict[str, int] .. py:attribute:: _n_nullified :type: int :value: 0 .. py:attribute:: _nullified_quantity :type: int :value: 0 .. py:attribute:: _nullified_price :type: float :value: 0 .. py:attribute:: _activity :value: 0 .. py:attribute:: trading_price_discount :value: 0.9 .. py:attribute:: catalog_quantities :value: 50 .. py:attribute:: publish_exogenous_summary :value: True .. py:attribute:: price_multiplier :value: 0.0 .. py:attribute:: wide_price_range :value: False .. py:attribute:: publish_trading_prices :value: True .. py:attribute:: penalize_bankrupt_for_future_contracts :value: True .. py:attribute:: agent_disposal_cost :type: dict[str, list[float]] .. py:attribute:: agent_storage_cost :type: dict[str, list[float]] .. py:attribute:: agent_shortfall_penalty :type: dict[str, list[float]] .. py:attribute:: compact :value: True .. py:attribute:: quantity_multiplier :value: 1.0 .. py:attribute:: one_time_per_negotiation :value: True .. py:attribute:: exogenous_dynamic :value: False .. py:attribute:: penalties_scale :value: 'trading' .. py:attribute:: bankruptcy_limit :value: -0.0 .. py:attribute:: profiles .. py:attribute:: catalog_prices .. py:attribute:: process_inputs .. py:attribute:: process_outputs .. py:attribute:: n_products .. py:attribute:: n_processes .. py:attribute:: exogenous_force_max :value: False .. py:attribute:: financial_reports_period :value: 5 .. py:attribute:: controller_types .. py:attribute:: agent_types .. py:attribute:: agent_params .. py:attribute:: agent_unique_types .. py:attribute:: agent_n_contracts .. py:attribute:: suppliers :type: list[list[str]] .. py:attribute:: consumers :type: list[list[str]] .. py:attribute:: production_capacity :type: list[int] .. py:attribute:: agent_processes :type: dict[str, list[int]] .. py:attribute:: agent_inputs :type: dict[str, list[int]] .. py:attribute:: agent_outputs :type: dict[str, list[int]] .. py:attribute:: agent_consumers :type: dict[str, list[str]] .. py:attribute:: agent_suppliers :type: dict[str, list[str]] .. py:attribute:: agent_profiles :type: dict[str, scml.oneshot.common.OneShotProfile] .. py:attribute:: is_bankrupt :type: dict[str, bool] .. py:attribute:: exogenous_contracts :type: dict[int:list[Contract]] .. py:attribute:: _traded_quantity .. py:attribute:: _real_price .. py:attribute:: _sold_quantity .. py:attribute:: _trading_price .. py:attribute:: _betas .. py:attribute:: _betas_sum .. py:attribute:: _input_quantity .. py:attribute:: _input_price .. py:attribute:: _output_quantity .. py:attribute:: _output_price .. py:attribute:: exogenous_qout .. py:attribute:: exogenous_qin .. py:attribute:: exogenous_pout .. py:attribute:: exogenous_pin .. py:attribute:: exogenous_contracts_summary :value: [] .. py:attribute:: initial_balances .. py:attribute:: _max_n_lines .. py:attribute:: a2i .. py:attribute:: _current_issues :type: list[list[negmas.ContiguousIssue]] :value: [] .. py:attribute:: __contracts :type: dict[str, list[negmas.Contract]] .. py:attribute:: _agent_negotiations :type: dict[str, dict[str, dict[str, scml.oneshot.common.NegotiationDetails]]] .. py:method:: action_info_cols() -> list[tuple[str, type]] .. py:method:: extract_action_info(action: Any) -> list[int] .. py:method:: agreement_info_cols() -> list[tuple[str, type]] .. py:method:: extract_agreement_info(agreement: negmas.Outcome | None) -> list[int] .. py:method:: extra_neg_info(info: negmas.situated.NegotiationInfo) -> dict[str, Any] .. py:method:: replace_agents(config: dict, old_types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | list[str | type[scml.oneshot.agent.OneShotAgent]], types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | list[str | type[scml.oneshot.agent.OneShotAgent]], params: list[dict[str, Any]] | tuple[dict[str, Any], Ellipsis] | None = None) :classmethod: Replaces all agents of a given type by agents of a new type .. py:method:: generate(agent_types: tuple[str | type[scml.oneshot.agent.OneShotAgent], Ellipsis] | list[str | type[scml.oneshot.agent.OneShotAgent]] | type[scml.oneshot.agent.OneShotAgent] | str, agent_params: list[dict[str, Any]] | tuple[dict[str, Any], Ellipsis] | None = None, agent_processes: list[int] | None = None, n_steps: tuple[int, int] | int = (50, 200), n_processes: tuple[int, int] | int = 2, n_lines: numpy.ndarray | tuple[int, int] | int = 10, n_agents_per_process: numpy.ndarray | tuple[int, int] | int = (4, 8), process_inputs: numpy.ndarray | tuple[int, int] | int = 1, process_outputs: numpy.ndarray | tuple[int, int] | int = 1, production_costs: numpy.ndarray | tuple[int, int] | int = (1, 4), profit_means: numpy.ndarray | tuple[float, float] | float = (0.1, 0.2), profit_stddevs: numpy.ndarray | tuple[float, float] | float = 0.05, max_productivity: numpy.ndarray | tuple[float, float] | float = (0.8, 1.0), initial_balance: numpy.ndarray | tuple[int, int] | int | None = None, exogenous_supply_predictability: tuple[float, float] | float = (0.6, 0.9), exogenous_sales_predictability: tuple[float, float] | float = (0.6, 0.9), exogenous_control: tuple[float, float] | float = -1, cash_availability: tuple[float, float] | float = (1.5, 2.5), shortfall_penalty: tuple[float, float] | float = (0.2, 1.0), shortfall_penalty_dev: tuple[float, float] | float = (0.0, 0.1), disposal_cost: tuple[float, float] | float = (0.0, 0.2), disposal_cost_dev: tuple[float, float] | float = (0.0, 0.02), storage_cost: tuple[float, float] | float = (0.0, 0.02), storage_cost_dev: tuple[float, float] | float = 0, exogenous_price_dev: tuple[float, float] | float = (0.1, 0.2), price_multiplier: numpy.ndarray | tuple[float, float] | float = (1.5, 2.0), cost_increases_with_level=True, equal_exogenous_supply=False, equal_exogenous_sales=False, force_signing=True, profit_basis=np.max, random_agent_types: bool = False, penalties_scale: str | list[str] = 'trading', cap_exogenous_quantities: bool = True, exogenous_generation_method='profitable', perishable: bool | None = True, max_supply: numpy.ndarray | tuple[float, float] | float = (0.8, 1.0), **kwargs) -> dict[str, Any] :classmethod: Generates the configuration for a world :param agent_types: All agent types :param agent_params: Agent parameters used to initialize them :param n_steps: Number of simulation steps :param n_processes: Number of processes in the production chain :param n_lines: Number of lines per factory :param process_inputs: Number of input units per process :param process_outputs: Number of output units per process :param production_costs: Production cost per factory :param profit_means: Mean profitability per production level (i.e. process). :param profit_stddevs: Std. Dev. of the profitability of every level (i.e. process). :param max_productivity: Maximum possible productivity per level (i.e. process). :param max_supply: Maximum possible supply level to the market, :param initial_balance: The initial balance of all agents :param n_agents_per_process: Number of agents per process :param agent_processes: The process for each agent. If not `None` , it will override `n_agents_per_process` and must be a list/tuple of the same length as `agent_types` . Morevoer, `random_agent_types` must be False in this case :param cost_increases_with_level: If true, production cost will be higher for processes nearer to the final product. :param profit_basis: The statistic used when controlling catalog prices by profit arguments. It can be np.mean, np.median, np.min, np.max or any Callable[[list[float]], float] and is used to summarize production costs at every level. :param equal_exogenous_supply: If true, external supply will be distributed equally among all agents in the first layer :param equal_exogenous_sales: If true, external sales will be distributed equally among all agents in the last layer :param exogenous_supply_predictability: How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random :param exogenous_sales_predictability: How predictable are exogenous supplies of each agent over time. 1.0 means that every agent will have the same quantity for all of its contracts over time. 0.0 means quantities per agent are completely random :param force_signing: Whether to force contract signatures (exogenous contracts are treated in the same way). :param exogenous_control: How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True :param cap_exogenous_quantities: If True, all exogenous quantities in all contracts are capped to be no more than the number of lines :param cash_availability: The fraction of the total money needs of the agent to work at maximum capacity that is available as `initial_balance` . This is only effective if `initial_balance` is set to `None` . :param exogenous_control: How much control does the agent have over exogenous contract signing. Only effective if force_signing is False and use_exogenous_contracts is True :param disposal_cost: A range to sample mean-disposal costs for all factories from (only used if perishable is True) :param shortfall_penalty: A range to sample mean-shortfall penalty for all factories from :param storage_cost: A range to sample mean-storage costs fro all factories from (only used if perishable is False) :param disposal_cost_dev: A range to sample std. dev of disposal costs for all factories from :param shortfall_penalty_dev: A range to sample std. dev of shortfall penalty for all factories from :param storage_cost_dev: The standard deviation of storage cost relative to the mean price :param exogenous_price_dev: The standard deviation of exogenous contract prices relative to the mean price :param price_multiplier: A value to multiply with trading/catalog price to get the upper limit on prices for all negotiations :param random_agent_types: If True, the final agent types used by the generator will always be sampled from the given types. If False, this random sampling will only happen if len(agent_types) != n_agents. :param penalties_scale: What are `disposal_cost` and `shortfall_penalty` relative to. There are four options: `trading`, `catalog` mean trading and catalog prices of the product. `unit` means the unit price in the contract and `none` means the `storage-cost` and `shortfall_penalty` are absolute values (in money unit). If not given will be read through the AWI :param exogenous_generation_method: the generation method. This is only for compatibility with SCML2020World and is not used. :param perishable: If True, storage_cost is set to zero as there is no storage and if False, disposal_cost is set to zero as there is no disposal. If None, neither is overridden. :param \*\*kwargs: :returns: world configuration as a Dict[str, Any]. A world can be generated from this dict by calling OneShotWorld(**d) Remarks: - There are two general ways to use this generator: 1. Pass `random_agent_types = False`, and pass `agent_types`, `agent_processes` to control placement of each agent in each level of the production graph. 2. Pass `random_agent_types = True` and pass `agent_types`, `n_agents_per_process` to make the system randomly place the specified number of agents in each production level - Most parameters (i.e. `process_inputs` , `process_outputs` , `n_agents_per_process` , `costs` ) can take a single value, a tuple of two values, or a list of values. If it has a single value, it is repeated for all processes/factories as appropriate. If it is a tuple of two numbers $(i, j)$, each process will take a number sampled from a uniform distribution supported on $[i, j]$ inclusive. If it is a list of values, of the length `n_processes` , it is used as it is otherwise, it is used to sample values for each process. .. py:method:: type_name_for_logs(agent: scml.oneshot.agent.OneShotAgent | None) -> str | None .. py:property:: negotiated_contract_records :type: list[dict[str, Any]] .. py:property:: exogenous_contract_records :type: list[dict[str, Any]] .. py:method:: current_balance(agent_id: str) .. py:method:: add_financial_report(agent: scml.oneshot.sysagents.DefaultOneShotAdapter, reports_agent, reports_time) -> None Records a financial report for the given agent in the agent indexed reports and time indexed reports :param agent: The agent :param reports_agent: A dictionary of financial reports indexed by agent id :param reports_time: A dictionary of financial reports indexed by time Returns: .. py:property:: agent_contracts .. py:method:: _update_exogenous(s) .. py:method:: step_with(actions: dict[str, dict[str, negmas.SAOResponse]], init=False) -> bool Runs a simulation step for the agents given in keys passing the corresponding values as counter offers. :returns: False if this is the last negotiation. Remarks: - You must call this with `init=True` once at the beginning of every simulation to make sure that `init()` and other initialization code is called correctly. - Every step advances all negotiations one step. - Negotiators belonging to the given agents are never called as long as a corresponding action (response) is given in the agents dict. - The world MUST be created with `one_offer_per_step` passed as `True` (default is `False`). .. py:method:: simulation_step(stage=0) A single step of the simulation. :param stage: How many times so far was this method called within the current simulation step Remarks: - Using the stage parameter, it is possible to have `Operations` . `SimulationStep` several times with the list of operations while differentiating between these calls. .. py:method:: _breach_record(perpetrator, level, type_) -> dict[str, Any] .. py:method:: _adjust_contract_types(contract) .. py:method:: on_contract_signed(contract: negmas.Contract) -> bool Called to add a contract to the existing set of contract after it is signed :param contract: The contract to add :returns: True if everything went OK and False otherwise Remarks: - By default this function just adds the contract to the set of contracts maintaned by the world. - You should ALWAYS call this function when overriding it. .. py:method:: contract_record(contract: negmas.Contract) -> dict[str, Any] Converts a contract to a record suitable for permanent storage .. py:method:: breach_record(breach: negmas.Breach) -> dict[str, Any] Converts a breach to a record suitable for storage during the simulation .. py:method:: execute_action(action, agent, callback: Callable | None = None) -> bool Executes the given action by the given agent .. py:method:: contract_size(contract: negmas.Contract) -> float Returns an estimation of the **activity level** associated with this contract. Higher is better :param contract: Returns: .. py:method:: post_step_stats() Called at the end of the simulation step to update all stats Kept for backward compatibility and will be dropped. Override `update_stats` ins .. py:method:: pre_step_stats() Called at the beginning of the simulation step to prepare stats or update them Kept for backward compatibility and will be dropped. Override `update_stats` instead .. py:method:: welfare(include_bankrupt: bool = False) -> float Total welfare of all agents .. py:method:: relative_welfare(include_bankrupt: bool = False) -> float | None Total welfare relative to expected value. Returns None if no expectation is found in self.info .. py:method:: is_valid_contact(contract: negmas.Contract) -> bool Checks whether a signed contract is valid .. py:method:: scores(assets_multiplier: float = 0.0) -> dict[str, float] Scores of all agents given the asset multiplier. :param assets_multiplier: A multiplier to multiply the assets with. .. py:property:: winners The winners of this world (factory managers with maximum wallet balance .. py:method:: trading_prices_for(discount: float = 1.0, condition='executed') -> numpy.ndarray Calculates the prices at which all products traded using an optional discount factor :param discount: A discount factor to treat older prices less importantly (exponential discounting). :param condition: The condition for contracts to consider. Possible values are executed, signed, concluded, nullified :returns: an n_products vector of trading prices .. py:property:: trading_prices .. py:property:: stats_df :type: pandas.DataFrame Returns a pandas data frame with the stats .. py:property:: contracts_df :type: pandas.DataFrame Returns a pandas data frame with the contracts .. py:property:: system_agents :type: list[scml.oneshot.sysagents._StdSystemAgent] Returns the two system agents .. py:property:: system_agent_names :type: list[str] Returns the names two system agents .. py:property:: non_system_agents :type: list[scml.oneshot.sysagents.DefaultOneShotAdapter] Returns all agents except system agents .. py:property:: non_system_agent_names :type: list[str] Returns names of all agents except system agents .. py:property:: agreement_fraction :type: float Fraction of negotiations ending in agreement and leading to signed contracts .. py:attribute:: system_agent_ids .. py:attribute:: non_system_agent_ids .. py:method:: draw(steps: tuple[int, int] | int | None = None, what: Collection[str] = DEFAULT_EDGE_TYPES, who: Callable[[negmas.Agent], bool] | None = None, where: Callable[[negmas.Agent], int | tuple[float, float]] | None = None, together: bool = True, axs: Collection[matplotlib.axis.Axis] | None = None, ncols: int = 4, figsize: tuple[int, int] = (15, 15), **kwargs) -> tuple[matplotlib.axis.Axis, networkx.Graph] | tuple[list[matplotlib.axis.Axis], list[networkx.Graph]] .. py:method:: _request_negotiations(agent_id: str, controller: negmas.sao.SAOController | None = None, negotiators: list[negmas.sao.SAONegotiator] | None = None, extra: dict[str, Any] | None = None) -> bool Requests negotiations (used internally) :param agent_id: the agent requesting :param product: The product to negotiate about :param quantity: The minimum and maximum quantities. Passing a single value q is equivalent to passing (q,q) :param unit_price: The minimum and maximum unit prices. Passing a single value u is equivalent to passing (u,u) :param time: The minimum and maximum delivery step. Passing a single value t is equivalent to passing (t,t) :param controller: The controller to manage the complete set of negotiations :param negotiators: An optional list of negotiators to use for negotiating with the given partners (in the same order). :param extra: Extra information accessible through the negotiation annotation to the caller :param # consumer_starts: Whether the consumer or supplier sends the first offer in the negotiation :returns: `True` if the partner accepted and the negotiation is ready to start .. py:method:: _request_negotiation(agent_id: str, product: int, partner: str, negotiator: negmas.sao.SAONegotiator, extra: dict[str, Any] | None = None, is_buy: bool = True) -> negmas.situated.NegotiationInfo | None Requests a negotiation :param product: The product to negotiate about :param quantity: The minimum and maximum quantities. Passing a single value q is equivalent to passing (q,q) :param unit_price: The minimum and maximum unit prices. Passing a single value u is equivalent to passing (u,u) :param time: The minimum and maximum delivery step. Passing a single value t is equivalent to passing (t,t) :param partner: ID of the partner to negotiate with. :param negotiator: The negotiator to use for this negotiation (if the partner accepted to negotiate) :param extra: Extra information accessible through the negotiation annotation to the caller :param is_buy: whether the consumer starts the negotiation :returns: `True` if the partner accepted and the negotiation is ready to start .. py:method:: _make_issues(product) -> tuple[tuple[int, int], tuple[int, int], tuple[int, int]] Creates the negotiation agendas :param product: The product to be negotiated about :type product: int :returns: A tuple of minimum and maximum values for unit-price, time, and quantity in that order .. py:method:: _make_negotiations() .. py:method:: order_contracts_for_execution(contracts: Collection[negmas.Contract]) -> Collection[negmas.Contract] Orders the contracts in a specific time-step that are about to be executed .. py:method:: get_private_state(agent: negmas.Agent) -> dict Reads the private state of the given agent .. py:method:: _contract_record(contract) Converts a contract to a record suitable for permanent storage .. py:method:: start_contract_execution(contract: negmas.Contract) -> set[negmas.Breach] | None Tries to execute the contract :param contract: :returns: The set of breaches committed if any. If there are no breaches return an empty set :rtype: 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). .. py:method:: complete_contract_execution(contract: negmas.Contract, breaches: list[negmas.Breach], resolution: negmas.Contract) -> None Called after breach resolution is completed for contracts for which some potential breaches occurred. :param contract: The contract considered. :param breaches: The list of potential breaches that was generated by `_execute_contract`. :param resolution: The agreed upon resolution Returns: .. py:method:: plot_combined_stats(worlds: tuple[SCMLBaseWorld, Ellipsis] | SCMLBaseWorld, stats: str | tuple[str, Ellipsis] | None = None, pertype=False, makefig=False, title=True, ylabel=False, xlabel=False, legend=True, figsize=None, perishable: bool = False, **kwargs) :classmethod: Plots combined statistics of multiple worlds in a single plot :param stats: The statistics to plot. If `None`, some selected stats will be displayed :param pertype: combine agent-statistics per type :param use_sum: plot sum for type statistics instead of mean :param title: If given a title will be added to each subplot :param ylabel: If given, the ylabel will be added to each subplot :param xlabel: If given The xlabel will be added (Simulation Step) :param legend: If given, a legend will be displayed :param makefig: If given a new figure will be started :param figsize: Size of the figure to host the plot :param ylegend: y-axis of legend for cases with large number of labels :param legend_n_cols: number of columns in the legend .. py:method:: plot_stats(stats: str | tuple[str, Ellipsis] | None = None, pertype=False, use_sum=False, makefig=False, title=True, ylabel=False, xlabel=False, legend=True, figsize=None, ylegend=2.0, legend_ncols=8) Plots statistics of the world in a single plot :param stats: The statistics to plot. If `None`, some selected stats will be displayed :param pertype: combine agent-statistics per type :param use_sum: plot sum for type statistics instead of mean :param title: If given a title will be added to each subplot :param ylabel: If given, the ylabel will be added to each subplot :param xlabel: If given The xlabel will be added (Simulation Step) :param legend: If given, a legend will be displayed :param makefig: If given a new figure will be started :param figsize: Size of the figure to host the plot :param ylegend: y-axis of legend for cases with large number of labels .. py:class:: OneShotWorld(catalog_prices: numpy.ndarray, profiles: list[scml.oneshot.common.OneShotProfile], agent_types: list[type[scml.oneshot.agent.OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | numpy.ndarray = 50, financial_report_period=5, bankruptcy_limit=0.0, penalize_bankrupt_for_future_contracts=True, penalties_scale: Literal['trading', 'catalog', 'unit', 'none'] = 'trading', exogenous_contracts: Collection[scml.oneshot.common.OneShotExogenousContract] = tuple(), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: numpy.ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=60 * 15, sync_calls=False, neg_n_steps=20, neg_time_limit=None, neg_hidden_time_limit=60, neg_step_time_limit=20, negotiation_speed=None, shuffle_negotiations=False, one_offer_per_step=False, publish_exogenous_summary=True, publish_trading_prices=True, publish_assets=False, publish_production_capacity=True, price_multiplier=0.0, price_range_fraction=0.0, wide_price_range=False, allow_zero_quantity: bool = False, trading_price_discount=0.9, signing_delay=0, force_signing=False, batch_signing=True, name: str | None = None, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_catalog=0, inventory_valuation_trading=0, perishable=True, horizon=0, one_time_per_negotiation=True, quantity_multiplier: float = 1.0, nullify_bankrupt_contracts: bool = False, debug: bool = False, verbose: bool = False, **kwargs) Bases: :py:obj:`SCMLBaseWorld` Basic oneshot simulation .. py:class:: SCML2020OneShotWorld(catalog_prices: numpy.ndarray, profiles: list[scml.oneshot.common.OneShotProfile], agent_types: list[type[scml.oneshot.agent.OneShotAgent]], agent_params: list[dict[str, Any]], catalog_quantities: int | numpy.ndarray = 50, financial_report_period=5, bankruptcy_limit=0.0, penalize_bankrupt_for_future_contracts=True, penalties_scale: Literal['trading', 'catalog', 'unit', 'none'] = 'trading', exogenous_contracts: Collection[scml.oneshot.common.OneShotExogenousContract] = tuple(), exogenous_dynamic: bool = False, exogenous_force_max: bool = False, initial_balance: numpy.ndarray | tuple[int, int] | int = 1000, compact=True, no_logs=True, fast=True, n_steps=1000, time_limit=60 * 15, sync_calls=False, neg_n_steps=20, neg_time_limit=None, neg_hidden_time_limit=60, neg_step_time_limit=20, negotiation_speed=None, shuffle_negotiations=False, one_offer_per_step=False, publish_exogenous_summary=True, publish_trading_prices=True, publish_assets=False, publish_production_capacity=True, price_multiplier=0.0, price_range_fraction=0.0, wide_price_range=False, allow_zero_quantity: bool = False, trading_price_discount=0.9, signing_delay=0, force_signing=False, batch_signing=True, name: str | None = None, agent_name_reveals_position: bool = True, agent_name_reveals_type: bool = True, inventory_valuation_catalog=0, inventory_valuation_trading=0, perishable=True, horizon=0, one_time_per_negotiation=True, quantity_multiplier: float = 1.0, nullify_bankrupt_contracts: bool = False, debug: bool = False, verbose: bool = False, **kwargs) Bases: :py:obj:`OneShotWorld` Oneshot simulation as used in SCML 2020 competition .. py:class:: SCML2021OneShotWorld(*args, **kwargs) Bases: :py:obj:`SCML2020OneShotWorld` Oneshot simulation as used in SCML 2021 competition .. py:class:: SCML2022OneShotWorld(*args, **kwargs) Bases: :py:obj:`SCML2021OneShotWorld` Oneshot simulation as used in SCML 2022 competition .. py:class:: SCML2023OneShotWorld(*args, **kwargs) Bases: :py:obj:`SCML2020OneShotWorld` Oneshot simulation as used in SCML 2023 competition .. py:class:: SCML2024OneShotWorld(*args, **kwargs) Bases: :py:obj:`SCML2023OneShotWorld` Oneshot simulation as used in SCML 2024 competition .. py:data:: PLACEHOLDER_AGENT_PREFIX :value: 'PlaceHolder__' .. py:data:: __all__