Tutorial materials

This document is part of the dune-fem tutorial. DOI
View Python source (code only)

Download code only mcf-algorithm_script.py

  1import time, io
  2import numpy
  3from matplotlib import pyplot as plt
  4from matplotlib.ticker import ScalarFormatter
  5from ufl import *
  6import dune.ufl
  7from dune.generator import algorithm
  8import dune.geometry as geometry
  9import dune.fem as fem
 10from dune.fem.view import geometryGridView as geoGridView
 11from dune.fem.space import lagrange as solutionSpace
 12from dune.fem.scheme import galerkin as solutionScheme
 13from dune.alugrid import aluConformGrid as leafGridView
 14
 15def plot(ct, ct2):
 16    fig, ax = plt.subplots()
 17    plt.loglog(ct[0][:], ct[1][:],'*-', markersize=15, label='hybrid')
 18    plt.loglog(ct2[0][:], ct2[1][:],'*-', markersize=15, label='python')
 19    plt.grid(True)
 20    for axis in [ax.xaxis, ax.yaxis]:
 21        axis.set_major_formatter(ScalarFormatter())
 22        axis.set_minor_formatter(ScalarFormatter())
 23    yticks = ax.yaxis.get_minor_ticks()
 24    for t in yticks:
 25        t.label1.set_visible(False)
 26    xticks = ax.xaxis.get_minor_ticks()
 27    for t in xticks:
 28        t.label1.set_visible(False)
 29    plt.yticks(numpy.append(ct[1], ct2[1]))
 30    plt.xticks(ct[0])
 31    plt.legend(loc="upper left")
 32    plt.xlabel('Number of Grid Elements (log)',fontsize=20)
 33    plt.gcf().subplots_adjust(bottom=0.17, left=0.16)
 34    plt.ylabel('Runtime in s (log)',fontsize=20)
 35# polynomial order of surface approximation
 36order = 2
 37# initial radius
 38R0 = 2.
 39# end time
 40endTime = 0.1
 41def calcRadius(surface):
 42    R,vol = 0, 0
 43    for e in surface.elements:
 44        rule = geometry.quadratureRule(e.type, 4)
 45        for p in rule:
 46            geo = e.geometry
 47            weight = geo.volume * p.weight
 48            R   += geo.toGlobal(p.position).two_norm * weight
 49            vol += weight
 50    return R/vol
 51code = """
 52#include <dune/geometry/quadraturerules.hh>
 53template< class Surface >
 54double calcRadius( const Surface &surface ) {
 55  double R = 0, vol = 0.;
 56  for( const auto &entity : elements( surface ) ) {
 57    const auto& rule = Dune::QuadratureRules<double, 2>::rule(entity.type(), 4);
 58    for ( const auto &p : rule ) {
 59      const auto geo = entity.geometry();
 60      const double weight = geo.volume() * p.weight();
 61      R   += geo.global(p.position()).two_norm() * weight;
 62      vol += weight;
 63    }
 64  }
 65  return R/vol;
 66}
 67"""
 68switchCalcRadius = lambda use_cpp,surface: \
 69             algorithm.load('calcRadius', io.StringIO(code), surface) \
 70             if use_cpp else calcRadius
 71def calculate(use_cpp, gridView):
 72    # space on Gamma_0 to describe position of Gamma(t)
 73    space = solutionSpace(gridView, dimRange=gridView.dimWorld, order=order)
 74    u = TrialFunction(space)
 75    v = TestFunction(space)
 76    x = SpatialCoordinate(space)
 77    positions = space.interpolate(x, name="position")
 78    # space for discrete solution on Gamma(t)
 79    surface = geoGridView(positions)
 80    space = solutionSpace(surface, dimRange=surface.dimWorld, order=order)
 81    solution  = space.interpolate(x, name="solution")
 82    # set up model using theta scheme
 83    theta = 0.5   # Crank-Nicolson
 84    I = Identity(3)
 85    dt = dune.ufl.Constant(0,"dt")
 86    a = (inner(u - x, v) + dt * inner(theta*grad(u)
 87        + (1 - theta)*I, grad(v))) * dx
 88    scheme = solutionScheme(a == 0, space, solver="cg")
 89    Rexact = lambda t: numpy.sqrt(R0*R0 - 4.*t)
 90    radius = switchCalcRadius(use_cpp,surface)
 91    dt.value = 0.02
 92    numberOfLoops = 3
 93    times = numpy.zeros(numberOfLoops)
 94    errors = numpy.zeros(numberOfLoops)
 95    totalIterations = numpy.zeros(numberOfLoops, numpy.dtype(numpy.uint32))
 96    gridSizes = numpy.zeros(numberOfLoops, numpy.dtype(numpy.uint32))
 97    for i in range(numberOfLoops):
 98        positions.interpolate(x * (R0/sqrt(dot(x,x))))
 99        solution.interpolate(x)
