This might be interesting to look at in order to generate more complicated tensor expressions: http://tensor-compiler.org/