UtilityFunction

class negmas.utilities.UtilityFunction(name: Optional[str] = None, reserved_value: Union[negmas.helpers.Distribution, float] = - inf, outcome_type: Optional[Type] = None, issue_names: Optional[List[str]] = None, issues: Optional[List[negmas.outcomes.Issue]] = None, ami: Optional[negmas.common.AgentMechanismInterface] = None, id: Optional[str] = None)[source]

Bases: abc.ABC, negmas.common.NamedObject

The abstract base class for all utility functions.

A utility function encapsulates a mapping from outcomes to UtilityValue(s). This is a generalization of standard utility functions that are expected to always return a real-value. This generalization is useful for modeling cases in which only partial knowledge of the utility function is available.

To define a new utility function, you have to override one of the following .. method:: - eval to define a standard ufun mapping outcomes to utility values.

- `is_better` to define prferences by a partial ordering over outcomes

implemented through bilateral comparisons

- `rank` to define the preferences by partial ordering defined by

a ranking of outcomes.

Parameters
  • name – Name of the utility function. If None, a random name will be given.

  • reserved_value – The value to return if the input offer to __call__ is None

  • outcome_type – The type to use when evauating utilities. It can be tuple, dict, or any OutcomeType

  • issue_names – The names of issues. Only needed if outcome_type is not tuple

  • issues – The list of issues for which the ufun is defined (optional)

  • ami – The AgentMechanismInterface for a mechanism for which the ufun is defined (optinoal)

  • id – An optional system-wide unique identifier. You should not change the default value except in special circumstances like during serialization and should always guarantee system-wide uniquness if you set this value explicitly

Remarks:
  • If ami is given, it overrides outcome_type, issues and issue_names

  • If issues is given, it overrides issue_names

  • One of eval, is_better, rank MUST be overriden, otherwise calling any of them will lead to an infinite loop which is very hard to debug.

Attributes Summary

ami

base_type

Returns the utility_function base type ignoring discounting and similar wrappings.

is_dynamic

Whether the utility function can potentially depend on negotiation state (mechanism information).

is_inverse_initialized

issues

outcome_type

type

Returns the utility_function type.

Methods Summary

__call__(offer)

Calculate the utility_function value for a given outcome.

approximate(ufuns, issues, n_outcomes[, …])

Approximates a list of ufuns with a list of mapping discrete ufuns

argsort(outcomes[, descending])

Finds the rank of each outcome as an integer

compare_real(o1, o2[, method])

Compares the two outcomes and returns a measure of the difference between their utilities.

conflict_level(u1, u2, outcomes[, max_tests])

Finds the conflict level in these two ufuns

eu(offer)

Calculate the expected utility value.

eval(offer)

Calculate the utility value for a given outcome.

eval_all(outcomes)

Calculates the utility value of a list of outcomes and returns their utility values

from_genius(file_name, **kwargs)

Imports a utility function from a GENIUS XML file.

from_str(s)

Creates an object out of a dict.

from_xml_str(xml_str[, domain_issues, …])

Imports a utility function from a GENIUS XML string.

generate_bilateral(outcomes[, …])

Generates a couple of utility functions

generate_random(n, outcomes[, normalized])

Generates N mapping utility functions

generate_random_bilateral(outcomes)

Generates a couple of utility functions

init_inverse([issues, outcomes, n_trials, …])

Initializes the inverse ufun used to map utilities to outcomes.

inverse(u[, eps, assume_normalized, issues, …])

Finds an outcmoe with the given utility value

is_better(first, second[, epsilon])

Compares two offers using the ufun returning whether the first is better than the second

opposition_level([ufuns, max_utils, …])

Finds the opposition level of the two ufuns defined as the minimum distance to outcome (1, 1)

outcome_with_utility(rng[, issues, …])

Gets one outcome within the given utility range or None on failure

random(issues[, reserved_value, normalized])

Generates a random ufun of the given type

rank(outcomes[, descending])

Ranks the given list of outcomes.

rank_with_weights(outcomes[, descending])

Ranks the given list of outcomes with weights.

sort(outcomes[, descending])

Sorts the given outcomes in place in ascending or descending order of utility value.

to_genius(u, issues, file_name, **kwargs)

Exports a utility function to a GENIUS XML file.

to_xml_str(u, issues[, discount_factor])

Exports a utility function to a well formatted string

uninialize_inverse()

utility_range([issues, outcomes, …])

Finds the range of the given utility function for the given outcomes

winwin_level(u1, u2, outcomes[, max_tests])

