Skip to content

Commit fbc4488

Browse files
committed
Add Hypersphere TestProblem to optimization fixtures
1 parent 0b0fe10 commit fbc4488

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

tests/optimization_problem_fixtures.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
__all__ = [
1616
'Quadratic',
17+
'Hypersphere',
1718
'Rosenbrock',
1819
'LinearConstraintsSooTestProblem',
1920
'LinearConstraintsSooTestProblem2',
@@ -127,6 +128,50 @@ def test_if_solved(self, optimization_results: OptimizationResults,
127128
np.testing.assert_allclose(x, x_true, **test_kwargs)
128129

129130

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+
130175
class Rosenbrock(TestProblem):
131176
def __init__(self, *args, n_var=2, **kwargs):
132177
super().__init__('rosenbrock', *args, **kwargs)

0 commit comments

Comments
 (0)