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