Skip to content

Commit

Permalink
Using InitVar in optimization problem test
Browse files Browse the repository at this point in the history
  • Loading branch information
S-Dafarra committed Apr 6, 2023
1 parent 875bd1a commit 34ba2dd
Showing 1 changed file with 12 additions and 10 deletions.
22 changes: 12 additions & 10 deletions test/test_optimization_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,37 +18,39 @@
@dataclasses.dataclass
class MyTestVar(OptimizationObject):
variable: StorageType = default_storage_field(ContinuousVariable)
size: dataclasses.InitVar[int] = dataclasses.field(default=3)

def __post_init__(self):
self.variable = np.zeros(3)
def __post_init__(self, size: int = 3):
self.variable = np.zeros(size)


def test_opti_solver():
size = 4
problem = OptimizationProblem()
var = problem.generate_optimization_objects(input_structure=MyTestVar())
var = problem.generate_optimization_objects(input_structure=MyTestVar(size=size))
np.random.seed(123)
a = 10.0 * np.random.rand(3) + 0.01
b = 20.0 * np.random.rand(3) - 10.0
c = 20.0 * np.random.rand(3) - 10.0
a = 10.0 * np.random.rand(size) + 0.01
b = 20.0 * np.random.rand(size) - 10.0
c = 20.0 * np.random.rand(size) - 10.0

problem.add_expression(
mode=ExpressionType.minimize,
expression=(
a[k] * cs.power(var.variable[k], 2) + b[k] * var.variable[k]
for k in range(0, 3)
for k in range(size)
),
)

problem.add_expression(
mode=ExpressionType.subject_to,
expression=(var.variable[k] >= c[k] for k in range(3)), # noqa
expression=(var.variable[k] >= c[k] for k in range(size)), # noqa
)

output, cost_value = problem.solver().solve()

expected_x = np.zeros(3)
expected_x = np.zeros(size)
expected_cost = 0
for i in range(3):
for i in range(size):
expected = -b[i] / (2 * a[i])
expected_x[i] = expected if expected >= c[i] else c[i]
expected_cost += (
Expand Down

0 comments on commit 34ba2dd

Please sign in to comment.