SimpleWorld
- class negmas.situated.SimpleWorld(bulletin_board=None, n_steps=10000, time_limit=3600, negotiation_speed=None, neg_n_steps=100, neg_time_limit=None, neg_step_time_limit=inf, shuffle_negotiations=True, negotiation_quota_per_step=9223372036854775807, negotiation_quota_per_simulation=9223372036854775807, default_signing_delay=1, force_signing=False, batch_signing=True, breach_processing=BreachProcessing.NONE, mechanisms=None, awi_type='negmas.situated.AgentWorldInterface', start_negotiations_immediately=False, log_folder=None, log_to_file=True, log_ufuns=False, log_negotiations=False, log_to_screen=False, log_stats_every=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=True, save_cancelled_contracts=True, save_negotiations=True, save_resolved_breaches=True, save_unresolved_breaches=True, saved_details_level=4, ignore_agent_exceptions=False, ignore_negotiation_exceptions=False, ignore_contract_execution_exceptions=False, ignore_simulation_exceptions=False, safe_stats_monitoring=False, construct_graphs=False, checkpoint_every=1, checkpoint_folder=None, checkpoint_filename=None, extra_checkpoint_info=None, single_checkpoint=True, exist_ok=True, operations=(Operations.StatsUpdate, Operations.Negotiations, Operations.ContractSigning, Operations.AgentSteps, Operations.ContractExecution, Operations.SimulationStep, Operations.ContractSigning, Operations.StatsUpdate), info=None, genius_port=25337, disable_agent_printing=False, debug=False, name=None, id=None)[source]
-
Represents a simple world with no simulation and sane values for most callbacks and methods.
Attributes Summary
Fraction of negotiations ending in agreement and leading to signed contracts
Fraction of negotiations ending in agreement and leading to signed contracts
Fraction of signed contracts that led to breaches
The average breach level per contract
Fraction of signed contracts that led to breaches
The total business size defined as the total money transferred within the system
Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.
Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.
Fraction of signed contracts that were never executed because they were signed to late to be executable
Fraction of signed contracts that caused exception during their execution
Fraction of signed contracts successfully executed with no breaches, or errors
Fraction of signed contracts were nullified by the system (e.g. due to bankruptcy).
The unique ID of this entity
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
Average number of rounds in a successful negotiation
Average number of rounds in a successful negotiation
Returns a mapping from agent ID to the total number of exceptions its negotiators have raised
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
Returns the total number of exceptions per step that are not directly raised by agents or their negotiators.
A convenient name of the entity (intended primarily for printing/logging/debugging).
Returns a number between
0
and1
indicating elapsed relative time or steps.Returns the remaining number of steps until the end of the mechanism run.
Returns remaining time in seconds.
Returns names of all stats available
Elapsed time since world started in seconds.
Returns total simulation time (till now) in mx
The unique ID of this entity
Methods Summary
announce
(event)Raises an event and informs all event sinks that are registered for notifications on this event type
breach_record
(breach)Converts a breach to a record suitable for storage during the simulation
call
(agent, method, *args, **kwargs)Calls a method on an agent updating exeption count
checkpoint
(path[, file_name, info, ...])Saves a checkpoint of the current object at the given path.
Should be called at the end of the simulation to save the final state
checkpoint_info
(file_name)Returns the information associated with a dump of the object saved in the given file
checkpoint_init
([step_attrib, every, ...])Initializes the object to automatically save a checkpoint
Should be called on every step to save checkpoints as needed.
combine_stats
(worlds, stat[, pertype, ...])Combines statistics by the given combination method.
complete_contract_execution
(contract, ...)Called after breach resolution is completed for contracts for which some potential breaches occurred.
contract_record
(contract)Converts a contract to a record suitable for permanent storage
contract_size
(contract)Returns an estimation of the activity level associated with this contract.
create
(*args, **kwargs)Creates an object and returns a proxy to it.
Called after processing executable contracts at every simulation step to delete processed contracts
draw
([steps, what, who, where, together, ...])Generates a graph showing some aspect of the simulation
Called at every time-step to get the contracts that are
executable
at this point of the simulationexecute_action
(action, agent[, callback])Executes the given action by the given agent
extra_agent_info
(agent)extra_neg_info
(info)extract_action_info
(action)extract_agreement_info
(agreement)from_checkpoint
(file_name[, return_info])Creates an object from a saved checkpoint
from_config
(config[, section, ...])Creates an object of this class given the configuration info.
Called at the end of every time-step to get a list of the contracts that are signed but will never be executed
get_private_state
(agent)Reads the private state of the given agent
graph
([steps, what, who, together])Generates a graph showing some aspect of the simulation
ignore_contract
(contract[, as_dropped])Ignores the contract as if it was never agreed upon or as if was dropped
Checks whether a given statistic is agent specific.
is_valid_agreement
(negotiation, agreement, ...)Confirms that the agreement is valid given the world rules.
is_valid_contract
(contract)Confirms that the agreement is valid given the world rules.
join
(x[, simulation_priority])Add an agent to the world.
logdebug
(s[, event])logs debug-level information
logdebug_agent
(aid, s[, event])logs debug to the agent individual log
logerror
(s[, event])logs error-level information
logerror_agent
(aid, s[, event])logs information to the agent individual log
loginfo
(s[, event])logs info-level information
loginfo_agent
(aid, s[, event])logs information to the agent individual log
logwarning
(s[, event])logs warning-level information
logwarning_agent
(aid, s[, event])logs warning to the agent individual log
n_saved_contracts
([ignore_no_issue])Number of saved contracts
on_contract_cancelled
(contract)Called whenever a concluded contract is not signed (cancelled)
on_contract_concluded
(contract, to_be_signed_at)Called to add a contract to the existing set of unsigned contract after it is concluded
on_contract_processed
(contract)Called whenever a contract finished processing to be removed from unsigned contracts
on_contract_signed
(contract)Called to add a contract to the existing set of contract after it is signed
on_event
(event, sender)Received when an event is raised
on_exception
(entity, e)Called when an exception happens.
on_negotiation_end
(info)on_negotiation_processed
(info, contract)Called whenever a negotiation is ended after calling on_negotiation_failure_/on_negotiation_success_
on_negotiation_start
(info)on_negotiation_stepped
(info)order_contracts_for_execution
(contracts)Orders the contracts in a specific time-step that are about to be executed
plot_combined_stats
(worlds, stats[, ...])Plots combined statistics of multiple worlds in a single plot
plot_stats
(stats[, pertype, use_sum, ...])Plots statistics of the world in a single plot
Called at the end of the simulation step to update all stats
Called at the beginning of the simulation step to prepare stats or update them
read_config
(config[, section])Reads the configuration from a file or a dict and prepares it for parsing.
register
(x[, simulation_priority])Registers an entity in the world so it can be looked up by name.
register_listener
(event_type, listener)Registers a listener for the given event_type.
request_negotiation_about
(req_id, caller, ...)Requests to start a negotiation with some other agents
run
()Runs the simulation until it ends
run_negotiation
(caller, issues, partners, ...)Runs a negotiation until completion
run_negotiations
(caller, issues, partners, ...)Requests to run a set of negotiations simultaneously.
run_with_progress
([callback])Runs the simulation showing progress, with optional callback
save_config
(file_name)Saves the config of the world as a yaml file
save_gif
([path, what, who, together, ...])- rtype:
set_bulletin_board
(bulletin_board)set_id
(id)Sets the unique ID of this entity
simulation_step
([stage])A single step of the simulation.
spawn
([spawn_as, spawn_params])spawn_object
(*args, **kwargs)start_contract_execution
(contract)Tries to execute the contract
step
([n_neg_steps, n_mechanisms, actions, ...])A single simulation step.
type_name_for_logs
(agent)update_stats
(stage)Called to update any custom stats that the world designer wants to keep
Attributes Documentation
- agreement_fraction
Fraction of negotiations ending in agreement and leading to signed contracts
- agreement_rate
Fraction of negotiations ending in agreement and leading to signed contracts
- breach_fraction
Fraction of signed contracts that led to breaches
- breach_level
The average breach level per contract
- breach_rate
Fraction of signed contracts that led to breaches
- business_size
The total business size defined as the total money transferred within the system
- cancellation_fraction
Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.
- cancellation_rate
Fraction of contracts concluded (through negotiation or otherwise) that were cancelled.
- cancelled_contracts
- contract_dropping_fraction
Fraction of signed contracts that were never executed because they were signed to late to be executable
- contract_err_fraction
Fraction of signed contracts that caused exception during their execution
- contract_execution_fraction
Fraction of signed contracts successfully executed with no breaches, or errors
- contract_nullification_fraction
Fraction of signed contracts were nullified by the system (e.g. due to bankruptcy)
- current_step
- erred_contracts
- executed_contracts
- id
The unique ID of this entity
- log_folder
- n_agent_exceptions
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
- n_contract_exceptions
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
- n_mechanism_exceptions
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
- n_negotiation_rounds_failed
Average number of rounds in a successful negotiation
- n_negotiation_rounds_successful
Average number of rounds in a successful negotiation
- n_negotiator_exceptions
Returns a mapping from agent ID to the total number of exceptions its negotiators have raised
- n_simulation_exceptions
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
- n_total_agent_exceptions
Returns a mapping from agent ID to the total number of exceptions it and its negotiators have raised
- n_total_simulation_exceptions
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
- name
A convenient name of the entity (intended primarily for printing/logging/debugging).
- nullified_contracts
- relative_time
Returns a number between
0
and1
indicating elapsed relative time or steps.
- remaining_steps
Returns the remaining number of steps until the end of the mechanism run. None if unlimited
- remaining_time
Returns remaining time in seconds. None if no time limit is given.
- resolved_breaches
- saved_breaches
- saved_contracts
- saved_negotiations
- short_type_name
- signed_contracts
- stat_names
Returns names of all stats available
- stats
- time
Elapsed time since world started in seconds. 0.0 if the world did not start running
- total_time
Returns total simulation time (till now) in mx
- type_name
- unresolved_breaches
- uuid
The unique ID of this entity
Methods Documentation
- announce(event)
Raises an event and informs all event sinks that are registered for notifications on this event type
- append_stats()
- breach_record(breach)[source]
Converts a breach to a record suitable for storage during the simulation
- call(agent, method, *args, **kwargs)
Calls a method on an agent updating exeption count
- checkpoint(path, file_name=None, info=None, exist_ok=False, single_checkpoint=True, step_attribs=('current_step', '_current_step', '_Entity__current_step', '_step'))
Saves a checkpoint of the current object at the given path.
- Parameters:
path (
PathLike
) – Full path to a directory to store the checkpointfile_name (
str
|None
) – Name of the file to dump into. If not given, a unique name is createdinfo (
dict
[str
,Any
] |None
) – Information to save with the checkpoint (must be json serializable)exist_ok (
bool
) – If true, override existing dumpsingle_checkpoint (
bool
) – If true, keep a single checkpoint for the last stepstep_attribs (
tuple
[str
,...
]) – Attributes to represent the time-step of the object. Any of the given attributes will be used in the file name generated if single_checkpoint is False. If single_checkpoint is True, the filename will not contain time-step information
- Return type:
- Returns:
full path to the file used to save the checkpoint
- checkpoint_final_step()
Should be called at the end of the simulation to save the final state
- Remarks:
Should be called after all processing of the final step is conducted.
- classmethod checkpoint_info(file_name)
Returns the information associated with a dump of the object saved in the given file
Returns:
- checkpoint_init(step_attrib='current_step', every=1, folder=None, filename=None, info=None, exist_ok=True, single=True)
Initializes the object to automatically save a checkpoint
- Parameters:
step_attrib (
str
) – The attribute that defines the current step. If None, there is no step conceptevery (
int
) – Number of steps per checkpoint. If < 1 no checkpoints will be savedfolder (
PathLike
|Path
|str
|None
) – The directory to store checkpoints underfilename (
str
|None
) – Name of the file to save the checkpoint under. If None, a unique name will be chosen. Ifsingle_checkpoint
was False, then multiple files will be used prefixed with the step numberinfo (
dict
[str
,Any
] |None
) – Any extra information to save in the json file associated with each checkpointexist_ok (
bool
) – Override existing files if anysingle (
bool
) – If True, only the most recent checkpoint will be kept
Remarks:
single_checkpoint implies exist_ok
- checkpoint_on_step_started()
Should be called on every step to save checkpoints as needed.
- Return type:
- Returns:
The path on which the checkpoint is stored if one is stored. None otherwise.
Remarks:
Should be called at the BEGINNING of every step before any processing takes place
- static combine_stats(worlds, stat, pertype=False, method=<function mean>, n_steps=None)
Combines statistics by the given combination method.
- Parameters:
worlds (
tuple
[World
,...
] |World
) – The worlds to combine stats fromstat (
str
) – The statistic to combinepertype – combine agent-statistics per type
method – plot sum for type statistics instead of mean
n_steps (
int
|None
) – 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
- abstract complete_contract_execution(contract, breaches, resolution)
Called after breach resolution is completed for contracts for which some potential breaches occurred.
- Parameters:
- Return type:
Returns:
- contract_size(contract)[source]
Returns an estimation of the activity level associated with this contract. Higher is better :type contract:
Contract
:param contract:Returns:
- Return type:
- classmethod create(*args, **kwargs)
Creates an object and returns a proxy to it.
- delete_executed_contracts()[source]
Called after processing executable contracts at every simulation step to delete processed contracts
- Return type:
- draw(steps=None, what=['negotiation-requests-rejected', 'negotiation-requests-accepted', 'negotiations-rejected', 'negotiations-started', 'negotiations-failed', 'contracts-concluded', 'contracts-cancelled', 'contracts-signed', 'contracts-breached', 'contracts-executed'], who=None, where=None, together=True, axs=None, ncols=4, figsize=(15, 15), show_node_labels=True, show_edge_labels=True, **kwargs)
Generates a graph showing some aspect of the simulation
- Parameters:
steps (
tuple
[int
,int
] |int
|None
) – 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 accomulatedwhat (
Collection
[str
]) – The edges to have on the graph. Options are: negotiations, concluded, signed, executedwho (
Optional
[Callable
[[TypeVar
(TAgent
, bound=Agent
)],bool
]]) – Either a callable that receives an agent and returns True if it is to be shown or None for allwhere (
Optional
[Callable
[[TypeVar
(TAgent
, bound=Agent
)],int
|tuple
[float
,float
]]]) – 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 (
bool
) – IF specified all edge types are put in the same graph.axs (
Optional
[Collection
[Axes
]]) – The axes used for drawing. If together is true, it should be a singleAxes
object otherwise it should be a list ofAxes
objects with the same length as what.show_node_labels – show node labels!
show_edge_labels – show edge labels!
kwargs – passed to networx.draw_networkx
- Return type:
- Returns:
A networkx graph representing the world if together==True else a list of graphs one for each item in what
- abstract executable_contracts()
Called at every time-step to get the contracts that are
executable
at this point of the simulation- Return type:
- abstract execute_action(action, agent, callback=None)
Executes the given action by the given agent
- Return type:
bool
- classmethod from_checkpoint(file_name, return_info=False)
Creates an object from a saved checkpoint
- Parameters:
- Return type:
- Returns:
Either the object or the object and dump-info as a dict (if return_info was true)
Remarks:
- If info is returned, it is guaranteed to have the following members:
time: Dump time
type: Type of the dumped object
id: ID
name: name
- classmethod from_config(config, section=None, ignore_children=True, try_parsing_children=True, scope=None)
Creates an object of this class given the configuration info.
- Parameters:
section (
str
|None
) – A section in the file or a key in the dictionary to use for loading paramsignore_children (
bool
) – If true then children will be ignored and there will be a single returntry_parsing_children (
bool
) – If true the children will first be parsed asConfigReader
classes if they are notint (simple types (e.g.)
str
float
Iterable[int|str|float]
scope – The scope at which to evaluate any child classes. This MUST be passed as scope=globals() if you are
parsed. (having any children that are to be)
- Returns:
An object of cls if ignore_children is True or a tuple with an object of cls and a dictionary with children that were not parsed.
Remarks:
This function will return an object of its class after passing the key-value pairs found in the config to the init function.
Requiring passing scope=globals() to this function is to get around the fact that in python eval() will be called with a globals dictionary based on the module in which the function is defined not called. This means that in general when eval() is called to create the children, it will not have access to the class definitions of these children (except if they happen to be imported in this file). To avoid this problem causing an undefined_name exception, the caller must pass her globals() as the scope.
- get_dropped_contracts()
Called at the end of every time-step to get a list of the contracts that are signed but will never be executed
- Return type:
- graph(steps=None, what=['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=None, together=True)
Generates a graph showing some aspect of the simulation
- Parameters:
steps (
tuple
[int
,int
] |int
|None
) – 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 accumulatedwhat (
list
[str
] |tuple
[str
,...
]) – The edges to have on the graph. Options are: negotiations, concluded, signed, executedwho (
Optional
[Callable
[[TypeVar
(TAgent
, bound=Agent
)],bool
]]) – Either a callable that receives an agent and returns True if it is to be shown or None for alltogether (
bool
) – IF specified all edge types are put in the same graph.
- Return type:
Graph
|list
[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)
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, agreement, mechanism)
Confirms that the agreement is valid given the world rules.
- Parameters:
negotiation (
NegotiationInfo
) – TheNegotiationInfo
that led to the agreementagreement (
tuple
) – The agreementmechanism (
Mechanism
) – The mechanism that led to the agreement
- Return type:
- 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)
Confirms that the agreement is valid given the world rules.
- Parameters:
contract (
Contract
) – The contract being tested- Return type:
- 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, simulation_priority=0, **kwargs)
Add an agent to the world.
- Parameters:
x (
TypeVar
(TAgent
, bound=Agent
)) – The agent to be registeredsimulation_priority (
int
) – The simulation priority. Entities with lower pprioritieswill be stepped first duringkwargs – Any key-value pairs specifying attributes of the agent. NegMAS internally uses the attribute ‘color’ when drawing the agent in
draw
Returns:
- logdebug(s, event=None)
logs debug-level information
- logdebug_agent(aid, s, event=None)
logs debug to the agent individual log
- logerror(s, event=None)
logs error-level information
- logerror_agent(aid, s, event=None)
logs information to the agent individual log
- loginfo(s, event=None)
logs info-level information
- loginfo_agent(aid, s, event=None)
logs information to the agent individual log
- logwarning(s, event=None)
logs warning-level information
- logwarning_agent(aid, s, event=None)
logs warning to the agent individual log
- n_saved_contracts(ignore_no_issue=True)
Number of saved contracts
- on_contract_cancelled(contract)
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, to_be_signed_at)
Called to add a contract to the existing set of unsigned contract after it is concluded
- Parameters:
- Return type:
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)
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)
Called to add a contract to the existing set of contract after it is signed
- Parameters:
contract (
Contract
) – The contract to add- Return type:
- 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, sender)
Received when an event is raised
- on_exception(entity, e)
Called when an exception happens.
- on_negotiation_end(info)
- on_negotiation_processed(info, contract)
Called whenever a negotiation is ended after calling on_negotiation_failure_/on_negotiation_success_
- Remarks:
If contract is
None
, the negotiation ended in failure otherwise it ended in success.
- on_negotiation_start(info)
- on_negotiation_stepped(info)
- order_contracts_for_execution(contracts)[source]
Orders the contracts in a specific time-step that are about to be executed
- Return type:
- classmethod plot_combined_stats(worlds, stats, n_steps=-1, pertype=False, use_sum=False, makefig=False, title=True, ylabel=False, xlabel=False, legend=True, figsize=None, ylegend=2.0, legend_ncols=8)
Plots combined statistics of multiple worlds in a single plot
- Parameters:
stats (
str
|tuple
[str
,...
]) – The statistics to plot. IfNone
, 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
makefig – If given a new figure will be started
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
- plot_stats(stats, pertype=False, use_sum=False, makefig=False, title=True, ylabel=False, xlabel=False, legend=True, figsize=None, ylegend=2.0, legend_ncols=8)
Plots statistics of the world in a single plot
- Parameters:
stats (
str
|tuple
[str
,...
]) – The statistics to plot. IfNone
, 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
makefig – If given a new figure will be started
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
- 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
- classmethod read_config(config, section=None)
Reads the configuration from a file or a dict and prepares it for parsing.
- Parameters:
- Return type:
- Returns:
A dict ready to be parsed by from_config
Remarks:
- register(x, simulation_priority=0)
Registers an entity in the world so it can be looked up by name. Should not be called directly
- Parameters:
Returns:
- register_listener(event_type, listener)
Registers a listener for the given event_type.
- register_stats_monitor(m)
- register_world_monitor(m)
- request_negotiation_about(req_id, caller, issues, partners, roles=None, annotation=None, mechanism_name=None, mechanism_params=None, group=None)
Requests to start a negotiation with some other agents
- Parameters:
req_id (
str
) – An ID For the request that is unique to the callercaller (
TypeVar
(TAgent
, bound=Agent
)) – The agent requesting the negotiationpartners (
list
[Union
[TypeVar
(TAgent
, bound=Agent
),str
]]) – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/Agent
or as a list containing a single string/Agent
, then he caller will be added at the beginning of the list. This will only be done ifroles
was passed as None.annotation (
dict
[str
,Any
] |None
) – Extra information to be passed to thepartners
when asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles (
list
[str
] |None
) – The roles of different partners. If None then each role for each partner will be Nonemechanism_name (
str
|None
) – Name of the mechanism to use. It must be one of the mechanism_names that are supported by theNone (must also be)
my_role (then roles and)
None
mechanism_params (
dict
[str
,Any
] |None
) – A dict of parameters used to initialize the mechanism objectgroup (
str
|None
) – An identifier for the group to which the negotiation belongs. This is not not used by the system.
- Return type:
- Returns:
None. The caller will be informed by a callback function
on_neg_request_accepted
oron_neg_request_rejected
about the status of the negotiation.
- run()
Runs the simulation until it ends
- run_negotiation(caller, issues, partners, negotiator, preferences=None, caller_role=None, roles=None, annotation=None, mechanism_name=None, mechanism_params=None)
Runs a negotiation until completion
- Parameters:
caller (
TypeVar
(TAgent
, bound=Agent
)) – The agent requesting the negotiationpartners (
list
[Union
[str
,TypeVar
(TAgent
, bound=Agent
)]]) – A list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners is passed as a single string/Agent
or as a list containing a single string/Agent
, then he caller will be added at the beginning of the list. This will only be done ifroles
was passed as None.negotiator (
Negotiator
) – The negotiator to be used in the negotiationpreferences (
Preferences
|None
) – The utility function. Only needed if the negotiator does not already know itcaller_role (
str
|None
) – The role of the caller in the negotiationannotation (
dict
[str
,Any
] |None
) – Extra information to be passed to thepartners
when asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles (
list
[str
] |None
) – The roles of different partners. If None then each role for each partner will be Nonemechanism_name (
str
|None
) – Name of the mechanism to use. It must be one of the mechanism_names that are supported by theNone (must also be)
my_role (then roles and)
None
mechanism_params (
dict
[str
,Any
] |None
) – A dict of parameters used to initialize the mechanism object
- Return type:
- 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, issues, partners, negotiators, preferences=None, caller_roles=None, roles=None, annotations=None, mechanism_names=None, mechanism_params=None, all_or_none=False)
Requests to run a set of negotiations simultaneously. Returns after all negotiations are run to completion
- Parameters:
caller (
TypeVar
(TAgent
, bound=Agent
)) – The agent requesting the negotiationpartners (
list
[list
[Union
[str
,TypeVar
(TAgent
, bound=Agent
)]]]) – A list of list of partners to participate in the negotiation. Note that the caller itself may not be in this list which makes it possible for an agent to request a negotaition that it does not participate in. If that is not to be allowed in some world, override this method and explicitly check for these kinds of negotiations and return False. If partners[i] is passed as a single string/Agent
or as a list containing a single string/Agent
, then he caller will be added at the beginning of the list. This will only be done ifroles
was passed as None.issues (
list
[Issue
] |list
[list
[Issue
]]) – Negotiation issuesnegotiators (
list
[Negotiator
]) – The negotiator to be used in the negotiationufuns – The utility function. Only needed if the negotiator does not already know it
caller_roles (
list
[str
] |None
) – The role of the caller in the negotiationannotations (
list
[dict
[str
,Any
] |None
] |None
) – Extra information to be passed to thepartners
when asking them to join the negotiationpartners – A list of partners to participate in the negotiation
roles (
list
[list
[str
] |None
] |None
) – The roles of different partners. If None then each role for each partner will be Nonemechanism_names (
str
|list
[str
] |None
) – Name of the mechanism to use. It must be one of the mechanism_names that are supported by theNone (must also be)
my_role (then roles and)
None
mechanism_params (
dict
[str
,Any
] |list
[dict
[str
,Any
]] |None
) – A dict of parameters used to initialize the mechanism objectall_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=None)
Runs the simulation showing progress, with optional callback
- Return type:
- save_config(file_name)
Saves the config of the world as a yaml file
- Parameters:
file_name (
str
) – Name of file to save the config to
Returns:
- save_gif(path=None, what=['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=None, together=True, draw_every=1, fps=5)
- Return type:
- set_bulletin_board(bulletin_board)
- set_id(id)
Sets the unique ID of this entity
- abstract simulation_step(stage=0)
A single step of the simulation.
- Parameters:
stage (
int
) – 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.
- classmethod spawn(spawn_as='object', spawn_params=None, *args, **kwargs)
- classmethod spawn_object(*args, **kwargs)
- abstract start_contract_execution(contract)
Tries to execute the contract
- Parameters:
contract (
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=None, n_mechanisms=None, actions=None, neg_actions=None)
A single simulation step.
- Parameters:
n_mechanisms (
int
|None
) – Number of mechanisms to step (None for all)n_neg_steps (
int
|None
) – Number of steps for every mechanism (None to complete one simulation step)actions (
dict
[str
,Any
] |None
) – Mapping of agent IDs to their actions. The agent will be asked to act only if this is not givenneg_actions (
dict
[str
,dict
[str
,MechanismAction
|None
]] |None
) – 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)
- Return type:
Remarks:
We have two modes of operation depending on
n_neg_steps
n_neg_steps is None
will run a single complete simulation step every callincluding all negotiations and everything before and after them.
n_neg_steps is an integer
will 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_mechanisms
n_mechanisms is None
will step all negotiations according ton_neg_steps
n_mechanisms
is an integer andn_neg_steps
will step this number ofmechanisms in parallel every call to step.
We have a total of four modes:
n_neg_steps
andn_mechanisms
are both None: Each call tostep
correspondsto one simulation step from start to end.
n_neg_steps
andn_mechanisms
are both integers: Each call tostep
stepsn_mechanisms
mechanisms byn_neg_steps
steps.n_neg_steps
is None andn_mechanisms
is an integer: Each call tostep
runsn_mechanisms
according tonegotiation_speed
n_neg_steps
is an integer andn_mechanisms
is None: Each call tostep
steps all mechanismsn_neg_steps
steps.
Never mix calls with
n_neg_steps
equalingNone
and an integer.Never call this method again on a world if it ever returned
False
on that world.
- unregister_stats_monitor(m)
- unregister_world_monitor(m)
- update_stats(stage)
Called to update any custom stats that the world designer wants to keep
- Parameters:
stage (
int
) – 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.