100        t = 0.
101        error = abs(radius(surface)-Rexact(t))
102        iterations = 0
103        start = time.time()
104        while t < endTime:
105            info = scheme.solve(target=solution)
106            # move the surface
107            positions.assign(solution)
108            # store some information about the solution process
109            iterations += int( info["linear_iterations"] )
110            t          += scheme.model.dt
111            error       = max(error, abs(radius(surface)-Rexact(t)))
112        print("time used:", time.time() - start)
113        times[i] = time.time() - start
114        errors[i] = error
115        totalIterations[i] = iterations
116        gridSizes[i] = gridView.size(2)
117        if i < numberOfLoops - 1:
118            gridView.hierarchicalGrid.globalRefine(1)
119            dt.value /= 2
120    eocs = numpy.log(errors[0:][:numberOfLoops-1] / errors[1:]) / numpy.log(numpy.sqrt(2))
121    try:
122        import pandas as pd
123        keys = {'size': gridSizes, 'error': errors, "eoc": numpy.insert(eocs, 0, None), 'iterations': totalIterations}
124        table = pd.DataFrame(keys, index=range(numberOfLoops),columns=['size', 'error', 'eoc', 'iterations'])
125        print(table)
126    except ImportError:
127        print("pandas module not found so not showing table - ignored")
128        pass
129    return gridSizes, times
130# set up reference domain Gamma_0
131results = []
132gridView = leafGridView("sphere.dgf", dimgrid=2, dimworld=3)
133results += [calculate(True, gridView)]
134gridView = leafGridView("sphere.dgf", dimgrid=2, dimworld=3)
135results += [calculate(False, gridView)]
136plot(results[0],results[1])

Mean Curvature Flow (revisited)

As discussed before we can simulate the shrinking of a sphere under mean curvature flow using a finite element approach based on the following time discrete approximation: \begin{align} \int_{\Gamma^n} \big( U^{n+1} - {\rm id}\big) \cdot \varphi + \tau \int_{\Gamma^n} \big( \theta\nabla_{\Gamma^n} U^{n+1} + (1-\theta) I \big) \colon\nabla_{\Gamma^n}\varphi =0~. \end{align} Here \(U^n\) parametrizes \(\Gamma(t^{n+1})\) over \(\Gamma^n:=\Gamma(t^{n})\), \(I\) is the identity matrix, \(\tau\) is the time step and \(\theta\in[0,1]\) is a discretization parameter.

If the initial surface \(\Gamma^0\) is a sphere of radius \(R_0\), the surface remains sphere and we have an exact formula for the evolution of the radius of the surface

\[R(t) = \sqrt{R_0^2 - 4t}.\]

To compare the accuracy of the surface approximation we compute an average radius of the discrete surface in each time step \(t^n\) using

\[R_h^n = \frac{ \int_{\Gamma^n} |x| }{ |\Gamma^n| }.\]

Computing \(R_h^n\) requires a grid traversal and a number of calls to interface methods on each element. Doing this on the Python side has a potential performance impact which we investigate here by comparing a pure python implementation with a hybrid approach where computing \(R_h^n\) is implemented in C++ using the dune.generator.algorithm functionality.

[1]:
import time, io
import numpy
from matplotlib import pyplot as plt
from matplotlib.ticker import ScalarFormatter

from ufl import *
import dune.ufl
from dune.generator import algorithm
import dune.geometry as geometry
import dune.fem as fem

