negmas.situated

This module defines the base classes for worlds within which multiple agents engage in situated negotiations

The Agent class encapsulates the managing entity that creates negotiators to engage in negotiations within a world Simulation in order to maximize its own total utility.

Remarks:

  • When immediate_negotiations is true, negotiations start in the same step they are registered in (they may also end in that step) and negotiation_speed_multiple steps of it are conducted. That entails that requesting a negotiation may result in new contracts in the same time-step only of immediate_negotiations is true.

Simulation steps:

It is possible to control the order of the simulation steps differently using the operations parameter to the world constructor. this is the default order

  1. prepare custom stats (call _pre_step_stats)

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

  3. Allow custom simulation (call simulation_step ) with stage 0

  4. run all Entity objects registered (i.e. all agents) in the predefined simulation_order.

  5. sign contracts that are to be signed at this step calling on_contracts_finalized / on_contract_signed as needed

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

  7. allow custom simulation steps to run (call simulation_step ) with stage 1

  8. remove any negotiations that are completed!

  9. update basic stats

  10. update custom stats (call _post_step_stats)

Monitoring a simulation:

You can monitor a running simulation using a WorldMonitor or StatsMonitor object. The former monitors events in the world while the later monitors the statistics of the simulation. This is a list of some of the events that can be monitored by WorldMonitor . World designers can add new events either by announcing them using announce or as a side-effect of logging them using any of the log functions.

Event

Data

extra-step

none

mechanism-creation-exception

exception: Exception

zero-outcomes-negotiation

caller: Agent, partners: List[Agent] , annotation: Dictionary displays [ str, Any ]

entity-exception

exception: Exception

contract-exception

contract: Contract, exception: Exception

agent-exception

method: str , exception: Exception

agent-joined

agent: Agent

negotiation-request

caller: Agent , partners: List [ Agent ], issues: List [ Issue ] , mechanism_name: str , annotation: Dictionary displays [ str, Any ], req_id: str

negotiation-request-immediate

caller: Agent , partners: List [ Agent ], issues: List [ Issue ] , mechanism_name: str , annotation: Dictionary displays [ str, Any ]

negotiation-request-rejected

caller: Agent , partners: List [ Agent ] , req_id: str , rejectors: List [ Agent ] , annotation: Dictionary displays [ str, Any ]

negotiation-request-accepted

caller: Agent , partners: List [ Agent ] , req_id: str , mechanism: Mechanism , annotation: Dictionary displays [ str, Any ]

negotiation-success

mechanism: Mechanism , contract: Contract , partners: List [ Agent ]

negotiation-failure

mechanism: Mechanism , partners: List [ Agent ]

contract-executing

contract: Contract

contract-nullified

contract: Contract

contract-breached

contract: Contract, breach: Breach

breach-resolved

contract: Contract, breaches: List[Breach], resolution

contract-executed

contract: Contract

dropped-contract

contract: Contract

class negmas.situated.Action(type: str, params: dict)[source]

Bases: object

An action that an Agent can execute in a World through the Simulator.

params: dict[source]

Any extra parameters to be passed for the action.

type: str[source]

The action type identifier.

class negmas.situated.Adapter(obj, include_adapter_type_name: bool | None = None, include_obj_type_name=True, **kwargs)[source]

Bases: Agent

Represents an adapter agent that makes some included object act as an agent in some world.

Parameters:
  • obj – The object to be adapted.

  • include_adapter_type_name – Whether to include the adapter type name. If None, then it will be included if it does not start with and underscore.

  • include_obj_type_name – Whether to include object type name in this adapter’s type name

  • type_postfix – A string to add to the end of the type name

Remarks:

  • Other than keeping an internal copy of the adapted object under obj, this class is used primarily to provide a way to give good type_name and short_type_name properties that combine the name of the adapter and the name of the enclosed object nicely.

  • The adapted object must be an Entity.

  • The World class uses the type names from this adapter whenever it needs to get a type-name (either type_name or short_type_name)

property adapted_object: Entity[source]

Adapted object.

Returns:

The result.

Return type:

Entity

init()[source]

Override this method to modify initialization logic

property short_type_name[source]

Returns a short name of the type of this entity

step()[source]

Override this method to modify stepping logic

property type_name[source]

Returns a short name of the type of this entity

class negmas.situated.Agent(name: str | None = None, type_postfix: str = '', preferences: Preferences | None = None, ufun: UtilityFunction | None = None)[source]

Bases: Entity, EventSink, ConfigReader, Notifier, Rational, Generic[TAWI], ABC

Base class for all agents that can run within a World and engage in situated negotiations

property accepted_negotiation_requests: list[NegotiationRequestInfo][source]

A list of negotiation requests sent to this agent that are already accepted by it.

Remarks:
  • These negotiations did not start yet as they are still not accepted by all partners. Once that happens, they will be moved to running_negotiations

property awi: TAWI[source]

Gets the Agent-world interface.

create_negotiation_request(issues: list[Issue] | tuple[Issue, ...], partners: list[str], annotation: dict[str, Any] | None, negotiator: Negotiator | None, extra: dict[str, Any] | None) str[source]

Creates a new NegotiationRequestInfo record and returns itS ID

Parameters:
  • issues – negotiation issues

  • partners – partners

  • annotation – annotation

  • negotiator – the negotiator to use

  • extra – any extra information

Returns:

A unique identifier for this negotiation info structure

abstractmethod init()[source]

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

property initialized: bool[source]

Was the agent initialized (i.e. was init_() called)

property negotiation_requests: list[NegotiationRequestInfo][source]

A list of the negotiation requests sent by this agent that are not yet accepted or rejected.

Remarks:
  • These negotiations did not start yet as they are still not accepted by all partners. Once that happens, they will be moved to running_negotiations

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

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

Parameters:
  • contract – The contract

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

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

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

Called whenever at least a partner did not sign the contract

on_contract_cancelled_(contract: Contract, rejectors: list[str]) None[source]

Called whenever at least a partner did not sign the contract

abstractmethod on_contract_executed(contract: Contract) None[source]

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

on_contract_signed(contract: Contract) None[source]

Called whenever a contract is signed by all partners

on_contract_signed_(contract: Contract) None[source]

Called whenever a contract is signed by all partners

on_contracts_finalized(signed: list[Contract], cancelled: list[Contract], rejectors: list[list[str]]) None[source]

Called for all contracts in a single step to inform the agent about which were finally signed and which were rejected by any agents (including itself)

Parameters:
  • signed – A list of signed contracts. These are binding

  • cancelled – A list of cancelled contracts. These are not binding

  • rejectors – A list of lists where each of the internal lists gives the rejectors of one of the cancelled contracts. Notice that it is possible that this list is empty which means that the contract other than being rejected by any agents (if that was possible in the specific world).

Remarks:

The default implementation is to call on_contract_signed for singed contracts and on_contract_cancelled for cancelled contracts

on_event(event: Event, sender: EventSource)[source]

On event.

Parameters:
  • event – Event.

  • sender – Sender.

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

Called when a requested negotiation is accepted

on_neg_request_accepted_(req_id: str, mechanism: NegotiatorMechanismInterface)[source]

Called when a requested negotiation is accepted

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

Called when a requested negotiation is rejected

Parameters:
  • req_id – The request ID passed to _request_negotiation

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

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

Called when a requested negotiation is rejected

Parameters:
  • req_id – The request ID passed to _request_negotiation

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

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

Called whenever a negotiation ends without agreement

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

Called whenever a negotiation ends without agreement

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

Called whenever a negotiation ends with agreement

on_negotiation_success_(contract: Contract, mechanism: NegotiatorMechanismInterface) None[source]

Called whenever a negotiation ends with agreement

on_simulation_step_ended()[source]

Will be called at the end of the simulation step after everything else

on_simulation_step_started()[source]

Will be called at the beginning of the simulation step before everything else (except init)

property requested_negotiations: list[NegotiationRequestInfo][source]

The negotiations currently requested by the agent.

Returns:

A list of negotiation request information objects (NegotiationRequestInfo)

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

Called when a negotiation request is received

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

Called to respond to a renegotiation request

Parameters:
  • agenda

  • contract

  • breaches

Returns:

property running_negotiations: list[RunningNegotiationInfo][source]

The negotiations currently requested by the agent.

Returns:

A list of negotiation information objects (RunningNegotiationInfo)

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

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

Parameters:
  • contract – The contract being breached

  • breaches – All breaches on contract

Returns:

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

sign_all_contracts(contracts: list[Contract]) None | str | dict[str, str | None] | list[str | None][source]

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

Parameters:

contracts – A list of contracts to sign/ refuse to sign

Returns:

  • None to indicate refusing to sign all contracts.

  • str (specifically, the agent ID) to indicate signing ALL contracts.

  • List[Optional[str]] A list with a value for each input contract where None means refusal to sign that contract and a string (agent ID) indicates acceptance to sign it. Note that in this case, the number of values in the returned list must match that of the contacts (and they should obviously correspond to the contracts).

  • Dict[str, Optional[str]] A mapping from contract ID to either a None for rejection to sign or a string (for acceptance to sign). Contracts with IDs not in the keys will assumed not to be signed.

