src_indices best practices

Viewed 43

After ver. 3.13 src_indices is changed, I could not find it in docs. Could you share a sample code for connecting a smaller portion of a large matrix?

i.e. source is 5x5 matrix and target is 2x2 starting from [2,3]

1 Answers

I find it easiest to think about connections as slices. We added om.slicer to handle indices via slicing notation. The following example connects a 2x2 portion of a 5x5 matrix, starting from indices [2, 3]:

import openmdao.api as om
import numpy as np

print('Connecting a 2x2 submatrix of M to B')

p = om.Problem()

ivc = p.model.add_subsystem('ivc', om.IndepVarComp())
ivc.add_output('M', val=np.arange(25).reshape((5, 5)))

exec = p.model.add_subsystem('exec', om.ExecComp())

exec.add_expr('A = B', A={'shape': (2, 2)}, B={'shape': (2, 2)})

p.model.connect('ivc.M', 'exec.B', src_indices=om.slicer[2:4, 3:5])

p.setup()

p.run_model()

print('M')
print(p.get_val('ivc.M'))

print('A')
print(p.get_val('exec.A'))
Connecting a 2x2 submatrix of M to B
M
[[ 0.  1.  2.  3.  4.]
 [ 5.  6.  7.  8.  9.]
 [10. 11. 12. 13. 14.]
 [15. 16. 17. 18. 19.]
 [20. 21. 22. 23. 24.]]
A
[[13. 14.]
 [18. 19.]]

Or, for instance, connecting only rows [0, 2, 3] of the 5x5 matrix to the target:

rint('Connecting rows 0, 2, and 3 of M to B')

p = om.Problem()

ivc = p.model.add_subsystem('ivc', om.IndepVarComp())
ivc.add_output('M', val=np.arange(25).reshape((5, 5)))

exec = p.model.add_subsystem('exec', om.ExecComp())

exec.add_expr('A = B', A={'shape': (3, 5)}, B={'shape': (3, 5)})

p.model.connect('ivc.M', 'exec.B', src_indices=om.slicer[[0, 2 ,3], :])

p.setup()

p.run_model()

print('M')
print(p.get_val('ivc.M'))

print('A')
print(p.get_val('exec.A'))
Connecting rows 0, 2, and 3 of M to B
M
[[ 0.  1.  2.  3.  4.]
 [ 5.  6.  7.  8.  9.]
 [10. 11. 12. 13. 14.]
 [15. 16. 17. 18. 19.]
 [20. 21. 22. 23. 24.]]
A
[[ 0.  1.  2.  3.  4.]
 [10. 11. 12. 13. 14.]
 [15. 16. 17. 18. 19.]]

While we discuss this feature in some of the parallelization docs, you're correct that we need to discuss it in our connection documentation.

Related