negmas.helpers

Helper modueles

class negmas.helpers.PathLike[source]

Bases: ABC

Abstract base class for implementing the file system path protocol.

class negmas.helpers.ReturnCause(*values)[source]

Bases: Enum

ReturnCause implementation.

FAILURE = 2[source]
SUCCESS = 1[source]
TIMEOUT = 0[source]
class negmas.helpers.TimeoutCaller[source]

Bases: object

TimeoutCaller implementation.

classmethod cleanup()[source]

Cleanup.

classmethod get_pool()[source]

Returns the shared thread pool, creating it if necessary.

pool = <concurrent.futures.thread.ThreadPoolExecutor object>[source]
classmethod run(to_run, timeout: float)[source]

Run.

Parameters:
  • to_run – To run.

  • timeout – Timeout.

exception negmas.helpers.TimeoutError[source]

Bases: OSError

Timeout expired.

negmas.helpers.camel_case(s: str, capitalize_first: bool = False, lower_first: bool = False) str[source]

Converts a string from snake_case to CamelCase

Example

>>> print(camel_case("this_is_a_test"))
thisIsATest
>>> print(camel_case("this_is_a_test", capitalize_first=True))
ThisIsATest
>>> print(camel_case("This_is_a_test", lower_first=True))
thisIsATest
>>> print(camel_case("This_is_a_test"))
ThisIsATest
Parameters:
  • s – input string

  • capitalize_first – if true, the first character will be capitalized

  • lower_first – If true, the first character will be lowered

Returns:

converted string

Return type:

str

negmas.helpers.create_loggers(file_name: str | None = None, module_name: str | None = None, screen_level: int | None = 30, file_level: int | None = 10, format_str: str = '%(asctime)s - %(levelname)s - %(message)s', colored: bool = True, app_wide_log_file: bool = True, module_wide_log_file: bool = False) Logger[source]

Create a set of loggers to report feedback.

The logger created can log to both a file and the screen at the same time with adjustable level for each of them. The default is to log everything to the file and to log WARNING at least to the screen

Parameters:
  • module_wide_log_file

  • app_wide_log_file

  • file_name – The file to export_to the logs to. If None only the screen is used for logging. If empty, a time-stamp is used

  • module_name – The module name to use. If not given the file name without .py is used

  • screen_level – level of the screen logger

  • file_level – level of the file logger

  • format_str – the format of logged items

  • colored – whether or not to try using colored logs

Returns:

The logger

Return type:

logging.Logger

negmas.helpers.distribute_integer_randomly(n: int, m: int, min_per_bin: int | None = 1) list[int][source]

Distributes an integer n over a list of m values randomly, with each value at least one.

Parameters:
  • n – The integer to distribute.

  • m – The number of values to distribute over.

  • min_per_bin – Minimum number of elements per bin. This is only guaranteed if n >= m * min_per_bin. If None, then the distribution will be as normal as possible

Returns:

A list of m integers, where each value is at least one.

Remarks:
  • if n < m * min_per_bin, n will be distributed randomly with some zeros inserted.

negmas.helpers.exception2str(limit=None, chain=True) str[source]

Exception2str.

Parameters:
  • limit – Limit.

  • chain – Chain.

Returns:

The result.

Return type:

str

negmas.helpers.floatin(x: float | tuple[float, float] | Sequence[float], log_uniform: bool) float[source]

Samples a value. A random choice is made if x is another sequence, a value between the two limits is used if the input is a tuple otherwise x is returned

negmas.helpers.force_single_thread(on: bool = True)[source]

Forces negmas to use a single thread for all internal calls.

Remarks:
  • This will have the effect of not enforcing time-limits on calls.

  • Only use this with caution and for debugging.

negmas.helpers.generate_random_weights(n)[source]

Generates a list of n random weights between 0 and 1 that sum to 1.

Parameters:

n – The number of weights to generate.

Returns:

A list of n random weights between 0 and 1 that sum to 1.

negmas.helpers.get_class(class_name: str | type, module_name: str | None = None, scope: dict | None = None, allow_nonstandard_names=False, extra_modules: tuple[str, ...] = (), extra_paths: tuple[str | Path, ...] = ()) type[source]

Imports and creates a class object for the given class name

negmas.helpers.get_free_tcp_port()[source]

Get free tcp port.

negmas.helpers.get_full_type_name(t: None) None[source]
negmas.helpers.get_full_type_name(t: str) str
negmas.helpers.get_full_type_name(t: type[Any] | Callable) str

Gets the full type name of a type. You should not pass an instance to this function but it may just work.

An exception is that if the input is of type str or if it is None, it will be returned as it is

negmas.helpers.humanize_time(secs: int | float | None, align=False, always_show_all_units=False, show_us=False, show_ms=False, always_show_from='') str | None[source]

Prints time that is given as seconds in human readable form. Useful only for times >=1sec.

Parameters:
  • secs – float: number of seconds

  • align – bool, optional: whether to align outputs so that they all take the same size (not implemented)

  • always_show_all_units – bool, optional: Whether to always show days, hours, and minutes even when they are zeros. default False

  • always_show_from – One of d,h,m,s,ms,u (day, hour, minute, second, milli-sec, micro-sec) to always show as well as everything shorter than it (i.e passing ‘m’ shows minutes, seconds, … etc)

  • show_us – bool, if given microseconds and milliseconds will be shown

  • show_ms – bool, if given milliseconds will be shown