Finds the win-win level in these two ufuns

xml(issues)

Converts the function into a well formed XML string preferrably in GENIUS format.

Attributes Documentation

ami
base_type

Returns the utility_function base type ignoring discounting and similar wrappings.

is_dynamic

Whether the utility function can potentially depend on negotiation state (mechanism information).

  • If this property is False, the ufun can safely be assumed to be static (not dependent on negotiation state).

  • If this property is True, the ufun may depend on negotiation state but it may also not depend on it.

is_inverse_initialized
issues
outcome_type
type

Returns the utility_function type.

Each class inheriting from this UtilityFunction class will have its own type. The default type is the empty string.

Examples

>>> from negmas.utilities import *
>>> print(LinearUtilityAggregationFunction({1:lambda x:x, 2:lambda x:x}).type)
linear_aggregation
>>> print(MappingUtilityFunction(lambda x: x).type)
mapping
>>> print(NonLinearUtilityAggregationFunction({1:lambda x:x}, f=lambda x: x).type)
non_linear_aggregation
Returns

utility_function type

Return type

str

Methods Documentation

__call__(offer: Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]])Union[negmas.helpers.Distribution, float][source]

Calculate the utility_function value for a given outcome.

Parameters

offer – The offer to be evaluated.

Remarks:

  • It calls the abstract method eval after opationally adjusting the outcome type.

  • It is preferred to override eval instead of directly overriding this method

  • You cannot return None from overriden eval() functions but raise an exception (ValueError) if it was not possible to calculate the UtilityValue.

  • Return A UtilityValue not a float for real-valued utilities for the benefit of inspection code.

  • Return the reserved value if the offer was None

Returns

The utility_function value which may be a distribution. If None it means the

utility_function value cannot be calculated.

Return type

UtilityValue

classmethod approximate(ufuns: List[UtilityFunction], issues: Iterable[Issue], n_outcomes: int, min_per_dim=5, force_single_issue=False)Tuple[List[MappingUtilityFunction], List[Outcome], List[Issue]][source]

Approximates a list of ufuns with a list of mapping discrete ufuns

Parameters
  • ufuns – The list of ufuns to approximate

  • issues – The issues

  • n_outcomes – The number of outcomes to use in the approximation

  • min_per_dim – Minimum number of levels per continuous dimension

  • force_single_issue – Force the output to have a single issue

Returns:

argsort(outcomes: List[Optional[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]], descending=True)List[int][source]

Finds the rank of each outcome as an integer

compare_real(o1: Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]], o2: Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]], method='mean')float[source]

Compares the two outcomes and returns a measure of the difference between their utilities.

Parameters
  • o1 – First outcome

  • o2 – Second outcome

  • method

    The comparison method if one of the two outcomes result in a distribution. Acceptable values are:

    • mean: Compares the means of the two distributions

    • min: Compares minimum values with nonzero probability

    • max: Compares maximum values with nonzero probability

    • int: Calculates \(int (u_1-u_2) du_1du_2\).

    • Callable: The callable is given u(o1), u(o2) and

      should return the comparison.

classmethod conflict_level(u1: negmas.utilities.UtilityFunction, u2: negmas.utilities.UtilityFunction, outcomes: Union[int, List[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]], max_tests: int = 10000)float[source]

Finds the conflict level in these two ufuns

Parameters
  • u1 – first utility function

  • u2 – second utility function

Examples

  • A nonlinear strictly zero sum case

>>> from negmas.utilities.nonlinear import MappingUtilityFunction
>>> outcomes = [(_,) for _ in range(10)]
>>> u1 = MappingUtilityFunction(dict(zip(outcomes,
... np.random.random(len(outcomes)))))
>>> u2 = MappingUtilityFunction(dict(zip(outcomes,
... 1.0 - np.array(list(u1.mapping.values())))))
>>> print(UtilityFunction.conflict_level(u1=u1, u2=u2, outcomes=outcomes))
1.0
  • The same ufun

>>> print(UtilityFunction.conflict_level(u1=u1, u2=u1, outcomes=outcomes))
0.0
  • A linear strictly zero sum case

>>> outcomes = [(i,) for i in range(10)]
>>> u1 = MappingUtilityFunction(dict(zip(outcomes,
... np.linspace(0.0, 1.0, len(outcomes), endpoint=True))))
>>> u2 = MappingUtilityFunction(dict(zip(outcomes,
... np.linspace(1.0, 0.0, len(outcomes), endpoint=True))))
>>> print(UtilityFunction.conflict_level(u1=u1, u2=u2, outcomes=outcomes))
1.0
eu(offer: Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]])Optional[float][source]

