ImpementedError:Cannot take length of non-vector expression

I am new to fenics am trying to solve 1D heat equation. i used theta method for time discretization and i am encountering error solving the variational problem. i would be grateful if i could get some help.
here

from fenics import *
import numpy as np
import matplotlib.pyplot as plt
from dolfin import * 
from ufl import *
from fenics import *
import math 


# Create mesh and define function space
nx = ny = 32
mesh = UnitSquareMesh(nx, ny)
V = FunctionSpace(mesh, 'CG', 1)
theta = Constant(0.5)
dt = Constant(0.1)
num_steps = 10

# Define boundary condition
u_D = Expression('sin(2*pi*x[0])', degree = 2)

def GammaD(x, on_boundary):
    return near(x[1], 0)

g = Constant('0')
bc = DirichletBC(V, g, GammaD)

#
#u_n = project(u_D, V)

# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
u_n = Function(V)
f = Constant(0)

F = (u*v -theta*dt*inner(grad(u),grad(v)))*dx*u_n - (u*v-(1-theta)*dt*inner(grad(u),grad(v)))*u*dx
a, L = lhs(F), rhs(F)


 #Define initial value
u_n = interpolate(u_D, V)


# Time-stepping
u = Function(V)
t = 0
for n in range(num_steps):

    # Update current time
    t += dt
    u_D.t = t

    # Compute solution
    solve(a == L, u, bc)

    # Plot solution
    plot(u)

    # Compute error at vertices
    u_e = interpolate(u_D, V)
    error = np.abs(u_e.vector().array() - u.vector().array()).max()
    print('t = %.2f: error = %.3g' % (t, error))

    # Update previous solution
    u_n.assign(u)

# Hold plot
interactive()

is the code

And error

NotImplementedError                       Traceback (most recent call last)
<ipython-input-13-f382af29c6b6> in <module>
     52 
     53     # Compute solution
---> 54     solve(a == L, u, bc)
     55 
     56     # Plot solution
1 Like

Please encapsulate your code using 3 times `
as it renders the code in the following way

def test():
    print("here")
1 Like

I formatted your code for you. Please try to carefully formulate your code with three backticks ``` in the future.

Your formulation doesn’t look correct for the linear heat equation. You’re getting an error because your forms are not bilinear. Consider the following which you have on line 36:

F = ... - (u*v-(1-theta)*dt*inner(grad(u),grad(v)))*u*dx

Note how you have terms like u*u which do not make sense for a linear problem.

1 Like