eckity.genetic_encodings.gp.tree.utils

This module implements some utility functions.

  1"""
  2This module implements some utility functions.
  3"""
  4
  5from typing import Callable, Dict, List, Union, get_type_hints
  6
  7import numpy as np
  8
  9from eckity.base.utils import arity
 10
 11
 12def create_terminal_set(
 13    X: np.ndarray, typed=False
 14) -> Union[List[str], Dict[str, type]]:
 15    """
 16    Create a terminal set from a 2D-shaped numpy array.
 17
 18    Example: \n
 19        X = array([[  4,   7,  -7, -10],  \n
 20                   [  7,  -3,   3,  -8],  \n
 21                   [  8,  -5,  -3,  -1]])
 22
 23    Returns the list: \n
 24        ['x0', 'x1', 'x2', 'x3']
 25
 26    Parameters
 27    ----------
 28    X : 2d numpy array
 29        The array from which we wish to extract features -- which will become terminals.
 30
 31    Returns
 32    -------
 33    Terminal set (a list).
 34
 35    """
 36
 37    features = [f"x{i}" for i in range(X.shape[1])]
 38    if not typed:
 39        return features
 40    # convert numpy dtypes to python types
 41    return {x: type(X[0, i].item()) for i, x in enumerate(features)}
 42
 43
 44def generate_args(X: np.ndarray) -> Dict[str, np.ndarray]:
 45    """
 46    Generate keyword arguments from a 2d array for passing to GPTree.execute.
 47
 48    Example: \n
 49        X = array([[  4,   7,  -7, -10],  \n
 50                   [  7,  -3,   3,  -8],  \n
 51                   [  8,  -5,  -3,  -1]])
 52
 53    Returns the dict: \n
 54        {'x0': array([4, 7, 8]), \n
 55         'x1': array([ 7, -3, -5]), \n
 56         'x2': array([-7,  3, -3]), \n
 57         'x3': array([-10,  -8,  -1])}
 58
 59    Returns
 60    -------
 61    kwargs : dict
 62        A keyword dictionary that includes a value for every variable x_i in the terminal set.
 63
 64    """
 65
 66    return {f"x{i}": X[:, i] for i in range(X.shape[1])}
 67
 68
 69def get_func_types(f: Callable) -> List[type]:
 70    """
 71    Return list of function types in the following format:
 72    [type_arg_1, type_arg_2, ..., type_arg_n, return_type]
 73
 74    Parameters
 75    ----------
 76    f : Callable
 77        function (builtin or user-defined)
 78
 79    Returns
 80    -------
 81    List[type]
 82        List of function types, sorted by argument order
 83        with the return type as the last element.
 84        For untyped functions, None is used.
 85
 86    Examples
 87    --------
 88    >>> def f(x: int, y: float) -> float:
 89    ...     return x + y
 90    >>> get_func_types(f)
 91    [int, float, float]
 92
 93    >>> def f(x, y):
 94    ...     return x + y
 95    >>> get_func_types(f)
 96    [None, None, None]
 97    """
 98    params_types: Dict = get_type_hints(f)
 99    type_list = list(params_types.values())
100    if not type_list:
101        # If we don't have type hints, assign None
102        type_list = [None] * (arity(f) + 1)
103    return type_list
104
105
106def get_return_type(func: Callable) -> type:
107    return get_type_hints(func).get("return", None)
def create_terminal_set(X: numpy.ndarray, typed=False) -> Union[List[str], Dict[str, type]]:
13def create_terminal_set(
14    X: np.ndarray, typed=False
15) -> Union[List[str], Dict[str, type]]:
16    """
17    Create a terminal set from a 2D-shaped numpy array.
18
19    Example: \n
20        X = array([[  4,   7,  -7, -10],  \n
21                   [  7,  -3,   3,  -8],  \n
22                   [  8,  -5,  -3,  -1]])
23
24    Returns the list: \n
25        ['x0', 'x1', 'x2', 'x3']
26
27    Parameters
28    ----------
29    X : 2d numpy array
30        The array from which we wish to extract features -- which will become terminals.
31
32    Returns
33    -------
34    Terminal set (a list).
35
36    """
37
38    features = [f"x{i}" for i in range(X.shape[1])]
39    if not typed:
40        return features
41    # convert numpy dtypes to python types
42    return {x: type(X[0, i].item()) for i, x in enumerate(features)}

