GAMechanism

class negmas.ga.GAMechanism(*args, n_population=100, mutate_rate=0.1, **kwargs)[source]

Bases: negmas.mechanisms.Mechanism

Naive GA-based mechanism that assume multi-issue discrete domains.

Parameters
  • *args – positional arguments to be passed to the base Mechanism

  • **kwargs – keyword arguments to be passed to the base Mechanism

  • n_population (int) – The number of outcomes for each generation

  • mutate_rate (float) – The rate of mutation

Attributes Summary

agent_ids

rtype

list[str]

agent_names

rtype

list[str]

agreement

completed

current_step

dynamic_entry

history

id

The unique ID of this entity

issues

rtype

list[Issue] | None

max_n_agents

n_outcomes

n_steps

name

A convenient name of the entity (intended primarily for printing/logging/debugging).

negotiator_ids

rtype

list[str]

negotiator_names

rtype

list[str]

negotiators

outcome_space

outcomes

participants

Returns a list of all participant names

relative_time

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

remaining_steps

Returns the remaining number of steps until the end of the mechanism run.

remaining_time

Returns remaining time in seconds.

requirements

A dictionary specifying the requirements that must be in the capabilities of any agent to join the mechanism.

running

short_type_name

rtype

str

state

Returns the current state.

state4history

Returns the state as it should be stored in the history

stats

time

Elapsed time since mechanism started in seconds.

time_limit

type_name

rtype

str

uuid

The unique ID of this entity

Methods Summary

abort()

Aborts the negotiation

add(negotiator, *[, preferences, role, ufun])

Add an agent to the negotiation.

add_requirements(requirements)

Adds requirements.

announce(event)

Raises an event and informs all event sinks that are registered for notifications on this event type

can_accept_more_agents()

Whether the mechanism can currently accept more negotiators.

can_enter(agent)

Whether the agent can enter the negotiation now.

can_leave(agent)

Can the agent leave now?

can_participate(agent)

Checks if the agent can participate in this type of negotiation in general.

checkpoint(path[, file_name, info, ...])

Saves a checkpoint of the current object at the given path.

checkpoint_final_step()

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

checkpoint_on_step_started()

Should be called on every step to save checkpoints as needed.

create(*args, **kwargs)

Creates an object and returns a proxy to it.

crossover(outcome1, outcome2)

Uniform crossover

discrete_outcome_space([levels, max_cardinality])

Returns a stable discrete version of the given outcome-space

discrete_outcomes([levels, max_cardinality])

A discrete set of outcomes that spans the outcome space

extra_state()

Returns any extra state information to be kept in the state and history properties

from_checkpoint(file_name[, return_info])

Creates an object from a saved checkpoint

generate(n)

rtype

List[tuple]

get_negotiator(nid)

Returns the negotiator with the given ID if present in the negotiation

is_satisfying(capabilities)

Checks if the given capabilities are satisfying mechanism requirements.

is_valid(outcome)

Checks whether the outcome is valid given the issues

mutate(outcome)

Uniform crossover with random outcome

nash_point([max_cardinality, frontier])

rtype

tuple[tuple[float], Outcome]

negotiator_index(nid)

Gets the negotiator index

next_generation(parents)

Generate the next generation from parents

on_mechanism_error()

Called when there is a mechanism error

on_negotiation_end()

Called at the end of each negotiation.

on_negotiation_start()

Called before starting the negotiation.

pareto_frontier([max_cardinality, ...])

rtype

tuple[list[tuple[float]], list[tuple]]

plot(**kwargs)

A method for plotting a negotiation session

random_outcomes([n])

Returns random offers.

register_listener(event_type, listener)

Registers a listener for the given event_type.

remove(negotiator)

Remove the agent from the negotiation.

remove_requirements(requirements)

Adds requirements.

round()

Implements a single step of the mechanism.

run([timeout])

rtype

MechanismState

runall(mechanisms[, keep_order, method])

Runs all mechanisms

select(outcomes)

Select Pareto optimal outcomes

spawn([spawn_as, spawn_params])

spawn_object(*args, **kwargs)

step()

Runs a single step of the mechanism.

stepall(mechanisms[, keep_order])

Step all mechanisms

update_dominant_outcomes()

Return dominant outcomes of population

update_ranks()

Attributes Documentation

agent_ids
Return type

list[str]

agent_names
Return type

list[str]

agreement
completed
current_step
dynamic_entry
history
id

The unique ID of this entity

issues
Return type

list[Issue] | None

max_n_agents
n_outcomes
n_steps
name

A convenient name of the entity (intended primarily for printing/logging/debugging).

negotiator_ids
Return type

list[str]

negotiator_names
Return type