Return type:

You can return any of the following

Remarks:

  • default implementation calls sign_contract for each contract returning the results

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

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

abstractmethod step()[source]

Called by the simulator at every simulation step

property unsigned_contracts: list[Contract][source]

All contracts that are not yet signed.

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

Bases: object

Agent World Interface class

property accepted_negotiation_requests: list[NegotiationRequestInfo][source]

A list of negotiation requests sent to this agent that are already accepted by it.

Remarks:
  • These negotiations did not start yet as they are still not accepted by all partners. Once that happens, they will be moved to running_negotiations

bb_query(section: str | list[str] | None, query: Any, query_keys=False) dict[str, Any] | None[source]

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

Parameters:
  • section – Either a section name, a list of sections or None specifying ALL public sections (see remarks)

  • query – The query which is USUALLY a dict with conditions on it when querying values and a RegExp when

  • keys (querying)

  • query_keys – Whether the query is to be applied to the keys or values.

Returns:

value pairs giving all records that satisfied the given requirements.

Return type:

  • A dictionary with key

Remarks:

  • A public section is a section with a name that does not start with an underscore

  • If a set of sections is given, and two records in different sections had the same key, only one of them will be returned

  • Key queries use regular expressions and match from the beginning using the standard re.match function

bb_read(section: str, key: str) Any | None[source]

Reads the value associated with given key from the bulletin board

Parameters:
  • section – section name

  • key – key

Returns:

Content of that key in the bulletin-board

bb_record(section: str, value: Any, key: str | None = None) None[source]

Records data in the given section of the bulletin board

Parameters:
  • section – section name (can contain subsections separated by ‘/’)

  • key – The key

  • value – The value

bb_remove(section: list[str] | str | None, *, query: Any | None = None, key: str | None = None, query_keys: bool = False, value: Any = None) bool[source]

Removes a value or a set of values from the bulletin Board

Parameters:
  • section – The section

  • query – the query to use to select what to remove

  • key – the key to remove (no need to give a full query)

  • query_keys – Whether to apply the query (if given) to keys or values

  • value – Value to be removed

Returns:

Success of failure

Return type:

bool

property current_step: int[source]

Current simulation step

property default_signing_delay: int[source]

Number of simulation steps between contract agreement and signing.

Returns:

The signing delay in steps, or 0 if the world forces immediate signing.

execute(action: Action, callback: Callable[[Action, bool], Any] | None = None) bool[source]

Executes an action in the world simulation

property initialized: bool[source]

Was the agent initialized (i.e. was init_() called)

logdebug(msg: str) None[source]

Logs a WARNING message

Parameters:

msg – The message to log

Returns:

logdebug_agent(msg: str) None[source]

Logs a WARNING message to the agent’s log

Parameters:

msg – The message to log

Returns:

logerror(msg: str) None[source]

Logs a WARNING message

Parameters:

msg – The message to log

Returns:

logerror_agent(msg: str) None[source]

Logs a WARNING message to the agent’s log

Parameters:

msg – The message to log

Returns:

loginfo(msg: str) None[source]

Logs an INFO message

Parameters:

msg – The message to log

Returns:

loginfo_agent(msg: str) None[source]

Logs an INFO message to the agent’s log

Parameters:

msg – The message to log

Returns:

logwarning(msg: str) None[source]

Logs a WARNING message

Parameters:

msg – The message to log

Returns:

logwarning_agent(msg: str) None[source]

Logs a WARNING message to the agent’s log

Parameters:

msg – The message to log

Returns:

property n_steps: int[source]

Number of steps in a simulation

property negotiation_requests: list[NegotiationRequestInfo][source]

A list of the negotiation requests sent by this agent that are not yet accepted or rejected.

Remarks:
  • These negotiations did not start yet as they are still not accepted by all partners. Once that happens, they will be moved to running_negotiations

property params: dict[str, Any][source]

Returns the basic parameters of the world

property relative_time: float[source]

Relative time of the simulation going from 0 to 1

request_negotiation_about(issues: list[Issue] | tuple[Issue, ...], partners: list[str], req_id: str, roles: list[str] | None = None, annotation: dict[str, Any] | None = None, mechanism_name: str | None = None, mechanism_params: dict[str, Any] | None = None, group: str | None = None) bool[source]

Requests to start a negotiation with some other agents

Parameters:
  • req_id

  • issues – Negotiation issues

  • annotation – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation. 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.

  • roles – The roles of different partners. If None then each role for each partner will be None

  • mechanism_name – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be)

  • my_role (then roles and)

  • None

  • mechanism_params – A dict of parameters used to initialize the mechanism object

  • group – An opational identifier for the group to which this negotiation belongs. It is not used by the system but is logged for debugging purposes. Moreover, the agent have access to it through its negotiations property.

Returns:

List[“Agent”] the list of partners who rejected the negotiation if any. If None then the negotiation was accepted. If empty then the negotiation was not started from the world manager

Remarks:

property requested_negotiations: list[NegotiationRequestInfo][source]

The negotiations currently requested by the agent.

Returns:

A list of negotiation request information objects (NegotiationRequestInfo)

run_negotiation(issues: list[Issue], partners: list[str | Agent], negotiator: Negotiator, preferences: Preferences | None = None, caller_role: str | None = None, roles: list[str] | None = None, annotation: dict[str, Any] | None = None, mechanism_name: str | None = None, mechanism_params: dict[str, Any] | None = None) tuple[Contract, NegotiatorMechanismInterface] | None[source]

Runs a negotiation until completion

Parameters:
  • partners – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/Agent or as a list containing a single string/Agent, then he caller will be added at the beginning of the list. This will only be done if roles was passed as None.

  • negotiator – The negotiator to be used in the negotiation

  • preferences – The preferences. Only needed if the negotiator does not already know it

  • caller_role – The role of the caller in the negotiation

  • issues – Negotiation issues

  • annotation – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation

  • roles – The roles of different partners. If None then each role for each partner will be None

  • mechanism_name – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be)

  • my_role (then roles and)

  • None

  • mechanism_params – A dict of parameters used to initialize the mechanism object

Returns:

A Tuple of a contract and the nmi of the mechanism used to get it in case of success. None otherwise

run_negotiations(issues: list[Issue] | list[list[Issue]], partners: list[list[str | Agent]], negotiators: list[Negotiator], preferences: list[Preferences] | None = None, caller_roles: list[str] | None = None, roles: list[list[str] | None] | None = None, annotations: list[dict[str, Any] | None] | None = None, mechanism_names: str | list[str] | None = None, mechanism_params: dict[str, Any] | list[dict[str, Any]] | None = None, all_or_none: bool = False) list[tuple[Contract, NegotiatorMechanismInterface]][source]

Requests to run a set of negotiations simultaneously. Returns after all negotiations are run to completion

Parameters:
  • partners – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/Agent or as a list containing a single string/Agent, then he caller will be added at the beginning of the list. This will only be done if roles was passed as None.

  • issues – Negotiation issues

  • negotiators – The negotiator to be used in the negotiation

  • ufuns – The utility function. Only needed if the negotiator does not already know it

  • caller_roles – The role of the caller in the negotiation

  • annotations – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation

  • roles – The roles of different partners. If None then each role for each partner will be None

  • mechanism_names – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be)

  • my_role (then roles and)

  • None

  • mechanism_params – A dict of parameters used to initialize the mechanism object

  • all_or_none – If true, either no negotiations will be started execpt if all partners accepted

Returns:

contract (None for failure) and nmi (The mechanism info [None if the corresponding partner refused to negotiation])

Return type:

A list of tuples each with two values

property running_mechanism_dicts: dict[str, RunningNegotiationInfo][source]

The negotiations currently requested by the agent as a mapping from mechanism ID to RunningNegotiationInfo

Returns:

A list of negotiation information objects (RunningNegotiationInfo)

property running_negotiations: list[RunningNegotiationInfo][source]

The negotiations currently requested by the agent.

Returns:

A list of negotiation information objects (RunningNegotiationInfo)

property settings[source]

World configuration settings from the bulletin board.

property state: Any[source]

Returns the private state of the agent in that world

property unsigned_contracts: list[Contract][source]

All contracts that are not yet signed.

class negmas.situated.Breach(contract: Contract, perpetrator: str, type: str, victims: list[str] = NOTHING, level: float = 1.0, step: int = -1, id: str = NOTHING)[source]

Bases: object

Represents a contract breach by an agent in the simulation.

as_dict()[source]

Converts the breach to a dictionary representation for serialization.

contract: Contract[source]

The agreement being breached

id: str[source]

Object name

level: float[source]

Breach level defaulting to full breach (a number between 0 and 1)

perpetrator: str[source]

ID of the agent committing the breach

step: int[source]

The simulation step at which the breach occurred

type: str[source]

refusal, product, money, penalty.

Type:

The type of the breach. Can be one of

victims: list[str][source]

Specific victims of the breach. If not given all partners in the agreement (except perpetrator) are considered victims

class negmas.situated.BreachProcessing(*values)[source]