Calculate the expected utility value.

Parameters

offer – The offer to be evaluated.

Returns

The expected utility value for UFuns that return a distribution and just utility value for real-valued utilities.

Return type

float

eval(offer: Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]])Union[negmas.helpers.Distribution, float][source]

Calculate the utility value for a given outcome.

Parameters

offer – The offer to be evaluated.

Returns

The utility_function value which may be a distribution.

If None it means the utility_function value cannot be calculated.

Return type

UtilityValue

Remarks:
  • You cannot return None from overriden eval() functions but raise an exception (ValueError) if it was not possible to calculate the UtilityValue.

  • Typehint the return type as a UtilityValue instead of a float for the benefit of inspection code.

  • Return the reserved value if the offer was None

  • NEVER call the baseclass using super() when overriding this method. Calling super will lead to an infinite loop.

  • The default implementation assumes that is_better is defined and uses it to do the evaluation. Note that the default implementation of is_better does assume that eval is defined and uses it. This means that failing to define both leads to an infinite loop.

eval_all(outcomes: List[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]])Iterable[Union[negmas.helpers.Distribution, float]][source]

Calculates the utility value of a list of outcomes and returns their utility values

Parameters

outcomes – A list of offers

Returns

An iterable with the utility values of the given outcomes in order

Remarks:
  • The default implementation just iterates over the outcomes calling the ufun for each of them. In a distributed environment, it is possible to do this in parallel using a thread-pool for example.

classmethod from_genius(file_name: Union[pathlib.Path, str], **kwargs)[source]

Imports a utility function from a GENIUS XML file.

Parameters

file_name (str) – File name to import from

Returns

A utility function object (depending on the input file)

Examples

>>> from negmas.utilities import UtilityFunction
>>> import pkg_resources
>>> u, d = UtilityFunction.from_genius(file_name = pkg_resources.resource_filename('negmas'
...                                      , resource_name='tests/data/Laptop/Laptop-C-prof1.xml'))
>>> u.__class__.__name__
'LinearUtilityAggregationFunction'
>>> u.reserved_value
0.0
>>> d
1.0
Remarks:

See from_xml_str for all the parameters

classmethod from_str(s)negmas.utilities.UtilityFunction[source]

Creates an object out of a dict.

classmethod from_xml_str(xml_str: str, domain_issues: Optional[List[negmas.outcomes.Issue]] = None, force_single_issue=False, force_numeric=False, keep_issue_names=True, keep_value_names=True, safe_parsing=True, normalize_utility=False, normalize_max_only=False, max_n_outcomes: int = 1000000, ignore_discount=False, ignore_reserved=False)[source]

Imports a utility function from a GENIUS XML string.

Parameters
  • xml_str (str) – The string containing GENIUS style XML utility function definition

  • domain_issues (List[Issue]) – Optional issue space to confirm that the utility function is valid

  • force_single_issue (bool) – Tries to generate a MappingUtility function with a single issue which is the

  • of all issues in the input (product) –

  • keep_issue_names (bool) – Keep names of issues

  • keep_value_names (bool) – Keep names of values

  • safe_parsing (bool) – Turn on extra checks

  • normalize_utility (bool) – Normalize the output utilities to the range from 0 to 1

  • normalize_max_only (bool) – If True ensures that max(utility) = 1 but does not ensure that min(utility) = 0. and if false, ensures both max(utility) = 1 and min(utility) = 0

  • max_n_outcomes (int) – Maximum number of outcomes allowed (effective only if force_single_issue is True)

Returns

A utility function object (depending on the input file)

Examples