list[str]

negotiators
outcome_space
outcomes
participants

Returns a list of all participant names

Return type

list[NegotiatorInfo]

relative_time

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

Return type

Optional[float]

remaining_steps

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

Return type

Optional[int]

remaining_time

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

Return type

Optional[float]

requirements

A dictionary specifying the requirements that must be in the capabilities of any agent to join the mechanism.

running
short_type_name
Return type

str

state

Returns the current state. Override extra_state if you want to keep extra state

state4history

Returns the state as it should be stored in the history

Return type

Any

stats
time

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

Return type

float

time_limit
type_name
Return type

str

uuid

The unique ID of this entity

Methods Documentation

abort()

Aborts the negotiation

Return type

MechanismState

add(negotiator, *, preferences=None, role=None, ufun=None)

Add an agent to the negotiation.

Parameters
  • negotiator (Negotiator) – The agent to be added.

  • preferences (Optional[Preferences]) – The utility function to use. If None, then the agent must already have a stored utility function otherwise it will fail to enter the negotiation.

  • ufun (Optional[BaseUtilityFunction]) – [depricated] same as preferences but must be a UFun object.

  • role (Optional[str]) – The role the agent plays in the negotiation mechanism. It is expected that mechanisms inheriting from this class will check this parameter to ensure that the role is a valid role and is still possible for negotiators to join on that role. Roles may include things like moderator, representative etc based on the mechanism

Return type

Optional[bool]

Returns

  • True if the agent was added.

  • False if the agent was already in the negotiation.

  • None if the agent cannot be added. This can happen in the following cases:

    1. The capabilities of the negotiator do not match the requirements of the negotiation

    2. The outcome-space of the negotiator’s preferences do not contain the outcome-space of the negotiation

    3. The negotiator refuses to join (by returning False from its join method) see Negotiator.join for possible reasons of that

add_requirements(requirements)

Adds requirements.

Return type

None

announce(event)

Raises an event and informs all event sinks that are registered for notifications on this event type

can_accept_more_agents()

Whether the mechanism can currently accept more negotiators.

Return type

bool

can_enter(agent)

Whether the agent can enter the negotiation now.

Return type

bool

can_leave(agent)

Can the agent leave now?

Return type

bool

can_participate(agent)

Checks if the agent can participate in this type of negotiation in general.

Parameters

agent (Negotiator) –

Returns

True if it can

Return type

bool

Remarks:

The only reason this may return False is if the mechanism requires some requirements that are not within the capabilities of the agent.

When evaluating compatibility, the agent is considered incapable of participation if any of the following conditions hold: * A mechanism requirement is not in the capabilities of the agent * A mechanism requirement is in the capabilities of the agent by the values required for it

is not in the values announced by the agent.

An agent that lists a None value for a capability is announcing that it can work with all its values. On the other hand, a mechanism that lists a requirement as None announces that it accepts any value for this requirement as long as it exist in the agent

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 checkpoint

  • file_name (Optional[str]) – Name of the file to dump into. If not given, a unique name is created

  • info (Optional[dict[str, Any]]) – Information to save with the checkpoint (must be json serializable)

  • exist_ok (bool) – If true, override existing dump

  • single_checkpoint (bool) – If true, keep a single checkpoint for the last step

  • step_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

Path

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.

Return type

Optional[Path]

classmethod checkpoint_info(file_name)

Returns the information associated with a dump of the object saved in the given file

Parameters

file_name (Path | str) – Name of the object

Returns:

Return type