Bases: Enum

The way breaches are to be handled

META_NEGOTIATION = 2[source]

A meta negotiation is instantiated between victim and perpetrator to set re-negotiation issues.

NONE = 0[source]

The breach should always be reported in the breach list and no re-negotiation is allowed.

VICTIM_THEN_PERPETRATOR = 1[source]

The victim is asked to set the re-negotiation agenda then the perpetrator.

class negmas.situated.BulletinBoard[source]

Bases: EventSource, ConfigReader

The bulletin-board which carries all public information. It consists of sections each with a dictionary of records.

add_section(name: str) None[source]

Adds a section to the bulletin Board

Parameters:

name – Section name

Returns:

property data[source]

This property is intended for use only by the world manager. No other agent is allowed to use it

query(section: str | list[str] | None, query: Any, query_keys=False) dict[str, Any] | None[source]

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

Parameters:
  • section – Either a section name, a list of sections or None specifying ALL public sections (see remarks)

  • query – The query which is USUALLY a dict with conditions on it when querying values and a RegExp when

  • keys (querying)

  • query_keys – Whether the query is to be applied to the keys or values.

Returns:

value pairs giving all records that satisfied the given requirements.

Return type:

  • A dictionary with key

Remarks:

  • A public section is a section with a name that does not start with an underscore

  • If a set of sections is given, and two records in different sections had the same key, only one of them will be returned

  • Key queries use regular expressions and match from the beginning using the standard re.match function

read(section: str, key: str) Any[source]

Reads the value associated with given key

Parameters:
  • section – section name

  • key – key

Returns:

Content of that key in the bulletin-board

record(section: str, value: Any, key: str | None = None) None[source]

Records data in the given section of the bulletin-board

Parameters:
  • section – section name (can contain subsections separated by ‘/’)

  • key – The key

  • value – The value

remove(section: list[str] | str | None, *, query: Any | None = None, key: str | None = None, query_keys: bool = False, value: Any = None) bool[source]

Removes a value or a set of values from the bulletin Board

Parameters:
  • section – The section

  • query – the query to use to select what to remove

  • key – the key to remove (no need to give a full query)

  • query_keys – Whether to apply the query (if given) to keys or values

  • value – Value to be removed

Returns:

Success of failure

Return type:

bool

classmethod satisfies(value: Any, query: Any) bool[source]

Satisfies.

Parameters:
  • value – Value.

  • query – Query.

Returns:

The result.

Return type:

bool

class negmas.situated.Condition(name: str, issues: tuple[Issue, ...], ufuns: tuple[Preferences, ...], partner_types: tuple[str | type[Negotiator] | type[SAOPRNegotiator], ...], index: int = 0, partner_params: tuple[dict[str, Any] | None, ...] | None = None, roles: tuple[str, ...] | None = None, annotation: dict[str, Any] | None = None, scored_indices: tuple[int, ...] | None = None)[source]

Bases: object

A representation of a negotiation scenario in which a negotiator can be evaluated

annotation: dict[str, Any] | None = None[source]

Any extra annotation to add to the mechanism.

classmethod from_dict(d, python_class_identifier='__python_class__')[source]

Deserializes a Condition instance from a dictionary representation.

Parameters:
  • d – The dictionary containing the serialized condition data.

  • python_class_identifier – The key used to identify Python class type information in the dict.

index: int = 0[source]

The index of the negotiator being evaluated in the list of negotiators passed to the mechanism

issues: tuple[Issue, ...][source]

The issue space as a list of issues

name: str[source]

Scenario name

partner_params: tuple[dict[str, Any] | None, ...] | None = None[source]

Any parameters used to construct partners (must be the same length as partner_types)

partner_types: tuple[str | type[Negotiator] | type[SAOPRNegotiator], ...][source]

The types of all partners (other than the agent being evaluated). Its length must be one less than ufuns

roles: tuple[str, ...] | None = None[source]

Roles of all negotiators (including the negotiator being evaluated) in order

scored_indices: tuple[int, ...] | None = None[source]

Indices of negotiators to be scored in this negotiation. None is equivalent to [self.index]

to_dict(python_class_identifier='__python_class__')[source]

Serializes this condition to a dictionary representation.

Parameters:

python_class_identifier – The key used to store Python class type information in the dict.

ufuns: tuple[Preferences, ...][source]

The utility functions used by all negotiators in the scenario

class negmas.situated.Contract(agreement: dict[str, Any] = NOTHING, partners=NOTHING, annotation: dict[str, Any] = NOTHING, issues=NOTHING, signed_at: int = -1, executed_at: int = -1, concluded_at: int = -1, nullified_at: int = -1, to_be_signed_at: int = -1, signatures: dict[str, str | None] = NOTHING, mechanism_state: MechanismState | None = None, mechanism_id: str | None = None, id: str = NOTHING)[source]

Bases: object

A agreement definition which encapsulates an agreement with partners and extra information

agreement: dict[str, Any][source]

The actual agreement of the negotiation in the form of an Outcome in the Issue space defined by issues

annotation: dict[str, Any][source]

Misc. information to be kept with the agreement.

concluded_at: int[source]

The time-step at which the contract was concluded (but it is still not binding until signed)

executed_at: int[source]

The time-step at which the contract was executed/breached

id: str[source]

Object name

issues: tuple[Issue][source]

Issues of the negotiations from which this agreement was concluded. It may be empty

mechanism_id: str | None[source]

The Id of the mechanism that led to this contract

mechanism_state: MechanismState | None[source]

The mechanism state at the contract conclusion

nullified_at: int[source]

The time-step at which the contract was nullified after being signed. That can happen if a partner declares bankruptcy

partners: tuple[str][source]

The partners

signatures: dict[str, str | None][source]

A mapping from each agent to its signature

signed_at: int[source]

The time-step at which the contract was signed

to_be_signed_at: int[source]

The time-step at which the contract should be signed

class negmas.situated.Entity(type_postfix: str = '')[source]

Bases: object

Defines an entity that is a part of the world but does not participate in the simulation

init()[source]

Override this method to modify initialization logic

init_()[source]

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

property short_type_name[source]

Returns a short name of the type of this entity

step()[source]

Override this method to modify stepping logic

step_()[source]

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

property type_name[source]

Returns the name of the type of this entity

property type_postfix[source]

Returns the type postfix used to distinguish entity subtypes.

class negmas.situated.MechanismFactory(world: World, mechanism_name: str, mechanism_params: dict[str, Any], issues: list[Issue], req_id: str, caller: Agent, partners: list[Agent], roles: list[str] | None = None, annotation: dict[str, Any] | None = None, neg_n_steps: int | None = None, neg_time_limit: int | None = None, neg_step_time_limit=None, allow_self_negotiation=False, log_ufuns_file=None, group: str | None = None)[source]

Bases: object

A mechanism creation class. It can invite agents to join a mechanism and then run it.

init() NegotiationInfo | None[source]

Start the negotiation by inviting partners and creating the mechanism.

Returns:

NegotiationInfo containing the mechanism and partners if successful, None if negotiation setup failed.

class negmas.situated.NegAgent(*args, negotiator_type: str | type[Negotiator], negotiator_params: dict[str, Any] | None = None, **kwargs)[source]

Bases: Agent

Wraps a negotiator for evaluaton

init()[source]

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

make_negotiator(preferences: Preferences | None = None)[source]

Makes a negotiator of the appropriate type passing it an optional ufun

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

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

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

Called whenever at least a partner did not sign the contract

on_contract_executed(contract: Contract) None[source]

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

on_contract_signed(contract: Contract) None[source]

Called whenever a contract is signed by all partners

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

Called when a requested negotiation is accepted

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

Called when a requested negotiation is rejected

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

Called whenever a negotiation ends without agreement

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

Called whenever a negotiation ends with agreement

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

Called to respond to a renegotiation request

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

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

property short_type_name[source]

Returns a short name of the type of this entity

step()[source]

Called by the simulator at every simulation step

property type_name[source]

Returns a short name of the type of this entity

class negmas.situated.NegWorld(*args, scenario: Condition, types: list[Negotiator | NegAgent], params: list[dict[str, Any] | None] | None = None, agent_names_reveal_type: bool = True, compact: bool = False, no_logs: bool = False, normalize_scores: bool = False, python_class_identifier: str = '__python_class__', **kwargs)[source]

Bases: NoContractExecutionMixin, World

A world that runs a list of negotiators in a given scenario to evaluate them

Parameters:
  • scenario – The NegScenario specifying all information about the situation in which negotiators are to be evaluated including the partners.

  • types – The negotiator types to be evaluated

  • params – Any parameters needed to create negotiators

  • agent_names_reveal_type – if given the agent name for each negotiator will simply be the negotiator’s type

  • compact – If given the system will strive to save memory and minimize logging

  • no_logs – disables all logging

  • kwargs – Any extra arguments to be passed to the World constructor

agreement_rate(aid: str)[source]

Returns the fraction of negotiations that ended in agreement for this agent.

Parameters:

aid – The agent’s unique identifier.

breach_record(breach: Breach) dict[str, Any][source]