>>> import pkg_resources
>>> u, _ = UtilityFunction.from_xml_str(open(pkg_resources.resource_filename('negmas'
...                                      , resource_name='tests/data/Laptop/Laptop-C-prof1.xml')
...                                      , 'r').read(), force_single_issue=False
...                                     , normalize_utility=True
...                                     , keep_issue_names=False, keep_value_names=True)
>>> u, _ = UtilityFunction.from_xml_str(open(pkg_resources.resource_filename('negmas'
...                                      , resource_name='tests/data/Laptop/Laptop-C-prof1.xml')
...                                      , 'r').read()
...                                      , force_single_issue=True, normalize_utility=False)
>>> assert abs(u(("Dell+60 Gb+19'' LCD",)) - 21.987727736172488) < 0.000001
>>> assert abs(u(("HP+80 Gb+20'' LCD",)) - 22.68559475583014) < 0.000001
>>> u, _ = UtilityFunction.from_xml_str(open(pkg_resources.resource_filename('negmas'
...                                      , resource_name='tests/data/Laptop/Laptop-C-prof1.xml')
...                                      , 'r').read(), force_single_issue=True
... , keep_issue_names=False, keep_value_names=False, normalize_utility=False)
>>> assert abs(u((0,)) - 21.987727736172488) < 0.000001
>>> u, _ = UtilityFunction.from_xml_str(open(pkg_resources.resource_filename('negmas'
...                                      , resource_name='tests/data/Laptop/Laptop-C-prof1.xml')
...                 , 'r').read(), force_single_issue=False, normalize_utility=False)
>>> assert abs(u({'Laptop': 'Dell', 'Harddisk': '60 Gb', 'External Monitor': "19'' LCD"}) - 21.987727736172488) < 0.000001
>>> assert abs(u({'Laptop': 'HP', 'Harddisk': '80 Gb', 'External Monitor': "20'' LCD"}) - 22.68559475583014) < 0.000001
>>> u, _ = UtilityFunction.from_xml_str(open(pkg_resources.resource_filename('negmas'
...                                      , resource_name='tests/data/Laptop/Laptop-C-prof1.xml')
...                                      , 'r').read()
...                                      , force_single_issue=True, normalize_utility=True)
>>> u, _ = UtilityFunction.from_xml_str(open(pkg_resources.resource_filename('negmas'
...                                      , resource_name='tests/data/Laptop/Laptop-C-prof1.xml')
...                                      , 'r').read(), force_single_issue=True
... , keep_issue_names=False, keep_value_names=False, normalize_utility=True)
>>> u, _ = UtilityFunction.from_xml_str(open(pkg_resources.resource_filename('negmas'
...                                      , resource_name='tests/data/Laptop/Laptop-C-prof1.xml')
...         , 'r').read(), force_single_issue=False, normalize_utility=True)
classmethod generate_bilateral(outcomes: Union[int, List[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]], conflict_level: float = 0.5, conflict_delta=0.005, win_win=0.5)Tuple[negmas.utilities.UtilityFunction, negmas.utilities.UtilityFunction][source]

Generates a couple of utility functions

Parameters
  • n_outcomes (int) – number of outcomes to use

  • conflict_level – How conflicting are the two ufuns to generate. 1.0 means maximum conflict.

  • conflict_delta – How variable is the conflict at different outcomes.

  • win_win – How much are their opportunities for win-win situations.

Examples

>>> u1, u2 = UtilityFunction.generate_bilateral(outcomes=10, conflict_level=0.0
...                                             , conflict_delta=0.0, win_win=0.0)
>>> print(UtilityFunction.conflict_level(u1, u2, outcomes=10))
0.0
>>> u1, u2 = UtilityFunction.generate_bilateral(outcomes=10, conflict_level=1.0
...                                             , conflict_delta=0.0, win_win=0.0)
>>> print(UtilityFunction.conflict_level(u1, u2, outcomes=10))
1.0
>>> u1, u2 = UtilityFunction.generate_bilateral(outcomes=10, conflict_level=0.5
...                                             , conflict_delta=0.0, win_win=1.0)
>>> 0.0 <= UtilityFunction.conflict_level(u1, u2, outcomes=10) <= 1.0
True
classmethod generate_random(n: int, outcomes: Union[int, List[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]], normalized: bool = True)List[negmas.utilities.UtilityFunction][source]

Generates N mapping utility functions

Parameters
  • n – number of utility functions to generate

  • outcomes – number of outcomes to use

  • normalized – if true, the resulting ufuns will be normlized between zero and one.

classmethod generate_random_bilateral(outcomes: Union[int, List[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]])Tuple[negmas.utilities.UtilityFunction, negmas.utilities.UtilityFunction][source]

Generates a couple of utility functions

Parameters
  • n_outcomes (int) – number of outcomes to use

  • conflict_level – How conflicting are the two ufuns to generate. 1.0 means maximum conflict.

  • conflict_delta – How variable is the conflict at different outcomes.

  • zero_summness – How zero-sum like are the two ufuns.

init_inverse(issues: Optional[List[negmas.outcomes.Issue]] = None, outcomes: Optional[List[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]] = None, n_trials: int = 10000, max_cache_size: int = 10000)None[source]

Initializes the inverse ufun used to map utilities to outcomes.

