Skip to main content

Single Tensor Summation using Einsum with Sparse Partials

This is an example of how to properly use the einsum function to compute the summation of a single vector while using sparse partial derivative.

from csdl_om import Simulatorimport numpy as npfrom csdl import Modelimport csdl

class ExampleTensorSummationSparse(Model):
    def define(self):        # Shape of Tensor        shape3 = (2, 4, 3)        c = np.arange(24).reshape(shape3)
        # Declaring tensor        tens = self.declare_variable('c', val=c)
        self.register_output(            'einsum_summ2_sparse_derivs',            csdl.einsum_new_api(tens,                                operation=[(33, 66, 99)],                                partial_format='sparse'))

sim = Simulator(ExampleTensorSummationSparse())sim.run()
print('c', sim['c'].shape)print(sim['c'])print('einsum_summ2_sparse_derivs',      sim['einsum_summ2_sparse_derivs'].shape)print(sim['einsum_summ2_sparse_derivs'])
[[[ 0.  1.  2.]  [ 3.  4.  5.]  [ 6.  7.  8.]  [ 9. 10. 11.]]
 [[12. 13. 14.]  [15. 16. 17.]  [18. 19. 20.]  [21. 22. 23.]]]einsum_summ2_sparse_derivs (1,)[276.]