|
| 1 | +import numpy as np |
| 2 | +import pandas as pd |
| 3 | +from typing import Union |
| 4 | + |
| 5 | + |
| 6 | +def get_boundaries(data: np.ndarray) -> tuple[np.ndarray, np.ndarray]: |
| 7 | + """ |
| 8 | + Calculates the minimum and maximum values for each column in a NumPy array. |
| 9 | +
|
| 10 | + Args: |
| 11 | + data (np.ndarray): A NumPy array of shape (n, k), where n is the number of rows |
| 12 | + and k is the number of columns. |
| 13 | +
|
| 14 | + Returns: |
| 15 | + tuple[np.ndarray, np.ndarray]: A tuple containing two NumPy arrays: |
| 16 | + - The first array contains the minimum values for each column, with shape (k,). |
| 17 | + - The second array contains the maximum values for each column, with shape (k,). |
| 18 | +
|
| 19 | + Raises: |
| 20 | + ValueError: If the input array has shape (1, 0) (empty array). |
| 21 | +
|
| 22 | + Examples: |
| 23 | + >>> from spotpython.design.utils import get_boundaries |
| 24 | + >>> import numpy as np |
| 25 | + >>> data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) |
| 26 | + >>> min_values, max_values = get_boundaries(data) |
| 27 | + >>> print("Minimum values:", min_values) |
| 28 | + Minimum values: [1 2 3] |
| 29 | + >>> print("Maximum values:", max_values) |
| 30 | + Maximum values: [7 8 9] |
| 31 | + """ |
| 32 | + if data.size == 0: |
| 33 | + raise ValueError("Input array cannot be empty.") |
| 34 | + min_values = np.min(data, axis=0) |
| 35 | + max_values = np.max(data, axis=0) |
| 36 | + return min_values, max_values |
| 37 | + |
| 38 | + |
| 39 | +def generate_search_grid(x_min: np.ndarray, x_max: np.ndarray, n_points: int = 5, col_names: list = None) -> Union[pd.DataFrame, np.ndarray]: |
| 40 | + """ |
| 41 | + Generates a search grid based on the minimum and maximum values of each feature. |
| 42 | +
|
| 43 | + Args: |
| 44 | + x_min (np.ndarray): A NumPy array containing the minimum values for each feature. |
| 45 | + x_max (np.ndarray): A NumPy array containing the maximum values for each feature. |
| 46 | + n_points (int, optional): The number of points to generate for each feature. Defaults to 5. |
| 47 | + col_names (list, optional): A list of column names for the DataFrame. If None, a NumPy array is returned. Defaults to None. |
| 48 | +
|
| 49 | + Returns: |
| 50 | + Union[pd.DataFrame, np.ndarray]: A Pandas DataFrame representing the search grid if col_names is provided, |
| 51 | + otherwise a NumPy array. |
| 52 | +
|
| 53 | + Raises: |
| 54 | + ValueError: If the length of x_min and x_max are different. |
| 55 | +
|
| 56 | + Examples: |
| 57 | + >>> from spotpython.design.utils import generate_search_grid |
| 58 | + >>> import numpy as np |
| 59 | + >>> x_min = np.array([0, 0, 0]) |
| 60 | + >>> x_max = np.array([1, 1, 1]) |
| 61 | + >>> search_grid = generate_search_grid(x_min, x_max, num_points=3) |
| 62 | + >>> print(search_grid) |
| 63 | + [[0. 0. 0. ] |
| 64 | + [0. 0. 0.5] |
| 65 | + [0. 0. 1. ] |
| 66 | + ... |
| 67 | + [1. 1. 0.5] |
| 68 | + [1. 1. 1. ]] |
| 69 | +
|
| 70 | + >>> search_grid = generate_search_grid(x_min, x_max, num_points=3, col_names=['feature_0', 'feature_1', 'feature_2']) |
| 71 | + >>> print(search_grid) |
| 72 | + feature_0 feature_1 feature_2 |
| 73 | + 0 0.0 0.00 0.00 |
| 74 | + 1 0.0 0.00 0.50 |
| 75 | + 2 0.0 0.00 1.00 |
| 76 | + 3 0.0 0.50 0.00 |
| 77 | + 4 0.0 0.50 0.50 |
| 78 | + .. ... ... ... |
| 79 | + 22 1.0 1.00 0.50 |
| 80 | + 23 1.0 1.00 1.00 |
| 81 | +
|
| 82 | + [27 rows x 3 columns] |
| 83 | + """ |
| 84 | + if len(x_min) != len(x_max): |
| 85 | + raise ValueError("x_min and x_max must have the same length.") |
| 86 | + |
| 87 | + num_features = len(x_min) |
| 88 | + # Create linspace for each dimension |
| 89 | + ranges = [np.linspace(x_min[i], x_max[i], n_points) for i in range(num_features)] |
| 90 | + |
| 91 | + # Use meshgrid to create all combinations |
| 92 | + # The maximum number of inputs for np.broadcast is 32 |
| 93 | + if num_features > 30: |
| 94 | + raise ValueError("Too many features for meshgrid. Maximum 30 features are supported.") |
| 95 | + mesh = np.meshgrid(*ranges, indexing="ij") |
| 96 | + |
| 97 | + # Reshape the meshgrid output to a list of points |
| 98 | + points = np.array([m.ravel() for m in mesh]).T |
| 99 | + |
| 100 | + if col_names: |
| 101 | + # Create a Pandas DataFrame from the points |
| 102 | + if len(col_names) != num_features: |
| 103 | + raise ValueError("The number of column names must match the number of features.") |
| 104 | + search_grid = pd.DataFrame(points, columns=col_names) |
| 105 | + return search_grid |
| 106 | + else: |
| 107 | + return points |
| 108 | + |
| 109 | + |
| 110 | +def map_to_original_scale(X_search: Union[pd.DataFrame, np.ndarray], x_min: np.ndarray, x_max: np.ndarray) -> Union[pd.DataFrame, np.ndarray]: |
| 111 | + """ |
| 112 | + Maps the values in X_search from the range [0, 1] to the original scale defined by x_min and x_max. |
| 113 | +
|
| 114 | + Args: |
| 115 | + X_search (Union[pd.DataFrame, np.ndarray]): A Pandas DataFrame or NumPy array containing the search points in the range [0, 1]. |
| 116 | + x_min (np.ndarray): A NumPy array containing the minimum values for each feature in the original scale. |
| 117 | + x_max (np.ndarray): A NumPy array containing the maximum values for each feature in the original scale. |
| 118 | +
|
| 119 | + Returns: |
| 120 | + Union[pd.DataFrame, np.ndarray]: A Pandas DataFrame or NumPy array with the values mapped to the original scale. |
| 121 | +
|
| 122 | + Examples: |
| 123 | + >>> from spotpython.design.utils import map_to_original_scale |
| 124 | + >>> import numpy as np |
| 125 | + >>> import pandas as pd |
| 126 | + >>> X_search = pd.DataFrame([[0.5, 0.5], [0.25, 0.75]], columns=['x', 'y']) |
| 127 | + >>> x_min = np.array([0, 0]) |
| 128 | + >>> x_max = np.array([10, 20]) |
| 129 | + >>> X_search_scaled = map_to_original_scale(X_search, x_min, x_max) |
| 130 | + >>> print(X_search_scaled) |
| 131 | + x y |
| 132 | + 0 5.0 10.0 |
| 133 | + 1 2.5 15.0 |
| 134 | + """ |
| 135 | + if not isinstance(X_search, (pd.DataFrame, np.ndarray)): |
| 136 | + raise TypeError("X_search must be a Pandas DataFrame or a NumPy array.") |
| 137 | + |
| 138 | + if len(x_min) != X_search.shape[1]: |
| 139 | + raise IndexError(f"x_min and X_search must have the same number of columns. x_min has {len(x_min)} columns and X_search has {X_search.shape[1]} columns.") |
| 140 | + if len(x_max) != X_search.shape[1]: |
| 141 | + raise IndexError(f"x_max and X_search must have the same number of columns. x_max has {len(x_max)} columns and X_search has {X_search.shape[1]} columns.") |
| 142 | + |
| 143 | + if isinstance(X_search, pd.DataFrame): |
| 144 | + X_search_scaled = X_search.copy() # Create a copy to avoid modifying the original DataFrame |
| 145 | + for i, col in enumerate(X_search.columns): |
| 146 | + X_search_scaled.loc[:, col] = X_search[col] * (x_max[i] - x_min[i]) + x_min[i] |
| 147 | + return X_search_scaled |
| 148 | + elif isinstance(X_search, np.ndarray): |
| 149 | + X_search_scaled = X_search.copy() # Create a copy to avoid modifying the original array |
| 150 | + for i in range(X_search.shape[1]): |
| 151 | + X_search_scaled[:, i] = X_search[:, i] * (x_max[i] - x_min[i]) + x_min[i] |
| 152 | + return X_search_scaled |
0 commit comments