Converts a breach to a flat dictionary for logging and serialization.

property competitors[source]

The agents being evaluated in this world.

complete_contract_execution(contract: Contract, breaches: list[Breach], resolution: Contract) None[source]

Finalizes contract execution after breach resolution (no-op in NegWorld).

contract_record(contract: Contract) dict[str, Any][source]

Converts a contract to a flat dictionary for logging and serialization.

contract_size(contract: Contract) float[source]

Returns the relative size/weight of a contract (inverse of competitor count).

delete_executed_contracts() None[source]

Removes executed contracts from storage (no-op in NegWorld).

executable_contracts() Collection[Contract][source]

Returns contracts ready for execution (always empty in NegWorld).

execute_action(action: Action, agent: Agent, callback: Callable | None = None) bool[source]

Executes the given action by the given agent

get_private_state(agent: Agent) dict[source]

Reads the private state of the given agent

order_contracts_for_execution(contracts: Collection[Contract]) Collection[Contract][source]

Returns contracts in the order they should be executed (unchanged in NegWorld).

partner_advantage(aid: str)[source]

Returns the average total advantage received by partners when negotiating with this agent.

Parameters:

aid – The agent’s unique identifier.

partner_utility(aid: str)[source]

Returns the average total utility received by partners when negotiating with this agent.

Parameters:

aid – The agent’s unique identifier.

property partners[source]

The partner agents that competitors negotiate against.

post_step_stats()[source]

Records statistics for all competitors after each simulation step.

pre_step_stats()[source]

Called before each simulation step to record statistics (no-op in NegWorld).

received_advantage(aid: str)[source]

Returns the average advantage (utility above reservation value) received by the agent.

Parameters:

aid – The agent’s unique identifier.

received_utility(aid: str)[source]

Returns the average utility received by the agent across all negotiations.

Parameters:

aid – The agent’s unique identifier.

simulation_step(stage)[source]

Runs one step of the simulation, executing negotiations and recording results.

start_contract_execution(contract: Contract) set[Breach][source]

Begins executing a contract (no-op in NegWorld, returns empty set).

class negmas.situated.NegotiationInfo(mechanism: Mechanism | None, partners: list[Agent], annotation: dict[str, Any], issues: list[Issue], requested_at: int, rejectors: list[Agent] | None = None, caller: Agent | None = None, group: str | None = None)[source]

Bases: object

Saves information about a negotiation

annotation: dict[str, Any][source]
caller: Agent | None[source]
group: str | None[source]
issues: list[Issue][source]
mechanism: Mechanism | None[source]
partners: list[Agent][source]
rejectors: list[Agent] | None[source]
requested_at: int[source]
class negmas.situated.NegotiationRequestInfo(partners, issues, annotation, uuid, negotiator, requested, extra)[source]

Bases: tuple

annotation[source]

Alias for field number 2

extra[source]

Alias for field number 6

issues[source]

Alias for field number 1

negotiator[source]

Alias for field number 4

partners[source]

Alias for field number 0

requested[source]

Alias for field number 5

uuid[source]

Alias for field number 3

class negmas.situated.NoContractExecutionMixin[source]

Bases: object

A mixin to add when there is no contract execution

complete_contract_execution(contract: Contract, breaches: list[Breach], resolution: Contract) None[source]

No-op since this mixin disables contract execution.

delete_executed_contracts() None[source]

Delete executed contracts.

executable_contracts() Collection[Contract][source]

Return empty collection since this mixin disables contract execution.

start_contract_execution(contract: Contract) set[Breach][source]

No-op since this mixin disables contract execution.

class negmas.situated.NoResponsesMixin[source]

Bases: object

A mixin that can be added to Agent to minimize the number of abstract methods

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

Called when a contract has been breached.

Parameters:
  • contract – The breached contract.

  • breaches – List of breaches that occurred.

  • resolution – New contract from renegotiation if any, None otherwise.

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

Called when a contract is cancelled due to rejections.

Parameters:
  • contract – The cancelled contract.

  • rejectors – List of agent IDs that rejected the contract.

on_contract_executed(contract: Contract) None[source]

Called when a contract has been successfully executed.

Parameters:

contract – The executed contract.

on_contract_signed(contract: Contract) bool[source]

Called when all parties have signed a contract.

Parameters:

contract – The fully signed contract.

Returns:

True to accept the contract, False to reject it.

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

Called when a negotiation request is accepted and the mechanism starts.

Parameters:
  • req_id – Unique identifier of the accepted request.

  • mechanism – Interface to the negotiation mechanism that was created.

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

Called when a negotiation request is rejected.

Parameters:
  • req_id – Unique identifier of the rejected request.

  • by – List of agent IDs that rejected the request, or None if unknown.

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

Called when a negotiation ends without reaching an agreement.

Parameters:
  • partners – List of agent IDs that participated in the negotiation.

  • annotation – Metadata associated with the negotiation.

  • mechanism – Interface to the negotiation mechanism.

  • state – Final state of the mechanism when it ended.

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

Called when a negotiation ends with a successful agreement.

Parameters:
  • contract – The resulting contract from the negotiation.

  • mechanism – Interface to the negotiation mechanism.

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

Decide whether to participate in renegotiation of a breached contract.

Parameters:
  • contract – The breached contract being renegotiated.

  • breaches – List of breaches that triggered renegotiation.

  • agenda – The proposed renegotiation agenda and terms.

Returns:

A negotiator to participate in renegotiation, None to refuse.

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

Create a renegotiation request when a contract is breached.

Parameters:
  • contract – The breached contract.

  • breaches – List of breaches that occurred.

Returns:

A renegotiation request if renegotiation is desired, None otherwise.

class negmas.situated.Operations(*values)[source]

Bases: Enum

Enumeration of world operation phases during each simulation step.

AgentSteps = 3[source]
ContractExecution = 4[source]
ContractSigning = 2[source]
Negotiations = 1[source]
SimulationStep = 5[source]
StatsUpdate = 6[source]
class negmas.situated.RenegotiationRequest(publisher: Agent, issues: list[Issue], annotation: dict[str, Any] = NOTHING)[source]

Bases: object

A request for renegotiation.

annotation: dict[str, Any][source]
issues: list[Issue][source]
publisher: Agent[source]
class negmas.situated.RunningNegotiationInfo(negotiator, annotation, uuid, extra, my_request)[source]

Bases: tuple

annotation[source]

Alias for field number 1

extra[source]

Alias for field number 3

my_request[source]

Alias for field number 4

negotiator[source]

Alias for field number 0

uuid[source]

Alias for field number 2

class negmas.situated.SimpleWorld(bulletin_board: BulletinBoard | None = None, n_steps: int = 10000, time_limit: int | float | None = 3600, negotiation_speed: int | None = None, neg_n_steps: int | None = 100, neg_time_limit: int | float | None = None, neg_step_time_limit: int | float | None = inf, shuffle_negotiations=True, negotiation_quota_per_step: int = 9223372036854775807, negotiation_quota_per_simulation: int = 9223372036854775807, default_signing_delay=1, force_signing=False, batch_signing=True, breach_processing=BreachProcessing.NONE, mechanisms: dict[str, dict[str, Any]] | None = None, awi_type: str | type[TAWI] = 'negmas.situated.AgentWorldInterface', start_negotiations_immediately: bool = False, log_folder=None, log_to_file=True, log_ufuns=False, log_negotiations: bool = False, log_to_screen: bool = False, log_stats_every: int = 0, log_file_level=10, log_screen_level=40, no_logs=False, event_file_name='events.json', event_types=None, log_file_name='log.txt', save_signed_contracts: bool = True, save_cancelled_contracts: bool = True, save_negotiations: bool = True, save_resolved_breaches: bool = True, save_unresolved_breaches: bool = True, saved_details_level: int = 4, ignore_agent_exceptions: bool = False, ignore_negotiation_exceptions: bool = False, ignore_contract_execution_exceptions: bool = False, ignore_simulation_exceptions: bool = False, safe_stats_monitoring: bool = False, construct_graphs: bool = False, checkpoint_every: int = 1, checkpoint_folder: str | Path | None = None, checkpoint_filename: str | None = None, extra_checkpoint_info: dict[str, Any] | None = None, single_checkpoint: bool = True, exist_ok: bool = True, operations: list[Operations] | tuple[Operations, ...] = (Operations.StatsUpdate, Operations.Negotiations, Operations.ContractSigning, Operations.AgentSteps, Operations.ContractExecution, Operations.SimulationStep, Operations.ContractSigning, Operations.StatsUpdate), info: dict[str, Any] | None = None, genius_port: int = 25337, disable_agent_printing: bool = False, debug: bool = False, name: str | None = None, id: str | None = None, storage_format: Literal['csv', 'gzip', 'parquet'] | None = None)[source]

Bases: World, ABC

Represents a simple world with no simulation and sane values for most callbacks and methods.

breach_record(breach: Breach) dict[str, Any][source]

Breach record.

Parameters:

breach – Breach.

Returns:

The result.

Return type:

dict[str, Any]

contract_record(contract: Contract) dict[str, Any][source]

