|
15 | 15 |
|
16 | 16 | __all__ = [ |
17 | 17 | 'Quadratic', |
| 18 | + 'Hypersphere', |
18 | 19 | 'Rosenbrock', |
19 | 20 | 'LinearConstraintsSooTestProblem', |
20 | 21 | 'LinearConstraintsSooTestProblem2', |
@@ -125,6 +126,50 @@ def test_if_solved(self, optimization_results: OptimizationResults, |
125 | 126 | np.testing.assert_allclose(x, x_true, **test_kwargs) |
126 | 127 |
|
127 | 128 |
|
| 129 | +class Hypersphere(TestProblem): |
| 130 | + def __init__(self, *args, n_var=1, **kwargs): |
| 131 | + super().__init__('quadratic', *args, **kwargs) |
| 132 | + |
| 133 | + for i in range(n_var): |
| 134 | + self.add_variable(f'x_{i}', lb=-1, ub=1) |
| 135 | + |
| 136 | + def objective_factory(i): |
| 137 | + def objective(x): |
| 138 | + return x[i] |
| 139 | + |
| 140 | + return objective |
| 141 | + |
| 142 | + for i in range(n_var): |
| 143 | + objective = objective_factory(i) |
| 144 | + |
| 145 | + self.add_objective(objective, name=f"f_{i}") |
| 146 | + |
| 147 | + self.add_nonlinear_constraint(self.hypersphere_constraint_violation) |
| 148 | + |
| 149 | + @staticmethod |
| 150 | + def hypersphere_constraint_violation(point, center=None, radius=1): |
| 151 | + """ |
| 152 | + Calculate the constraint violation for a point relative to an n-dimensional hypersphere. |
| 153 | +
|
| 154 | + Args: |
| 155 | + - center (list/tuple): The coordinates of the center of the hypersphere. |
| 156 | + - radius (float): The radius of the hypersphere. |
| 157 | + - point (list/tuple): The coordinates of the point to check. |
| 158 | +
|
| 159 | + Returns: |
| 160 | + - float: Negative value if the point is inside the hypersphere, positive if outside, |
| 161 | + where the value represents the squared distance from the surface of the hypersphere. |
| 162 | + """ |
| 163 | + if center is None: |
| 164 | + center = np.zeros((len(point),)) |
| 165 | + |
| 166 | + if len(center) != len(point): |
| 167 | + raise ValueError("Center and point must have the same dimensions") |
| 168 | + |
| 169 | + squared_distance = sum((c - p) ** 2 for c, p in zip(center, point)) |
| 170 | + return squared_distance - radius ** 2 |
| 171 | + |
| 172 | + |
128 | 173 | class Rosenbrock(TestProblem): |
129 | 174 | def __init__(self, *args, n_var=2, **kwargs): |
130 | 175 | super().__init__('rosenbrock', *args, **kwargs) |
|
0 commit comments