forked from pytorch/botorch
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest_parameter_constraints.py
659 lines (622 loc) · 26 KB
/
test_parameter_constraints.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from collections.abc import Callable
from itertools import product
import numpy as np
import torch
from botorch.exceptions.errors import CandidateGenerationError, UnsupportedError
from botorch.optim.parameter_constraints import (
_arrayify,
_generate_unfixed_lin_constraints,
_generate_unfixed_nonlin_constraints,
_make_linear_constraints,
_make_nonlinear_constraints,
eval_lin_constraint,
evaluate_feasibility,
INTRA_POINT_CONST_ERR,
lin_constraint_jac,
make_scipy_bounds,
make_scipy_linear_constraints,
make_scipy_nonlinear_inequality_constraints,
nonlinear_constraint_is_feasible,
)
from botorch.utils.testing import BotorchTestCase
from scipy.optimize import Bounds
class TestParameterConstraints(BotorchTestCase):
def test_arrayify(self):
for dtype in (torch.float, torch.double, torch.int, torch.long):
t = torch.tensor([[1, 2], [3, 4]], device=self.device).type(dtype)
t_np = _arrayify(t)
self.assertIsInstance(t_np, np.ndarray)
self.assertTrue(t_np.dtype == np.float64)
def test_eval_lin_constraint(self):
res = eval_lin_constraint(
flat_idxr=[0, 2],
coeffs=np.array([1.0, -2.0]),
rhs=0.5,
x=np.array([1.0, 2.0, 3.0]),
)
self.assertEqual(res, -5.5)
def test_lin_constraint_jac(self):
dummy_array = np.array([1.0])
res = lin_constraint_jac(
dummy_array, flat_idxr=[0, 2], coeffs=np.array([1.0, -2.0]), n=3
)
self.assertTrue(all(np.equal(res, np.array([1.0, 0.0, -2.0]))))
def test_make_nonlinear_constraints(self):
def nlc(x):
return 4 - x.sum()
def f_np_wrapper(x: np.ndarray, f: Callable):
"""Given a torch callable, compute value + grad given a numpy array."""
X = (
torch.from_numpy(x)
.to(self.device)
.view(shapeX)
.contiguous()
.requires_grad_(True)
)
loss = f(X).sum()
# compute gradient w.r.t. the inputs (does not accumulate in leaves)
gradf = _arrayify(torch.autograd.grad(loss, X)[0].contiguous().view(-1))
fval = loss.item()
return fval, gradf
shapeX = torch.Size((3, 2, 4))
b, q, d = shapeX
x = np.random.rand(shapeX.numel())
# intra
constraints = _make_nonlinear_constraints(
f_np_wrapper=f_np_wrapper, nlc=nlc, is_intrapoint=True, shapeX=shapeX
)
self.assertEqual(len(constraints), b * q)
self.assertTrue(
all(set(c.keys()) == {"fun", "jac", "type"} for c in constraints)
)
self.assertTrue(all(c["type"] == "ineq" for c in constraints))
self.assertEqual(constraints[0]["fun"](x), 4.0 - x[:d].sum())
self.assertEqual(constraints[1]["fun"](x), 4.0 - x[d : 2 * d].sum())
jac_exp = np.zeros(shapeX.numel())
jac_exp[:4] = -1
self.assertTrue(np.allclose(constraints[0]["jac"](x), jac_exp))
jac_exp = np.zeros(shapeX.numel())
jac_exp[4:8] = -1
self.assertTrue(np.allclose(constraints[1]["jac"](x), jac_exp))
# inter
constraints = _make_nonlinear_constraints(
f_np_wrapper=f_np_wrapper, nlc=nlc, is_intrapoint=False, shapeX=shapeX
)
self.assertEqual(len(constraints), 3)
self.assertTrue(
all(set(c.keys()) == {"fun", "jac", "type"} for c in constraints)
)
self.assertTrue(all(c["type"] == "ineq" for c in constraints))
self.assertTrue(np.allclose(constraints[0]["fun"](x), 4.0 - x[: q * d].sum()))
self.assertTrue(
np.allclose(constraints[1]["fun"](x), 4.0 - x[q * d : 2 * q * d].sum())
)
jac_exp = np.zeros(shapeX.numel())
jac_exp[: q * d] = -1.0
self.assertTrue(np.allclose(constraints[0]["jac"](x), jac_exp))
jac_exp = np.zeros(shapeX.numel())
jac_exp[q * d : 2 * q * d] = -1.0
self.assertTrue(np.allclose(constraints[1]["jac"](x), jac_exp))
def test_make_scipy_nonlinear_inequality_constraints(self):
def nlc(x):
return 4 - x.sum()
def f_np_wrapper(x: np.ndarray, f: Callable):
"""Given a torch callable, compute value + grad given a numpy array."""
X = (
torch.from_numpy(x)
.to(self.device)
.view(shapeX)
.contiguous()
.requires_grad_(True)
)
loss = f(X).sum()
# compute gradient w.r.t. the inputs (does not accumulate in leaves)
gradf = _arrayify(torch.autograd.grad(loss, X)[0].contiguous().view(-1))
fval = loss.item()
return fval, gradf
shapeX = torch.Size((3, 2, 4))
b, q, _ = shapeX
x = torch.ones(shapeX.numel(), device=self.device)
with self.assertRaisesRegex(
ValueError, f"A nonlinear constraint has to be a tuple, got {type(nlc)}."
):
make_scipy_nonlinear_inequality_constraints([nlc], f_np_wrapper, x, shapeX)
with self.assertRaisesRegex(
ValueError,
"A nonlinear constraint has to be a tuple of length 2, got length 1.",
):
make_scipy_nonlinear_inequality_constraints(
[(nlc,)], f_np_wrapper, x, shapeX
)
with self.assertRaisesRegex(
ValueError,
"`batch_initial_conditions` must satisfy the non-linear inequality "
"constraints.",
):
make_scipy_nonlinear_inequality_constraints(
[(nlc, False)], f_np_wrapper, x, shapeX
)
# empty list
res = make_scipy_nonlinear_inequality_constraints([], f_np_wrapper, x, shapeX)
self.assertEqual(res, [])
# only inter
x = torch.zeros(shapeX.numel(), device=self.device)
res = make_scipy_nonlinear_inequality_constraints(
[(nlc, False)], f_np_wrapper, x, shapeX
)
self.assertEqual(len(res), b)
# only intra
res = make_scipy_nonlinear_inequality_constraints(
[(nlc, True)], f_np_wrapper, x, shapeX
)
self.assertEqual(len(res), b * q)
# intra and inter
res = make_scipy_nonlinear_inequality_constraints(
[(nlc, True), (nlc, False)], f_np_wrapper, x, shapeX
)
self.assertEqual(len(res), b * q + b)
def test_make_linear_constraints(self):
# equality constraints, 1d indices
indices = torch.tensor([1, 2], dtype=torch.long, device=self.device)
for dtype, shapeX in product(
(torch.float, torch.double), (torch.Size([3, 2, 4]), torch.Size([2, 4]))
):
coefficients = torch.tensor([1.0, 2.0], dtype=dtype, device=self.device)
constraints = _make_linear_constraints(
indices=indices,
coefficients=coefficients,
rhs=1.0,
shapeX=shapeX,
eq=True,
)
self.assertTrue(
all(set(c.keys()) == {"fun", "jac", "type"} for c in constraints)
)
self.assertTrue(all(c["type"] == "eq" for c in constraints))
self.assertEqual(len(constraints), shapeX[:-1].numel())
x = np.random.rand(shapeX.numel())
self.assertEqual(constraints[0]["fun"](x), x[1] + 2 * x[2] - 1.0)
jac_exp = np.zeros(shapeX.numel())
jac_exp[[1, 2]] = [1, 2]
self.assertTrue(np.allclose(constraints[0]["jac"](x), jac_exp))
self.assertEqual(constraints[-1]["fun"](x), x[-3] + 2 * x[-2] - 1.0)
jac_exp = np.zeros(shapeX.numel())
jac_exp[[-3, -2]] = [1, 2]
self.assertTrue(np.allclose(constraints[-1]["jac"](x), jac_exp))
# inequality constraints, 1d indices
for shapeX in [torch.Size([1, 1, 2]), torch.Size([1, 2])]:
lcs = _make_linear_constraints(
indices=torch.tensor([1]),
coefficients=torch.tensor([1.0]),
rhs=1.0,
shapeX=shapeX,
eq=False,
)
self.assertEqual(len(lcs), 1)
self.assertEqual(lcs[0]["type"], "ineq")
# constraint across q-batch (2d indics), equality constraint
indices = torch.tensor([[0, 3], [1, 2]], dtype=torch.long, device=self.device)
for dtype, shapeX in product(
(torch.float, torch.double), (torch.Size([3, 2, 4]), torch.Size([2, 4]))
):
q, d = shapeX[-2:]
b = 1 if len(shapeX) == 2 else shapeX[0]
coefficients = torch.tensor([1.0, 2.0], dtype=dtype, device=self.device)
constraints = _make_linear_constraints(
indices=indices,
coefficients=coefficients,
rhs=1.0,
shapeX=shapeX,
eq=True,
)
self.assertTrue(
all(set(c.keys()) == {"fun", "jac", "type"} for c in constraints)
)
self.assertTrue(all(c["type"] == "eq" for c in constraints))
self.assertEqual(len(constraints), b)
x = np.random.rand(shapeX.numel())
offsets = [q * d, d]
# rule is [i, j, k] is i * offset[0] + j * offset[1] + k
for i in range(b):
pos1 = i * offsets[0] + 3
pos2 = i * offsets[0] + 1 * offsets[1] + 2
self.assertEqual(constraints[i]["fun"](x), x[pos1] + 2 * x[pos2] - 1.0)
jac_exp = np.zeros(shapeX.numel())
jac_exp[[pos1, pos2]] = [1, 2]
self.assertTrue(np.allclose(constraints[i]["jac"](x), jac_exp))
# make sure error is raised for scalar tensors
with self.assertRaises(ValueError):
constraints = _make_linear_constraints(
indices=torch.tensor(0),
coefficients=torch.tensor([1.0]),
rhs=1.0,
shapeX=torch.Size([1, 1, 2]),
eq=False,
)
# test that len(shapeX) < 2 raises an error
with self.assertRaises(UnsupportedError):
_make_linear_constraints(
shapeX=torch.Size([2]),
indices=indices,
coefficients=coefficients,
rhs=0.0,
)
def test_make_scipy_linear_constraints(self):
for shapeX in [torch.Size([2, 1, 4]), torch.Size([1, 4])]:
b = shapeX[0] if len(shapeX) == 3 else 1
res = make_scipy_linear_constraints(
shapeX=shapeX, inequality_constraints=None, equality_constraints=None
)
self.assertEqual(res, [])
indices = torch.tensor([0, 1], dtype=torch.long, device=self.device)
coefficients = torch.tensor([1.5, -1.0], device=self.device)
# both inequality and equality constraints
cs = make_scipy_linear_constraints(
shapeX=shapeX,
inequality_constraints=[(indices, coefficients, 1.0)],
equality_constraints=[(indices, coefficients, 1.0)],
)
self.assertEqual(len(cs), 2 * b)
self.assertTrue({c["type"] for c in cs} == {"ineq", "eq"})
# inequality only
cs = make_scipy_linear_constraints(
shapeX=shapeX, inequality_constraints=[(indices, coefficients, 1.0)]
)
self.assertEqual(len(cs), b)
self.assertTrue(all(c["type"] == "ineq" for c in cs))
# equality only
cs = make_scipy_linear_constraints(
shapeX=shapeX, equality_constraints=[(indices, coefficients, 1.0)]
)
self.assertEqual(len(cs), b)
self.assertTrue(all(c["type"] == "eq" for c in cs))
# test that 2-dim indices work properly
indices = indices.unsqueeze(0)
cs = make_scipy_linear_constraints(
shapeX=shapeX,
inequality_constraints=[(indices, coefficients, 1.0)],
equality_constraints=[(indices, coefficients, 1.0)],
)
self.assertEqual(len(cs), 2 * b)
self.assertTrue({c["type"] for c in cs} == {"ineq", "eq"})
def test_make_scipy_linear_constraints_unsupported(self):
shapeX = torch.Size([2, 1, 4])
coefficients = torch.tensor([1.5, -1.0], device=self.device)
# test that >2-dim indices raises an UnsupportedError
indices = torch.tensor([0, 1], dtype=torch.long, device=self.device)
indices = indices.unsqueeze(0).unsqueeze(0)
with self.assertRaises(UnsupportedError):
make_scipy_linear_constraints(
shapeX=shapeX,
inequality_constraints=[(indices, coefficients, 1.0)],
equality_constraints=[(indices, coefficients, 1.0)],
)
# test that out of bounds index raises an error
indices = torch.tensor([0, 4], dtype=torch.long, device=self.device)
with self.assertRaises(RuntimeError):
make_scipy_linear_constraints(
shapeX=shapeX,
inequality_constraints=[(indices, coefficients, 1.0)],
equality_constraints=[(indices, coefficients, 1.0)],
)
# test that two-d index out-of-bounds raises an error
# q out of bounds
indices = torch.tensor([[0, 0], [1, 0]], dtype=torch.long, device=self.device)
with self.assertRaises(RuntimeError):
make_scipy_linear_constraints(
shapeX=shapeX,
inequality_constraints=[(indices, coefficients, 1.0)],
equality_constraints=[(indices, coefficients, 1.0)],
)
# d out of bounds
indices = torch.tensor([[0, 0], [0, 4]], dtype=torch.long, device=self.device)
with self.assertRaises(RuntimeError):
make_scipy_linear_constraints(
shapeX=shapeX,
inequality_constraints=[(indices, coefficients, 1.0)],
equality_constraints=[(indices, coefficients, 1.0)],
)
def test_nonlinear_constraint_is_feasible(self):
def nlc(x):
return 4 - x.sum()
self.assertTrue(
nonlinear_constraint_is_feasible(
nlc, True, torch.tensor([[[1.5, 1.5], [1.5, 1.5]]], device=self.device)
)
)
self.assertFalse(
nonlinear_constraint_is_feasible(
nlc,
True,
torch.tensor(
[[[1.5, 1.5], [1.5, 1.5], [3.5, 1.5]]], device=self.device
),
)
)
self.assertFalse(
nonlinear_constraint_is_feasible(
nlc,
True,
torch.tensor(
[[[1.5, 1.5], [1.5, 1.5]], [[1.5, 1.5], [1.5, 3.5]]],
device=self.device,
),
)
)
self.assertTrue(
nonlinear_constraint_is_feasible(
nlc, False, torch.tensor([[[1.0, 1.0], [1.0, 1.0]]], device=self.device)
)
)
self.assertTrue(
nonlinear_constraint_is_feasible(
nlc,
False,
torch.tensor(
[[[1.0, 1.0], [1.0, 1.0]], [[1.0, 1.0], [1.0, 1.0]]],
device=self.device,
),
)
)
self.assertFalse(
nonlinear_constraint_is_feasible(
nlc, False, torch.tensor([[[1.5, 1.5], [1.5, 1.5]]], device=self.device)
)
)
self.assertFalse(
nonlinear_constraint_is_feasible(
nlc,
False,
torch.tensor(
[[[1.0, 1.0], [1.0, 1.0]], [[1.5, 1.5], [1.5, 1.5]]],
device=self.device,
),
)
)
def test_generate_unfixed_nonlin_constraints(self):
def nlc1(x):
return 4 - x.sum(dim=-1)
def nlc2(x):
return x[..., 0] - 1
# first test with one constraint
(new_nlc1,) = _generate_unfixed_nonlin_constraints(
constraints=[(nlc1, True)], fixed_features={1: 2.0}, dimension=3
)
self.assertAllClose(
nlc1(torch.tensor([[4.0, 2.0, 2.0]], device=self.device)),
new_nlc1[0](torch.tensor([[4.0, 2.0]], device=self.device)),
)
# test with several constraints
constraints = [(nlc1, True), (nlc2, True)]
new_constraints = _generate_unfixed_nonlin_constraints(
constraints=constraints, fixed_features={1: 2.0}, dimension=3
)
for nlc, new_nlc in zip(constraints, new_constraints):
self.assertAllClose(
nlc[0](torch.tensor([[4.0, 2.0, 2.0]], device=self.device)),
new_nlc[0](torch.tensor([[4.0, 2.0]], device=self.device)),
)
# test with several constraints and two fixes
constraints = [(nlc1, True), (nlc2, True)]
new_constraints = _generate_unfixed_nonlin_constraints(
constraints=constraints, fixed_features={1: 2.0, 2: 1.0}, dimension=3
)
for nlc, new_nlc in zip(constraints, new_constraints):
self.assertAllClose(
nlc[0](torch.tensor([[4.0, 2.0, 1.0]], device=self.device)),
new_nlc[0](torch.tensor([[4.0]], device=self.device)),
)
def test_generate_unfixed_lin_constraints(self):
# Case 1: some fixed features are in the indices
indices = [
torch.arange(4, device=self.device),
torch.arange(2, -1, -1, device=self.device),
]
coefficients = [
torch.tensor([-0.1, 0.2, -0.3, 0.4], device=self.device),
torch.tensor([-0.1, 0.3, -0.5], device=self.device),
]
rhs = [0.5, 0.5]
dimension = 4
fixed_features = {1: 1, 3: 2}
new_constraints = _generate_unfixed_lin_constraints(
constraints=list(zip(indices, coefficients, rhs)),
fixed_features=fixed_features,
dimension=dimension,
eq=False,
)
for i, (new_indices, new_coefficients, new_rhs) in enumerate(new_constraints):
if i % 2 == 0: # first list of indices is [0, 1, 2, 3]
self.assertTrue(
torch.equal(new_indices, torch.arange(2, device=self.device))
)
else: # second list of indices is [2, 1, 0]
self.assertTrue(
torch.equal(
new_indices, torch.arange(1, -1, -1, device=self.device)
)
)
mask = [True] * indices[i].shape[0]
subtract = 0
for j, old_idx in enumerate(indices[i]):
if old_idx.item() in fixed_features:
mask[j] = False
subtract += fixed_features[old_idx.item()] * coefficients[i][j]
self.assertTrue(torch.equal(new_coefficients, coefficients[i][mask]))
self.assertEqual(new_rhs, rhs[i] - subtract)
# Case 2: none of fixed features are in the indices, but have to be renumbered
indices = [
torch.arange(2, 6, device=self.device),
torch.arange(5, 2, -1, device=self.device),
]
fixed_features = {0: -10, 1: 10}
dimension = 6
new_constraints = _generate_unfixed_lin_constraints(
constraints=list(zip(indices, coefficients, rhs)),
fixed_features=fixed_features,
dimension=dimension,
eq=False,
)
for i, (new_indices, new_coefficients, new_rhs) in enumerate(new_constraints):
if i % 2 == 0: # first list of indices is [2, 3, 4, 5]
self.assertTrue(
torch.equal(new_indices, torch.arange(4, device=self.device))
)
else: # second list of indices is [5, 4, 3]
self.assertTrue(
torch.equal(new_indices, torch.arange(3, 0, -1, device=self.device))
)
self.assertTrue(torch.equal(new_coefficients, coefficients[i]))
self.assertEqual(new_rhs, rhs[i])
# Case 3: all fixed features are in the indices
indices = [
torch.arange(4, device=self.device),
torch.arange(2, -1, -1, device=self.device),
]
# Case 3a: problem is feasible
dimension = 4
fixed_features = {0: 2, 1: 1, 2: 1, 3: 2}
for eq in [False, True]:
new_constraints = _generate_unfixed_lin_constraints(
constraints=[(indices[0], coefficients[0], rhs[0])],
fixed_features=fixed_features,
dimension=dimension,
eq=eq,
)
self.assertEqual(new_constraints, [])
# Case 3b: problem is infeasible
for eq in [False, True]:
prefix = "Ineq" if not eq else "Eq"
with self.assertRaisesRegex(CandidateGenerationError, prefix):
new_constraints = _generate_unfixed_lin_constraints(
constraints=[(indices[1], coefficients[1], rhs[1])],
fixed_features=fixed_features,
dimension=dimension,
eq=eq,
)
def test_evaluate_feasibility_intra_point_checks(self) -> None:
# Check that `evaluate_feasibility` raises an error if inter-point
# constraints are used.
X = torch.ones(3, 2, device=self.device)
inter_cons = (
torch.tensor([[0, 0], [1, 0]], device=self.device),
torch.tensor([1.0, -1.0], device=self.device),
0,
)
for const_arg in (
{"inequality_constraints": [inter_cons]},
{"equality_constraints": [inter_cons]},
{"nonlinear_inequality_constraints": [(None, False)]},
):
with self.assertRaisesRegex(UnsupportedError, INTRA_POINT_CONST_ERR):
evaluate_feasibility(X=X, **const_arg)
def test_evaluate_feasibility(self) -> None:
# Check that the feasibility is evaluated correctly.
X = torch.tensor(
[
[[1.0, 1.0, 1.0]],
[[1.0, 1.0, 3.0]],
[[2.0, 2.0, 1.0]],
[[2.0, 2.0, 5.0]],
[[3.0, 3.0, 3.0]],
],
device=self.device,
)
# X[..., 2] * 4 >= 5.
inequality_constraints = [
(
torch.tensor([2], device=self.device),
torch.tensor([4], device=self.device),
5.0,
)
]
# X[..., 0] + X[..., 1] == 4.
equality_constraints = [
(
torch.tensor([0, 1], device=self.device),
torch.ones(2, device=self.device),
4.0,
)
]
# sum(X, dim=-1) < 4.
def nlc1(x):
return 4 - x.sum(dim=-1)
# Only inequality.
self.assertAllClose(
evaluate_feasibility(
X=X,
inequality_constraints=inequality_constraints,
),
torch.tensor(
[[False], [True], [False], [True], [True]], device=self.device
),
)
# Only equality.
self.assertAllClose(
evaluate_feasibility(
X=X,
equality_constraints=equality_constraints,
),
torch.tensor(
[[False], [False], [True], [True], [False]], device=self.device
),
)
# Both inequality and equality.
self.assertAllClose(
evaluate_feasibility(
X=X,
inequality_constraints=inequality_constraints,
equality_constraints=equality_constraints,
),
torch.tensor(
[[False], [False], [False], [True], [False]], device=self.device
),
)
# Nonlinear inequality.
self.assertAllClose(
evaluate_feasibility(
X=X,
nonlinear_inequality_constraints=[(nlc1, True)],
),
torch.tensor(
[[True], [False], [False], [False], [False]], device=self.device
),
)
class TestMakeScipyBounds(BotorchTestCase):
def test_make_scipy_bounds(self):
X = torch.zeros(3, 1, 2)
# both None
self.assertIsNone(make_scipy_bounds(X=X, lower_bounds=None, upper_bounds=None))
# lower None
upper_bounds = torch.ones(2)
bounds = make_scipy_bounds(X=X, lower_bounds=None, upper_bounds=upper_bounds)
self.assertIsInstance(bounds, Bounds)
self.assertTrue(
np.all(np.equal(bounds.lb, np.full((3, 1, 2), float("-inf")).flatten()))
)
self.assertTrue(np.all(np.equal(bounds.ub, np.ones((3, 1, 2)).flatten())))
# upper None
lower_bounds = torch.zeros(2)
bounds = make_scipy_bounds(X=X, lower_bounds=lower_bounds, upper_bounds=None)
self.assertIsInstance(bounds, Bounds)
self.assertTrue(np.all(np.equal(bounds.lb, np.zeros((3, 1, 2)).flatten())))
self.assertTrue(
np.all(np.equal(bounds.ub, np.full((3, 1, 2), float("inf")).flatten()))
)
# floats
bounds = make_scipy_bounds(X=X, lower_bounds=0.0, upper_bounds=1.0)
self.assertIsInstance(bounds, Bounds)
self.assertTrue(np.all(np.equal(bounds.lb, np.zeros((3, 1, 2)).flatten())))
self.assertTrue(np.all(np.equal(bounds.ub, np.ones((3, 1, 2)).flatten())))
# 1-d tensors
bounds = make_scipy_bounds(
X=X, lower_bounds=lower_bounds, upper_bounds=upper_bounds
)
self.assertIsInstance(bounds, Bounds)
self.assertTrue(np.all(np.equal(bounds.lb, np.zeros((3, 1, 2)).flatten())))
self.assertTrue(np.all(np.equal(bounds.ub, np.ones((3, 1, 2)).flatten())))