use common subexpression for fast evaluation

2012-08-16
2013-04-11
  • Ruge, Vitalij

    Ruge, Vitalij - 2012-08-16

    Is it possible to force casADi to evaluate common subexpression and reuse them for further processing?

    I have the following casADi code segment:

    f = cas.SXMatrix(self.md.nx, self.mm)
            for j in xrange(self.mm):
                Zj = self.__getZj(j, (1-self.const_u)*j)
                f[:,j] = feval([Zj])[0]
                
            Q = self.Q
            Q = Q[:,1:]
            Q = cas.SXMatrix(Q.T)
            X0 = cas.reshape(cas.veccat(self.m*[ self.X[:,0]]),(self.m, self.md.nx))
            X1 = self.X[:,1:self.mm].T
            
            f_system = X0 + self.dt*cas.mul(Q,f.T) - X1
    

    which produces the generated SXMatrix f_system:

    SXMatrix: Matrix<SX>(rows = 3, cols = 2):
    [[((x_0_0+(0.4*((((0.110301*((((1-(x_1_0*x_1_0))*x_0_0)-x_1_0)+u_0))+(0.189699*((((1-(x_1_1*x_1_1))
     *x_0_1)-x_1_1)+u_1)))+(-0.0339074*((((1-(x_1_2*x_1_2))*x_0_2)-x_1_2)+u_2)))+(0.0103006*((((1-
     (x_1_3*x_1_3))*x_0_3)-x_1_3)+u_3)))))-x_0_1),  ((x_1_0+(0.4*((((0.110301*x_0_0)+(0.189699*x_0_1))+
     (-0.0339074*x_0_2))+(0.0103006*x_0_3))))-x_1_1) ]
     [((x_0_0+(0.4*((((0.0730328*((((1-(x_1_0*x_1_0))*x_0_0)-x_1_0)+u_0))+(0.450574*((((1-(x_1_1*x_1_1))
      *x_0_1)-x_1_1)+u_1)))+(0.226967*((((1-(x_1_2*x_1_2))*x_0_2)-x_1_2)+u_2)))+(-0.0269672*((((1-
      (x_1_3*x_1_3))*x_0_3)-x_1_3)+u_3)))))-x_0_2),  ((x_1_0+(0.4*((((0.0730328*x_0_0)+(0.450574*x_0_1))+
      (0.226967*x_0_2))+(-0.0269672*x_0_3))))-x_1_2) ]
     [((x_0_0+(0.4*((((0.0833333*((((1-(x_1_0*x_1_0))*x_0_0)-x_1_0)+u_0))+(0.416667*((((1-(x_1_1*x_1_1))
      *x_0_1)-x_1_1)+u_1)))+(0.416667*((((1-(x_1_2*x_1_2))*x_0_2)-x_1_2)+u_2)))+(0.0833333*((((1-
      (x_1_3*x_1_3))*x_0_3)-x_1_3)+u_3)))))-x_0_3),  ((x_1_0+(0.4*((((0.0833333*x_0_0)+(0.416...
    

    , where several expression occure multiple times. Is there a way to optimize this?

     
  • Ruge, Vitalij

    Ruge, Vitalij - 2012-08-16

    excellent!!
    Thanks.

    Best Vitalij

     

Log in to post a comment.