Contract record.

Parameters:

contract – Contract.

Returns:

The result.

Return type:

dict[str, Any]

contract_size(contract: Contract) float[source]

Contract size.

Parameters:

contract – Contract.

Returns:

The result.

Return type:

float

delete_executed_contracts() None[source]

Delete executed contracts.

order_contracts_for_execution(contracts: Collection[Contract]) Collection[Contract][source]

Order contracts for execution.

Parameters:

contracts – Contracts.

Returns:

The result.

Return type:

Collection[Contract]

post_step_stats()[source]

Post step stats.

pre_step_stats()[source]

Pre step stats.

class negmas.situated.StatsMonitor(type_postfix: str = '')[source]

Bases: Entity

A monitor object capable of receiving stats of a world

init(stats: dict[str, Any], world_name: str)[source]

Called to initialize the monitor before running first step

step(stats: dict[str, Any], world_name: str)[source]

Called at the END of every simulation step

class negmas.situated.TimeInAgreementMixin[source]

Bases: object

Mixin that tracks contracts by their execution time step for efficient retrieval.

delete_executed_contracts() None[source]

Delete executed contracts.

executable_contracts() Collection[Contract][source]

Called at every time-step to get the contracts that are executable at this point of the simulation

get_dropped_contracts() Collection[Contract][source]

Return contracts scheduled for this step that were signed but not executed, breached, nullified, or errored.

init(time_field='time')[source]

Initialize contract tracking by time step.

Parameters:

time_field – Name of the field in contract agreements that specifies execution time.

on_contract_signed(contract: Contract)[source]

Register newly signed contract for execution at its scheduled time step.

Parameters:

contract – The contract that was just signed.

class negmas.situated.World(bulletin_board: BulletinBoard | None = None, n_steps: int = 10000, time_limit: int | float | None = 3600, negotiation_speed: int | None = None, neg_n_steps: int | None = 100, neg_time_limit: int | float | None = None, neg_step_time_limit: int | float | None = inf, shuffle_negotiations=True, negotiation_quota_per_step: int = 9223372036854775807, negotiation_quota_per_simulation: int = 9223372036854775807, default_signing_delay=1, force_signing=False, batch_signing=True, breach_processing=BreachProcessing.NONE, mechanisms: dict[str, dict[str, Any]] | None = None, awi_type: str | type[TAWI] = 'negmas.situated.AgentWorldInterface', start_negotiations_immediately: bool = False, log_folder=None, log_to_file=True, log_ufuns=False, log_negotiations: bool = False, log_to_screen: bool = False, log_stats_every: int = 0, log_file_level=10, log_screen_level=40, no_logs=False, event_file_name='events.json', event_types=None, log_file_name='log.txt', save_signed_contracts: bool = True, save_cancelled_contracts: bool = True, save_negotiations: bool = True, save_resolved_breaches: bool = True, save_unresolved_breaches: bool = True, saved_details_level: int = 4, ignore_agent_exceptions: bool = False, ignore_negotiation_exceptions: bool = False, ignore_contract_execution_exceptions: bool = False, ignore_simulation_exceptions: bool = False, safe_stats_monitoring: bool = False, construct_graphs: bool = False, checkpoint_every: int = 1, checkpoint_folder: str | Path | None = None, checkpoint_filename: str | None = None, extra_checkpoint_info: dict[str, Any] | None = None, single_checkpoint: bool = True, exist_ok: bool = True, operations: list[Operations] | tuple[Operations, ...] = (Operations.StatsUpdate, Operations.Negotiations, Operations.ContractSigning, Operations.AgentSteps, Operations.ContractExecution, Operations.SimulationStep, Operations.ContractSigning, Operations.StatsUpdate), info: dict[str, Any] | None = None, genius_port: int = 25337, disable_agent_printing: bool = False, debug: bool = False, name: str | None = None, id: str | None = None, storage_format: Literal['csv', 'gzip', 'parquet'] | None = None)[source]

Bases: EventSink, EventSource, ConfigReader, NamedObject, CheckpointMixin, Generic[TAWI, TAgent], ABC

Base world class encapsulating a world that runs a simulation with several agents interacting within some dynamically changing environment.

A world maintains its own session.

Parameters:
  • * (* Checkpoints)

  • name – World Name

  • bulletin_board – A bulletin board object to use. If not given one will be created

  • awi_type – The type used for agent world interfaces (must descend from or behave like AgentWorldInterface )

  • info – A dictionary of key-value pairs that is kept within the world but never used. It is useful for storing contextual information. For example, when running tournaments.

  • *

  • n_steps – Total simulation time in steps

  • time_limit – Real-time limit on the simulation

  • operations – A list of Operations to run in order during every simulation step

  • *

  • negotiation_speed – The number of negotiation steps per simulation step. None means infinite

  • neg_n_steps – Maximum number of steps allowed for a negotiation.

  • neg_step_time_limit – Time limit for single step of the negotiation protocol.

  • neg_time_limit – Real-time limit on each single negotiation.

  • shuffle_negotiations – Whether negotiations are shuffled everytime when stepped.

  • negotiation_quota_per_step – Number of negotiations an agent is allowed to start per step

  • negotiation_quota_per_simulation – Number of negotiations an agent is allowed to start in the simulation

  • start_negotiations_immediately – If true negotiations start immediately when registered rather than waiting for the next step

  • mechanisms – The mechanism types allowed in this world associated with each keyward arguments to be passed to it.

  • *

  • default_signing_delay – The default number of steps between contract conclusion and signing it. Only takes effect if force_signing is False

  • force_signing – If true, agents are not asked to sign contracts. They are forced to do so. In this case, default_singing_delay is not effective and signature is immediate

  • batch_signing – If true, contracts are signed in batches not individually

  • *

  • breach_processing – How to handle breaches. Can be any of BreachProcessing values

  • *

  • log_folder – Folder to save all logs

  • log_to_file – If true, will log to a file

  • log_file_name – Name of the log file

  • log_file_level – The log-level to save to file (WARNING, ERROR, INFO, DEBUG, CRITICAL, …)

  • log_ufuns – Log utility functions

  • log_negotiations – Log all negotiation events

  • log_to_screen – Whether to log to screen

  • log_screen_level – The log-level to show on screen (WARNING, ERROR, INFO, DEBUG, CRITICAL, …)

  • no_logs – If True, All logging will be disabled no matter what other options are given.

  • log_stats_every – If nonzero and positive, the period of saving stats

  • construct_graphs – If true, information needed to draw graphs using draw method are kept.

  • event_file_name – If not None, the file-name to store events into.

  • event_types – Types of events to log

  • *

  • save_signed_contracts – Save all signed contracts

  • save_cancelled_contracts – Save all cancelled contracts

  • save_negotiations – Save all negotiation records

  • save_resolved_breaches – Save all resolved breaches

  • save_unresolved_breaches – Save all unresolved breaches

  • saved_details_level – The level of details to save agent info (>=1), simulation info (>=1), negotiation info (>=2), negotiator action info (>=3)

  • *

  • ignore_agent_exceptions – Ignore agent exceptions and keep running

  • ignore_negotiation_exceptions – If true, all mechanism exceptions are ignored and the mechanism is aborted

  • ignore_simulation_exceptions – Ignore simulation exceptions and keep running

  • ignore_contract_execution_exceptions – Ignore contract execution exceptions and keep running

  • safe_stats_monitoring – Never throw an exception for a failure to save stats or because of a Stats Monitor object

  • *

  • checkpoint_every – The number of steps to checkpoint after. Set to <= 0 to disable

  • checkpoint_folder – The folder to save checkpoints into. Set to None to disable

  • checkpoint_filename – The base filename to use for checkpoints (multiple checkpoints will be prefixed with step number).

  • single_checkpoint – If true, only the most recent checkpoint will be saved.

  • extra_checkpoint_info – Any extra information to save with the checkpoint in the corresponding json file as a dictionary with string keys

  • exist_ok – IF true, checkpoints override existing checkpoints with the same filename.

  • genius_port – the port used to connect to Genius for all negotiators in this mechanism (0 means any).

action_info_cols() list[tuple[str, type]][source]

Returns column definitions for action logging.

Override this method to customize the action information columns stored during negotiation logging.

Returns:

List of (column_name, column_type) tuples for action data.

property agreement_fraction: float[source]

Fraction of negotiations ending in agreement and leading to signed contracts

agreement_info_cols() list[tuple[str, type]][source]

Returns column definitions for agreement logging.

Override this method to customize the agreement information columns stored during negotiation logging.

Returns:

List of (column_name, column_type) tuples for agreement data.

property agreement_rate: float[source]

Fraction of negotiations ending in agreement and leading to signed contracts

append_stats()[source]

Appends current statistics to the stats file if configured.

property breach_fraction: float[source]

Fraction of signed contracts that led to breaches

property breach_level: float[source]

The average breach level per contract

property breach_rate: float[source]

Fraction of signed contracts that led to breaches

abstractmethod breach_record(breach: Breach) dict[str, Any][source]

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

property business_size: float[source]

The total business size defined as the total money transferred within the system