Parameters
  • issues – The issue space to be searched for inverse. If not given, the issue space of the mechanism may be used.

  • outcomes – The outcomes to consider. This takes precedence over issues

  • n_trials – Used for constraining computation if necessary

  • max_cache_size – The maximum allowed number of outcomes to cache

inverse(u: float, eps: Union[float, Tuple[float, float]] = (0.001, 0.2), assume_normalized=True, issues: Optional[List[negmas.outcomes.Issue]] = None, outcomes: Optional[List[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]] = None, n_trials: int = 10000, return_all_in_range=False, max_n_outcomes=10000)Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]], None, Tuple[List[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]], List[Union[negmas.helpers.Distribution, float]]]][source]

Finds an outcmoe with the given utility value

Parameters
  • u – the utility value to find an outcome for.

  • eps – An approximation error. If a number, it is mapped to (eps, eps)

  • n_trials – the number of time to try (used if random sampling is employed)

  • issues – If given the issue space to search (not recommended)

  • outcomes – If given the outcomes to search (not recommended)

  • assume_normalized – If true, the ufun will be assumed normalized between 0 and 1 (faster)

  • return_all_in_range – If given all outcomes in the given range (or samples of them) will be returned up to max_n_outcomes

  • max_n_outcomes – Only used if return_all_in_range is given and gives the maximum number of outcomes to return

Returns

  • A tuple with all outcomes in the given range (or samples thereof)
    • A tuple of corresponding utility values

  • Otherwise, An outcome with utility between u-eps[0] and u+eps[1] if found

Return type

  • if return_all_in_range

Remarks:
  • If issues or outcomes are not None, then init_inverse will be called first

is_better(first: Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]], second: Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]], epsilon=1e-10)Optional[bool][source]

Compares two offers using the ufun returning whether the first is better than the second

Parameters
  • first – First outcome to be compared

  • second – Second outcome to be compared

  • epsilon – comparison threshold. If the utility difference within the range [-epsilon, epsilon] the two outcomes are assumed to be compatible

Returns

True if utility(first) > utility(second) + epsilon None if |utility(first) - utility(second)| <= epsilon False if utility(first) < utility(second) - epsilon

classmethod opposition_level(ufuns=typing.List[ForwardRef('UtilityFunction')], max_utils: Union[float, Tuple[float, float]] = 1.0, outcomes: Optional[Union[int, List[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]]] = None, issues: Optional[List[negmas.outcomes.Issue]] = None, max_tests: int = 10000)float[source]

Finds the opposition level of the two ufuns defined as the minimum distance to outcome (1, 1)

Parameters
  • ufuns – A list of utility functions to use.

  • max_utils – A list of maximum utility value for each ufun (or a single number if they are equal).

  • outcomes – A list of outcomes (should be the complete issue space) or an integer giving the number of outcomes. In the later case, ufuns should expect a tuple of a single integer.

  • issues – The issues (only used if outcomes is None).

  • max_tests – The maximum number of outcomes to use. Only used if issues is given and has more outcomes than this value.

Examples

  • Opposition level of the same ufun repeated is always 0

>>> from negmas.utilities.nonlinear import MappingUtilityFunction
>>> u1, u2 = lambda x: x[0], lambda x: x[0]
>>> UtilityFunction.opposition_level([u1, u2], outcomes=10, max_utils=9)
0.0
  • Opposition level of two ufuns that are zero-sum

>>> u1, u2 = MappingUtilityFunction(lambda x: x[0]), MappingUtilityFunction(lambda x: 9 - x[0])
>>> UtilityFunction.opposition_level([u1, u2], outcomes=10, max_utils=9)
0.7114582486036499
outcome_with_utility(rng: Tuple[Optional[float], Optional[float]], issues: Optional[List[negmas.outcomes.Issue]] = None, outcomes: Optional[List[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]] = None, n_trials: int = 100)Optional[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]][source]

Gets one outcome within the given utility range or None on failure

Parameters
  • self – The utility function

  • rng – The utility range

  • issues – The issues the utility function is defined on

  • outcomes – The outcomes to sample from

  • n_trials – The maximum number of trials

Returns

  • Either issues, or outcomes should be given but not both

classmethod random(issues, reserved_value=(0.0, 0.5), normalized=True, **kwargs)negmas.utilities.UtilityFunction[source]

Generates a random ufun of the given type

rank(outcomes: List[Optional[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]], descending=True)List[int]

Ranks the given list of outcomes. None stands for the null outcome

rank_with_weights(outcomes: List[Optional[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]], descending=True)List[Tuple[int, float]][source]