dict[str, Any]

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 concept

  • every (int) – Number of steps per checkpoint. If < 1 no checkpoints will be saved

  • folder (Optional[PathLike]) – The directory to store checkpoints under

  • filename (Optional[str]) – Name of the file to save the checkpoint under. If None, a unique name will be chosen. If single_checkpoint was False, then multiple files will be used prefixed with the step number

  • info (Optional[Dict[str, Any]]) – Any extra information to save in the json file associated with each checkpoint

  • exist_ok (bool) – Override existing files if any

  • single (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

Optional[Path]

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

classmethod create(*args, **kwargs)

Creates an object and returns a proxy to it.

crossover(outcome1, outcome2)[source]

Uniform crossover

Return type

tuple

discrete_outcome_space(levels=5, max_cardinality=100000)

Returns a stable discrete version of the given outcome-space

Return type

DiscreteOutcomeSpace

discrete_outcomes(levels=5, max_cardinality=inf)

A discrete set of outcomes that spans the outcome space

Parameters
  • max_cardinality (int | float) – The maximum number of outcomes to return. If None, all outcomes will be returned for discrete issues

  • continuous (and 10_000 if any of the issues was) –

Returns

list of n or less outcomes

Return type

list[Outcome]

extra_state()[source]

Returns any extra state information to be kept in the state and history properties

classmethod from_checkpoint(file_name, return_info=False)

Creates an object from a saved checkpoint

Parameters
  • file_name (Path | str) –

  • return_info – If True, tbe information saved when the file was dumped are returned

Return type

NamedObject | tuple[NamedObject, dict[str, Any]]

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

generate(n)[source]
Return type

List[tuple]

get_negotiator(nid)

Returns the negotiator with the given ID if present in the negotiation

Return type

Optional[Negotiator]

is_satisfying(capabilities)

Checks if the given capabilities are satisfying mechanism requirements.

Parameters

capabilities (dict) – capabilities to check

Return type

bool

Returns

bool are the requirements satisfied by the capabilities.

Remarks:

  • Requirements are also a dict with the following meanings:

    • tuple: Min and max acceptable values

    • list/set: Any value in the iterable is acceptable

    • Single value: The capability must match this value

  • Capabilities can also have the same three possibilities.

is_valid(outcome)

Checks whether the outcome is valid given the issues

mutate(outcome)[source]

Uniform crossover with random outcome

Return type

tuple

nash_point(max_cardinality=None, frontier=None)
Return type

tuple[tuple[float], Outcome]

negotiator_index(nid)

Gets the negotiator index

Parameters

nid (str) – nid

Return type

int | None

next_generation(parents)[source]

Generate the next generation from parents

Return type

List[tuple]

on_mechanism_error()

Called when there is a mechanism error

Remarks:
  • When overriding this function you MUST call the base class version

Return type

None

on_negotiation_end()

Called at the end of each negotiation.

Remarks:
  • When overriding this function you MUST call the base class version

Return type

None

on_negotiation_start()

Called before starting the negotiation. If it returns False then negotiation will end immediately

Return type

bool

pareto_frontier(max_cardinality=None, sort_by_welfare=True)
Return type

tuple[list[tuple[float]], list[tuple]]

plot(**kwargs)

A method for plotting a negotiation session

random_outcomes(n=1)

Returns random offers.

Parameters

n (int) – Number of outcomes to generate

Return type

list[Outcome]

Returns

A list of outcomes of at most n outcomes.

Remarks:

  • If the number of outcomes n cannot be satisfied, a smaller number will be returned

  • Sampling is done without replacement (i.e. returned outcomes are unique).

register_listener(event_type, listener)

Registers a listener for the given event_type.

Parameters
  • event_type (Optional[str]) – The type to register. If None, the listener will be registered for all types

  • listener (EventSink) – The listening agent (must have an on_event method that receives an event: Event and a sender: EventSource)

remove(negotiator)

Remove the agent from the negotiation.

Parameters

agent

Return type

Optional[bool]

Returns

  • True if the agent was removed.

  • False if the agent was not in the negotiation already.

  • None if the agent cannot be removed.

remove_requirements(requirements)

Adds requirements.

Return type

None

round()[source]

Implements a single step of the mechanism. Override this!

Return type

MechanismRoundResult

Returns

MechanismRoundResult giving whether the negotiation was broken or timedout and the agreement if any.

run(timeout=None)
Return type

MechanismState

classmethod runall(mechanisms, keep_order=True, method='serial')

Runs all mechanisms

Parameters
  • mechanisms (list['Mechanism']) – list of mechanisms

  • keep_order – if True, the mechanisms will be run in order every step otherwise the order will be randomized at every step. This is only allowed if the method is serial

  • method – the method to use for running all the sessions. Acceptable options are: serial, threads, processes

Return type

list[MechanismState | None]

Returns

  • list of states of all mechanisms after completion

  • None for any such states indicates disagreements

select(outcomes)[source]

Select Pareto optimal outcomes

Return type

List[tuple]

classmethod spawn(spawn_as='object', spawn_params=None, *args, **kwargs)
classmethod spawn_object(*args, **kwargs)
step()

Runs a single step of the mechanism.

Returns

The state of the negotiation after the round is conducted

Return type

MechanismState

Remarks:

  • Every call yields the results of one round (see round())

  • If the mechanism was yet to start, it will start it and runs one round

  • There is another function (run()) that runs the whole mechanism in blocking mode

classmethod stepall(mechanisms, keep_order=True)

Step all mechanisms

Parameters
  • mechanisms (list[Mechanism]) – list of mechanisms

  • keep_order – if True, the mechanisms will be run in order every step otherwise the order will be randomized at every step

Return type

list[MechanismState]

Returns

  • list of states of all mechanisms after completion

update_dominant_outcomes()[source]

Return dominant outcomes of population

update_ranks()[source]