#!/usr/bin/env python
# coding: utf-8
# In[1]:
# This is to make the results reproducible if you are using the Jupyter notebook version.
from rich import print
from random import seed
seed(0)
# # Overview
#
# negmas was designed mainly as a research and educational tool with special emphasis on supporting multi-strand multilateral multi-issue negotiations with complex utility
# functions. This section gives an introduction to the main concepts of the public interface.
#
# In order to use the library you will need to import it as follows (assuming that you followed the instructions in the installation section of this document):
# In[2]:
import negmas
# To simplify the use of this platform, all classes and functions from all base modules are aliased in the root package (except generics and helpers). This is an example of importing just `Outcome` which is defined in the `outcomes` package
# In[3]:
from negmas import Outcome
# It is possible *but not recommended* to just import everything in the package using:
# In[4]:
from negmas import *
from negmas.helpers import *
from negmas.helpers.prob import *
# ## Organization
#
# The package is organized into a set of modules/packages that combine together related functionality. There are base modules, protocol specific modules, advanced and helper modules.
#
# * **Base Modules** Implements basic automated negotiation functionality:
# 1. **outcomes** This module represents issues, outcome and responses and provides basic functions and methods to operator with and on them.
# 1. **preferences** This modules represents the base type of all preferences and different widely used utility function types including linear and nonlinear utilities and constraint-based utilities. This module also implements basic analysis tools like finding the pareto-frontier, sampling outcomes with given utilities from the outcome space, etc.
# 1. **negotiators** This module represents basic negotiation agent implementation and provides basic interfaces to be overriden (implemented) by higher specialized modules
# 1. **mechanisms** This module represents the most basic conceptual view of a negotiation protocol supporting both mediate and unmediated mechanisms. The term `mechanism` was used instead of the more common `protocol` to stress the fact that this mechanism need not be a standard negotiation protocol. For example auction mechanisms (like second-price auctions) can easily be implemented as a `Mechanism` in negmas.
# 1. **common** Provides data structures that are used by all modules including mechanism-state, and the agent-mechanism-interface.
# 1. **genius** Implements a specific type negotiator for the stacked alternating offers protocol called `GeniusNegotiator` which can run `NegotiationParty` based agents from the Java [Genius](http://ii.tudelft.nl/genius/) platform.
#
# * **Mechanism Specific Modules** These modules implement the base mechanism, negotiator type(s), state, and related computational resources specific to a single (or a set of related) negotiation/auction protocols
# 1. **sao** Implements that stacked alternating offers protocol for unmediated multiparty multi-issue negotiations. Other than providing the `SAOMechanism` class representing the protocol, this package provides a set of simple negotiators including the time-based `AspirationNegotiator`, a `SimpleTitForTatNegotiator`, among others.
# 1. **st** Implements two basic single-text mediated negotiation protocols (veto and hill-climbing) and the basic negotiator types to support them.
# 1. **mt** Implements and extension of single text mediated protocols to handle multiple *proposed agreements* in parallel.
# 1. **ga** Implements a Genetic Algorithm based single text mediated negotiation protocol
#
# * **Advanced Negotiation Modules** These modules model advanced negotiation problems and techniques
# 1. **situated** Implements world simulations within which agents with intrinsic utility functions can engage in simultaneous interconnected situated negotiations. It is the most important module for the goals of this library. The `Agent` and `World` classes described in details later belong to this module
# 1. **modeling** This is a set of submodules implementing modeling of opponent utility, opponent strategy, opponent's future offers and opponent's probability of accepting offers.
# 1. **elicitation** Implements several preference elicitation during negotiation methods.
# 1. **concurrent** Implements mechanism types, and other computational resources to support concurrent negotiation.
#
# * **Helper Modules** These modules provide basic activities that is not directly related to the negotiation but that are relied upon by different base modules. The end user is not expected to interact directly with these modules.
# * **common** Provides common interfaces that are used by all other modules.
# * **helpers** Various helper functions and classes used throughout the library including mixins for logging.
# * **inout** Provides functions to load and store XML Genius domains and utility functions.
# * **java** \[Depricated\] Provides an interface to JNegMAS allowing agents and negotiators to be developed in Java.
# * **tournaments** Supports creating and running tournaments to compare agents and negotiators.
# * **checkpoints** Supports saving and reloading world simulations to/from secondary storage.
# * **visualizers** \[Under development\] Supports visualization of world simulation, negotiation sessions, negotiators, and agents.
# * **generics** Provides a set of types and interfaces to increase the representation flexibility of different base modules.
#
# ## A (not very) brief introduction to NegMAS
#
# This figure shows the main active components of a simulation in a NegMAS world:
# ![NegMAS world](figs/world.png)
#
# The simulation is run using a **World** object which defines what happens in
# every simulation **step**, provides a **BulletinBoard** object containing all
# public information about the game, calls various callbacks defined in the
# **Agent** object representing each agent in the environment, takes care of
# running negotiations and keeps track of agreement signing and the resulting
# **Contract**s. The **World** object also controls logging, event management,
# serialization, visualization, etc. Refer to the
# [World](http://www.yasserm.com/negmas/api/negmas.situated.World.html)
# documentation for more details (*you need to do that only if you are
# implementing new world simulations*).
#
# The designer of the game implements a **World** class by overriding few
# abstract methods in the base **World** class.
#
# The logic of an agent is NegMAS is implemented in an **Agent** object. The
# designer of the simulation, should provide a base class for its specific world
# inherited from NegMAS's **Agent** class. Refer to the
# [Agent](http://www.yasserm.com/negmas/api/negmas.situated.Agent.html)
# documentation for more details about general NegMAS agents.
#
# So now we have the **World** and the **Agent** objects, and we already said
# that the agent does not directly interact with the world. How does these two
# types of entities interact then?
#
# - When the **World** wants to interact with the **Agent**, it calls some method
# in it. For example, to instruct the agent to *initialize* itself, the world
# calls the **init()** method defined by the **Agent**. To inform the agent
# that a negotiation it is involved in is concluded with success, the **World**
# calls the method **on_negotiation_success()** defined by the agent.
# - When the **Agent** wants to interact with the **World**, it accesses an
# interface object called an **AgentWorldInterface** or **AWI** for short which
# provides all the services available to the **Agent**. For example, to request
# a negotiation with another agent, the **Agent** object needs to call
# **request_negotiation()** defined in the **AWI**.
#
# The world designer usually defines an AWI for its world that inherits NegMAS's
# **AgentWorldInterface** class and provides any special services for agents
# interacting in this world. You can find all the services available to your agent
# through the AgentWorldInterface
# [here](http://www.yasserm.com/negmas/api/negmas.situated.AgentWorldInterface.html).
# These methods and properties are still available for your agent in SCML. Nevertheless,
# in many cases, more convenient ways to access some of the information (e.g. the
# bulletin board) is provided in the specific AWIs implemented in the SCML package
# to be described now.
#
# Now that we know how worlds and agents work and interact, we can look at how
# negotiation is managed in NegMAS. **Note that you can create negotiations that do
# not belong to any world**
#
# A negotiation is controlled by a **Mechanism** object which implements the
# negotiation protocol (e.g. the alternating offers protocol). NegMAS provides
# several mediated and unmediated negotiation protocols (as well as auction
# mechanisms). The specific **Mechanism** that is used in SCML is the
# **SAOMechanism** which implements the bargaining protocol.
#
# Negotiation strategies are implemented in a **Negotiator** object which usually
# inherits some base negotiator-class corresponding to the mechanism(s) it supports.
#
# The interaction between **Mechanism** and **Negotiator** objects mirrors the
# interaction between **World** and **Agent** objects. **Mechanism** objects call
# methods in **Negotiator** objects directly but **Negotiator** objects can only
# access services provided by the **Mechanism** object through a
# **NegotiatorMechanismInterface** (AMI). You can find more details about the general NegMAS NMI
# [here](http://www.yasserm.com/negmas/api/negmas.common.NegotiatorMechanismInterface.html).
#
# Each specific **Mechanism** defines a corresponding specific
# **AgentMechanismInterface** class (in the same way that **World** classes
# define their own AWI).
#
# To negotiate effectively, negotiators employ a **UtilityFunction**
# (or any other form of **Preferences** objects) to represent
# their preferences over different possible **Outcome**s of the negotiation
# (where an outcome is a full assignment of values to all negotiated **Issue**s).
# NegMAS provides an extensive set of preferences types, utility functions, and issue types. Please
# refer to this [overview](http://www.yasserm.com/negmas/overview.html) and
# [tutorials](http://www.yasserm.com/negmas/tutorials.html) for more details.
# NegMAS also provides some basic **SAONegotiator**s for the **SAOMechanism**
# (Check the class diagram
# [here](http://www.yasserm.com/negmas/modules/sao.html)). Moreover, you can
# access almost all [Genius](http://ii.tudelft.nl/genius/) agents using NegMAS's
# [GeniusNegotiator](http://www.yasserm.com/negmas/api/negmas.genius.GeniusNegotiator.html)
# including all finalists and winners of all past ANAC competitions.
#
# Now we understand how agents interact with worlds through AWIs and negotiators
# interact with mechanisms through AMIs. We know that the general simulation is
# controlled by the world while each negotiation is controlled by a mechanism
# within that world. **We need now to connect these two triplets of objects**
#
# As the figure above shows: **Negotiator** objects can be created and controlled
# by **Agent** objects for the purpose of negotiating with other **Agent**
# objects. The standard flow of operations is something like this:
#
# 1. **Agent** A uses its AWI to *request_negotiation()* with Agent B passing a
# **Negotiator** to be used in this negotiation. Usually Agent A will also
# create a **UtilityFunction** and attach it to the **Negotiator** it just
# created (by setting its *ufun* attribute).
# 2. The **World** calls Agent B's *respond_to_negotiation_request()* asking it
# to provide its own **Negotiator** to negotiate with Agent A's Negotiator. It
# can also just reject the negotiation request by returning no negotiators.
# 3. The **World** will then create a **Mechanism** and ask both **Negotiator**s
# to *join* it. If all goes well, the negotiation starts (at a time defined
# by the simulation rules) and runs until either an agreement or disagreement
# is reached.
# 4. The **World** class will then inform **Agent**s A and B about the results of
# the negotiation using their *on_negotiation_success* and
# *on_negotiation_failure* callbacks.
# 5. Successful negotiations lead to **Agreement**s but are still not binding in
# general until signed by all agents involved (A and B in this case).
# **Agent**'s '*sign_all_contracts* is used for this.
# 6. Signed agreements become *Contract*s and are executed (as specified in the
# simulation rules) by the **World**.
#
# When negotiations are independent, these are all the objects needed.
# Nevertheless, in many cases, negotiations are
# inter-dependent. This means that what is *good* in one negotiation depends on
# other concurrently running negotiations (or on expectations of future
# negotiations). NegMAS provides two ways to support this case shown in the
# following figure:
#
# ![controllers](figs/controllers.png)
#
# 1. Let **Negotiator**s use **UtilityFunction**s that depend on some common
# state. That is what is happening in the left two negotiations.
# 2. Have multiple **Negotiator**s be controlled by a single **Controller**
# object with its own utility function that depends on what is happening on
# all the negotiations controlled.
#
# The **Negotiator**s connected to a controller lost their autonomy and just pass
# control to their *owning* **Controller**.
#
# This concludes our introduction to NegMAS and different objects you need to know
# about to develop your agent.
# ## Outcomes, Issues and Outcome Spaces
#
# Negotiations are conducted between multiple agents with the goal of achieving an *agreement* (usually called a contract) on one of several possible outcomes. Each *outcome* is in general an assignment of some value to a set of issues. Each *issue* is a variable that can take one of a -- probably infinite -- set of values from some predefined *domain*.
#
# The classes and functions supporting management of issues, outcome-spaces and outcomes are implemented in the `outcomes` module.
#
# Issues are represented in ``negmas`` using the `Issue` class. An issue is defined by a set of ``values`` and a ``name``.
#
# NegMAS supports a variety of `Issue` types.
# * Using a set of strings:
# In[5]:
# an issue with randomly assigned name
issue1 = make_issue(values=['to be', 'not to be'])
print(issue1)
# an issue with given name:
issue2 = make_issue(values=['to be', 'not to be'], name='The Problem')
print(issue2)
# * Using a single integer to give an issue which takes any value from `0` to the given integer minus 1:
# In[6]:
issue3 = make_issue(values=10, name='number of items')
print(issue3)
# * Using a `tuple` with a lower and upper real-valued boundaries to give an issue with an infinite number of possibilities (all real numbers in between)
# In[7]:
issue4 = make_issue(values=(0.0, 1.0), name='cost')
print(issue4)
# The `Issue` class provides some useful functions. For example you can find the ``cardinality`` of any issue using:
# In[8]:
[issue2.cardinality, issue3.cardinality, issue4.cardinality]
# It is also possible to check the `type` of the issue and whether it is discrete or continuous:
# In[9]:
[issue2.type, issue2.is_discrete(), issue2.is_continuous()]
# It is possible to check the total cardinality for a set of issues:
# In[10]:
[num_outcomes([issue1, issue2, issue3, issue4]), # expected inf
num_outcomes([issue1, issue2, issue3])] # expected 40 = 2 * 2 * 10
# You can pick random valid or invalid values for the issue:
# In[11]:
[
[issue1.rand_valid(), issue1.rand_invalid()],
[issue3.rand_valid(), issue3.rand_invalid()],
[issue4.rand_valid(), issue4.rand_invalid()],
]
# You can also list all valid values for an issue using `all` or sample from them using `value_generator`. Notice that `all` and `value_generator` return generators so both are memory efficient.
# In[12]:
print(tuple(issue1.all))
print(tuple(issue2.all))
print(tuple(issue3.all))
try:
print(tuple(issue4.all))
except ValueError as e:
print(e)
# ### Outcomes
# Now that we know how to define issues, defining outcomes from a negotiation is even simpler. An outcome can be any python `mapping` or `iterable` with a known length. That includes dictionaries, lists, tuples among many other.
#
# Here is how to define an outcome for the last three issues mentioned above:
# In[13]:
valid_outcome = {'The Problem': 'to be', 'number of items': 5, 'cost': 0.15}
invalid_outcome = {'The Problem': 'to be', 'number of items': 10, 'cost': 0.15}
# Notice that the ``invalid_outcome`` is assigning a value of ``10`` to the ``number of items`` issue which is not an acceptable value (``cost`` ranges between ``0`` and ``9``).
#
# Because `outcomes` can be represented with many built-in collection classes, the only common ancestor of all outcome objects is the `object` class. Nevertheless, the `outcomes` module provide a type-alias `Outcome` that can be used for static type checking if needed. The `outcomes` module also provides some functions for dealing with `outcome` objects in relation to `Issue`s. These are some examples:
# In[14]:
[
outcome_is_valid(valid_outcome, [issue2, issue3, issue4]), # valid giving True
outcome_is_valid(invalid_outcome, [issue2, issue3, issue4]) # invalid giving False
]
# It is not necessary for an outcome to assign a value for *all* issues to be considered *valid*. For example the following outcomes are all valid for the last three issues given above:
#
# In[15]:
[
outcome_is_valid({'The Problem': 'to be'}, [issue2, issue3, issue4]),
outcome_is_valid({'The Problem': 'to be', 'number of items': 5}, [issue2, issue3, issue4])
]
# You can check the validity of outcomes defined as tuples or lists the same way.
# In[16]:
[
outcome_is_valid(['to be', 4, 0.5], [issue2, issue3, issue4]),
outcome_is_valid(('to be', 4, 1.5), [issue2, issue3, issue4])
]
# It is also important for some applications to check if an outcome is `complete` in the sense that it assigns a *valid* value to every issue in the given set of issues. This can be done using the `outcome_is_complete` function:
# In[17]:
[
outcome_is_complete(valid_outcome, [issue2, issue3, issue4]), # complete -> True
outcome_is_complete(invalid_outcome, [issue2, issue3, issue4]), # invalid -> incomplete -> False
outcome_is_complete({'The Problem': 'to be'}, [issue2, issue3, issue4]) # incomplete -> False
]
# #### Outcome Ranges and constraints
# Sometimes, it is important to represent not only a single outcome but a range of outcomes. This can be represented using an `OutcomeRange`. Again, an outcome range can be almost any `mapping` or `iterable` in python including dictionaries, lists, tuples, etc with the only exception that the values stored in it can be not only be `int`, `str`, `float` but also `tuple`s of two of any of them representing a range or a `list` of values. This is easier shown:
# In[18]:
range1 = {'The Problem': ['to be', 'not to be'], 'number of items': 5, 'cost': (0.1, 0.2)}
# ``range1`` represents the following range of outcomes:
#
# * **The Problem**: accepts both ``to be`` and ``not to be``
#
# * **number of items**: accepts only the value ``5``
#
# * **cost**: accepts any real number between ``0.1`` and ``0.2`` up to representation error
#
# It is easy to check whether a specific outcome is within a given range:
# In[19]:
outcome1 = {'The Problem': 'to be', 'number of items': 5, 'cost': 0.15}
outcome2 = {'The Problem': 'to be', 'number of items': 10, 'cost': 0.15}
[
outcome_in_range(outcome1, range1), # True
outcome_in_range(outcome2, range1) # False
]
# In general outcome ranges constraint outcomes depending on the type of the constraint:
#
# * **tuple** The outcome must fall within the range specified by the first and second elements. Only valid for values that can be compared using `__lt__` (e.g. int, float, str).
# * **single value** The outcome must equal this given value.
# * **list of values** The outcome must be within the list.
# * **list of tuples** The outcome must fall within one of the ranges specified by the tuples.
#
#
# ### Outcome Spaces
#
# An outcome-space is a *set of outcomes* which can be enumerated, sampled, etc.
#
# NegMAS supports a special kind of outcome-spaces called `CartesianOutcomeSpace` which represents the Cartesian product of a set of issues and can be created using `make_os` function:
# In[20]:
myos = make_os([issue1, issue2, issue3, issue4])
print(type(myos))
# A special case of `CartesianOutcomeSpace` is a `DiscreteCartesianOutcomeSpace` (see the examle above) which represent a Cartesian outcome-space with discrete issues (i.e. no issues are continuous).
#
# `OutcomeSpace` provide convenient methods for gettin information about the outcome-space or manipulating it. Some of the most important examples are:
#
# - **is_numeric, is_integer, is_float** Checks if all components of all outcomes are numeric, integer or float.
# - **is_discrete, is_finite, is_continuous** Check if the outcome space itself is discrete, finite or continuous.
# - **cardinality** returns the number of outcomes in the outcome-space.
# - **cardinality_if_discretized** returns the number of outcomes in the outcome-space if we discretize it.
# - **to_discrete, to_largest_discrete** create an discrete outcome-space that ranges over the input outcome-space.
# - **sample** returns outcomes from the outcome-space.
# - **enumerate_or_sample** sample from continuous outcome-spaces and enumerate all outcomes of discrete outcome-spaces.
#
#
# `DiscreteOutcomeSpace` is a special case of `OutcomeSpace` representing a finite outcome space and adds some operations including:
#
# - **to_single_issue** generates a single-issue outcome-space with the same number of outcomes as the given outcome-space
# - **limit_cardinality** generates a discrete outcome-space that *approximates* the input outcome-space using at most some predefined number of outcomes.
#
# ## Utilities and Preferences
# Agents engage in negotiations to maximize their utility. That is the central dogma in negotiation research. `negmas` allows the user to define their own utility functions based on a set of predefined base classes that can be found in the `utilities` module.
#
# ### Utility Values
# In most applications, utility values can be represented by real numbers. Nevertheless, some applications need a more complicated representation. For example, during utility elicitation (the process of learning about the utility function of the human being represented by the agent) or opponent modeling (the process of learning about the utility function of an opponent), the need may arise to represent a probability distribution over utilities.
#
# `negmas` allows all functions that receive a utility value to receive a utility distribution. This is achieved through the use of two basic type definitions:
#
# * `Distribution` That is a probability distribution class capable of representing probabilistic variables having both continuous and discrete distributions and applying basic operations on them (addition, subtraction and multiplication). Currently we use `scipy.stats` for modeling these distributions but this is an implementation detail that should not be relied upon as it is likely that the probabilistic framework will be changed in the future to enhance the flexibility of the package and its integration with other probabilistic modeling packages (e.g. PyMC3). A concrete implementation of `Distribution` provided by NegMAS is `ScipyDistribution`. A special case if the `Real` distribution which represents a delta distribution $\delta(v)$ at a given real value $v$ (i.e. $p(x)=1$ for $x=v$ and $0$ otherwise) which acts both as a `Distribution` and a `float`.
#
# * `Value` This is the input and output type used whenever a utility value is to be represented in the whole package. It is defined as a union of a real value and a `Distribution` (`float | Distribution`). This way, it is possible to pass utility distributions to most functions expecting (or returning) a utility value including utility functions.
#
# This means that both of the following are valid utility values
# In[21]:
u1 = Real(1.0)
u2 = UniformDistribution() # standard normal distribution
print(u1)
print(u2)
# ### Preferences
#
# `Rational` entities in NegMAS (including `Agent`s, `Negotiator`s, and `Controller`s) can have `Preferences` which define how much they prefer an `Outcome` over another. Several types of preferences are supported in NegMAS and they all must implement the `BasePref` protocol.
#
# ### Ordinal and Cardinal Preferences
#
# The most general `Preferences` type in NegMAS is `Ordinal` `Preferences` which can only represent partial ordering of outcomes in the outcome-space throgh the `is_not_worse()` method. An entity with this kind of preferences can compare two outcomes but it gets one bit of information out of this comparison (which is better for the entity) and has no way to know *how much* is the difference
#
# `CarindalProb` `Preferences`, on the other hand, implement `difference_prob()` which return a `Distribution` indicating *how much* is the difference between two outcomes. A crisp version (`CardinalCrisp`) moreover implements `difference()` which returns a `float` indicating *exactly* the difference in value for the entity between two outcomes.
#
# Every `CadrinalCrisp` object is a `CardinalProb` which is also an `Ordinal` object.
#
# ### Crisp and Prob Preferences
#
# NegMAS usually implements two versions of each `Preferences` type (other than `Ordinal`) that represent a probabilistic version (ending with `Prob`) returing `Distribution`s when queried, and a crisp version (ending with `Crisp`) returning a `float`. This simplifies the development of agents and negotiators working with probability distributions.
#
# ### Stationary and Non-Stationary Preferences
#
# Stationary `Preferences` are those that *do not change during the lifetime of their owner*, while non-stationary `Preferences` are allowed to change. The entity having non-stationary preferences usually faces a harder problem achieving its goals as it needs to take into account this possible change. Entities interacting with other entities with non-stationary `Preferences` are also in reatively harder situation comapred with those dealing with entities with stationary `Preferences`.
#
# Stationary Preference type names start with `Stationary` (e.g. `StationaryCardinalProb`) while non-stationary types start with `NonStationary` (e.g. `NonStationaryCardinalProb`).
#
#
# ### Utility Functions
#
# Utility functions are entities that take an `Outcome` and return its `Value`. There are many types of utility functions defined in the literature. In this package, the base of all utiliy functions is the `BaseUtilityFunction` class which is defined in the `preferences.ufun` module. It behaves like a standard python `Callable` which can be called with a single `Outcome` object (i.e. a dictionary, list, tuple etc representing an outcome) and returns a `Value`. This allows utility functions to return a distribution instead of a single utility value. Special cases are `UtilityFunction` which is the base class of all crisp ufuns (returning a `float` when called) and `ProbUtilityFunction` which is the base class of all probabilistic ufuns (returning a `Distribution` when called).
#
# Utility functions in `negmas` have a helper `property` called `type` which returns the type of the utility function and a helper function `eu` for returning the expected utility of a given outcome which is guaranteed to return a real number (`float`) even if the utiliy function itself is returning a utility distribution.
#
# To implement a specific utility function, you need to override the single `eval` function provided in the `UtilityFunction`/`ProbUtilityFunction` abstract base class. This is a simple example:
#
# In[22]:
COST = 0
class ConstUtilityFunction(UtilityFunction):
def eval(self, offer):
try:
return 3.0 * offer[COST]
except KeyError: # No value was given to the cost
return None
def xml(self):
return '