def plot(ct, ct2):
    fig, ax = plt.subplots()
    plt.loglog(ct[0][:], ct[1][:],'*-', markersize=15, label='hybrid')
    plt.loglog(ct2[0][:], ct2[1][:],'*-', markersize=15, label='python')
    plt.grid(True)
    for axis in [ax.xaxis, ax.yaxis]:
        axis.set_major_formatter(ScalarFormatter())
        axis.set_minor_formatter(ScalarFormatter())
    yticks = ax.yaxis.get_minor_ticks()
    for t in yticks:
        t.label1.set_visible(False)
    xticks = ax.xaxis.get_minor_ticks()
    for t in xticks:
        t.label1.set_visible(False)
    plt.yticks(numpy.append(ct[1], ct2[1]))
    plt.xticks(ct[0])
    plt.legend(loc="upper left")
    plt.xlabel('Number of Grid Elements (log)',fontsize=20)
    plt.gcf().subplots_adjust(bottom=0.17, left=0.16)
    plt.ylabel('Runtime in s (log)',fontsize=20)

# polynomial order of surface approximation
order = 2

# initial radius
R0 = 2.

# end time
endTime = 0.1

Main function for calculating the mean curvature flow of a given surface. If first argument is True the radius of the computed surface is computed using an algorithm implemented in C++ otherwise the computation is done in Python.

[2]:
def calcRadius(surface):
    R,vol = 0, 0
    for e in surface.elements:
        rule = geometry.quadratureRule(e.type, 4)
        for p in rule:
            geo = e.geometry
            weight = geo.volume * p.weight
            R   += geo.toGlobal(p.position).two_norm * weight
            vol += weight
    return R/vol

code = """
#include <dune/geometry/quadraturerules.hh>
template< class Surface >
double calcRadius( const Surface &surface ) {
  double R = 0, vol = 0.;
  for( const auto &entity : elements( surface ) ) {
    const auto& rule = Dune::QuadratureRules<double, 2>::rule(entity.type(), 4);
    for ( const auto &p : rule ) {
      const auto geo = entity.geometry();
      const double weight = geo.volume() * p.weight();
      R   += geo.global(p.position()).two_norm() * weight;
      vol += weight;
    }
  }
  return R/vol;
}
"""
switchCalcRadius = lambda use_cpp,surface: \
             algorithm.load('calcRadius', io.StringIO(code), surface) \
             if use_cpp else calcRadius

Timings for a number of different grid refinements is dumped to disk

[3]:
from dune.fem.view import geometryGridView as geoGridView
from dune.fem.space import lagrange as solutionSpace
from dune.fem.scheme import galerkin as solutionScheme
def calculate(use_cpp, gridView):
    # space on Gamma_0 to describe position of Gamma(t)
    space = solutionSpace(gridView, dimRange=gridView.dimWorld, order=order)
    u = TrialFunction(space)
    v = TestFunction(space)
    x = SpatialCoordinate(space)
    positions = space.interpolate(x, name="position")

    # space for discrete solution on Gamma(t)
    surface = geoGridView(positions)
    space = solutionSpace(surface, dimRange=surface.dimWorld, order=order)
    solution  = space.interpolate(x, name="solution")

    # set up model using theta scheme
    theta = 0.5   # Crank-Nicolson

    I = Identity(3)
    dt = dune.ufl.Constant(0,"dt")

    a = (inner(u - x, v) + dt * inner(theta*grad(u)
        + (1 - theta)*I, grad(v))) * dx

    scheme = solutionScheme(a == 0, space, solver="cg")

    Rexact = lambda t: numpy.sqrt(R0*R0 - 4.*t)
    radius = switchCalcRadius(use_cpp,surface)

    dt.value = 0.02

    numberOfLoops = 3
    times = numpy.zeros(numberOfLoops)
    errors = numpy.zeros(numberOfLoops)
    totalIterations = numpy.zeros(numberOfLoops, numpy.dtype(numpy.uint32))
    gridSizes = numpy.zeros(numberOfLoops, numpy.dtype(numpy.uint32))
    for i in range(numberOfLoops):
        positions.interpolate(x * (R0/sqrt(dot(x,x))))
        solution.interpolate(x)
        t = 0.
        error = abs(radius(surface)-Rexact(t))
        iterations = 0
        start = time.time()
        while t < endTime:
            info = scheme.solve(target=solution)
            # move the surface
            positions.assign(solution)
            # store some information about the solution process
            iterations += int( info["linear_iterations"] )
            t          += scheme.model.dt
            error       = max(error, abs(radius(surface)-Rexact(t)))
        print("time used:", time.time() - start)
        times[i] = time.time() - start
        errors[i] = error
        totalIterations[i] = iterations
        gridSizes[i] = gridView.size(2)
        if i < numberOfLoops - 1:
            gridView.hierarchicalGrid.globalRefine(1)
            dt.value /= 2
    eocs = numpy.log(errors[0:][:numberOfLoops-1] / errors[1:]) / numpy.log(numpy.sqrt(2))
    try:
        import pandas as pd
        keys = {'size': gridSizes, 'error': errors, "eoc": numpy.insert(eocs, 0, None), 'iterations': totalIterations}
        table = pd.DataFrame(keys, index=range(numberOfLoops),columns=['size', 'error', 'eoc', 'iterations'])
        print(table)
    except ImportError:
        print("pandas module not found so not showing table - ignored")
        pass
    return gridSizes, times

