/
test_group.py
1461 lines (1104 loc) · 55 KB
/
test_group.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
"""
Unit tests for Group.
"""
from __future__ import print_function
import itertools
import unittest
from six import assertRaisesRegex, iteritems
from six.moves import range
import numpy as np
try:
from parameterized import parameterized
except ImportError:
from openmdao.utils.assert_utils import SkipParameterized as parameterized
import openmdao.api as om
from openmdao.test_suite.components.sellar import SellarDis2
from openmdao.utils.assert_utils import assert_rel_error, assert_warning
from openmdao.utils.logger_utils import TestLogger
from openmdao.error_checking.check_config import _check_hanging_inputs
class SimpleGroup(om.Group):
def __init__(self):
super(SimpleGroup, self).__init__()
self.add_subsystem('comp1', om.IndepVarComp('x', 5.0))
self.add_subsystem('comp2', om.ExecComp('b=2*a'))
self.connect('comp1.x', 'comp2.a')
class BranchGroup(om.Group):
def __init__(self):
super(BranchGroup, self).__init__()
b1 = self.add_subsystem('Branch1', om.Group())
g1 = b1.add_subsystem('G1', om.Group())
g2 = g1.add_subsystem('G2', om.Group())
g2.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0))
b2 = self.add_subsystem('Branch2', om.Group())
g3 = b2.add_subsystem('G3', om.Group())
g3.add_subsystem('comp2', om.ExecComp('b=3.0*a', a=4.0, b=12.0))
class SetOrderGroup(om.Group):
def setup(self):
self.add_subsystem('C1', om.ExecComp('y=2.0*x'))
self.add_subsystem('C2', om.ExecComp('y=2.0*x'))
self.add_subsystem('C3', om.ExecComp('y=2.0*x'))
self.set_order(['C1', 'C3', 'C2'])
self.connect('C1.y', 'C3.x')
self.connect('C3.y', 'C2.x')
class ReportOrderComp(om.ExplicitComponent):
def __init__(self, order_list):
super(ReportOrderComp, self).__init__()
self._order_list = order_list
def setup(self):
self.add_input('x', 0.0)
self.add_output('y', 0.0)
def compute(self, inputs, outputs):
self._order_list.append(self.pathname)
class TestGroup(unittest.TestCase):
def test_add_subsystem_class(self):
p = om.Problem()
try:
p.model.add_subsystem('comp', om.IndepVarComp)
except TypeError as err:
self.assertEqual(str(err), "Group: Subsystem 'comp' should be an instance, "
"but a IndepVarComp class object was found.")
else:
self.fail('Exception expected.')
def test_same_sys_name(self):
"""Test error checking for the case where we add two subsystems with the same name."""
p = om.Problem()
p.model.add_subsystem('comp1', om.IndepVarComp('x', 5.0))
p.model.add_subsystem('comp2', om.ExecComp('b=2*a'))
try:
p.model.add_subsystem('comp2', om.ExecComp('b=2*a'))
except Exception as err:
self.assertEqual(str(err), "Group: Subsystem name 'comp2' is already used.")
else:
self.fail('Exception expected.')
def test_deprecated_runonce(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', 5.0))
p.model.add_subsystem('comp', om.ExecComp('b=2*a'))
msg = "NonLinearRunOnce is deprecated. Use NonlinearRunOnce instead."
with assert_warning(DeprecationWarning, msg):
p.model.nonlinear_solver = om.NonLinearRunOnce()
def test_group_simple(self):
import openmdao.api as om
p = om.Problem()
p.model.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0))
p.setup()
self.assertEqual(p['comp1.a'], 3.0)
self.assertEqual(p['comp1.b'], 6.0)
def test_group_add(self):
model = om.Group()
ecomp = om.ExecComp('b=2.0*a', a=3.0, b=6.0)
msg = "The 'add' method provides backwards compatibility with OpenMDAO <= 1.x ; " \
"use 'add_subsystem' instead."
with assert_warning(DeprecationWarning, msg):
comp1 = model.add('comp1', ecomp)
self.assertTrue(ecomp is comp1)
def test_group_simple_promoted(self):
import openmdao.api as om
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('a', 3.0),
promotes_outputs=['a'])
p.model.add_subsystem('comp1', om.ExecComp('b=2.0*a'),
promotes_inputs=['a'])
p.setup()
p.run_model()
self.assertEqual(p['a'], 3.0)
self.assertEqual(p['comp1.b'], 6.0)
def test_inner_connect_w_extern_promote(self):
p = om.Problem()
g = p.model.add_subsystem('g', om.Group(), promotes_inputs=['c0.x'])
g.add_subsystem('ivc', om.IndepVarComp('x', 2.))
g.add_subsystem('c0', om.ExecComp('y = 2*x'))
g.connect('ivc.x', 'c0.x')
p.setup()
p.final_setup()
from openmdao.error_checking.check_config import _get_promoted_connected_ins
ins = _get_promoted_connected_ins(p.model)
self.assertEqual(len(ins), 1)
inp, tup = list(ins.items())[0]
in_proms, mans = tup
self.assertEqual(inp, 'g.c0.x')
self.assertEqual(in_proms, ['g'])
self.assertEqual(mans, [('c0.x', 'g')])
def test_inner_connect_w_2extern_promotes(self):
p = om.Problem()
g0 = p.model.add_subsystem('g0', om.Group(), promotes_inputs=['c0.x'])
g = g0.add_subsystem('g', om.Group(), promotes_inputs=['c0.x'])
g.add_subsystem('ivc', om.IndepVarComp('x', 2.))
g.add_subsystem('c0', om.ExecComp('y = 2*x'))
g.connect('ivc.x', 'c0.x')
p.setup()
p.final_setup()
from openmdao.error_checking.check_config import _get_promoted_connected_ins
ins = _get_promoted_connected_ins(p.model)
self.assertEqual(len(ins), 1)
inp, tup = list(ins.items())[0]
in_proms, mans = tup
self.assertEqual(inp, 'g0.g.c0.x')
self.assertEqual(list(sorted(in_proms)), ['g0', 'g0.g'])
self.assertEqual(mans, [('c0.x', 'g0.g')])
def test_group_rename_connect(self):
import openmdao.api as om
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('aa', 3.0),
promotes=['aa'])
p.model.add_subsystem('comp1', om.ExecComp('b=2.0*aa'),
promotes_inputs=['aa'])
# here we alias 'a' to 'aa' so that it will be automatically
# connected to the independent variable 'aa'.
p.model.add_subsystem('comp2', om.ExecComp('b=3.0*a'),
promotes_inputs=[('a', 'aa')])
p.setup()
p.run_model()
self.assertEqual(p['comp1.b'], 6.0)
self.assertEqual(p['comp2.b'], 9.0)
def test_double_promote_conns(self):
p = om.Problem()
gouter = p.model.add_subsystem('gouter', om.Group())
gouter.add_subsystem('couter', om.ExecComp('xx = a * 3.'), promotes_outputs=['xx'])
g = gouter.add_subsystem('g', om.Group(), promotes_inputs=[('x', 'xx')])
g.add_subsystem('ivc', om.IndepVarComp('x', 2.), promotes_outputs=['x'])
g.add_subsystem('c0', om.ExecComp('y = 2*x'), promotes_inputs=['x'])
with self.assertRaises(RuntimeError) as cm:
p.setup()
self.assertEqual(str(cm.exception),
"Group (gouter): The following inputs have multiple connections: gouter.g.c0.x from ['gouter.couter.xx', 'gouter.g.ivc.x']")
def test_double_promote_one_conn(self):
p = om.Problem()
gouter = p.model.add_subsystem('gouter', om.Group())
gouter.add_subsystem('couter', om.ExecComp('xx = a * 3.'))
g = gouter.add_subsystem('g', om.Group(), promotes_inputs=[('x', 'xx')])
g.add_subsystem('ivc', om.IndepVarComp('x', 2.), promotes_outputs=['x'])
g.add_subsystem('c0', om.ExecComp('y = 2*x'), promotes_inputs=['x'])
p.setup()
self.assertEqual(p.model._conn_global_abs_in2out['gouter.g.c0.x'], 'gouter.g.ivc.x')
def test_check_unconn_inputs_w_promote_rename(self):
p = om.Problem()
gouter = p.model.add_subsystem('gouter', om.Group())
gouter.add_subsystem('couter', om.ExecComp('xx = a * 3.'))
g = gouter.add_subsystem('g', om.Group(), promotes_inputs=['xx'])
g.add_subsystem('ivc', om.IndepVarComp('x', 2.), promotes_outputs=['x'])
g.add_subsystem('c0', om.ExecComp('y = 2*x'), promotes_inputs=[('x', 'xx')])
p.setup()
logger = TestLogger()
_check_hanging_inputs(p, logger)
for w in logger.get('warning'):
if 'The following inputs are not connected:' in w:
if "gouter.couter.a" in w and "gouter.xx: ['gouter.g.c0.x']" in w:
break
else:
self.fail("Expected warning not found.")
self.assertEqual(p.model._conn_global_abs_in2out, {})
def test_subsys_attributes(self):
p = om.Problem()
class MyGroup(om.Group):
def setup(self):
# two subsystems added during setup
self.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0))
self.add_subsystem('comp2', om.ExecComp('b=3.0*a', a=4.0, b=12.0))
# subsystems become attributes
my_group = p.model.add_subsystem('gg', MyGroup())
self.assertTrue(p.model.gg is my_group)
# after calling setup(), MyGroup's subsystems are also attributes
p.setup()
self.assertTrue(hasattr(p.model.gg, 'comp1'))
self.assertTrue(hasattr(p.model.gg, 'comp2'))
# calling setup() again doesn't break anything
p.setup()
self.assertTrue(p.model.gg is my_group)
self.assertTrue(hasattr(p.model.gg, 'comp1'))
self.assertTrue(hasattr(p.model.gg, 'comp2'))
# name cannot start with an underscore
with self.assertRaises(Exception) as err:
p.model.add_subsystem('_bad_name', om.Group())
self.assertEqual(str(err.exception),
"Group (<model>): '_bad_name' is not a valid sub-system name.")
# 'name', 'pathname', 'comm' and 'options' are reserved names
for reserved in ['name', 'pathname', 'comm', 'options']:
with self.assertRaises(Exception) as err:
p.model.add_subsystem(reserved, om.Group())
self.assertEqual(str(err.exception),
"Group (<model>): Can't add subsystem '%s' because an attribute with that name already exits." %
reserved)
def test_group_nested(self):
import openmdao.api as om
p = om.Problem()
p.model.add_subsystem('G1', om.Group())
p.model.G1.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0))
p.model.G1.add_subsystem('comp2', om.ExecComp('b=3.0*a', a=4.0, b=12.0))
p.setup()
self.assertEqual(p['G1.comp1.a'], 3.0)
self.assertEqual(p['G1.comp1.b'], 6.0)
self.assertEqual(p['G1.comp2.a'], 4.0)
self.assertEqual(p['G1.comp2.b'], 12.0)
def test_group_getsystem_top(self):
import openmdao.api as om
from openmdao.core.tests.test_group import BranchGroup
p = om.Problem(model=BranchGroup())
p.setup()
c1 = p.model.Branch1.G1.G2.comp1
self.assertEqual(c1.pathname, 'Branch1.G1.G2.comp1')
c2 = p.model.Branch2.G3.comp2
self.assertEqual(c2.pathname, 'Branch2.G3.comp2')
def test_group_nested_promoted1(self):
import openmdao.api as om
# promotes from bottom level up 1
p = om.Problem()
g1 = p.model.add_subsystem('G1', om.Group())
g1.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0),
promotes_inputs=['a'], promotes_outputs=['b'])
g1.add_subsystem('comp2', om.ExecComp('b=3.0*a', a=4.0, b=12.0),
promotes_inputs=['a'])
p.setup()
# output G1.comp1.b is promoted
self.assertEqual(p['G1.b'], 6.0)
# output G1.comp2.b is not promoted
self.assertEqual(p['G1.comp2.b'], 12.0)
# use unpromoted names for the following 2 promoted inputs
self.assertEqual(p['G1.comp1.a'], 3.0)
self.assertEqual(p['G1.comp2.a'], 4.0)
def test_group_nested_promoted2(self):
import openmdao.api as om
# promotes up from G1 level
p = om.Problem()
g1 = om.Group()
g1.add_subsystem('comp1', om.ExecComp('b=2.0*a', a=3.0, b=6.0))
g1.add_subsystem('comp2', om.ExecComp('b=3.0*a', a=4.0, b=12.0))
# use glob pattern 'comp?.a' to promote both comp1.a and comp2.a
# use glob pattern 'comp?.b' to promote both comp1.b and comp2.b
p.model.add_subsystem('G1', g1,
promotes_inputs=['comp?.a'],
promotes_outputs=['comp?.b'])
p.setup()
# output G1.comp1.b is promoted
self.assertEqual(p['comp1.b'], 6.0)
# output G1.comp2.b is promoted
self.assertEqual(p['comp2.b'], 12.0)
# access both promoted inputs using unpromoted names.
self.assertEqual(p['G1.comp1.a'], 3.0)
self.assertEqual(p['G1.comp2.a'], 4.0)
def test_group_promotes(self):
"""Promoting a single variable."""
p = om.Problem()
p.model.add_subsystem('comp1', om.IndepVarComp([('a', 2.0), ('x', 5.0)]),
promotes_outputs=['x'])
p.model.add_subsystem('comp2', om.ExecComp('y=2*x'), promotes_inputs=['x'])
p.setup()
p.set_solver_print(level=0)
p.run_model()
self.assertEqual(p['comp1.a'], 2)
self.assertEqual(p['x'], 5)
self.assertEqual(p['comp2.y'], 10)
def test_group_renames(self):
p = om.Problem()
p.model.add_subsystem('comp1', om.IndepVarComp('x', 5.0),
promotes_outputs=[('x', 'foo')])
p.model.add_subsystem('comp2', om.ExecComp('y=2*foo'), promotes_inputs=['foo'])
p.setup()
p.set_solver_print(level=0)
p.run_model()
self.assertEqual(p['foo'], 5)
self.assertEqual(p['comp2.y'], 10)
def test_group_renames_errors_single_string(self):
p = om.Problem()
with self.assertRaises(Exception) as err:
p.model.add_subsystem('comp1', om.IndepVarComp('x', 5.0),
promotes_outputs='x')
self.assertEqual(str(err.exception),
"Group: promotes must be an iterator of strings and/or tuples.")
def test_group_renames_errors_not_found(self):
p = om.Problem()
p.model.add_subsystem('comp1', om.IndepVarComp('x', 5.0),
promotes_outputs=[('xx', 'foo')])
p.model.add_subsystem('comp2', om.ExecComp('y=2*foo'), promotes_inputs=['foo'])
with self.assertRaises(Exception) as err:
p.setup()
self.assertEqual(str(err.exception),
"IndepVarComp (comp1): 'promotes_outputs' failed to find any matches for "
"the following names or patterns: ['xx']. "
"Check to make sure it is not empty")
def test_group_renames_errors_bad_tuple(self):
p = om.Problem()
p.model.add_subsystem('comp1', om.IndepVarComp('x', 5.0),
promotes_outputs=[('x', 'foo', 'bar')])
p.model.add_subsystem('comp2', om.ExecComp('y=2*foo'), promotes_inputs=['foo'])
with self.assertRaises(Exception) as err:
p.setup()
self.assertEqual(str(err.exception),
"when adding subsystem 'comp1', entry '('x', 'foo', 'bar')' "
"is not a string or tuple of size 2")
def test_group_promotes_multiple(self):
"""Promoting multiple variables."""
p = om.Problem()
p.model.add_subsystem('comp1', om.IndepVarComp([('a', 2.0), ('x', 5.0)]),
promotes_outputs=['a', 'x'])
p.model.add_subsystem('comp2', om.ExecComp('y=2*x'),
promotes_inputs=['x'])
p.setup()
p.set_solver_print(level=0)
p.run_model()
self.assertEqual(p['a'], 2)
self.assertEqual(p['x'], 5)
self.assertEqual(p['comp2.y'], 10)
def test_group_promotes_all(self):
"""Promoting all variables with asterisk."""
p = om.Problem()
p.model.add_subsystem('comp1', om.IndepVarComp([('a', 2.0), ('x', 5.0)]),
promotes_outputs=['*'])
p.model.add_subsystem('comp2', om.ExecComp('y=2*x'),
promotes_inputs=['x'])
p.setup()
p.set_solver_print(level=0)
p.run_model()
self.assertEqual(p['a'], 2)
self.assertEqual(p['x'], 5)
self.assertEqual(p['comp2.y'], 10)
def test_group_promotes2(self):
class Sellar(om.Group):
def setup(self):
dv = self.add_subsystem('des_vars', om.IndepVarComp(), promotes=['*'])
dv.add_output('x', 1.0)
dv.add_output('z', np.array([5.0, 2.0]))
self.add_subsystem('d1', SellarDis2(),
promotes_inputs=['y1'], promotes_outputs=['foo'])
self.add_subsystem('d2', SellarDis2())
p = om.Problem()
p.model = Sellar()
with self.assertRaises(Exception) as err:
p.setup()
self.assertEqual(str(err.exception),
"SellarDis2 (d1): 'promotes_outputs' failed to find any matches for "
"the following names or patterns: ['foo']. "
"Check to make sure it is not empty")
def test_group_nested_conn(self):
"""Example of adding subsystems and issuing connections with nested groups."""
g1 = om.Group()
c1_1 = g1.add_subsystem('comp1', om.IndepVarComp('x', 5.0))
c1_2 = g1.add_subsystem('comp2', om.ExecComp('b=2*a'))
g1.connect('comp1.x', 'comp2.a')
g2 = om.Group()
c2_1 = g2.add_subsystem('comp1', om.ExecComp('b=2*a'))
c2_2 = g2.add_subsystem('comp2', om.ExecComp('b=2*a'))
g2.connect('comp1.b', 'comp2.a')
model = om.Group()
model.add_subsystem('group1', g1)
model.add_subsystem('group2', g2)
model.connect('group1.comp2.b', 'group2.comp1.a')
p = om.Problem(model=model)
p.setup()
c1_1 = p.model.group1.comp1
c1_2 = p.model.group1.comp2
c2_1 = p.model.group2.comp1
c2_2 = p.model.group2.comp2
self.assertEqual(c1_1.name, 'comp1')
self.assertEqual(c1_2.name, 'comp2')
self.assertEqual(c2_1.name, 'comp1')
self.assertEqual(c2_2.name, 'comp2')
c1_1 = p.model.group1.comp1
c1_2 = p.model.group1.comp2
c2_1 = p.model.group2.comp1
c2_2 = p.model.group2.comp2
self.assertEqual(c1_1.name, 'comp1')
self.assertEqual(c1_2.name, 'comp2')
self.assertEqual(c2_1.name, 'comp1')
self.assertEqual(c2_2.name, 'comp2')
s = p.model._get_subsystem('')
self.assertEqual(s, None)
p.set_solver_print(level=0)
p.run_model()
self.assertEqual(p['group1.comp1.x'], 5.0)
self.assertEqual(p['group1.comp2.b'], 10.0)
self.assertEqual(p['group2.comp1.b'], 20.0)
self.assertEqual(p['group2.comp2.b'], 40.0)
def test_reused_output_promoted_names(self):
prob = om.Problem()
prob.model.add_subsystem('px1', om.IndepVarComp('x1', 100.0))
G1 = prob.model.add_subsystem('G1', om.Group())
G1.add_subsystem("C1", om.ExecComp("y=2.0*x"), promotes=['y'])
G1.add_subsystem("C2", om.ExecComp("y=2.0*x"), promotes=['y'])
msg = r"Output name 'y' refers to multiple outputs: \['G1.C1.y', 'G1.C2.y'\]."
with assertRaisesRegex(self, Exception, msg):
prob.setup()
def test_basic_connect_units(self):
import numpy as np
import openmdao.api as om
p = om.Problem()
indep_comp = om.IndepVarComp()
indep_comp.add_output('x', np.ones(5), units='ft')
exec_comp = om.ExecComp('y=sum(x)',
x={'value': np.zeros(5), 'units': 'inch'},
y={'units': 'inch'})
p.model.add_subsystem('indep', indep_comp)
p.model.add_subsystem('comp1', exec_comp)
p.model.connect('indep.x', 'comp1.x')
p.setup()
p.run_model()
assert_rel_error(self, p['indep.x'], np.ones(5))
assert_rel_error(self, p['comp1.x'], np.ones(5)*12.)
assert_rel_error(self, p['comp1.y'], 60.)
def test_connect_1_to_many(self):
import numpy as np
import openmdao.api as om
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5)))
p.model.add_subsystem('C1', om.ExecComp('y=sum(x)*2.0', x=np.zeros(5)))
p.model.add_subsystem('C2', om.ExecComp('y=sum(x)*4.0', x=np.zeros(5)))
p.model.add_subsystem('C3', om.ExecComp('y=sum(x)*6.0', x=np.zeros(5)))
p.model.connect('indep.x', ['C1.x', 'C2.x', 'C3.x'])
p.setup()
p.run_model()
assert_rel_error(self, p['C1.y'], 10.)
assert_rel_error(self, p['C2.y'], 20.)
assert_rel_error(self, p['C3.y'], 30.)
def test_double_src_indices(self):
class MyComp1(om.ExplicitComponent):
def setup(self):
self.add_input('x', np.ones(3), src_indices=[0, 1, 2])
self.add_output('y', 1.0)
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])*2.0
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5)))
p.model.add_subsystem('C1', MyComp1())
p.model.connect('indep.x', 'C1.x', src_indices=[1, 0, 2])
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception),
"Group (<model>): src_indices has been defined in both "
"connect('indep.x', 'C1.x') and add_input('C1.x', ...).")
def test_connect_src_indices(self):
import numpy as np
import openmdao.api as om
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5)))
p.model.add_subsystem('C1', om.ExecComp('y=sum(x)*2.0', x=np.zeros(3)))
p.model.add_subsystem('C2', om.ExecComp('y=sum(x)*4.0', x=np.zeros(2)))
# connect C1.x to the first 3 entries of indep.x
p.model.connect('indep.x', 'C1.x', src_indices=[0, 1, 2])
# connect C2.x to the last 2 entries of indep.x
# use -2 (same as 3 in this case) to show that negative indices work.
p.model.connect('indep.x', 'C2.x', src_indices=[-2, 4])
p.setup()
p.run_model()
assert_rel_error(self, p['C1.x'], np.ones(3))
assert_rel_error(self, p['C1.y'], 6.)
assert_rel_error(self, p['C2.x'], np.ones(2))
assert_rel_error(self, p['C2.y'], 8.)
def test_connect_src_indices_noflat(self):
import numpy as np
import openmdao.api as om
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', np.arange(12).reshape((4, 3))))
p.model.add_subsystem('C1', om.ExecComp('y=sum(x)*2.0', x=np.zeros((2, 2))))
# connect C1.x to entries (0,0), (-1,1), (2,1), (1,1) of indep.x
p.model.connect('indep.x', 'C1.x',
src_indices=[[(0, 0), (-1, 1)],
[(2, 1), (1, 1)]], flat_src_indices=False)
p.setup()
p.run_model()
assert_rel_error(self, p['C1.x'], np.array([[0., 10.],
[7., 4.]]))
assert_rel_error(self, p['C1.y'], 42.)
def test_promote_not_found1(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5)),
promotes_outputs=['x'])
p.model.add_subsystem('C1', om.ExecComp('y=x'), promotes_inputs=['x'])
p.model.add_subsystem('C2', om.ExecComp('y=x'), promotes_outputs=['x*'])
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception),
"ExecComp (C2): 'promotes_outputs' failed to find any matches for "
"the following names or patterns: ['x*']. "
"Check to make sure it is not empty")
def test_promote_not_found2(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5)),
promotes_outputs=['x'])
p.model.add_subsystem('C1', om.ExecComp('y=x'), promotes_inputs=['x'])
p.model.add_subsystem('C2', om.ExecComp('y=x'), promotes_inputs=['xx'])
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception),
"ExecComp (C2): 'promotes_inputs' failed to find any matches for "
"the following names or patterns: ['xx']. "
"Check to make sure it is not empty")
def test_promote_not_found3(self):
p = om.Problem()
p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5)),
promotes_outputs=['x'])
p.model.add_subsystem('C1', om.ExecComp('y=x'), promotes=['x'])
p.model.add_subsystem('C2', om.ExecComp('y=x'), promotes=['xx'])
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception),
"ExecComp (C2): 'promotes' failed to find any matches for "
"the following names or patterns: ['xx']. "
"Check to make sure it is not empty")
def test_empty_group(self):
p = om.Problem()
g1 = p.model.add_subsystem('G1', om.Group(), promotes=['*'])
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception),
"Group (G1): 'promotes' failed to find any matches for "
"the following names or patterns: ['*']. "
"Check to make sure it is not empty")
def test_missing_promote_var(self):
p = om.Problem()
indep_var_comp = om.IndepVarComp('z', val=2.)
p.model.add_subsystem('indep_vars', indep_var_comp, promotes=['*'])
p.model.add_subsystem('d1', om.ExecComp("y1=z+bar"),
promotes_inputs=['z', 'foo'])
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception),
"ExecComp (d1): 'promotes_inputs' failed to find any matches for "
"the following names or patterns: ['foo']. "
"Check to make sure it is not empty")
def test_missing_promote_var2(self):
p = om.Problem()
indep_var_comp = om.IndepVarComp('z', val=2.)
p.model.add_subsystem('indep_vars', indep_var_comp, promotes=['*'])
p.model.add_subsystem('d1', om.ExecComp("y1=z+bar"),
promotes_outputs=['y1', 'blammo', ('bar', 'blah')])
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception),
"ExecComp (d1): 'promotes_outputs' failed to find any matches for "
"the following names or patterns: ['bar', 'blammo']. "
"Check to make sure it is not empty")
def test_promote_src_indices(self):
import numpy as np
import openmdao.api as om
class MyComp1(om.ExplicitComponent):
def setup(self):
# this input will connect to entries 0, 1, and 2 of its source
self.add_input('x', np.ones(3), src_indices=[0, 1, 2])
self.add_output('y', 1.0)
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])*2.0
class MyComp2(om.ExplicitComponent):
def setup(self):
# this input will connect to entries 3 and 4 of its source
self.add_input('x', np.ones(2), src_indices=[3, 4])
self.add_output('y', 1.0)
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])*4.0
p = om.Problem()
# by promoting the following output and inputs to 'x', they will
# be automatically connected
p.model.add_subsystem('indep', om.IndepVarComp('x', np.ones(5)),
promotes_outputs=['x'])
p.model.add_subsystem('C1', MyComp1(), promotes_inputs=['x'])
p.model.add_subsystem('C2', MyComp2(), promotes_inputs=['x'])
p.setup()
p.run_model()
assert_rel_error(self, p['C1.x'], np.ones(3))
assert_rel_error(self, p['C1.y'], 6.)
assert_rel_error(self, p['C2.x'], np.ones(2))
assert_rel_error(self, p['C2.y'], 8.)
def test_promote_src_indices_nonflat(self):
import numpy as np
import openmdao.api as om
class MyComp(om.ExplicitComponent):
def setup(self):
# We want to pull the following 4 values out of the source:
# [(0,0), (3,1), (2,1), (1,1)].
# Because our input is also non-flat we arrange the
# source index tuples into an array having the same shape
# as our input. If we didn't set flat_src_indices to False,
# we could specify src_indices as a 1D array of indices into
# the flattened source.
self.add_input('x', np.ones((2, 2)),
src_indices=[[(0, 0), (3, 1)],
[(2, 1), (1, 1)]],
flat_src_indices=False)
self.add_output('y', 1.0)
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])
p = om.Problem()
# by promoting the following output and inputs to 'x', they will
# be automatically connected
p.model.add_subsystem('indep',
om.IndepVarComp('x', np.arange(12).reshape((4, 3))),
promotes_outputs=['x'])
p.model.add_subsystem('C1', MyComp(),
promotes_inputs=['x'])
p.setup()
p.run_model()
assert_rel_error(self, p['C1.x'],
np.array([[0., 10.],
[7., 4.]]))
assert_rel_error(self, p['C1.y'], 21.)
def test_promote_src_indices_nonflat_to_scalars(self):
class MyComp(om.ExplicitComponent):
def setup(self):
self.add_input('x', 1.0, src_indices=[(3, 1)], shape=(1,))
self.add_output('y', 1.0)
def compute(self, inputs, outputs):
outputs['y'] = inputs['x']*2.0
p = om.Problem()
p.model.add_subsystem('indep',
om.IndepVarComp('x', np.arange(12).reshape((4, 3))),
promotes_outputs=['x'])
p.model.add_subsystem('C1', MyComp(), promotes_inputs=['x'])
p.set_solver_print(level=0)
p.setup()
p.run_model()
assert_rel_error(self, p['C1.x'], 10.)
assert_rel_error(self, p['C1.y'], 20.)
def test_promote_src_indices_nonflat_error(self):
class MyComp(om.ExplicitComponent):
def setup(self):
self.add_input('x', 1.0, src_indices=[(3, 1)])
self.add_output('y', 1.0)
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])
p = om.Problem()
p.model.add_subsystem('indep',
om.IndepVarComp('x', np.arange(12).reshape((4, 3))),
promotes_outputs=['x'])
p.model.add_subsystem('C1', MyComp(), promotes_inputs=['x'])
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception),
"src_indices for 'x' is not flat, so its input shape "
"must be provided. src_indices may contain an extra "
"dimension if the connected source is not flat, making "
"the input shape ambiguous.")
@parameterized.expand(itertools.product(
[((4, 3), [(0, 0), (3, 1), (2, 1), (1, 1)]),
((1, 12), [(0, 0), (0, 10), (0, 7), (0, 4)]),
((12,), [0, 10, 7, 4]),
((12, 1), [(0, 0), (10, 0), (7, 0), (4, 0)])],
[(2, 2), (4,), (4, 1), (1, 4)],
), name_func=lambda f, n, p: 'test_promote_src_indices_'+'_'.join(str(a) for a in p.args))
def test_promote_src_indices_param(self, src_info, tgt_shape):
src_shape, idxvals = src_info
class MyComp(om.ExplicitComponent):
def setup(self):
if len(tgt_shape) == 1:
tshape = None # don't need to set shape if input is flat
sidxs = idxvals
else:
tshape = tgt_shape
sidxs = []
i = 0
for r in range(tgt_shape[0]):
sidxs.append([])
for c in range(tgt_shape[1]):
sidxs[-1].append(idxvals[i])
i += 1
self.add_input('x', np.ones(4).reshape(tgt_shape),
src_indices=sidxs, shape=tshape)
self.add_output('y', 1.0)
def compute(self, inputs, outputs):
outputs['y'] = np.sum(inputs['x'])
p = om.Problem()
p.model.add_subsystem('indep',
om.IndepVarComp('x', np.arange(12).reshape(src_shape)),
promotes_outputs=['x'])
p.model.add_subsystem('C1', MyComp(), promotes_inputs=['x'])
p.set_solver_print(level=0)
p.setup()
p.run_model()
assert_rel_error(self, p['C1.x'],
np.array([0., 10., 7., 4.]).reshape(tgt_shape))
assert_rel_error(self, p['C1.y'], 21.)
def test_set_order_feature(self):
import openmdao.api as om
class ReportOrderComp(om.ExplicitComponent):
"""Adds name to list."""
def __init__(self, order_list):
super(ReportOrderComp, self).__init__()
self._order_list = order_list
def compute(self, inputs, outputs):
self._order_list.append(self.pathname)
# this list will record the execution order of our C1, C2, and C3 components
order_list = []
prob = om.Problem()
model = prob.model
model.add_subsystem('indeps', om.IndepVarComp('x', 1.))
model.add_subsystem('C1', ReportOrderComp(order_list))
model.add_subsystem('C2', ReportOrderComp(order_list))
model.add_subsystem('C3', ReportOrderComp(order_list))
prob.setup()
prob.run_model()
self.assertEqual(order_list, ['C1', 'C2', 'C3'])
# reset the shared order list
order_list[:] = []
# now swap C2 and C1 in the order
model.set_order(['indeps', 'C2', 'C1', 'C3'])
# after changing the order, we must call setup again
prob.setup()
prob.run_model()
self.assertEqual(order_list, ['C2', 'C1', 'C3'])
def test_set_order(self):
order_list = []
prob = om.Problem()
model = prob.model
model.nonlinear_solver = om.NonlinearRunOnce()
model.add_subsystem('indeps', om.IndepVarComp('x', 1.))
model.add_subsystem('C1', ReportOrderComp(order_list))
model.add_subsystem('C2', ReportOrderComp(order_list))
model.add_subsystem('C3', ReportOrderComp(order_list))
model.connect('indeps.x', 'C1.x')
model.connect('C1.y', 'C2.x')
model.connect('C2.y', 'C3.x')
prob.set_solver_print(level=0)
self.assertEqual(['indeps', 'C1', 'C2', 'C3'],
[s.name for s in model._static_subsystems_allprocs])
prob.setup()
prob.run_model()
self.assertEqual(['C1', 'C2', 'C3'], order_list)
order_list[:] = []
# Big boy rules
model.set_order(['indeps', 'C2', 'C1', 'C3'])
prob.setup()
prob.run_model()
self.assertEqual(['C2', 'C1', 'C3'], order_list)
# Extra
with self.assertRaises(ValueError) as cm:
model.set_order(['indeps', 'C2', 'junk', 'C1', 'C3'])
self.assertEqual(str(cm.exception),
"Group (<model>): subsystem(s) ['junk'] found in subsystem order but don't exist.")
# Missing
with self.assertRaises(ValueError) as cm:
model.set_order(['indeps', 'C2', 'C3'])
self.assertEqual(str(cm.exception),
"Group (<model>): ['C1'] expected in subsystem order and not found.")
# Extra and Missing
with self.assertRaises(ValueError) as cm:
model.set_order(['indeps', 'C2', 'junk', 'C1', 'junk2'])