Ranks the given list of outcomes with weights. None stands for the null outcome.

Returns

  • an integer giving the index in the input array (outcomes) of an outcome
    • the weight of that outcome

  • The list is sorted by weights descendingly

Return type

  • A list of tuples each with two values

sort(outcomes: List[Optional[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]], descending=True)List[Optional[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]][source]

Sorts the given outcomes in place in ascending or descending order of utility value.

Returns

Returns the input list after being sorted. Notice that the array is sorted in-place

classmethod to_genius(u: negmas.utilities.UtilityFunction, issues: List[negmas.outcomes.Issue], file_name: Union[pathlib.Path, str], **kwargs)[source]

Exports a utility function to a GENIUS XML file.

Parameters
  • file_name (str) – File name to export to

  • u – utility function

  • issues – The issues being considered as defined in the domain

Returns

None

Examples

>>> from negmas.utilities import UtilityFunction
>>> from negmas.inout import load_genius_domain
>>> import pkg_resources
>>> _, _, issues = load_genius_domain(domain_file_name=pkg_resources.resource_filename('negmas'
...                                             , resource_name='tests/data/Laptop/Laptop-C-domain.xml')
...             , keep_issue_names=False)
>>> u, discount = UtilityFunction.from_genius(file_name=pkg_resources.resource_filename('negmas'
...                                             , resource_name='tests/data/Laptop/Laptop-C-prof1.xml')
...             , keep_issue_names=False)
>>> UtilityFunction.to_genius(u=u, issues=issues, discount_factor=discount
...     , file_name = pkg_resources.resource_filename('negmas'
...                                             , resource_name='tests/data/LaptopConv/Laptop-C-prof1.xml'))
Remarks:

See to_xml_str for all the parameters

classmethod to_xml_str(u: negmas.utilities.UtilityFunction, issues: List[negmas.outcomes.Issue], discount_factor=None)str[source]

Exports a utility function to a well formatted string

uninialize_inverse()[source]
utility_range(issues: List[negmas.outcomes.Issue] = None, outcomes: Collection[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]] = None, infeasible_cutoff: Optional[float] = None, return_outcomes=False, max_n_outcomes=1000, ami: Optional[AgentMechnismInterface] = None)Union[Tuple[Union[negmas.helpers.Distribution, float], Union[negmas.helpers.Distribution, float]], Tuple[Union[negmas.helpers.Distribution, float], Union[negmas.helpers.Distribution, float], Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]], Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]][source]

Finds the range of the given utility function for the given outcomes

Parameters
  • self – The utility function

  • issues – List of issues (optional)

  • outcomes – A collection of outcomes (optional)

  • infeasible_cutoff – A value under which any utility is considered infeasible and is not used in calculation

  • return_outcomes – If true, will also return an outcome for min and max utils

  • max_n_outcomes – the maximum number of outcomes to try sampling (if sampling is used and outcomes are not given)

  • ami – Optional AMI to use

Returns

A utility function that is guaranteed to be normalized for the set of given outcomes

Return type

UtilityFunction

classmethod winwin_level(u1: negmas.utilities.UtilityFunction, u2: negmas.utilities.UtilityFunction, outcomes: Union[int, List[Union[negmas.outcomes.OutcomeType, Tuple[Union[int, float, str, list]], Dict[Union[int, str], Union[int, float, str, list]]]]], max_tests: int = 10000)float[source]

Finds the win-win level in these two ufuns

Parameters
  • u1 – first utility function

  • u2 – second utility function

Examples

  • A nonlinear same ufun case

>>> from negmas.utilities.nonlinear import MappingUtilityFunction
>>> outcomes = [(_,) for _ in range(10)]
>>> u1 = MappingUtilityFunction(dict(zip(outcomes,
... np.linspace(1.0, 0.0, len(outcomes), endpoint=True))))
  • A linear strictly zero sum case

>>> outcomes = [(_,) for _ in range(10)]
>>> u1 = MappingUtilityFunction(dict(zip(outcomes,
... np.linspace(0.0, 1.0, len(outcomes), endpoint=True))))
>>> u2 = MappingUtilityFunction(dict(zip(outcomes,
... np.linspace(1.0, 0.0, len(outcomes), endpoint=True))))
abstract xml(issues: List[negmas.outcomes.Issue])str[source]

Converts the function into a well formed XML string preferrably in GENIUS format.

If the output has with </objective> then discount factor and reserved value should also be included If the output has </utility_space> it will not be appended in to_xml_str