Returns:

str: formated string with the humanized form

negmas.helpers.import_by_name(full_name: str) Any[source]

Imports something form a module using its full name

negmas.helpers.instantiate(class_name: str | type | None, module_name: str | None = None, scope: dict | None = None, **kwargs) Any[source]

Imports and instantiates an object of a class

negmas.helpers.intin(x: int | tuple[int, int] | Sequence[int], log_uniform: bool = False) int[source]

Samples a value. A random choice is made if x is another sequence, a value between the two limits is used if the input is a tuple otherwise x is returned

negmas.helpers.is_jsonable(x)[source]

Check if an object can be serialized to JSON.

Parameters:

x – Object to test for JSON compatibility

Returns:

True if the object can be serialized to JSON, False otherwise

Return type:

bool

negmas.helpers.is_lambda_function(obj)[source]

Checks if the given object is a lambda function

negmas.helpers.is_lambda_or_partial_function(obj)[source]

Checks if the given object is a lambda function or a partial function

negmas.helpers.is_not_lambda_nor_partial_function(obj)[source]

Checks if the given object is not a lambda function

negmas.helpers.is_partial_function(obj)[source]

Checks if the given object is a lambda function

negmas.helpers.is_type(obj)[source]

Checks if the given object is a type converted to string

negmas.helpers.jit(nopython=True)[source]

Jit.

Parameters:

nopython – Nopython.

negmas.helpers.make_callable(x: dict | Sequence | Callable | None) Callable[source]

Converts its input to a callable (i.e. can be called using () operator).

Examples

>>> make_callable(lambda x: 2 * x)(4)
8
>>> make_callable(dict(a=1, b=3))("a")
1
>>> make_callable((3, 4, 5))(1)
4
negmas.helpers.monotonic_minmax(input: HasMinMax, f: Callable[[Any], float]) tuple[float, float][source]

Finds the limits of a function f for the input assuming that it is monotonic and input has min_value and max_value members

negmas.helpers.monotonic_multi_minmax(input: Iterable[HasMinMax], f: Callable[[Any], float]) tuple[float, float][source]

Finds the limits of a function f for the input assuming that it is monotonic and each input has min_value and max_value members

negmas.helpers.nonmonotonic_minmax(input: Iterable, f: Callable[[Any], float]) tuple[float, float][source]

Finds the limits of a function f for the input assuming that it is non-monotonic and input is iterable

negmas.helpers.nonmonotonic_multi_minmax(input: Iterable[Iterable], f: Callable[[Any], float]) tuple[float, float][source]

Finds the limits of a function f for each input assuming that it is non-monotonic and input is iterable

negmas.helpers.pretty_string(src, tab_size=2, compact=False) str[source]

Recursively print nested elements.

Parameters:
  • src (Any) – The source to be converted to a printable string

  • tab_size (int) – Tab size in spaces

  • compact (bool) – If true the output is converted into a single line

Returns:

The pretty version of the input

Return type:

str

Remarks:
  • This function assumes that the patterns `` “`` and ": do not appear anywhere in the input. If they appear, the space, : will be removed.

negmas.helpers.shorten(name: str, length: int = 4, common_parts=('Mechanism', 'Negotiator', 'Agent', 'Controller', 'Acceptance', 'Component', 'Model', 'Strategy', 'Offering', 'Entity')) str[source]

Returns a short version of the name.

Remarks:
  • Removes common parts of names in negmas like Negotiator, Agent, etc

  • Keeps Capital letters up to the given length

  • Adds some of the lowercase letters to fit the length

  • If the input is shorter than the length, it is returned as it is

negmas.helpers.shortest_unique_names(strs: list[str], sep='.', max_compression=False, guarantee_unique=False)[source]

Finds the shortest unique strings starting from the end of each input string based on the separator.

The final strings will only be unique if the inputs are unique.

Parameters:
  • strs – A list of strings

  • sep – The separator used to separate fields in each string

  • max_compression – If True, each string will be further compressed by taking the shortest prefix that keeps the strings unique (if they were originally unique)

  • guarantee_unique – If given, random characters will be postfixed on strings to guarantee uniquness

Example

given [“a.b.cat”, “d.e.f”, “a.d.cat”] it will generate [“b.c”, “f”, “d.cat”] if max_compression was false and will generate [“b”, “f”, “d”] if it was True

negmas.helpers.single_thread()[source]

Context manager that temporarily forces single-threaded execution.

negmas.helpers.snake_case(s: str) str[source]

Converts a string from CamelCase to snake_case

Example

>>> print(snake_case("ThisIsATest"))
this_is_a_test
Parameters:

s – input string

Returns:

converted string

Return type:

str

negmas.helpers.unique_name(base, add_time=True, add_host=False, rand_digits=8, sep='/') str[source]

Return a unique name.

Can be used to return a unique directory name on the givn base.

Parameters:
  • base – (any): base path/string (it is converted to string whatever it is)

  • add_time (bool, optional) – Defaults to True. Add current time

  • rand_digits (int, optional) – Defaults to 8. The number of random characters to add to the name

Examples

>>> a = unique_name("")
>>> len(a) == 8 + 1 + 6 + 8 + 6
True
Returns:

The unique name.

Return type:

str