Issue with Component and Shape Length mismatch - as_tensor

Hi everyone,

I am currently quite new to Fenics and I am trying to build a model of the heating of a 3D block by a guassian source confined to a surface of the block. However, I am currently trying to resolve an error I am getting regarding a piece of code using as_tensor. I am setting up some tensors as shown:

i = indices(3)
G = as_tensor(T.dx(i), (i))  
G0 = as_tensor(T0.dx(i), (i))

q = as_tensor(dt/(dt + tau_q) * (tau_q/dt*q0[i] - kappa*(1+tau_T/dt)*G[i] + kappa*tau_T/dt*G0[i]),(i))

This bit of code gives me the error:

Traceback (most recent call last):
  File "target2.py", line 68, in <module>
    q = as_tensor(dt/(dt + tau_q) * (tau_q/dt*q0[i] - kappa*(1+tau_T/dt)*G[i] + kappa*tau_T/dt*G0[i]),(i))
  File "/usr/local/lib/python3.6/dist-packages/ufl/exproperators.py", line 449, in _getitem
    all_indices, slice_indices, repeated_indices = create_slice_indices(component, shape, self.ufl_free_indices)
  File "/usr/local/lib/python3.6/dist-packages/ufl/index_combination_utils.py", line 181, in create_slice_indices
    error("Component and shape length don't match.")
  File "/usr/local/lib/python3.6/dist-packages/ufl/log.py", line 172, in error
    raise self._exception_type(self._format_raw(*message))
ufl.log.UFLException: Component and shape length don't match.

I am unsure what this error actually means and how I can resolve it. For full context, my complete code is shown below:

from __future__ import print_function
from fenics import *
import numpy as np
import matplotlib.pyplot as plt
from dolfin import *
from mshr import *
from ufl import as_tensor
from ufl import indices
import math

parameters["allow_extrapolation"] = True
parameters["form_compiler"]["cpp_optimize"] = True
set_log_level(20)

# SOLVE THE HEAT TRANSFER PROBLEM FOR A 3D TARGET

#--Dimensions in mm----
x0 = 0 
y0 = 0
z0 = 0
x1 = 8
y1 = 8
z1 = 8
#----------------
t_start = 0.0
t_end = 900
nstep = 450
dt = (t_start - t_end)/ nstep
#-----------------
#Configure for dimensions of system

pi = 3.141592653589793
T_am = 0.0 #ambient vacuum temperature
T_a4 = T_am**4
epsilon = 0.05  # material emissivity
sigma = 5.67E-14 # W/(m2.K4)
es = epsilon*sigma
Laser = Expression('2*A*Pmax/(pi*w*w)*exp(-2*pow((x[0] - 4), 2)/(w*w)-2*pow((x[1]-4), 2)/(w*w)-2*pow((x[2]-z1), 2)/(w2*w2) )',degree=3, A=0.1, Pmax=500,w=1, w2= 0.1,z1=z1) #power (w2 localises the z-coordinates)
#----------THERMAL--PROPERTIES--[W]--------
kappa = 0.174         #conductivity [W/mm K] 
c = 0.132         #Specific Heat Capacity [J/gK]
rho = 0.019            #Density [g/mm^3]
const = kappa /(c * rho)
tau_T = 0.0 #Temperature Gradient Lag
tau_q = 0.0 #Heat Flux Lag
#---------------------------------------

mesh = BoxMesh(Point(x0,y0,z0), Point(x1,y1,z1), 80,80,80)
Space = FunctionSpace((mesh), 'P', 1)
VectorSpace = VectorFunctionSpace(mesh, 'P', 1)
cells = MeshFunction('size_t',mesh,mesh.topology().dim())
facets = MeshFunction('size_t',mesh,mesh.topology().dim()-1)
da = Measure('ds', domain=mesh, subdomain_data = facets)
dv = Measure('dx', domain=mesh, subdomain_data = cells)

initial_T = Expression("Tini", Tini=T_am, degree=3)
T0 = interpolate(initial_T, Space)
T = Function(Space)
V = TestFunction(Space)
dT = TrialFunction(Space)
q0 = Function(VectorSpace)
i = indices(3)
G = as_tensor(T.dx(i), (i))  
G0 = as_tensor(T0.dx(i), (i))

# ERROR: COMPONENT AND SHAPE LENGTH DO NOT MATCH
q = as_tensor(dt/(dt + tau_q) * (tau_q/dt*q0[i] - kappa*(1+tau_T/dt)*G[i] + kappa*tau_T/dt*G0[i]),(i))
F = (rho*c/dt*(T-T0)*V - q[i]*V.dx(i) - rho*Laser*V ) * dv + es*(T**4 - T_a4)*V*da
Gain = derivative(Form, T, dT)

file_T = File('target3D/solution.pvd')
for t in np.arange(t_start,t_end,dtime):
	print( "Time", t)
	solve(F==0, T, [], J = Gain, solver_parameters={"newton_solver":{"linear_solver": "mumps", "relative_tolerance": 1e-3} }, form_compiler_parameters={"cpp_optimize": True, "representation": "quadrature","quadrature_degree": 2} )
	file_T << (T,t)
	q0 = project(q, VectorSpace)
	T0.assign(T)

Does anyone have any suggestions? Thank you in advance.

Right now your tensors G and G0 are third order tensors grad(grad(grad(T))) and (grad(grad(grad(T0))), check with

print(G)
print(G.ufl_shape)

I don’t know if this is intended. If you just want grad(T) you can try defining i differently

from ufl import Index
i=Index()

Also I recommend reading
https://readthedocs.org/projects/fenics-ufl/downloads/pdf/latest/