call(agent: TAgent, method: Callable, *args, **kwargs) Any[source]

Calls a method on an agent updating exeption count

Parameters:
  • agent – The agent on which the method is to be called

  • method – The bound method (bound to the agent)

  • *args – position arguments

  • **kwargs – keyword arguments

Returns:

whatever method returns

property cancellation_fraction: float[source]

Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.

property cancellation_rate: float[source]

Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.

property cancelled_contracts: list[dict[str, Any]][source]

Returns contracts that were concluded but not signed.

Returns:

List of contract records that were rejected by at least one partner.

static combine_stats(worlds: tuple[~negmas.situated.world.World, ...] | ~negmas.situated.world.World, stat: str, pertype=False, method=<function mean>, n_steps: int | None = None)[source]

Combines statistics by the given combination method.

Parameters:
  • worlds – The worlds to combine stats from

  • stat – The statistic to combine

  • pertype – combine agent-statistics per type

  • method – plot sum for type statistics instead of mean

  • n_steps – If not given, then absolute step number will be used for combining stats, otherwise all stats will be resampled to be n_steps before being combined. If a negative number, then the maximum number of steps in all worlds will be used

abstractmethod complete_contract_execution(contract: Contract, breaches: list[Breach], resolution: Contract) None[source]

Called after breach resolution is completed for contracts for which some potential breaches occurred.

Parameters:
  • contract – The contract considered.

  • breaches – The list of potential breaches that was generated by _execute_contract.

  • resolution – The agreed upon resolution

Returns:

property contract_dropping_fraction: float[source]

Fraction of signed contracts that were never executed because they were signed to late to be executable

property contract_err_fraction: float[source]

Fraction of signed contracts that caused exception during their execution

property contract_execution_fraction: float[source]

Fraction of signed contracts successfully executed with no breaches, or errors

property contract_nullification_fraction: float[source]

Fraction of signed contracts were nullified by the system (e.g. due to bankruptcy)

abstractmethod contract_record(contract: Contract) dict[str, Any][source]

Converts a contract to a record suitable for permanent storage

abstractmethod contract_size(contract: Contract) float[source]

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

Returns:

property current_step[source]

Returns the current simulation step number.

abstractmethod delete_executed_contracts() None[source]

Called after processing executable contracts at every simulation step to delete processed contracts

draw(steps: tuple[int, int] | int | None = None, what: Collection[str] = ['negotiation-requests-rejected', 'negotiation-requests-accepted', 'negotiations-rejected', 'negotiations-started', 'negotiations-failed', 'contracts-concluded', 'contracts-cancelled', 'contracts-signed', 'contracts-breached', 'contracts-executed'], who: Callable[[TAgent], bool] | None = None, where: Callable[[TAgent], int | tuple[float, float]] | None = None, together: bool = True, ncols: int = 4, figsize: tuple[int, int] = (15, 15), show_node_labels=True, show_edge_labels=True, show: bool = True, **kwargs)[source]

Generates a graph showing some aspect of the simulation

Parameters:
  • steps – The step/steps to generate the graphs for. If a tuple is given all edges within the given range (inclusive beginning, exclusive end) will be accomulated

  • what – The edges to have on the graph. Options are: negotiations, concluded, signed, executed

  • who – Either a callable that receives an agent and returns True if it is to be shown or None for all

  • where – A callable that returns for each agent the position it showed by drawn at either as an integer specifying the column in which to draw the column or a tuple of two floats specifying the position within the drawing area of the agent. If None, the default Networkx layout will be used.

  • together – IF specified all edge types are put in the same graph.

  • ncols – Number of columns for subplot grid when together=False.

  • figsize – Figure size as (width, height).

  • show_node_labels – show node labels!

  • show_edge_labels – show edge labels!

  • show – Whether to display the figure immediately.

  • kwargs – Additional keyword arguments.

Returns:

A tuple of (figure, networkx graph) if together==True else (figure, list of graphs)

property erred_contracts: list[dict[str, Any]][source]

Returns contracts that caused exceptions during execution.

Returns:

List of contract records where execution raised an error.

abstractmethod executable_contracts() Collection[Contract][source]

Called at every time-step to get the contracts that are executable at this point of the simulation

abstractmethod execute_action(action: Action, agent: TAgent, callback: Callable | None = None) bool[source]

Executes the given action by the given agent

property executed_contracts: list[dict[str, Any]][source]

Returns contracts that have been successfully executed.

Returns:

List of contract records where execution completed without issues.

extra_agent_info(agent: Agent | None) dict[str, Any][source]

Returns additional agent-specific data to include in logs/exports.

Override this method to add custom agent attributes to saved data.

Parameters:

agent – The agent to extract additional information from, or None.

Returns:

A dictionary of custom agent attributes to include in output files.

extra_neg_info(info: NegotiationInfo) dict[str, Any][source]

Returns additional negotiation-specific data to include in logs.

Override to add custom negotiation attributes to saved negotiation records.

Parameters:

info – The negotiation info object containing details about the negotiation.

Returns:

A dictionary of custom negotiation data to include in output files.

extra_sim_step_info_post() dict[str, Any][source]

Returns additional data to log at the end of each simulation step.

Override to add custom metrics collected after the step completes.

Returns:

A dictionary of custom post-step data to include in simulation logs.

extra_sim_step_info_pre() dict[str, Any][source]

Returns additional data to log at the start of each simulation step.

Override to add custom metrics collected before the step executes.

Returns:

A dictionary of custom pre-step data to include in simulation logs.

extract_action_info(action: Any) list[Any][source]

Extracts loggable information from a negotiation action.

Override this method to customize what action information is stored during negotiation logging.

Parameters:

action – The negotiation action (e.g., an offer).

Returns:

A list of values corresponding to action_info_cols().

extract_agreement_info(agreement: tuple | None) list[Any][source]

Extracts loggable information from a negotiation agreement.

Override this method to customize what agreement information is stored during negotiation logging.

Parameters:

agreement – The negotiation outcome/agreement, or None if no agreement.

Returns:

A list of values corresponding to agreement_info_cols().

get_dropped_contracts() Collection[Contract][source]

Called at the end of every time-step to get a list of the contracts that are signed but will never be executed

abstractmethod get_private_state(agent: TAgent) dict[source]

Reads the private state of the given agent

graph(steps: tuple[int, int] | int | None = None, what: list[str] | tuple[str, ...] = ['negotiation-requests-rejected', 'negotiation-requests-accepted', 'negotiations-rejected', 'negotiations-started', 'negotiations-failed', 'negotiations-succeeded', 'contracts-concluded', 'contracts-cancelled', 'contracts-signed', 'contracts-nullified', 'contracts-erred', 'contracts-breached', 'contracts-executed'], who: Callable[[TAgent], bool] | None = None, together: bool = True) nx.Graph | list[nx.Graph][source]

Generates a graph showing some aspect of the simulation

Parameters:
  • steps – The step/steps to generate the graphs for. If a tuple is given all edges within the given range (inclusive beginning, exclusive end) will be accumulated

  • what – The edges to have on the graph. Options are: negotiations, concluded, signed, executed

  • who – Either a callable that receives an agent and returns True if it is to be shown or None for all

  • together – IF specified all edge types are put in the same graph.

Returns:

A networkx graph representing the world if together==True else a list of graphs one for each item in what

ignore_contract(contract, as_dropped=False)[source]

Ignores the contract as if it was never agreed upon or as if was dropped

Parameters:
  • contract – The contract to ignore

  • as_dropped – If true, the contract is treated as a dropped invalid contract, otherwise it is treated as if it never happened.

classmethod is_basic_stat(s: str) bool[source]

Checks whether a given statistic is agent specific.

is_valid_agreement(negotiation: NegotiationInfo, agreement: tuple, mechanism: Mechanism) bool[source]

Confirms that the agreement is valid given the world rules.

Parameters:
  • negotiation – The NegotiationInfo that led to the agreement

  • agreement – The agreement

  • mechanism – The mechanism that led to the agreement

Returns:

Returns True for valid agreements and False for invalid agreements

Remarks:

  • This test is conducted before the agents are asked to sign the corresponding contract

  • Invalid agreements will be treated as never happened and agents will not be asked to sign it

is_valid_contract(contract: Contract) bool[source]

Confirms that the agreement is valid given the world rules.

Parameters:

contract – The contract being tested

Returns:

Returns True for valid contracts and False for invalid contracts

Remarks:

  • This test will be conducted after agents are asked to sign the contract and only for signed contracts.

  • If False is returned, the contract will considered unsigned and will be recorded as a concluded but not signed contract with no rejectors

join(x: TAgent, simulation_priority: int = 0, **kwargs)[source]

Add an agent to the world.

Parameters:
  • x – The agent to be registered

  • simulation_priority – The simulation priority. Entities with lower pprioritieswill be stepped first during

  • kwargs – Any key-value pairs specifying attributes of the agent. NegMAS internally uses the attribute ‘color’ when drawing the agent in draw

Returns:

property log_folder[source]

Returns the path to the logging folder for this world.

