heat_gaussian.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """
  2. FEniCS tutorial demo program: Diffusion of a Gaussian hill.
  3. u'= Laplace(u) + f in a square domain
  4. u = u_D on the boundary
  5. u = u_0 at t = 0
  6. u_D = f = 0
  7. The initial condition u_0 is chosen as a Gaussian hill.
  8. """
  9. # https://fenicsproject.org/pub/tutorial/html/._ftut1006.html
  10. from fenics import *
  11. set_log_level(30)
  12. num_steps = 50 # number of time steps
  13. dt = 0.02 # time step size
  14. # Create mesh and define function space
  15. nx = ny = 30
  16. mesh = RectangleMesh(Point(-2, -2), Point(2, 2), nx, ny)
  17. V = FunctionSpace(mesh, 'P', 1)
  18. # Define boundary condition
  19. def boundary(x, on_boundary):
  20. return on_boundary
  21. bc = DirichletBC(V, Constant(0), boundary)
  22. # Define initial value
  23. u_0 = Expression('exp(-5*pow(x[0],2) - 5*pow(x[1],2))', degree=2)
  24. u_n = interpolate(u_0, V)
  25. # Define variational problem
  26. u = TrialFunction(V)
  27. v = TestFunction(V)
  28. f = Constant(0)
  29. F = u*v*dx + dt*dot(grad(u), grad(v))*dx - (u_n + dt*f)*v*dx
  30. a, L = lhs(F), rhs(F)
  31. ############################################################# vedo
  32. from vedo.dolfin import plot
  33. from vedo import Latex
  34. f = r'\frac{\partial u}{\partial t}=\nabla^2 u+f~\mathrm{in}~\Omega\times(0,T]'
  35. formula = Latex(f, pos=(-.4,-.8, .1), s=0.6, c='w')
  36. formula.crop(0.2, 0.4) # crop top and bottom 20% and 40%
  37. # Time-stepping
  38. u = Function(V)
  39. for n in range(num_steps):
  40. # Compute solution
  41. solve(a == L, u, bc)
  42. # Plot solution
  43. plot(u, formula, scalarbar=False, interactive=False)
  44. # Update previous solution
  45. u_n.assign(u)
  46. plot()