calc_surface_area.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from dolfin import *
  2. import sympy as sp
  3. # Credits:
  4. # https://github.com/pf4d/fenics_scripts/calc_surface_area.py
  5. x, y = sp.symbols('x, y')
  6. # surface :
  7. def s(x,y): return sp.exp(x)
  8. # x-derivative of surface
  9. def dsdx(x,y): return s(x,y).diff(x, 1)
  10. # y-derivative of surface
  11. def dsdy(x,y): return s(x,y).diff(y, 1)
  12. # outward-pointing-normal-vector magnitude at surface :
  13. def n_mag_s(x,y): return sp.sqrt(1 + dsdx(x,y)**2 + dsdy(x,y)**2)
  14. # surface area of surface :
  15. def area(x,y): return sp.integrate(n_mag_s(x,y), (x,0,1), (y,0,1))
  16. A_exact = area(x,y)
  17. for n in [5,10,100,500]:
  18. mesh = UnitSquareMesh(n,n)
  19. Q = FunctionSpace(mesh, "CG", 1)
  20. e = Expression('exp(x[0])', degree=2)
  21. f = interpolate(e, Q)
  22. A_num = assemble( sqrt(f.dx(0)**2 + f.dx(1)**2 + 1) * dx)
  23. print('for n = %i -- error = %.2e' % (n, abs(A_exact.evalf()-A_num)))
  24. n = 10
  25. mesh = UnitSquareMesh(n,n)
  26. Q = FunctionSpace(mesh, "CG", 1)
  27. e = Expression('exp(x[0])', degree=2)
  28. f = interpolate(e, Q)
  29. A_vector = project( sqrt(f.dx(0)**2 + f.dx(1)**2 + 1), Q)
  30. from vedo.dolfin import plot
  31. plot(A_vector)