logdebug(s: str | None, event: Event | None = None) None[source]

logs debug-level information

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

logdebug_agent(aid: str, s: str, event: Event | None = None) None[source]

logs debug to the agent individual log

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

logerror(s: str | None, event: Event | None = None) None[source]

logs error-level information

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

logerror_agent(aid: str, s: str | None, event: Event | None = None) None[source]

logs information to the agent individual log

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

loginfo(s: str, event: Event | None = None) None[source]

logs info-level information

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

loginfo_agent(aid: str, s: str | None, event: Event | None = None) None[source]

logs information to the agent individual log

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

logwarning(s: str | None, event: Event | None = None) None[source]

logs warning-level information

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

logwarning_agent(aid: str, s: str | None, event: Event | None = None) None[source]

logs warning to the agent individual log

Parameters:
  • s (str) – The string to log

  • event (Event) – The event to announce after logging

property n_agent_exceptions: dict[str, int][source]

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

property n_contract_exceptions: dict[int, int][source]

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

property n_mechanism_exceptions: dict[int, int][source]

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

property n_negotiation_rounds_failed: float[source]

Average number of rounds in a successful negotiation

property n_negotiation_rounds_successful: float[source]

Average number of rounds in a successful negotiation

property n_negotiator_exceptions: dict[str, int][source]

Returns a mapping from agent ID to the total number of exceptions its negotiators have raised

n_saved_contracts(ignore_no_issue: bool = True) int[source]

Number of saved contracts

Parameters:

ignore_no_issue – If true, only contracts resulting from negotiation (has some issues) will be counted

property n_simulation_exceptions: dict[int, int][source]

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

property n_total_agent_exceptions: dict[str, int][source]

Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised

property n_total_simulation_exceptions: dict[int, int][source]

Returns the total number of exceptions per step that are not directly raised by agents or their negotiators.

Remarks:
property nullified_contracts: list[dict[str, Any]][source]

Returns contracts that were nullified (e.g., due to bankruptcy).

Returns:

List of contract records that were invalidated by the system.

on_contract_cancelled(contract)[source]

Called whenever a concluded contract is not signed (cancelled)

Parameters:

contract – The contract to add

Remarks:

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

  • You should ALWAYS call this function when overriding it.

on_contract_concluded(contract: Contract, to_be_signed_at: int) None[source]

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

Parameters:
  • contract – The contract to add

  • to_be_signed_at – The timestep at which the contract is to be signed

Remarks:

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

  • You should ALWAYS call this function when overriding it.

on_contract_processed(contract)[source]

Called whenever a contract finished processing to be removed from unsigned contracts

Parameters:

contract – Contract

Remarks:

  • called by on_contract_cancelled and on_contract_signed

on_contract_signed(contract: Contract) bool[source]

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

Parameters:

contract – The contract to add

Returns:

True if everything went OK and False otherwise

Remarks:

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

  • You should ALWAYS call this function when overriding it.

on_event(event: Event, sender: EventSource)[source]

Received when an event is raised

on_exception(entity: Entity, e: Exception) None[source]

Called when an exception happens.

Parameters:
  • entity – The entity that caused the exception

  • e – The exception

on_negotiation_end(info: NegotiationInfo)[source]

On negotiation end.

Parameters:

info – Info.

on_negotiation_processed(info: NegotiationInfo, contract: Contract | None)[source]

Called whenever a negotiation is ended after calling on_negotiation_failure or on_negotiation_success.

Remarks:

If contract is None, the negotiation ended in failure otherwise it ended in success.

on_negotiation_start(info: NegotiationInfo)[source]

On negotiation start.

Parameters:

info – Info.

on_negotiation_stepped(info: NegotiationInfo)[source]

On negotiation stepped.

Parameters:

info – Info.

abstractmethod order_contracts_for_execution(contracts: Collection[Contract]) Collection[Contract][source]

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

classmethod plot_combined_stats(worlds: tuple[World, ...] | World, stats: str | tuple[str, ...], n_steps: int | None = -1, pertype=False, use_sum=False, title=True, ylabel=False, xlabel=False, legend=True, figsize=None, ylegend=2.0, legend_ncols=8, show: bool = True)[source]

Plots combined statistics of multiple worlds in a single plot

Parameters:
  • stats – The statistics to plot. If None, some selected stats will be displayed

  • pertype – combine agent-statistics per type

  • use_sum – plot sum for type statistics instead of mean

  • title – If given a title will be added to each subplot

  • ylabel – If given, the ylabel will be added to each subplot

  • xlabel – If given The xlabel will be added (Simulation Step)

  • legend – If given, a legend will be displayed

  • figsize – Size of the figure to host the plot

  • ylegend – y-axis of legend for cases with large number of labels

  • legend_n_cols – number of columns in the legend

  • show – Whether to display the figure immediately.

Returns:

The plotly Figure object.

plot_stats(stats: str | tuple[str, ...], pertype=False, use_sum=False, title=True, ylabel=False, xlabel=False, legend=True, figsize=None, ylegend=2.0, legend_ncols=8, show: bool = True)[source]

Plots statistics of the world in a single plot

Parameters:
  • stats – The statistics to plot. If None, some selected stats will be displayed

  • pertype – combine agent-statistics per type

  • use_sum – plot sum for type statistics instead of mean

  • title – If given a title will be added to each subplot

  • ylabel – If given, the ylabel will be added to each subplot

  • xlabel – If given The xlabel will be added (Simulation Step)

  • legend – If given, a legend will be displayed

  • figsize – Size of the figure to host the plot

  • ylegend – y-axis of legend for cases with large number of labels

  • legend_n_cols – number of columns in the legend

  • show – Whether to display the figure immediately.

Returns:

The plotly Figure object.

post_step_stats()[source]

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

Kept for backward compatibility and will be dropped. Override update_stats ins

pre_step_stats()[source]

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

Kept for backward compatibility and will be dropped. Override update_stats instead

register(x: Entity, simulation_priority: int = 0)[source]

Registers an entity in the world so it can be looked up by name. Should not be called directly

Parameters:
  • x – The entity to be registered

  • simulation_priority – The simulation periority. Entities with lower periorities will be stepped first during

Returns:

register_stats_monitor(m: StatsMonitor)[source]

Adds a statistics monitor to receive periodic stats updates.

Parameters:

m – The StatsMonitor to register for receiving simulation statistics.

register_world_monitor(m: WorldMonitor)[source]

Adds a world monitor to observe simulation state changes.

Parameters:

m – The WorldMonitor to register for observing simulation progress.

property relative_time: float[source]

Returns a number between 0 and 1 indicating elapsed relative time or steps.

property remaining_steps: int | None[source]

Returns the remaining number of steps until the end of the mechanism run. None if unlimited

property remaining_time: float | None[source]

Returns remaining time in seconds. None if no time limit is given.

request_negotiation_about(req_id: str, caller: TAgent, issues: list[Issue], partners: list[TAgent | str], roles: list[str] | None = None, annotation: dict[str, Any] | None = None, mechanism_name: str | None = None, mechanism_params: dict[str, Any] | None = None, group: str | None = None) NegotiationInfo[source]

Requests to start a negotiation with some other agents

Parameters:
  • req_id – An ID For the request that is unique to the caller

  • caller – The agent requesting the negotiation

  • partners – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/Agent or as a list containing a single string/Agent, then he caller will be added at the beginning of the list. This will only be done if roles was passed as None.

  • issues – Negotiation issues

  • annotation – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation

  • roles – The roles of different partners. If None then each role for each partner will be None

  • mechanism_name – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be)

  • my_role (then roles and)

  • None

  • mechanism_params – A dict of parameters used to initialize the mechanism object

  • group – An identifier for the group to which the negotiation belongs. This is not not used by the system.

Returns:

None. The caller will be informed by a callback function on_neg_request_accepted or on_neg_request_rejected about the status of the negotiation.

property resolved_breaches: list[dict[str, Any]][source]

Returns breach records that have been successfully resolved.

Returns:

List of breach records where resolution was achieved.

run()[source]

Runs the simulation until it ends

run_negotiation(caller: TAgent, issues: list[Issue], partners: list[str | TAgent], negotiator: Negotiator, preferences: Preferences | None = None, caller_role: str | None = None, roles: list[str] | None = None, annotation: dict[str, Any] | None = None, mechanism_name: str | None = None, mechanism_params: dict[str, Any] | None = None) tuple[Contract | None, NegotiatorMechanismInterface | None][source]

Runs a negotiation until completion

Parameters:
  • caller – The agent requesting the negotiation

  • partners – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/Agent or as a list containing a single string/Agent, then he caller will be added at the beginning of the list. This will only be done if roles was passed as None.

  • negotiator – The negotiator to be used in the negotiation

  • preferences – The utility function. Only needed if the negotiator does not already know it

  • caller_role – The role of the caller in the negotiation

  • issues – Negotiation issues

  • annotation – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation

  • roles – The roles of different partners. If None then each role for each partner will be None

  • mechanism_name – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be)

  • my_role (then roles and)

  • None

  • mechanism_params – A dict of parameters used to initialize the mechanism object