Compute the mean curvature flow evolution of a spherical surface. Compare computational time of a pure Python implementation and using a C++ algorithm to compute the radius of the surface for verifying the algorithm.

[4]:
# set up reference domain Gamma_0
results = []
from dune.alugrid import aluConformGrid as leafGridView
gridView = leafGridView("sphere.dgf", dimgrid=2, dimworld=3)
results += [calculate(True, gridView)]

gridView = leafGridView("sphere.dgf", dimgrid=2, dimworld=3)
results += [calculate(False, gridView)]
time used: 0.4076554775238037
time used: 2.277174949645996
time used: 9.731925964355469
   size     error       eoc  iterations
0   318  0.001060       NaN          76
1   766  0.000605  1.619153         208
2  1745  0.000275  2.275142         420
time used: 0.5225670337677002
time used: 2.802943229675293
time used: 12.061583042144775
   size     error       eoc  iterations
0   318  0.001060       NaN          76
1   766  0.000605  1.619153         208
2  1745  0.000275  2.275142         420

Compare the hybrid and pure Python versions

[5]:
plot(results[0],results[1])
_images/mcf-algorithm_nb_9_0.jpg

Tutorial materials

This document is part of the dune-fem tutorial. DOI
View Python source (code only)

Download code only mcf-algorithm_script.py

  1import time, io
  2import numpy
  3from matplotlib import pyplot as plt
  4from matplotlib.ticker import ScalarFormatter
  5from ufl import *
  6import dune.ufl
  7from dune.generator import algorithm
  8import dune.geometry as geometry
  9import dune.fem as fem
 10from dune.fem.view import geometryGridView as geoGridView
 11from dune.fem.space import lagrange as solutionSpace
 12from dune.fem.scheme import galerkin as solutionScheme
 13from dune.alugrid import aluConformGrid as leafGridView
 14
 15def plot(ct, ct2):
 16    fig, ax = plt.subplots()
 17    plt.loglog(ct[0][:], ct[1][:],'*-', markersize=15, label='hybrid')
 18    plt.loglog(ct2[0][:], ct2[1][:],'*-', markersize=15, label='python')
 19    plt.grid(True)
 20    for axis in [ax.xaxis, ax.yaxis]:
 21        axis.set_major_formatter(ScalarFormatter())
 22        axis.set_minor_formatter(ScalarFormatter())
 23    yticks = ax.yaxis.get_minor_ticks()
 24    for t in yticks:
 25        t.label1.set_visible(False)
 26    xticks = ax.xaxis.get_minor_ticks()
 27    for t in xticks:
 28        t.label1.set_visible(False)
 29    plt.yticks(numpy.append(ct[1], ct2[1]))
 30    plt.xticks(ct[0])
 31    plt.legend(loc="upper left")
 32    plt.xlabel('Number of Grid Elements (log)',fontsize=20)
 33    plt.gcf().subplots_adjust(bottom=0.17, left=0.16)
 34    plt.ylabel('Runtime in s (log)',fontsize=20)
 35# polynomial order of surface approximation
 36order = 2
 37# initial radius
 38R0 = 2.
 39# end time
 40endTime = 0.1
 41def calcRadius(surface):
 42    R,vol = 0, 0
 43    for e in surface.elements:
 44        rule = geometry.quadratureRule(e.type, 4)
 45        for p in rule:
 46            geo = e.geometry
 47            weight = geo.volume * p.weight
 48            R   += geo.toGlobal(p.position).two_norm * weight
 49            vol += weight
 50    return R/vol
 51code = """
 52#include <dune/geometry/quadraturerules.hh>
 53template< class Surface >
 54double calcRadius( const Surface &surface ) {
 55  double R = 0, vol = 0.;
 56  for( const auto &entity : elements( surface ) ) {
 57    const auto& rule = Dune::QuadratureRules<double, 2>::rule(entity.type(), 4);
 58    for ( const auto &p : rule ) {
 59      const auto geo = entity.geometry();
 60      const double weight = geo.volume() * p.weight();
 61      R   += geo.global(p.position()).two_norm() * weight;
 62      vol += weight;
 63    }
 64  }
 65  return R/vol;
 66}
 67"""
 68switchCalcRadius = lambda use_cpp,surface: \
 69             algorithm.load('calcRadius', io.StringIO(code), surface) \
 70             if use_cpp else calcRadius
 71def calculate(use_cpp, gridView):
 72    # space on Gamma_0 to describe position of Gamma(t)
 73    space = solutionSpace(gridView, dimRange=gridView.dimWorld, order=order)
 74    u = TrialFunction(space)
 75    v = TestFunction(space)
 76    x = SpatialCoordinate(space)
 77    positions = space.interpolate(x, name="position")
 78    # space for discrete solution on Gamma(t)
 79    surface = geoGridView(positions)
 80    space = solutionSpace(surface, dimRange=surface.dimWorld, order=order)
 81    solution  = space.interpolate(x, name="solution")
 82    # set up model using theta scheme
 83    theta = 0.5   # Crank-Nicolson
 84    I = Identity(3)
 85    dt = dune.ufl.Constant(0,"dt")
 86    a = (inner(u - x, v) + dt * inner(theta*grad(u)
 87        + (1 - theta)*I, grad(v))) * dx
 88    scheme = solutionScheme(a == 0, space, solver="cg")
 89    Rexact = lambda t: numpy.sqrt(R0*R0 - 4.*t)
 90    radius = switchCalcRadius(use_cpp,surface)
 91    dt.value = 0.02
 92    numberOfLoops = 3
 93    times = numpy.zeros(numberOfLoops)
 94    errors = numpy.zeros(numberOfLoops)
 95    totalIterations = numpy.zeros(numberOfLoops, numpy.dtype(numpy.uint32))
 96    gridSizes = numpy.zeros(numberOfLoops, numpy.dtype(numpy.uint32))
 97    for i in range(numberOfLoops):
 98        positions.interpolate(x * (R0/sqrt(dot(x,x))))
 99        solution.interpolate(x)
