-
Notifications
You must be signed in to change notification settings - Fork 240
/
test_exec_comp.py
1983 lines (1559 loc) · 73.9 KB
/
test_exec_comp.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
import itertools
import unittest
import math
import os
import shutil
import tempfile
import numpy as np
from numpy.testing import assert_almost_equal
import scipy
from io import StringIO
from packaging.version import Version
try:
from parameterized import parameterized
except ImportError:
from openmdao.utils.assert_utils import SkipParameterized as parameterized
import openmdao.api as om
from openmdao.components.exec_comp import _expr_dict, _temporary_expr_dict
from openmdao.utils.assert_utils import assert_near_equal, assert_check_partials, assert_warning
from openmdao.utils.general_utils import env_truthy
from openmdao.utils.testing_utils import force_check_partials
from openmdao.utils.om_warnings import SetupWarning
_ufunc_test_data = {
'min': {
'str': 'f=min(x)',
'check_func': np.min,
'args': { 'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'max': {
'str': 'f=max(x)',
'check_func': np.max,
'args': { 'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'diff': {
'str': 'f=diff(x)',
'check_func': np.diff,
'args': { 'f': {'val': np.zeros(5)},
'x': {'val': np.random.random(6)}}},
'abs': {
'str': 'f=abs(x)',
'check_func': np.abs,
'args': { 'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'acos': {
'str': 'f=acos(x)',
'check_func': np.arccos,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6) - 0.5}}},
'arccos': {
'str': 'f=arccos(x)',
'check_func': np.arccos,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6) - 0.5}}},
'arccosh': {
'str': 'f=arccosh(x)',
'check_func': np.arccosh,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': 1.1 + np.random.random(6)}}},
'acosh': {
'str': 'f=acosh(x)',
'check_func': np.arccosh,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': 1.1 + np.random.random(6)}}},
'arange': {
'str': 'f=arange(0,10,2)',
'check_val': np.arange(0, 10, 2),
'args': {'f': {'val': np.zeros(5)}}},
'arcsin': {
'str': 'f=arcsin(x)',
'check_func': np.arcsin,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6) - .5}}},
'arcsinh': {
'str': 'f=arcsinh(x)',
'check_func': np.arcsinh,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'asinh': {
'str': 'f=asinh(x)',
'check_func': np.arcsinh,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'asin': {
'str': 'f=asin(x)',
'check_func': np.arcsin,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6) - .5}}},
'arctan': {
'str': 'f=arctan(x)',
'check_func': np.arctan,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'arctan2': {
'str': 'f=arctan2(y, x)',
'check_val': np.array([-2.35619449, -0.78539816, 0.78539816, 2.35619449]),
'args': {'f': {'val': np.zeros(4)},
'x': {'val': np.array([-1, +1, +1, -1])},
'y': {'val': np.array([-1, -1, +1, +1])}}},
'atan': {
'str': 'f=atan(x)',
'check_func': np.arctan,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'cos': {
'str': 'f=cos(x)',
'check_func': np.cos,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'cosh': {
'str': 'f=cosh(x)',
'check_func': np.cosh,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'dot': {
'str': 'f=dot(x, y)',
'check_func': np.dot,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)},
'y': {'val': np.random.random(6)}}},
'e': {
'str': 'f=e',
'check_val': np.e,
'args': {'f': {'val': 0.0}}},
'erf': {
'str': 'f=erf(x)',
'check_func': scipy.special.erf,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'erfc': {
'str': 'f=erfc(x)',
'check_func': scipy.special.erfc,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'exp': {
'str': 'f=exp(x)',
'check_func': np.exp,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'expm1': {
'str': 'f=expm1(x)',
'check_func': np.expm1,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'fmax': {
'str': 'f=fmax(x, y)',
'check_func': np.fmax,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)},
'y': {'val': np.random.random(6)}}},
'fmin': {
'str': 'f=fmin(x, y)',
'check_func': np.fmin,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)},
'y': {'val': np.random.random(6)}}},
'inner': {
'str': 'f=inner(x, y)',
'check_func': np.inner,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)},
'y': {'val': np.random.random(6)}}},
'isinf': {
'str': 'f=isinf(x)',
'check_func': np.isinf,
'args': {'f': {'val': np.zeros(3)},
'x': {'val': [0, np.inf, 5.0]}}},
'isnan': {
'str': 'f=isnan(x)',
'check_func': np.isnan,
'args': {'f': {'val': np.zeros(3)},
'x': {'val': [0, np.nan, np.nan]}}},
'kron': {
'str': 'f=kron(x, y)',
'check_func': np.kron,
'args': {'f': {'val': np.zeros(36)},
'x': {'val': np.random.random(6)},
'y': {'val': np.random.random(6)}}},
'linspace': {
'str': 'f=linspace(0,10,50)',
'check_val': np.linspace(0, 10, 50),
'args': {'f': {'val': np.zeros(50)}}},
'log': {
'str': 'f=log(x)',
'check_func': np.log,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6) + 0.1}}},
'log10': {
'str': 'f=log10(x)',
'check_func': np.log10,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6) + 0.1}}},
'log1p': {
'str': 'f=log1p(x)',
'check_func': np.log1p,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'matmul': {
'str': 'f=matmul(x, y)',
'check_func': np.matmul,
'args': {'f': {'val': np.zeros((3, 1))},
'x': {'val': np.random.random((3, 3))},
'y': {'val': np.random.random((3, 1))}}},
'maximum': {
'str': 'f=maximum(x, y)',
'check_func': np.maximum,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)},
'y': {'val': np.random.random(6)}}},
'minimum': {
'str': 'f=minimum(x, y)',
'check_func': np.minimum,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)},
'y': {'val': np.random.random(6)}}},
'ones': {
'str': 'f=ones(21)',
'check_val': np.ones(21),
'args': {'f': {'val': np.zeros(21)}}},
'outer': {
'str': 'f=outer(x, y)',
'check_func': np.outer,
'args': {'f': {'val': np.zeros((6, 6))},
'x': {'val': np.random.random(6)},
'y': {'val': np.random.random(6)}}},
'pi': {
'str': 'f=pi',
'check_val': np.pi,
'args': {'f': {'val': 0.0}}},
'power': {
'str': 'f=power(x, y)',
'check_func': np.power,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)},
'y': {'val': np.random.random(6) + 1.0}}},
'prod': {
'str': 'f=prod(x)',
'check_func': np.prod,
'args': {'f': {'val': 0.0},
'x': {'val': np.random.random(6)}}},
'sin': {
'str': 'f=sin(x)',
'check_func': np.sin,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'sinh': {
'str': 'f=sinh(x)',
'check_func': np.sinh,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'sum': {
'str': 'f=sum(x)',
'check_func': np.sum,
'args': {'f': {'val': 0.0},
'x': {'val': np.random.random(6)}}},
'tan': {
'str': 'f=tan(x)',
'check_func': np.tan,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'tanh': {
'str': 'f=tanh(x)',
'check_func': np.tanh,
'args': {'f': {'val': np.zeros(6)},
'x': {'val': np.random.random(6)}}},
'tensordot': {
'str': 'f=tensordot(x, y)',
'check_func': np.tensordot,
'args': {'f': {'val': 0.0},
'x': {'val': np.random.random((6, 6))},
'y': {'val': np.random.random((6, 6))}}},
'zeros': {
'str': 'f=zeros(21)',
'check_val': np.zeros(21),
'args': {'f': {'val': np.zeros(21)}}},
}
class TestExecComp(unittest.TestCase):
def test_missing_partial_warn(self):
p = om.Problem()
model = p.model
comp = om.ExecComp('z=3.0*x + 2.5*y')
model.add_subsystem('comp', comp)
comp.declare_partials('z', 'x', method='fd')
p.setup()
with assert_warning(UserWarning, "'comp' <class ExecComp>: The following partial derivatives have not been declared so they are assumed to be zero: ['z' wrt 'y']."):
p.final_setup()
def test_colon_vars(self):
prob = om.Problem()
prob.model.add_subsystem('C1', om.ExecComp('y=foo:bar+1.'))
with self.assertRaises(Exception) as context:
prob.setup()
self.assertEqual(str(context.exception),
"'C1' <class ExecComp>: failed to compile expression 'y=foo:bar+1.'.")
def test_bad_kwargs(self):
prob = om.Problem()
prob.model.add_subsystem('C1', om.ExecComp('y=x+1.', xx=2.0))
with self.assertRaises(Exception) as context:
prob.setup()
self.assertEqual(str(context.exception),
"'C1' <class ExecComp>: arg 'xx' in call to ExecComp() does not refer to any variable "
"in the expressions ['y=x+1.']")
def test_bad_kwargs_meta(self):
prob = om.Problem()
prob.model.add_subsystem('C1', om.ExecComp('y=x+1.',
x={'val': 2, 'low': 0, 'high': 10, 'units': 'ft'}))
with self.assertRaises(Exception) as context:
prob.setup()
self.assertEqual(str(context.exception),
"'C1' <class ExecComp>: the following metadata names were not recognized for "
"variable 'x': ['high', 'low']")
def test_name_collision_const(self):
prob = om.Problem()
prob.model.add_subsystem('C1', om.ExecComp('e=x+1.'))
with self.assertRaises(Exception) as context:
prob.setup()
self.assertEqual(str(context.exception),
"'C1' <class ExecComp>: cannot assign to variable 'e' because it's already defined "
"as an internal function or constant.")
def test_name_collision_func(self):
prob = om.Problem()
prob.model.add_subsystem('C1', om.ExecComp('sin=x+1.'))
with self.assertRaises(Exception) as context:
prob.setup()
self.assertEqual(str(context.exception),
"'C1' <class ExecComp>: cannot assign to variable 'sin' because it's already defined "
"as an internal function or constant.")
def test_func_as_rhs_var(self):
prob = om.Problem()
prob.model.add_subsystem('C1', om.ExecComp('y=sin+1.'))
with self.assertRaises(Exception) as context:
prob.setup()
self.assertEqual(str(context.exception),
"'C1' <class ExecComp>: cannot use 'sin' as a variable because it's already defined "
"as an internal function or constant.")
def test_mixed_type(self):
prob = om.Problem()
C1 = prob.model.add_subsystem('C1', om.ExecComp('y=sum(x)',
x=np.arange(10, dtype=float)))
prob.setup()
# Conclude setup but don't run model.
prob.final_setup()
self.assertTrue('x' in C1._inputs)
self.assertTrue('y' in C1._outputs)
prob.set_solver_print(level=0)
prob.run_model()
assert_near_equal(C1._outputs['y'], 45.0, 0.00001)
def test_simple(self):
prob = om.Problem()
C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+1.', x=2.0))
prob.setup()
# Conclude setup but don't run model.
prob.final_setup()
self.assertTrue('x' in C1._inputs)
self.assertTrue('y' in C1._outputs)
prob.set_solver_print(level=0)
prob.run_model()
assert_near_equal(C1._outputs['y'], 3.0, 0.00001)
def test_for_spaces(self):
prob = om.Problem()
C1 = prob.model.add_subsystem('C1', om.ExecComp('y = pi * x', x=2.0))
prob.setup()
# Conclude setup but don't run model.
prob.final_setup()
self.assertTrue('x' in C1._inputs)
self.assertTrue('y' in C1._outputs)
self.assertTrue('pi' not in C1._inputs)
prob.set_solver_print(level=0)
prob.run_model()
assert_near_equal(C1._outputs['y'], 2 * math.pi, 0.00001)
def test_units(self):
prob = om.Problem()
prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm'))
C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+z+1.',
x={'val': 2.0, 'units': 'm'},
y={'units': 'm'},
z=2.0))
prob.model.connect('indep.x', 'C1.x')
prob.setup()
prob.set_solver_print(level=0)
prob.run_model()
assert_near_equal(C1._outputs['y'], 4.0, 0.00001)
def test_units_varname(self):
prob = om.Problem()
with self.assertRaises(TypeError) as cm:
prob.model.add_subsystem('C1', om.ExecComp('y=x+units+1.',
x={'val': 2.0, 'units': 'm'},
y={'units': 'm'},
units=2.0))
self.assertEqual(str(cm.exception),
"ExecComp: Value (2.0) of option 'units' has type 'float', "
"but type 'str' was expected.")
def test_units_varname_str(self):
prob = om.Problem()
with self.assertRaises(ValueError) as cm:
prob.model.add_subsystem('C1', om.ExecComp('y=x+units+1.',
x={'val': 2.0, 'units': 'm'},
y={'units': 'm'},
units='two'))
self.assertEqual(str(cm.exception), "The units 'two' are invalid.")
def test_units_varname_novalue(self):
prob = om.Problem()
prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm'))
C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+units+1.',
x={'val': 2.0, 'units': 'm'},
y={'units': 'm'}))
prob.model.connect('indep.x', 'C1.x')
with self.assertRaises(NameError) as cm:
prob.setup()
self.assertEqual(str(cm.exception),
"'C1' <class ExecComp>: cannot use variable name 'units' because it's a reserved keyword.")
def test_common_units(self):
# all variables in the ExecComp have the same units
prob = om.Problem()
prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm'))
prob.model.add_subsystem('comp', om.ExecComp('y=x+z+1.', units='m',
x={'val': 2.0},
z=2.0))
prob.model.connect('indep.x', 'comp.x')
prob.setup()
prob.run_model()
assert_near_equal(prob['comp.y'], 4.0, 0.00001)
def test_common_units_no_meta(self):
# make sure common units are assigned when no metadata is provided
prob = om.Problem()
prob.model.add_subsystem('indep', om.IndepVarComp('x', 2.0, units='km'))
prob.model.add_subsystem('comp', om.ExecComp('y = x+1', units='m'))
prob.model.connect('indep.x', 'comp.x')
prob.setup()
prob.run_model()
assert_near_equal(prob['comp.y'], 2001., 0.00001)
def test_conflicting_units(self):
prob = om.Problem()
prob.model.add_subsystem('indep', om.IndepVarComp('x', 100.0, units='cm'))
C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+z+1.', units='m',
x={'val': 2.0, 'units': 'km'},
z=2.0))
prob.model.connect('indep.x', 'C1.x')
with self.assertRaises(RuntimeError) as cm:
prob.setup()
self.assertEqual(str(cm.exception),
"'C1' <class ExecComp>: units of 'km' have been specified for variable 'x', but "
"units of 'm' have been specified for the entire component.")
def test_shape_and_value(self):
p = om.Problem()
model = p.model
model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5',
x={'shape': (5,), 'val': np.zeros(5)},
y={'shape': (5,), 'val': np.zeros(5)}))
p.setup()
p.run_model()
J = p.compute_totals(of=['comp.y'], wrt=['comp.x'], return_format='array')
assert_almost_equal(J, np.eye(5)*3., decimal=6)
def test_conflicting_shape(self):
p = om.Problem()
model = p.model
model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5',
x={'shape': (5,), 'val': 5},
y={'shape': (5,)}))
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception).replace('L,', ','), # L on Windows
"'comp' <class ExecComp>: shape of (5,) has been specified for variable 'x', "
"but a value of shape (1,) has been provided.")
def test_common_shape(self):
p = om.Problem()
model = p.model
model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,)))
p.setup()
p.run_model()
J = p.compute_totals(of=['comp.y'], wrt=['comp.x'], return_format='array')
assert_almost_equal(J, np.eye(5)*3., decimal=6)
def test_common_shape_with_values(self):
p = om.Problem()
model = p.model
model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,),
x={'val': np.zeros(5)},
y={'val': np.zeros(5)}))
p.setup()
p.run_model()
J = p.compute_totals(of=['comp.y'], wrt=['comp.x'], return_format='array')
assert_almost_equal(J, np.eye(5)*3., decimal=6)
def test_common_shape_conflicting_shape(self):
p = om.Problem()
model = p.model
model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,),
y={'shape': (10,)}))
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception).replace('L,', ','), # L on Windows
"'comp' <class ExecComp>: shape of (10,) has been specified for variable 'y', "
"but shape of (5,) has been specified for the entire component.")
def test_common_shape_conflicting_value(self):
p = om.Problem()
model = p.model
model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', shape=(5,),
x={'val': 5}))
with self.assertRaises(Exception) as context:
p.setup()
self.assertEqual(str(context.exception).replace('1L,', '1,'), # 1L on Windows
"'comp' <class ExecComp>: value of shape (1,) has been specified for variable 'x', "
"but shape of (5,) has been specified for the entire component.")
def test_math(self):
prob = om.Problem()
C1 = prob.model.add_subsystem('C1', om.ExecComp('y=sin(x)', x=2.0))
prob.setup()
# Conclude setup but don't run model.
prob.final_setup()
self.assertTrue('x' in C1._inputs)
self.assertTrue('y' in C1._outputs)
prob.set_solver_print(level=0)
prob.run_model()
assert_near_equal(C1._outputs['y'], math.sin(2.0), 0.00001)
def test_np(self):
prob = om.Problem()
prob.model.add_subsystem('C1', om.ExecComp(['y1=sin(x)', 'y2=np.cos(x)'], x=2.0))
prob.setup()
with self.assertRaises(Exception) as context:
prob.run_model()
self.assertEqual(str(context.exception),
"'C1' <class ExecComp>: Error occurred evaluating 'y2=np.cos(x)':\n"
" ExecComp supports a subset of numpy functions directly, without the 'np' prefix.\n"
" 'cos' is supported (See the documentation).")
def test_numpy(self):
prob = om.Problem()
prob.model.add_subsystem('C1', om.ExecComp('y=numpy.sin(x)', x=2.0))
prob.setup()
with self.assertRaises(Exception) as context:
prob.run_model()
self.assertEqual(str(context.exception),
"'C1' <class ExecComp>: Error occurred evaluating 'y=numpy.sin(x)':\n"
" ExecComp supports a subset of numpy functions directly, without the 'numpy' prefix.\n"
" 'sin' is supported (See the documentation).")
def test_numpy_fft(self):
prob = om.Problem()
prob.model.add_subsystem('C1', om.ExecComp('y=numpy.fft(x)', x=2.0))
prob.setup()
with self.assertRaises(Exception) as context:
prob.run_model()
self.assertEqual(str(context.exception),
"'C1' <class ExecComp>: Error occurred evaluating 'y=numpy.fft(x)':\n"
" ExecComp supports a subset of numpy functions directly, without the 'numpy' prefix.\n"
" 'fft' is not supported (See the documentation).")
def test_array(self):
prob = om.Problem()
C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x[1]',
x=np.array([1., 2., 3.]),
y=0.0))
prob.setup()
# Conclude setup but don't run model.
prob.final_setup()
self.assertTrue('x' in C1._inputs)
self.assertTrue('y' in C1._outputs)
prob.set_solver_print(level=0)
prob.run_model()
assert_near_equal(C1._outputs['y'], 2.0, 0.00001)
def test_array_lhs(self):
prob = om.Problem()
C1 = prob.model.add_subsystem('C1', om.ExecComp(['y[0]=x[1]', 'y[1]=x[0]'],
x=np.array([1., 2., 3.]),
y=np.array([0., 0.])))
prob.setup()
# Conclude setup but don't run model.
prob.final_setup()
self.assertTrue('x' in C1._inputs)
self.assertTrue('y' in C1._outputs)
prob.set_solver_print(level=0)
prob.run_model()
assert_near_equal(C1._outputs['y'], np.array([2., 1.]), 0.00001)
def test_simple_array_model(self):
prob = om.Problem()
prob.model.add_subsystem('comp', om.ExecComp(['y[0]=2.0*x[0]+7.0*x[1]',
'y[1]=5.0*x[0]-3.0*x[1]'],
x=np.zeros([2]), y=np.zeros([2])))
prob.setup()
prob.set_solver_print(level=0)
prob.run_model()
data = force_check_partials(prob, out_stream=None)
assert_check_partials(data, atol=1e-5, rtol=1e-5)
def test_simple_array_model2(self):
prob = om.Problem()
prob.model.add_subsystem('comp', om.ExecComp('y = mat.dot(x)',
x=np.zeros((2,)), y=np.zeros((2,)),
mat=np.array([[2., 7.], [5., -3.]])))
prob.setup()
prob.set_solver_print(level=0)
prob.run_model()
data = force_check_partials(prob, out_stream=None)
assert_check_partials(data, atol=1e-5, rtol=1e-5)
def test_complex_step(self):
prob = om.Problem()
C1 = prob.model.add_subsystem('C1', om.ExecComp(['y=2.0*x+1.'], x=2.0))
prob.setup()
# Conclude setup but don't run model.
prob.final_setup()
self.assertTrue('x' in C1._inputs)
self.assertTrue('y' in C1._outputs)
prob.set_solver_print(level=0)
prob.run_model()
assert_near_equal(C1._outputs['y'], 5.0, 0.00001)
C1._linearize()
assert_near_equal(C1._jacobian[('y', 'x')], [[2.0]], 0.00001)
def test_complex_step2(self):
prob = om.Problem(om.Group())
prob.model.add_subsystem('comp', om.ExecComp('y=x*x + x*2.0', x=2.0))
prob.set_solver_print(level=0)
prob.setup(check=False, mode='fwd')
prob.run_model()
J = prob.compute_totals(['comp.y'], ['comp.x'], return_format='flat_dict')
assert_near_equal(J['comp.y', 'comp.x'], np.array([[6.0]]), 0.00001)
prob.setup(check=False, mode='rev')
prob.run_model()
J = prob.compute_totals(['comp.y'], ['comp.x'], return_format='flat_dict')
assert_near_equal(J['comp.y', 'comp.x'], np.array([[6.0]]), 0.00001)
def test_abs_complex_step(self):
prob = om.Problem()
C1 = prob.model.add_subsystem('C1', om.ExecComp('y=2.0*abs(x)', x=-2.0))
prob.setup()
prob.set_solver_print(level=0)
prob.run_model()
assert_near_equal(C1._outputs['y'], 4.0, 0.00001)
# any positive C1.x should give a 2.0 derivative for dy/dx
C1._inputs['x'] = 1.0e-10
C1._linearize()
assert_near_equal(C1._jacobian['y', 'x'], [[2.0]], 0.00001)
C1._inputs['x'] = -3.0
C1._linearize()
assert_near_equal(C1._jacobian['y', 'x'], [[-2.0]], 0.00001)
C1._inputs['x'] = 0.0
C1._linearize()
assert_near_equal(C1._jacobian['y', 'x'], [[2.0]], 0.00001)
def test_arctan_complex_step(self):
prob = om.Problem()
C1 = prob.model.add_subsystem('C1', om.ExecComp('z=2.0*arctan2(y, x)', x=np.array([1+2j]), y=1))
prob.setup()
prob.set_solver_print(level=0)
prob.run_model()
assert_near_equal(C1._outputs['z'], np.array([1.57079633]), 1e-8)
def test_abs_array_complex_step(self):
prob = om.Problem()
C1 = prob.model.add_subsystem('C1', om.ExecComp('y=2.0*abs(x)',
x=np.ones(3)*-2.0, y=np.zeros(3)))
prob.setup()
prob.set_solver_print(level=0)
prob.run_model()
assert_near_equal(C1._outputs['y'], np.ones(3)*4.0, 0.00001)
# any positive C1.x should give a 2.0 derivative for dy/dx
C1._inputs['x'] = np.ones(3)*1.0e-10
C1._linearize()
assert_near_equal(C1._jacobian['y', 'x'], np.eye(3)*2.0, 0.00001)
C1._inputs['x'] = np.ones(3)*-3.0
C1._linearize()
assert_near_equal(C1._jacobian['y', 'x'], np.eye(3)*-2.0, 0.00001)
C1._inputs['x'] = np.zeros(3)
C1._linearize()
assert_near_equal(C1._jacobian['y', 'x'], np.eye(3)*2.0, 0.00001)
C1._inputs['x'] = np.array([1.5, -0.6, 2.4])
C1._linearize()
expect = np.zeros((3, 3))
expect[0, 0] = 2.0
expect[1, 1] = -2.0
expect[2, 2] = 2.0
assert_near_equal(C1._jacobian['y', 'x'], expect, 0.00001)
def test_has_diag_partials_error(self):
p = om.Problem()
model = p.model
mat = np.arange(15).reshape((3,5))
model.add_subsystem('comp', om.ExecComp('y=A.dot(x)', has_diag_partials=True, A=mat,
x=np.ones(5), y=np.ones(3)))
p.setup()
with self.assertRaises(Exception) as context:
p.final_setup()
self.assertEqual(str(context.exception),
"'comp' <class ExecComp>: has_diag_partials is True but partial(y, A) is not square (shape=(3, 15)).")
def test_has_diag_partials(self):
# Really check to see that the has_diag_partials argument had its intended effect
# run with has_diag_partials=False
p = om.Problem()
model = p.model
comp = om.ExecComp('y=3.0*x + 2.5', has_diag_partials=False, x=np.ones(5), y=np.ones(5))
model.add_subsystem('comp', comp)
p.setup()
self.assertEqual(len(comp._declared_partials_patterns), 0)
# run with has_diag_partials=True
p = om.Problem()
model = p.model
comp = om.ExecComp('y=3.0*x + 2.5', has_diag_partials=True, x=np.ones(5), y=np.ones(5))
model.add_subsystem('comp', comp)
p.setup()
p.final_setup()
declared_partials = comp._declared_partials_patterns[('y','x')]
self.assertTrue('rows' in declared_partials )
self.assertListEqual([0,1,2,3,4], list( comp._declared_partials_patterns[('y','x')]['rows']))
self.assertTrue('cols' in declared_partials )
self.assertListEqual([0,1,2,3,4], list( comp._declared_partials_patterns[('y','x')]['cols']))
def test_exec_comp_deriv_sparsity(self):
# Check to make sure that when an ExecComp has more than one
# expression that only the partials that are needed are declared and computed
# with has_diag_partials set to the default of False and just scalars
p = om.Problem()
model = p.model
comp = om.ExecComp(['y1=2.0*x1+1.', 'y2=3.0*x2-1.'],x1=1.0, x2=2.0)
model.add_subsystem('comp', comp)
p.setup()
p.final_setup()
## make sure only the partials that are needed are declared
declared_partials = comp._declared_partials_patterns
self.assertListEqual( sorted([('y1', 'x1'), ('y2', 'x2') ]),
sorted(declared_partials.keys()))
p.run_model()
# make sure only what is needed was computed
subjacs_info = comp._jacobian._subjacs_info
self.assertListEqual(sorted([('comp.y1', 'comp.x1'), ('comp.y2', 'comp.x2'),
('comp.y1', 'comp.y1'),('comp.y2', 'comp.y2')]),
sorted(subjacs_info.keys()))
# make sure the result of compute_partials is correct
J = p.compute_totals(of=['comp.y1'], wrt=['comp.x1'], return_format='array')
self.assertEqual(2.0, J)
J = p.compute_totals(of=['comp.y2'], wrt=['comp.x2'], return_format='array')
self.assertEqual(3.0, J)
# make sure this works with arrays and when has_diag_partials is the default of False
p = om.Problem()
model = p.model
comp = om.ExecComp(['y1=2.0*x1+1.', 'y2=3.0*x2-1.'],
x1=np.ones(5), y1=np.ones(5), x2=np.ones(5), y2=np.ones(5))
model.add_subsystem('comp', comp)
p.setup()
p.final_setup()
declared_partials = comp._declared_partials_patterns
self.assertListEqual( sorted([('y1', 'x1'), ('y2', 'x2') ]),
sorted(declared_partials.keys()))
p.run_model()
J = p.compute_totals(of=['comp.y1'], wrt=['comp.x1'], return_format='array')
self.assertTrue(np.all(2.0*np.identity(5) == J))
J = p.compute_totals(of=['comp.y2'], wrt=['comp.x2'], return_format='array')
self.assertTrue(np.all(3.0*np.identity(5) == J))
# with has_diag_partials True to make sure that still works with arrays
p = om.Problem()
model = p.model
comp = om.ExecComp(['y1=2.0*x1+1.', 'y2=3.0*x2-1.'], has_diag_partials=True,
x1=np.ones(5), y1=np.ones(5), x2=np.ones(5), y2=np.ones(5) )
model.add_subsystem('comp', comp)
p.setup()
p.final_setup()
declared_partials = comp._declared_partials_patterns
self.assertListEqual( sorted([('y1', 'x1'), ('y2', 'x2') ]),
sorted(declared_partials.keys()))
self.assertTrue('cols' in declared_partials[('y1', 'x1')] )
self.assertTrue('rows' in declared_partials[('y1', 'x1')] )
self.assertTrue('cols' in declared_partials[('y2', 'x2')] )
self.assertTrue('rows' in declared_partials[('y2', 'x2')] )
self.assertListEqual([0,1,2,3,4], list( comp._declared_partials_patterns[('y1','x1')]['rows']))
self.assertListEqual([0,1,2,3,4], list( comp._declared_partials_patterns[('y1','x1')]['cols']))
self.assertListEqual([0,1,2,3,4], list( comp._declared_partials_patterns[('y2','x2')]['rows']))
self.assertListEqual([0,1,2,3,4], list( comp._declared_partials_patterns[('y2','x2')]['cols']))
p.run_model()
J = p.compute_totals(of=['comp.y1'], wrt=['comp.x1'], return_format='array')
self.assertTrue(np.all(2.0*np.identity(5) == J))
J = p.compute_totals(of=['comp.y2'], wrt=['comp.x2'], return_format='array')
self.assertTrue(np.all(3.0*np.identity(5) == J))
def test_has_diag_partials_shape_only(self):
p = om.Problem()
model = p.model
model.add_subsystem('comp', om.ExecComp('y=3.0*x + 2.5', has_diag_partials=True,
x={'shape': (5,)}, y={'shape': (5,)}))
p.setup()
p.run_model()
J = p.compute_totals(of=['comp.y'], wrt=['comp.x'], return_format='array')
assert_almost_equal(J, np.eye(5)*3., decimal=6)
def test_tags(self):
prob = om.Problem(model=om.Group())
C1 = prob.model.add_subsystem('C1', om.ExecComp('y=x+z+1.',
x={'val': 1.0, 'units': 'm', 'tags': 'tagx'},
y={'units': 'm', 'tags': ['tagy','tagq']},
z={'val': 2.0, 'tags': 'tagz'}))
prob.setup(check=False)
prob.set_solver_print(level=0)
prob.run_model()
# Inputs no tags
inputs = prob.model.list_inputs(val=False, prom_name=False, out_stream=None)
self.assertEqual(sorted(inputs), [
('C1.x', {}),
('C1.z', {}),
])
# Inputs with tags
inputs = prob.model.list_inputs(val=False, prom_name=False, out_stream=None, tags="tagx")
self.assertEqual(sorted(inputs), [
('C1.x', {}),
])
# Inputs with multiple tags
inputs = prob.model.list_inputs(val=False, prom_name=False, out_stream=None, tags=["tagx", "tagz"])
self.assertEqual(sorted(inputs), [
('C1.x', {}),
('C1.z', {}),
])
# Inputs with tag that does not match
inputs = prob.model.list_inputs(val=False, prom_name=False, out_stream=None, tags="tag_wrong")
self.assertEqual(sorted(inputs), [])
# Outputs no tags
outputs = prob.model.list_outputs(val=False, prom_name=False, out_stream=None)
self.assertEqual(sorted(outputs), [
('C1.y', {}),
])
# Outputs with tags
outputs = prob.model.list_outputs(val=False, prom_name=False, out_stream=None, tags="tagy")
self.assertEqual(sorted(outputs), [
('C1.y', {}),
])
# Outputs with multiple tags
outputs = prob.model.list_outputs(val=False, prom_name=False, out_stream=None, tags=["tagy", "tagx"])
self.assertEqual(sorted(outputs), [
('C1.y', {}),
])
# Outputs with tag that does not match
outputs = prob.model.list_outputs(val=False, prom_name=False, out_stream=None, tags="tag_wrong")
self.assertEqual(sorted(outputs), [])