Returns:

A Tuple of a contract and the nmi of the mechanism used to get it in case of success. None otherwise

run_negotiations(caller: TAgent, issues: list[Issue] | list[list[Issue]], partners: list[list[str | TAgent]], negotiators: list[Negotiator], preferences: list[Preferences] | None = None, caller_roles: list[str] | None = None, roles: list[list[str] | None] | None = None, annotations: list[dict[str, Any] | None] | None = None, mechanism_names: str | list[str] | None = None, mechanism_params: dict[str, Any] | list[dict[str, Any]] | None = None, all_or_none: bool = False) list[tuple[Contract, NegotiatorMechanismInterface]][source]

Requests to run a set of negotiations simultaneously. Returns after all negotiations are run to completion

Parameters:
  • caller – The agent requesting the negotiation

  • partners – A list of list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners[i] is passed as a single string/Agent or as a list containing a single string/Agent, then he caller will be added at the beginning of the list. This will only be done if roles was passed as None.

  • issues – Negotiation issues

  • negotiators – The negotiator to be used in the negotiation

  • ufuns – The utility function. Only needed if the negotiator does not already know it

  • caller_roles – The role of the caller in the negotiation

  • annotations – Extra information to be passed to the partners when asking them to join the negotiation

  • partners – A list of partners to participate in the negotiation

  • roles – The roles of different partners. If None then each role for each partner will be None

  • mechanism_names – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the

  • None (must also be)

  • my_role (then roles and)

  • None

  • mechanism_params – A dict of parameters used to initialize the mechanism object

  • all_of_none – If True, ALL partners must agree to negotiate to go through.

Returns:

contract (None for failure) and nmi (The mechanism info [None if the partner refused the negotiation])

Return type:

A list of tuples each with two values

run_with_progress(callback: Callable[[int], None] | None = None) None[source]

Runs the simulation showing progress, with optional callback

save_config(file_name: str)[source]

Saves the config of the world as a yaml file

Parameters:

file_name – Name of file to save the config to

Returns:

save_gif(path: str | Path | None = None, what: Collection[str] = ['negotiation-requests-rejected', 'negotiation-requests-accepted', 'negotiations-rejected', 'negotiations-started', 'negotiations-failed', 'negotiations-succeeded', 'contracts-concluded', 'contracts-cancelled', 'contracts-signed', 'contracts-nullified', 'contracts-erred', 'contracts-breached', 'contracts-executed'], who: Callable[[TAgent], bool] | None = None, together: bool = True, draw_every: int = 1, fps: int = 5) None[source]

Generates an animated GIF showing the simulation’s agent interaction graph over time.

Parameters:
  • path – Output file path for the GIF. Defaults to log_folder/name.gif.

  • what – Edge types to include (e.g., negotiations, contracts).

  • who – Filter function to select which agents to display.

  • together – If True, combine all edge types in one graph.

  • draw_every – Interval between frames (in simulation steps).

  • fps – Frames per second in the output GIF.

property saved_breaches: list[dict[str, Any]][source]

Returns all saved breach records as a list of dictionaries.

Returns:

List of breach records containing perpetrator, victims, and resolution status.

property saved_contracts: list[dict[str, Any]][source]

Returns all saved contract records as a list of dictionaries.

Returns:

List of contract records containing agreement details and execution status.

property saved_negotiations: list[dict[str, Any]][source]

Returns all saved negotiation records as a list of dictionaries.

Returns:

List of negotiation records containing metadata, outcomes, and history.

set_bulletin_board(bulletin_board)[source]

Initializes or replaces the world’s bulletin board with required sections.

Parameters:

bulletin_board – A BulletinBoard instance, or None to create a new one.

property signed_contracts: list[dict[str, Any]][source]

Returns contracts that have been signed by all parties.

Returns:

List of contract records where all partners signed.

abstractmethod simulation_step(stage: int = 0)[source]

A single step of the simulation.

Parameters:

stage – How many times so far was this method called within the current simulation step

Remarks:

  • Using the stage parameter, it is possible to have Operations . SimulationStep several times with the list of operations while differentiating between these calls.

abstractmethod start_contract_execution(contract: Contract) set[Breach] | None[source]

Tries to execute the contract

Parameters:

contract

Returns:

The set of breaches committed if any. If there are no breaches return an empty set

Return type:

Set[Breach]

Remarks:

  • You must call super() implementation of this method before doing anything

  • It is possible to return None which indicates that the contract was nullified (i.e. not executed due to a reason other than an execution exeception).

property stat_names[source]

Returns names of all stats available

property stats: dict[str, Any][source]

Simulation statistics collected over time (negotiations, contracts, breaches, etc.).

Returns:

Dict mapping statistic names to lists of values per simulation step

Return type:

dict[str, Any]

step(n_neg_steps: int | None = None, n_mechanisms: int | None = None, actions: dict[str, Any] | None = None, neg_actions: dict[str, dict[str, MechanismAction | None]] | None = None) bool[source]

A single simulation step.

Parameters:
  • n_mechanisms – Number of mechanisms to step (None for all)

  • n_neg_steps – Number of steps for every mechanism (None to complete one simulation step)

  • actions – Mapping of agent IDs to their actions. The agent will be asked to act only if this is not given

  • neg_actions – Mapping of mechanism IDs to a negotiator action. Negotiators will be called upon to act only if no action is passed here. This is a dict with keys corresponding to mechanism IDs and values corresponding to a dict mapping a negotiator (key) to its action (value)

Remarks:

  • We have two modes of operation depending on n_neg_steps

    1. n_neg_steps is None will run a single complete simulation step every call

      including all negotiations and everything before and after them.

    2. n_neg_steps is an integer will step the simulation so that the given number

      of simulation steps are executed every call. The simulator will run operations before and after negotiations appropriately.

  • We have two modes of operation depending on n_mechanisms

    1. n_mechanisms is None will step all negotiations according to n_neg_steps

    2. n_mechanisms is an integer and n_neg_steps will step this number of

      mechanisms in parallel every call to step.

  • We have a total of four modes:

    1. n_neg_steps and n_mechanisms are both None: Each call to step corresponds

      to one simulation step from start to end.

    2. n_neg_steps and n_mechanisms are both integers: Each call to step steps n_mechanisms mechanisms by n_neg_steps steps.

    3. n_neg_steps is None and n_mechanisms is an integer: Each call to step runs n_mechanisms according to negotiation_speed

    4. n_neg_steps is an integer and n_mechanisms is None: Each call to step steps all mechanisms n_neg_steps steps.

  • Never mix calls with n_neg_steps equaling None and an integer.

  • Never call this method again on a world if it ever returned False on that world.

property time: float[source]

Elapsed time since world started in seconds. 0.0 if the world did not start running

property total_time[source]

Returns total simulation time (till now) in mx

type_name_for_logs(agent: Agent | None) str | None[source]

Type name for logs.

Parameters:

agent – Agent.

Returns:

The result.

Return type:

str | None

unregister_stats_monitor(m: StatsMonitor)[source]

Removes a previously registered statistics monitor.

Parameters:

m – The StatsMonitor to unregister.

unregister_world_monitor(m: WorldMonitor)[source]

Removes a previously registered world monitor.

Parameters:

m – The WorldMonitor to unregister.

property unresolved_breaches: list[dict[str, Any]][source]

Returns breach records that remain unresolved.

Returns:

List of breach records where no resolution was reached.

update_stats(stage: int)[source]

Called to update any custom stats that the world designer wants to keep

Parameters:

stage – How many times was this method called during this stage

Remarks:

  • Default behavior is: - If Operations . StatsUpdate appears once in operations, it calls post_step_stats once - Otherwise: it calls pre_step_stats for stage 0, and post_step_stats for any other stage.

class negmas.situated.WorldMonitor(type_postfix: str = '')[source]

Bases: Entity

A monitor object capable of monitoring a world. It has read/write access to the world

init(world: World)[source]

Called to initialize the monitor before running first step

step(world: World)[source]

Called at the END of every simulation step

negmas.situated.deflistdict()[source]

Create a defaultdict that returns empty lists for missing keys.

negmas.situated.safe_min(a, b)[source]

Returns min(a, b) assuming None is less than anything.

negmas.situated.save_stats(world: World, log_dir: PathLike | str, params: dict[str, Any] | None = None, stats_file_name: str | None = None, python_class_identifier='__python_class__', storage_format: TableStorageFormat | None = None)[source]

Saves the statistics of a world run.

Parameters:
  • world – The world

  • log_dir – The directory to save the stats into.

  • params – A parameter list to save with the world

  • stats_file_name – File name to use for stats file(s) without extension

  • python_class_identifier – The identifier for Python class serialization

  • storage_format – Format for saving tables (‘csv’, ‘gzip’, ‘parquet’). Defaults to DEFAULT_TABLE_STORAGE_FORMAT.

Returns:

negmas.situated.show_edge_colors(show: bool = True)[source]

Plots the edge colors used with their meaning

Parameters:

show – If True, displays the figure. If False, returns the figure without displaying.

Returns:

The plotly figure if show=False, None otherwise.