100        t = 0.
101        error = abs(radius(surface)-Rexact(t))
102        iterations = 0
103        start = time.time()
104        while t < endTime:
105            info = scheme.solve(target=solution)
106            # move the surface
107            positions.assign(solution)
108            # store some information about the solution process
109            iterations += int( info["linear_iterations"] )
110            t          += scheme.model.dt
111            error       = max(error, abs(radius(surface)-Rexact(t)))
112        print("time used:", time.time() - start)
113        times[i] = time.time() - start
114        errors[i] = error
115        totalIterations[i] = iterations
116        gridSizes[i] = gridView.size(2)
117        if i < numberOfLoops - 1:
118            gridView.hierarchicalGrid.globalRefine(1)
119            dt.value /= 2
120    eocs = numpy.log(errors[0:][:numberOfLoops-1] / errors[1:]) / numpy.log(numpy.sqrt(2))
121    try:
122        import pandas as pd
123        keys = {'size': gridSizes, 'error': errors, "eoc": numpy.insert(eocs, 0, None), 'iterations': totalIterations}
124        table = pd.DataFrame(keys, index=range(numberOfLoops),columns=['size', 'error', 'eoc', 'iterations'])
125        print(table)
126    except ImportError:
127        print("pandas module not found so not showing table - ignored")
128        pass
129    return gridSizes, times
130# set up reference domain Gamma_0
131results = []
132gridView = leafGridView("sphere.dgf", dimgrid=2, dimworld=3)
133results += [calculate(True, gridView)]
134gridView = leafGridView("sphere.dgf", dimgrid=2, dimworld=3)
135results += [calculate(False, gridView)]
136plot(results[0],results[1])