Create a terminal set from a 2D-shaped numpy array.

Example:

X = array([[  4,   7,  -7, -10],  

           [  7,  -3,   3,  -8],  

           [  8,  -5,  -3,  -1]])

Returns the list:

['x0', 'x1', 'x2', 'x3']
Parameters
  • X (2d numpy array): The array from which we wish to extract features -- which will become terminals.
Returns
  • Terminal set (a list).
def generate_args(X: numpy.ndarray) -> Dict[str, numpy.ndarray]:
45def generate_args(X: np.ndarray) -> Dict[str, np.ndarray]:
46    """
47    Generate keyword arguments from a 2d array for passing to GPTree.execute.
48
49    Example: \n
50        X = array([[  4,   7,  -7, -10],  \n
51                   [  7,  -3,   3,  -8],  \n
52                   [  8,  -5,  -3,  -1]])
53
54    Returns the dict: \n
55        {'x0': array([4, 7, 8]), \n
56         'x1': array([ 7, -3, -5]), \n
57         'x2': array([-7,  3, -3]), \n
58         'x3': array([-10,  -8,  -1])}
59
60    Returns
61    -------
62    kwargs : dict
63        A keyword dictionary that includes a value for every variable x_i in the terminal set.
64
65    """
66
67    return {f"x{i}": X[:, i] for i in range(X.shape[1])}

Generate keyword arguments from a 2d array for passing to GPTree.execute.

Example:

X = array([[  4,   7,  -7, -10],  

           [  7,  -3,   3,  -8],  

           [  8,  -5,  -3,  -1]])

Returns the dict:

{'x0': array([4, 7, 8]), 

 'x1': array([ 7, -3, -5]), 

 'x2': array([-7,  3, -3]), 

 'x3': array([-10,  -8,  -1])}
Returns
  • kwargs (dict): A keyword dictionary that includes a value for every variable x_i in the terminal set.
def get_func_types(f: Callable) -> List[type]:
 70def get_func_types(f: Callable) -> List[type]:
 71    """
 72    Return list of function types in the following format:
 73    [type_arg_1, type_arg_2, ..., type_arg_n, return_type]
 74
 75    Parameters
 76    ----------
 77    f : Callable
 78        function (builtin or user-defined)
 79
 80    Returns
 81    -------
 82    List[type]
 83        List of function types, sorted by argument order
 84        with the return type as the last element.
 85        For untyped functions, None is used.
 86
 87    Examples
 88    --------
 89    >>> def f(x: int, y: float) -> float:
 90    ...     return x + y
 91    >>> get_func_types(f)
 92    [int, float, float]
 93
 94    >>> def f(x, y):
 95    ...     return x + y
 96    >>> get_func_types(f)
 97    [None, None, None]
 98    """
 99    params_types: Dict = get_type_hints(f)
100    type_list = list(params_types.values())
101    if not type_list:
102        # If we don't have type hints, assign None
103        type_list = [None] * (arity(f) + 1)
104    return type_list

Return list of function types in the following format: [type_arg_1, type_arg_2, ..., type_arg_n, return_type]

Parameters
  • f (Callable): function (builtin or user-defined)
Returns
  • List[type]: List of function types, sorted by argument order with the return type as the last element. For untyped functions, None is used.
Examples
>>> def f(x: int, y: float) -> float:
...     return x + y
>>> get_func_types(f)
[int, float, float]
>>> def f(x, y):
...     return x + y
>>> get_func_types(f)
[None, None, None]
def get_return_type(func: Callable) -> type:
107def get_return_type(func: Callable) -> type:
108    return get_type_hints(func).get("return", None)