-
Notifications
You must be signed in to change notification settings - Fork 18
/
test_symbols.py
2484 lines (1944 loc) · 75.1 KB
/
test_symbols.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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2024 D-Wave Systems Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import abc
import collections.abc
import itertools
import math
import operator
import typing
import unittest
import warnings
import numpy as np
import dwave.optimization
import dwave.optimization.symbols
from dwave.optimization import (
Model,
logical,
logical_and,
logical_or,
logical_not,
logical_xor,
mod,
sqrt,
)
class utils:
"""We want to add subclasses of unittest.TestCase that implement universal
tests for different symbols. But they get executed as tests if they
are in the main namspace. So we nest them in this "namespace".
"""
class SymbolTests(abc.ABC, unittest.TestCase):
@abc.abstractmethod
def generate_symbols(self):
"""Yield symbol(s) for testing.
The model must be topologically sorted before returning.
The symbols must all be unique from eachother.
"""
def test_equality(self):
DEFINITELY = 2
for x in self.generate_symbols():
self.assertEqual(DEFINITELY, x.maybe_equals(x))
self.assertTrue(x.equals(x))
for x, y in zip(self.generate_symbols(), self.generate_symbols()):
self.assertTrue(DEFINITELY, x.maybe_equals(y))
self.assertTrue(x.equals(y))
def test_inequality(self):
MAYBE = 1
for x, y in itertools.combinations(self.generate_symbols(), 2):
self.assertLessEqual(x.maybe_equals(y), MAYBE)
self.assertFalse(x.equals(y))
def test_iter_symbols(self):
for x in self.generate_symbols():
model = x.model
index = x.topological_index()
# Get the symbol back
y, = itertools.islice(model.iter_symbols(), index, index+1)
self.assertTrue(x.shares_memory(y))
self.assertIs(type(x), type(y))
self.assertTrue(x.equals(y))
def test_namespace(self):
x = next(self.generate_symbols())
self.assertIn(type(x).__name__, dwave.optimization.symbols.__all__)
def test_serialization(self):
for x in self.generate_symbols():
model = x.model
index = x.topological_index()
with model.to_file() as f:
new = Model.from_file(f)
# Get the symbol back
y, = itertools.islice(new.iter_symbols(), index, index+1)
self.assertFalse(x.shares_memory(y))
self.assertIs(type(x), type(y))
self.assertTrue(x.equals(y))
def test_state_serialization(self):
for x in self.generate_symbols():
model = x.model
# without some way to randomly initialize states this is really just
# smoke test
model.states.resize(1)
# get the states before serialization
states = []
for sym in model.iter_symbols():
if hasattr(sym, "state"):
states.append(sym.state())
else:
states.append(None)
with model.states.to_file() as f:
new = Model.from_file(f)
for i, sym in enumerate(model.iter_symbols()):
if hasattr(sym, "state"):
np.testing.assert_equal(sym.state(), states[i])
def test_state_size_smoke(self):
for x in self.generate_symbols():
self.assertGreaterEqual(x.state_size(), 0)
class BinaryOpTests(SymbolTests):
@abc.abstractmethod
def op(self, lhs, rhs):
pass
def symbol_op(self, lhs, rhs):
# if the op is different for symbols, allow the override
return self.op(lhs, rhs)
def test_numpy_equivalence(self):
lhs_array = np.arange(10)
rhs_array = np.arange(1, 11)
model = Model()
lhs_symbol = model.constant(lhs_array)
rhs_symbol = model.constant(rhs_array)
op_array = self.op(lhs_array, rhs_array)
op_symbol = self.symbol_op(lhs_symbol, rhs_symbol)
model.states.resize(1)
with model.lock():
np.testing.assert_array_equal(op_array, op_symbol.state())
def test_scalar_broadcasting(self):
lhs_array = 5
rhs_array = np.asarray([-10, 100, 16])
model = Model()
lhs_symbol = model.constant(lhs_array)
rhs_symbol = model.constant(rhs_array)
op_array = self.op(lhs_array, rhs_array)
op_symbol = self.symbol_op(lhs_symbol, rhs_symbol)
model.states.resize(1)
with model.lock():
np.testing.assert_array_equal(op_array, op_symbol.state())
def test_size1_broadcasting(self):
lhs_array = np.asarray([5])
rhs_array = np.asarray([-10, 100, 16])
model = Model()
lhs_symbol = model.constant(lhs_array)
rhs_symbol = model.constant(rhs_array)
op_array = self.op(lhs_array, rhs_array)
op_symbol = self.symbol_op(lhs_symbol, rhs_symbol)
model.states.resize(1)
with model.lock():
np.testing.assert_array_equal(op_array, op_symbol.state())
class NaryOpTests(SymbolTests):
@abc.abstractmethod
def op(self, *xs):
pass
@abc.abstractmethod
def node_op(self, *xs):
pass
@abc.abstractmethod
def node_class(self):
pass
def generate_symbols(self):
model = Model()
a, b, c = model.constant(-5), model.constant(7), model.constant(0)
op_abc = self.node_op(a, b, c)
model.lock()
yield op_abc
def test_scalar_input(self):
model = Model()
a, b, c = model.constant(-5), model.constant(7), model.constant(0)
op_abc = self.node_op(a, b, c)
self.assertEqual(model.num_symbols(), 4)
# Make sure we got the right type of node
self.assertIsInstance(op_abc, self.node_class())
# Should be a scalar
self.assertEqual(op_abc.shape(), ())
self.assertEqual(op_abc.size(), 1)
model.lock()
model.states.resize(1)
self.assertEqual(op_abc.state(0), self.op(-5, 7, 0))
def test_1d_input(self):
model = Model()
x, y, z = [model.integer(10, -5, 5) for _ in range(3)]
op_xyz = self.node_op(x, y, z)
# Make sure we got the right type of node
self.assertIsInstance(op_xyz, self.node_class())
# Make sure the shape is correct
self.assertEqual(op_xyz.shape(), (10,))
self.assertEqual(op_xyz.size(), 10)
model.lock()
model.states.resize(1)
data_x = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
x.set_state(0, data_x)
data_y = [5, 4, 3, 2, 1, 0, -1, -2, -3, -4]
y.set_state(0, data_y)
data_z = [5, -5, 4, -4, 3, -3, 2, -2, 1, 0]
z.set_state(0, data_z)
np.testing.assert_equal(
op_xyz.state(0),
[self.op(*vs) for vs in zip(data_x, data_y, data_z)]
)
class UnaryOpTests(SymbolTests):
@abc.abstractmethod
def op(self, x):
pass
def symbol_op(self, x):
# if the op is different for symbols, allow the override
return self.op(x)
def generate_symbols(self):
model = Model()
a = model.constant(-5)
op_a = self.symbol_op(a)
model.lock()
yield op_a
def test_scalar_input(self):
for scalar in [-5, -.5, 0, 1, 1.5]:
with self.subTest(f"a = {scalar}"):
model = Model()
a = model.constant(scalar)
op_a = self.symbol_op(a)
self.assertEqual(model.num_symbols(), 2)
# Should be a scalar
self.assertEqual(op_a.shape(), ())
self.assertEqual(op_a.size(), 1)
model.lock()
model.states.resize(1)
self.assertEqual(op_a.state(0), self.op(scalar))
def test_1d_input(self):
model = Model()
x = model.integer(10, -5, 5)
op_x = self.symbol_op(x)
model.lock()
model.states.resize(1)
data = [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]
x.set_state(0, data)
np.testing.assert_equal(op_x.state(0), [self.op(v) for v in data])
class TestAbsolute(utils.UnaryOpTests):
def op(self, x):
return abs(x)
def test_abs(self):
from dwave.optimization.symbols import Absolute
model = Model()
x = model.integer(5, lower_bound=-5, upper_bound=5)
a = abs(x)
self.assertIsInstance(a, Absolute)
self.assertEqual(model.num_symbols(), 2)
class TestAdd(utils.BinaryOpTests):
def generate_symbols(self):
model = Model()
a = model.constant(5)
b = model.constant(7)
ab = a + b
ba = b + a
model.lock()
yield ab
yield ba
def op(self, lhs, rhs):
return lhs + rhs
def test_broadcasting(self):
# todo: allow array broadcasting, for now just test that it raises
# an error
model = Model()
a = model.integer(5)
b = model.integer((5, 5))
with self.assertRaises(ValueError):
a + b
def test_scalar_addition(self):
model = Model()
a = model.constant(5)
b = model.constant(7)
x = a + b
self.assertEqual(model.num_symbols(), 3)
self.assertEqual(x.shape(), a.shape())
self.assertEqual(x.shape(), b.shape())
self.assertEqual(x.size(), a.size())
self.assertEqual(x.size(), b.size())
model.lock()
model.states.resize(1)
self.assertEqual(x.state(0), 12)
def test_scalar_broadcasting(self):
# todo: allow array broadcasting, for now just test that it raises
# an error
model = Model()
a = model.integer(1)
b = model.integer(5)
x = a + b
model.lock()
model.states.resize(1)
a.set_state(0, 3)
b.set_state(0, [4, 0, 3, 100, 17])
np.testing.assert_array_equal(x.state(), [7, 3, 6, 103, 20])
def test_unlike_shapes(self):
model = Model()
a = model.constant(np.zeros((5, 5)))
b = model.constant(np.zeros((6, 4)))
with self.assertRaises(ValueError):
a + b
class TestAdvancedIndexing(unittest.TestCase):
def test_out_of_bounds(self):
model = Model()
a = model.constant([0, 1, 2, 3])
b = model.constant(1.5)
x = model.integer(lower_bound=1, upper_bound=100)
# Error messages are chosen to be similar to NumPy's
with self.assertRaisesRegex(
IndexError,
"index's smallest possible value -100 is out of bounds for axis 0 with size 4"):
a[-x]
with self.assertRaisesRegex(
IndexError,
"index's largest possible value 100 is out of bounds for axis 0 with size 4"):
a[x]
with self.assertRaisesRegex(
IndexError,
"index may not contain non-integer values for axis 0"):
a[b]
a = model.constant(np.arange(12).reshape(3, 4))
with self.assertRaisesRegex(
IndexError,
"index may not contain non-integer values for axis 1"):
a[:, b]
s = model.set(5, min_size=3)
with self.assertRaisesRegex(
IndexError,
"index's largest possible value 100 is out of bounds for axis 0 "
"with minimum size 3"):
s[x]
def test_higher_dimenional_indexers_not_allowed(self):
model = Model()
constant = model.constant(np.arange(10))
i0 = model.integer(lower_bound=0, upper_bound=9)
self.assertTrue(constant[i0].shape() == tuple())
i1 = model.integer(3, lower_bound=0, upper_bound=9)
self.assertTrue(constant[i1].shape() == (3,))
i2 = model.integer((2, 3), lower_bound=0, upper_bound=9)
with self.assertRaises(ValueError):
constant[i2]
class TestAll(utils.SymbolTests):
def generate_symbols(self):
model = Model()
nodes = [
model.constant(0).all(),
model.constant(1).all(),
model.constant([]).all(),
model.constant([0, 0]).all(),
model.constant([0, 1]).all(),
model.constant([1, 1]).all(),
]
model.lock()
yield from nodes
def test_empty(self):
model = Model()
empty = model.constant([]).all()
model.lock()
model.states.resize(1)
self.assertTrue(empty.state())
self.assertEqual(empty.state(), np.asarray([]).all()) # confirm consistency with NumPy
def test_scalar(self):
model = Model()
model.states.resize(1)
for val in [0, .0001, 1, 7]:
with self.subTest(f"[{val}].all()"):
symbol = model.constant([val]).all()
model.lock()
np.testing.assert_array_equal(symbol.state(0), bool(val))
model.unlock()
with self.subTest(f"({val}).all()"):
symbol = model.constant(val).all()
model.lock()
np.testing.assert_array_equal(symbol.state(0), bool(val))
model.unlock()
for arr in [np.zeros(5), np.ones(5), np.asarray([0, 1])]:
with self.subTest(f"[{arr}].all()"):
symbol = model.constant([arr]).all()
model.lock()
np.testing.assert_array_equal(symbol.state(0), arr.all())
model.unlock()
with self.subTest(f"{val}.all()"):
symbol = model.constant(arr).all()
model.lock()
np.testing.assert_array_equal(symbol.state(0), arr.all())
model.unlock()
class TestAnd(utils.BinaryOpTests):
def generate_symbols(self):
model = Model()
a = model.constant(1)
b = model.constant(1)
c = model.constant(0)
d = model.constant(0)
ab = logical_and(a, b)
ac = logical_and(a, c)
cd = logical_and(c, d)
cb = logical_and(c, b)
self.assertEqual(model.num_symbols(), 8)
model.lock()
yield from (ab, ac, cd, cb)
def op(self, lhs, rhs):
return np.logical_and(lhs, rhs)
def symbol_op(self, lhs, rhs):
return logical_and(lhs, rhs)
def test_scalar_and(self):
model = Model()
a = model.constant(1)
b = model.constant(1)
c = model.constant(0)
d = model.constant(0)
ab = logical_and(a, b)
ac = logical_and(a, c)
cd = logical_and(c, d)
cb = logical_and(c, b)
self.assertEqual(model.num_symbols(), 8)
model.lock()
model.states.resize(1)
self.assertEqual(ab.state(0), 1)
self.assertEqual(ac.state(0), 0)
self.assertEqual(cd.state(0), 0)
self.assertEqual(cb.state(0), 0)
with self.assertRaises(TypeError):
x = a & b
with self.assertRaises(AttributeError):
x = a.logical_and(b)
class TestAny(utils.SymbolTests):
def generate_symbols(self):
model = Model()
nodes = [
model.constant(0).any(),
model.constant(1).any(),
model.constant([]).any(),
model.constant([0, 0]).any(),
model.constant([0, 1]).any(),
model.constant([1, 1]).any(),
]
model.lock()
yield from nodes
def test_empty(self):
model = Model()
empty = model.constant([]).any()
model.lock()
model.states.resize(1)
self.assertFalse(empty.state())
self.assertEqual(empty.state(), np.asarray([]).any()) # confirm consistency with NumPy
def test_scalar(self):
model = Model()
model.states.resize(1)
for val in [0, .0001, 1, 7]:
with self.subTest(f"[{val}].all()"):
symbol = model.constant([val]).any()
model.lock()
np.testing.assert_array_equal(symbol.state(0), bool(val))
model.unlock()
with self.subTest(f"({val}).all()"):
symbol = model.constant(val).any()
model.lock()
np.testing.assert_array_equal(symbol.state(0), bool(val))
model.unlock()
for arr in [np.zeros(5), np.ones(5), np.asarray([0, 1])]:
with self.subTest(f"[{arr}].all()"):
symbol = model.constant([arr]).any()
model.lock()
np.testing.assert_array_equal(symbol.state(0), arr.any())
model.unlock()
with self.subTest(f"{val}.all()"):
symbol = model.constant(arr).any()
model.lock()
np.testing.assert_array_equal(symbol.state(0), arr.any())
model.unlock()
class TestArrayValidation(utils.SymbolTests):
def generate_symbols(self):
model = Model()
x = model.binary(10)
a = dwave.optimization.symbols._ArrayValidation(x)
model.lock()
yield a
def test_namespace(self):
pass
class TestBasicIndexing(utils.SymbolTests):
def generate_symbols(self):
symbols = []
model = Model()
x = model.binary(10)
y = model.set(10)
z = model.binary((5, 5))
symbols.append(x[::2])
symbols.append(x[0])
symbols.append(y[:4])
symbols.append(z[0, 3])
symbols.append(z[::2, 4])
model.lock()
yield from symbols
def test_infer_indices_1d(self):
model = Model()
x = model.binary(10)
self.assertEqual(x[:]._infer_indices(), (slice(0, 10, 1),))
self.assertEqual(x[1::]._infer_indices(), (slice(1, 10, 1),))
self.assertEqual(x[:3:]._infer_indices(), (slice(0, 3, 1),))
self.assertEqual(x[::2]._infer_indices(), (slice(0, 10, 2),))
self.assertEqual(x[1::2]._infer_indices(), (slice(1, 10, 2),))
self.assertEqual(x[2::2]._infer_indices(), (slice(2, 10, 2),))
self.assertEqual(x[::100]._infer_indices(), (slice(0, 10, 100),))
self.assertEqual(x[100::100]._infer_indices(), (slice(10, 10, 100),))
self.assertEqual(x[:3:100]._infer_indices(), (slice(0, 10, 100),)) # harmless
self.assertEqual(x[0]._infer_indices(), (0,))
self.assertEqual(x[5]._infer_indices(), (5,))
def test_infer_indices_2d(self):
model = Model()
x = model.binary(shape=(5, 6))
self.assertEqual(x[3, 4]._infer_indices(), (3, 4))
self.assertEqual(x[0, 4]._infer_indices(), (0, 4))
self.assertEqual(x[0, 0]._infer_indices(), (0, 0))
self.assertEqual(x[3, 4::2]._infer_indices(), (3, slice(4, 6, 2)))
self.assertEqual(x[3, 4:4:2]._infer_indices(), (3, slice(4, 4, 2)))
self.assertEqual(x[:, :]._infer_indices(), (slice(0, 5, 1), slice(0, 6, 1)))
self.assertEqual(x[::2, :]._infer_indices(), (slice(0, 5, 2), slice(0, 6, 1)))
self.assertEqual(x[:, ::2]._infer_indices(), (slice(0, 5, 1), slice(0, 6, 2)))
self.assertEqual(x[2:, ::2]._infer_indices(), (slice(2, 5, 1), slice(0, 6, 2)))
def test_infer_indices_3d(self):
model = Model()
x = model.binary(shape=(5, 6, 7))
self.assertEqual(x[3, 4, 0]._infer_indices(), (3, 4, 0))
self.assertEqual(x[0, 4, 0]._infer_indices(), (0, 4, 0))
self.assertEqual(x[0, 0, 0]._infer_indices(), (0, 0, 0))
self.assertEqual(x[:]._infer_indices(), (slice(0, 5, 1), slice(0, 6, 1), slice(0, 7, 1)))
self.assertEqual(x[:, 3, :]._infer_indices(), (slice(0, 5, 1), 3, slice(0, 7, 1)))
self.assertEqual(x[:, :, 3]._infer_indices(), (slice(0, 5, 1), slice(0, 6, 1), 3))
def test_infer_indices_1d_dynamic(self):
MAX = np.iinfo(np.intp).max # constant for unbounded slices
model = Model()
x = model.set(10)
self.assertEqual(x[:]._infer_indices(), (slice(0, MAX, 1),))
self.assertEqual(x[::2]._infer_indices(), (slice(0, MAX, 2),))
self.assertEqual(x[5:2:2]._infer_indices(), (slice(5, 2, 2),))
self.assertEqual(x[:2:]._infer_indices(), (slice(0, 2, 1),))
def test_state_size(self):
model = Model()
self.assertEqual(model.set(10)[::2].state_size(), 5 * 8)
class TestBinaryVariable(utils.SymbolTests):
def generate_symbols(self):
model = Model()
x = model.binary(10)
y = model.binary((3, 3))
model.lock()
yield x
yield y
model = Model()
z = model.binary([5])
model.lock()
yield z
def test(self):
model = Model()
x = model.binary([10])
def test_no_shape(self):
model = Model()
x = model.binary()
self.assertEqual(x.shape(), tuple())
model.states.resize(1)
self.assertEqual(x.state(0).shape, tuple())
def test_subscript(self):
model = Model()
x = model.binary(5)
self.assertEqual(x[0].shape(), tuple())
self.assertEqual(x[1:3].shape(), (2,))
# Todo: we can generalize many of these tests for all decisions that can have
# their state set
def test_shape(self):
model = Model()
with self.assertRaises(TypeError):
model.binary(3.5)
with self.assertRaises(ValueError):
model.binary([0.5])
def test_set_state(self):
with self.subTest("array-like"):
model = Model()
model.states.resize(1)
x = model.binary([5, 5])
x.set_state(0, np.arange(25) % 2)
np.testing.assert_array_equal(x.state(), np.arange(25).reshape((5, 5)) % 2)
x.set_state(0, 1 - np.arange(25).reshape((5, 5)) % 2)
np.testing.assert_array_equal(x.state(), 1 - np.arange(25).reshape((5, 5)) % 2)
with self.subTest("invalid state index"):
model = Model()
x = model.binary(5)
# No states have been created
with self.assertRaisesRegex(ValueError, r"^index out of range: 0$"):
x.set_state(0, range(5))
with self.assertRaisesRegex(ValueError, r"^index out of range: -1$"):
x.set_state(-1, range(5))
# Some states have been created
model.states.resize(5)
with self.assertRaisesRegex(ValueError, r"^index out of range: 5$"):
x.set_state(5, range(5))
with self.assertRaisesRegex(ValueError, r"^index out of range: -1$"):
x.set_state(-1, range(5))
with self.subTest("non-integer"):
# gets translated into integer according to NumPy rules
model = Model()
model.states.resize(1)
x = model.binary(5)
x.set_state(0, [0.5, 0.75, 0.5, 1.0, 0.1])
np.testing.assert_array_equal(x.state(), [0, 0, 0, 1, 0])
with self.subTest("invalid"):
model = Model()
model.states.resize(1)
x = model.binary([5])
# wrong entries
with self.assertRaisesRegex(ValueError, r"Invalid data provided for node"):
x.set_state(0, [0, 0, 1, 2, 0])
# wrong size
with self.assertRaises(ValueError):
x.set_state(0, [0, 1, 2])
class TestConcatenate(utils.SymbolTests):
def generate_symbols(self):
model = Model()
x = model.constant(np.arange(12)).reshape((2,1,2,3))
y = model.constant(np.arange(24)).reshape((2,2,2,3))
z = model.constant(np.arange(36)).reshape((2,3,2,3))
c = dwave.optimization.symbols.Concatenate((x,y,z), axis=1)
model.lock()
yield c
def test_simple_concatenate(self):
model = Model()
with self.subTest("Concatenate ndarray of binary returns Concatenate"):
A = [model.binary(5), model.binary(5)]
self.assertIsInstance(
dwave.optimization.concatenate(np.asarray(tuple(A), dtype=object)),
dwave.optimization.symbols.Concatenate
)
with self.subTest("Concatenate ArraySymbol returns ArraySymbol"):
self.assertIsInstance(
dwave.optimization.concatenate(model.constant(5)),
dwave.optimization.model.ArraySymbol
)
self.assertIsInstance(
dwave.optimization.concatenate(model.binary(5)),
dwave.optimization.model.ArraySymbol
)
with self.subTest("Concatenate Iterable and Sized of length 1 returns ArraySymbol"):
self.assertIsInstance(
dwave.optimization.concatenate((model.binary(5), )),
dwave.optimization.model.ArraySymbol
)
self.assertIsInstance(
dwave.optimization.concatenate((model.constant(5),)),
dwave.optimization.model.ArraySymbol
)
def test_errors(self):
model = Model()
with self.subTest("same number of dimensions"):
A = model.constant(np.arange(6)).reshape((1,2,3))
B = model.constant(np.arange(24)).reshape((1,2,3,4))
with self.assertRaisesRegex(
ValueError, (r"^all the input arrays must have the same "
r"number of dimensions, but the array at index 0 "
r"has 3 dimension\(s\) and the array at index 1 "
r"has 4 dimension\(s\)")
):
dwave.optimization.symbols.Concatenate((A,B))
with self.subTest("array shapes are the same"):
A = model.constant(np.arange(6)).reshape((1,2,3))
B = model.constant(np.arange(6)).reshape((3,2,1))
axis = 1
with self.assertRaisesRegex(
ValueError, (r"^all the input array dimensions except for the "
r"concatenation axis must match exactly, but "
r"along dimension 0, the array at index 0 has "
r"size 1 and the array at index 1 has size 3")
):
dwave.optimization.symbols.Concatenate((A,B), axis)
with self.subTest("axis out of bounds"):
A = model.constant(np.arange(6)).reshape((1,2,3))
B = model.constant(np.arange(6)).reshape((1,2,3))
axis = 3
with self.assertRaisesRegex(
ValueError, r"^axis 3 is out of bounds for array of dimension 3"
):
dwave.optimization.symbols.Concatenate((A,B), axis)
class TestConstant(utils.SymbolTests):
def generate_symbols(self):
model = Model()
A = model.constant(np.arange(25, dtype=np.double).reshape((5, 5)))
B = model.constant([0, 1, 2, 3, 4])
C = model.constant(np.arange(25, dtype=np.double))
D = model.constant(np.arange(1, 26, dtype=np.double).reshape((5, 5)))
model.lock()
yield A
yield B
def test_truthy(self):
model = Model()
self.assertTrue(model.constant(1))
self.assertFalse(model.constant(0))
self.assertTrue(model.constant(1.1))
self.assertFalse(model.constant(0.0))
self.assertTrue(not model.constant(0))
self.assertFalse(not model.constant(1))
# these are all ambiguous
with self.assertRaises(ValueError):
bool(model.constant([]))
with self.assertRaises(ValueError):
bool(model.constant([0, 1]))
with self.assertRaises(ValueError):
bool(model.constant([0]))
# the type is correct
self.assertIsInstance(model.constant(123.4).__bool__(), bool)
def test_comparisons(self):
model = Model()
# zero = model.constant(0)
one = model.constant(1)
onetwo = model.constant([1, 2])
operators = [
operator.eq,
operator.ge,
operator.gt,
operator.le,
operator.lt,
operator.ne
]
for op in operators:
with self.subTest(op):
self.assertEqual(op(one, 1), op(1, 1))
self.assertEqual(op(1, one), op(1, 1))
self.assertEqual(op(one, 2), op(1, 2))
self.assertEqual(op(2, one), op(2, 1))
self.assertEqual(op(one, 0), op(1, 0))
self.assertEqual(op(0, one), op(0, 1))
np.testing.assert_array_equal(op(onetwo, [1, 2]), op(np.asarray([1, 2]), [1, 2]))
np.testing.assert_array_equal(op(onetwo, [1, 0]), op(np.asarray([1, 2]), [1, 0]))
np.testing.assert_array_equal(op([1, 2], onetwo), op(np.asarray([1, 2]), [1, 2]))
np.testing.assert_array_equal(op([1, 0], onetwo), op(np.asarray([1, 0]), [1, 2]))
def test_copy(self):
model = Model()
arr = np.arange(25, dtype=np.double).reshape((5, 5))
A = model.constant(arr)
np.testing.assert_array_equal(A, arr)
self.assertTrue(np.shares_memory(A, arr))
def test_index(self):
model = Model()
self.assertEqual(list(range(model.constant(0))), [])
self.assertEqual(list(range(model.constant(4))), [0, 1, 2, 3])
with self.assertRaises(TypeError):
range(model.constant([0])) # not a scalar
self.assertEqual(int(model.constant(0)), 0)
self.assertEqual(int(model.constant(1)), 1)
with self.assertRaises(TypeError):
int(model.constant([0])) # not a scalar
def test_noncontiguous(self):
model = Model()
c = model.constant(np.arange(6)[::2])
np.testing.assert_array_equal(c, [0, 2, 4])
def test_scalar(self):
model = Model()
c = model.constant(5)
self.assertEqual(c.shape(), tuple())
np.testing.assert_array_equal(c, 5)
class TestDisjointBitSetsVariable(utils.SymbolTests):
def test_inequality(self):
# TODO re-enable this once equality has been fixed
pass
def generate_symbols(self):
model = Model()
d, ds = model.disjoint_bit_sets(10, 4)
model.lock()
yield d
yield from ds
def test(self):
model = Model()
model.disjoint_bit_sets(10, 4)
def test_construction(self):
model = Model()
with self.assertRaises(ValueError):
model.disjoint_bit_sets(-5, 1)
with self.assertRaises(ValueError):
model.disjoint_bit_sets(1, -5)
model.states.resize(1)
ds, (x,) = model.disjoint_bit_sets(0, 1)
self.assertEqual(x.shape(), (0,))
def test_num_returned_nodes(self):
model = Model()
d, ds = model.disjoint_bit_sets(10, 4)
def test_set_state(self):
with self.subTest("array-like output lists"):
model = Model()
model.states.resize(1)
x, ys = model.disjoint_bit_sets(5, 3)
model.lock()
x.set_state(0, [[1, 1, 0, 0, 0], [0, 0, 1, 1, 0], [0, 0, 0, 0, 1]])
np.testing.assert_array_equal(ys[0].state(), [1, 1, 0, 0, 0])
np.testing.assert_array_equal(ys[1].state(), [0, 0, 1, 1, 0])
np.testing.assert_array_equal(ys[2].state(), [0, 0, 0, 0, 1])
with self.subTest("invalid state index"):
model = Model()
x, _ = model.disjoint_bit_sets(5, 3)
state = [[1, 1, 0, 0, 0], [0, 0, 1, 1, 0], [0, 0, 0, 0, 1]]
# No states have been created
with self.assertRaisesRegex(ValueError, r"^index out of range: 0$"):
x.set_state(0, state)