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_multiplesteps of it are conducted. That entails that requesting a negotiation may result in new contracts in the same time-step only ofimmediate_negotiationsis true.
Simulation steps:¶
It is possible to control the order of the simulation steps differently using the
operationsparameter to the world constructor. this is the default order
prepare custom stats (call
_pre_step_stats)step all existing negotiations
negotiation_speed_multipletimes handling any failed negotiations and creating contracts for any resulting agreementsAllow custom simulation (call
simulation_step) with stage 0run all
Entityobjects registered (i.e. all agents) in the predefinedsimulation_order.sign contracts that are to be signed at this step calling
on_contracts_finalized/on_contract_signedas neededexecute contracts that are executable at this time-step handling any breaches
allow custom simulation steps to run (call
simulation_step) with stage 1remove any negotiations that are completed!
update basic stats
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: |
zero-outcomes-negotiation |
caller: |
entity-exception |
exception: |
contract-exception |
|
agent-exception |
|
agent-joined |
agent: |
negotiation-request |
caller: |
negotiation-request-immediate |
caller: |
negotiation-request-rejected |
caller: |
negotiation-request-accepted |
caller: |
negotiation-success |
mechanism: |
negotiation-failure |
|
contract-executing |
contract: |
contract-nullified |
contract: |
contract-breached |
|
breach-resolved |
contract: |
contract-executed |
contract: |
dropped-contract |
contract: |
- class negmas.situated.Action(type: str, params: dict)[source]¶
Bases:
objectAn action that an
Agentcan execute in aWorldthrough theSimulator.
- class negmas.situated.Adapter(obj, include_adapter_type_name: bool | None = None, include_obj_type_name=True, **kwargs)[source]¶
Bases:
AgentRepresents 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
Worldclass uses the type names from this adapter whenever it needs to get a type-name (eithertype_nameorshort_type_name)
- 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],ABCBase class for all agents that can run within a
Worldand 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
- 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
NegotiationRequestInforecord 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 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_signedfor singed contracts andon_contract_cancelledfor 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:
Noneto 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 whereNonemeans 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 aNonefor 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_contractfor each contract returning the results
- class negmas.situated.AgentWorldInterface(world: World, agent: Agent)[source]¶
Bases:
objectAgent 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:
- property default_signing_delay: int[source]¶
Default signing delay.
- Returns:
The result.
- Return type:
- execute(action: Action, callback: Callable[[Action, bool], Any] | None = None) bool[source]¶
Executes an action in the world simulation
- 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_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 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
- 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
partnerswhen asking them to join the negotiationpartners – 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/
Agentor 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 ifroleswas 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
negotiationsproperty.
- 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:
- The function will create a request ID that will be used in callbacks
on_neg_request_acceptedand
- The function will create a request ID that will be used in callbacks
- 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/
Agentor 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 ifroleswas 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
partnerswhen asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles – The roles of different partners. If None then each role for each partner will be None
mechanism_name – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the
None (must also be)
my_role (then roles and)
None
mechanism_params – A dict of parameters used to initialize the mechanism object
- Returns:
A Tuple of a contract and the nmi of the mechanism used to get it in case of success. None otherwise
- run_negotiations(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/
Agentor 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 ifroleswas 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
partnerswhen asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles – The roles of different partners. If None then each role for each partner will be None
mechanism_names – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the
None (must also be)
my_role (then roles and)
None
mechanism_params – A dict of parameters used to initialize the mechanism object
all_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)
- 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:
objectBreach implementation.
- class negmas.situated.BreachProcessing(*values)[source]¶
Bases:
EnumThe way breaches are to be handled
- META_NEGOTIATION = 2[source]¶
A meta negotiation is instantiated between victim and perpetrator to set re-negotiation issues.
- class negmas.situated.BulletinBoard[source]¶
Bases:
EventSource,ConfigReaderThe 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:
- 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:
objectA representation of a negotiation scenario in which a negotiator can be evaluated
- classmethod from_dict(d, python_class_identifier='__python_class__')[source]¶
From dict.
- Parameters:
d –
python_class_identifier – Python class identifier.
- index: int = 0[source]¶
The index of the negotiator being evaluated in the list of negotiators passed to the mechanism
- 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.
Noneis equivalent to[self.index]
- to_dict(python_class_identifier='__python_class__')[source]¶
To dict.
- Parameters:
python_class_identifier – Python class identifier.
- 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:
objectA 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
Outcomein theIssuespace defined byissues
- concluded_at: int[source]¶
The time-step at which the contract was concluded (but it is still not binding until signed)
- issues: tuple[Issue][source]¶
Issues of the negotiations from which this agreement was concluded. It may be empty
- mechanism_state: MechanismState | None[source]¶
The mechanism state at the contract conclusion
- class negmas.situated.Entity(type_postfix: str = '')[source]¶
Bases:
objectDefines an entity that is a part of the world but does not participate in the simulation
- 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:
objectA mechanism creation class. It can invite agents to join a mechanism and then run it.
- init() NegotiationInfo | None[source]¶
Init.
- Returns:
The result.
- Return type:
NegotiationInfo | None
- class negmas.situated.NegAgent(*args, negotiator_type: str | type[Negotiator], negotiator_params: dict[str, Any] | None = None, **kwargs)[source]¶
Bases:
AgentWraps 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
- 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,WorldA world that runs a list of negotiators in a given scenario to evaluate them
- Parameters:
scenario – The
NegScenariospecifying 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
Worldconstructor
- complete_contract_execution(contract: Contract, breaches: list[Breach], resolution: Contract) None[source]¶
Complete contract execution.
- Parameters:
contract – Contract.
breaches – Breaches.
resolution – Resolution.
- contract_size(contract: Contract) float[source]¶
Contract size.
- Parameters:
contract – Contract.
- Returns:
The result.
- Return type:
- executable_contracts() Collection[Contract][source]¶
Executable contracts.
- Returns:
The result.
- Return type:
Collection[Contract]
- execute_action(action: Action, agent: Agent, callback: Callable | None = None) bool[source]¶
Executes the given action by the given agent
- order_contracts_for_execution(contracts: Collection[Contract]) Collection[Contract][source]¶
Order contracts for execution.
- Parameters:
contracts – Contracts.
- Returns:
The result.
- Return type:
Collection[Contract]
- 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:
objectSaves information about a negotiation
- class negmas.situated.NegotiationRequestInfo(partners, issues, annotation, uuid, negotiator, requested, extra)[source]¶
Bases:
tuple
- class negmas.situated.NoContractExecutionMixin[source]¶
Bases:
objectA mixin to add when there is no contract execution
- complete_contract_execution(contract: Contract, breaches: list[Breach], resolution: Contract) None[source]¶
Complete contract execution.
- Parameters:
contract – Contract.
breaches – Breaches.
resolution – Resolution.
- class negmas.situated.NoResponsesMixin[source]¶
Bases:
objectA 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]¶
On contract breached.
- Parameters:
contract – Contract.
breaches – Breaches.
resolution – Resolution.
- on_contract_cancelled(contract: Contract, rejectors: list[str]) None[source]¶
On contract cancelled.
- Parameters:
contract – Contract.
rejectors – Rejectors.
- on_contract_executed(contract: Contract) None[source]¶
On contract executed.
- Parameters:
contract – Contract.
- on_contract_signed(contract: Contract) bool[source]¶
On contract signed.
- Parameters:
contract – Contract.
- Returns:
The result.
- Return type:
- on_neg_request_accepted(req_id: str, mechanism: NegotiatorMechanismInterface)[source]¶
On neg request accepted.
- Parameters:
req_id – Req id.
mechanism – Mechanism.
- on_neg_request_rejected(req_id: str, by: list[str] | None)[source]¶
On neg request rejected.
- Parameters:
req_id – Req id.
by – By.
- on_negotiation_failure(partners: list[str], annotation: dict[str, Any], mechanism: NegotiatorMechanismInterface, state: MechanismState) None[source]¶
On negotiation failure.
- Parameters:
partners – Partners.
annotation – Annotation.
mechanism – Mechanism.
state – Current state.
- on_negotiation_success(contract: Contract, mechanism: NegotiatorMechanismInterface) None[source]¶
On negotiation success.
- Parameters:
contract – Contract.
mechanism – Mechanism.
- respond_to_renegotiation_request(contract: Contract, breaches: list[Breach], agenda: RenegotiationRequest) Negotiator | None[source]¶
Respond to renegotiation request.
- Parameters:
contract – Contract.
breaches – Breaches.
agenda – Agenda.
- Returns:
The result.
- Return type:
Negotiator | None
- set_renegotiation_agenda(contract: Contract, breaches: list[Breach]) RenegotiationRequest | None[source]¶
Set renegotiation agenda.
- Parameters:
contract – Contract.
breaches – Breaches.
- Returns:
The result.
- Return type:
RenegotiationRequest | None
- class negmas.situated.RenegotiationRequest(publisher: Agent, issues: list[Issue], annotation: dict[str, Any] = NOTHING)[source]¶
Bases:
objectA request for renegotiation.
- class negmas.situated.RunningNegotiationInfo(negotiator, annotation, uuid, extra, my_request)[source]¶
Bases:
tuple
- 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)[source]¶
-
Represents a simple world with no simulation and sane values for most callbacks and methods.
- contract_size(contract: Contract) float[source]¶
Contract size.
- Parameters:
contract – Contract.
- Returns:
The result.
- Return type:
- class negmas.situated.StatsMonitor(type_postfix: str = '')[source]¶
Bases:
EntityA monitor object capable of receiving stats of a world
- class negmas.situated.TimeInAgreementMixin[source]¶
Bases:
objectTimeInAgreementMixin implementation.
- executable_contracts() Collection[Contract][source]¶
Called at every time-step to get the contracts that are
executableat this point of the simulation
- 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)[source]¶
Bases:
EventSink,EventSource,ConfigReader,NamedObject,CheckpointMixin,Generic[TAWI,TAgent],ABCBase 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
Operationsto 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_signingisFalseforce_signing – If true, agents are not asked to sign contracts. They are forced to do so. In this case,
default_singing_delayis not effective and signature is immediatebatch_signing – If true, contracts are signed in batches not individually
*
breach_processing – How to handle breaches. Can be any of
BreachProcessingvalues*
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
drawmethod 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).
- property agreement_fraction: float[source]¶
Fraction of negotiations ending in agreement and leading to signed contracts
- property agreement_rate: float[source]¶
Fraction of negotiations ending in agreement and leading to signed contracts
- 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.
- 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:
- 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)
- abstractmethod executable_contracts() Collection[Contract][source]¶
Called at every time-step to get the contracts that are
executableat 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
- extract_action_info(action: Any) list[Any][source]¶
Extract action info.
- Parameters:
action – Action.
- Returns:
The result.
- Return type:
list[Any]
- extract_agreement_info(agreement: tuple | None) list[Any][source]¶
Extract agreement info.
- Parameters:
agreement – Agreement.
- Returns:
The result.
- Return type:
list[Any]
- 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.
- is_valid_agreement(negotiation: NegotiationInfo, agreement: tuple, mechanism: Mechanism) bool[source]¶
Confirms that the agreement is valid given the world rules.
- Parameters:
negotiation – The
NegotiationInfothat led to the agreementagreement – 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:
- logdebug_agent(aid: str, s: str, event: Event | None = None) None[source]¶
logs debug to the agent individual log
- logerror_agent(aid: str, s: str | None, event: Event | None = None) None[source]¶
logs information to the agent individual log
- loginfo_agent(aid: str, s: str | None, event: Event | None = None) None[source]¶
logs information to the agent individual log
- logwarning_agent(aid: str, s: str | None, event: Event | None = None) None[source]¶
logs warning to the agent individual log
- 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:
This property sums the totals of
n_simulation_exceptions,n_contract_exceptions, andn_mechanism_exceptions
- 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_failureoron_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 displayedpertype – 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 displayedpertype – 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_statsins
- 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_statsinstead
- 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]¶
Register stats monitor.
- Parameters:
m –
- register_world_monitor(m: WorldMonitor)[source]¶
Register world monitor.
- Parameters:
m –
- property relative_time: float[source]¶
Returns a number between
0and1indicating 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/
Agentor 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 ifroleswas passed as None.issues – Negotiation issues
annotation – Extra information to be passed to the
partnerswhen asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles – The roles of different partners. If None then each role for each partner will be None
mechanism_name – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the
None (must also be)
my_role (then roles and)
None
mechanism_params – A dict of parameters used to initialize the mechanism object
group – An identifier for the group to which the negotiation belongs. This is not not used by the system.
- Returns:
None. The caller will be informed by a callback function
on_neg_request_acceptedoron_neg_request_rejectedabout the status of the negotiation.
- 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/
Agentor 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 ifroleswas 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
partnerswhen asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles – The roles of different partners. If None then each role for each partner will be None
mechanism_name – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the
None (must also be)
my_role (then roles and)
None
mechanism_params – A dict of parameters used to initialize the mechanism object
- Returns:
A Tuple of a contract and the nmi of the mechanism used to get it in case of success. None otherwise
- run_negotiations(caller: 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/
Agentor 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 ifroleswas 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
partnerswhen asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles – The roles of different partners. If None then each role for each partner will be None
mechanism_names – Name of the mechanism to use. It must be one of the mechanism_names that are supported by the
None (must also be)
my_role (then roles and)
None
mechanism_params – A dict of parameters used to initialize the mechanism object
all_of_none – If True, ALL partners must agree to negotiate to go through.
- Returns:
contract (None for failure) and nmi (The mechanism info [None if the partner refused the negotiation])
- Return type:
A list of tuples each with two values
- 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]¶
Save gif.
- Parameters:
path – Path.
what – What.
who – Who.
together – Together.
draw_every – Draw every.
fps – Fps.
- set_bulletin_board(bulletin_board)[source]¶
Set bulletin board.
- Parameters:
bulletin_board – Bulletin board.
- 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.SimulationStepseveral 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).
- 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_stepsn_neg_steps is Nonewill run a single complete simulation step every callincluding all negotiations and everything before and after them.
n_neg_steps is an integerwill step the simulation so that the given numberof 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_mechanismsn_mechanisms is Nonewill step all negotiations according ton_neg_stepsn_mechanismsis an integer andn_neg_stepswill step this number ofmechanisms in parallel every call to step.
We have a total of four modes:
n_neg_stepsandn_mechanismsare both None: Each call tostepcorrespondsto one simulation step from start to end.
n_neg_stepsandn_mechanismsare both integers: Each call tostepstepsn_mechanismsmechanisms byn_neg_stepssteps.n_neg_stepsis None andn_mechanismsis an integer: Each call tosteprunsn_mechanismsaccording tonegotiation_speedn_neg_stepsis an integer andn_mechanismsis None: Each call tostepsteps all mechanismsn_neg_stepssteps.
Never mix calls with
n_neg_stepsequalingNoneand an integer.Never call this method again on a world if it ever returned
Falseon that world.
- property time: float[source]¶
Elapsed time since world started in seconds. 0.0 if the world did not start running
- 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]¶
Unregister stats monitor.
- Parameters:
m –
- unregister_world_monitor(m: WorldMonitor)[source]¶
Unregister world monitor.
- Parameters:
m –
- 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.StatsUpdateappears 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:
EntityA monitor object capable of monitoring a world. It has read/write access to the world
- 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__')[source]¶
Saves the statistics of a world run.
- Parameters:
world – The world
logdir – 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
Returns: