Esempio n. 1
0
def mark(indicator,
         refineTolerance,
         coarsenTolerance=0,
         minLevel=0,
         maxLevel=None,
         gridView=None):
    if ufl and (isinstance(indicator, list) or isinstance(indicator, tuple)):
        indicator = ufl.as_vector(indicator)
    if ufl and isinstance(indicator, ufl.core.expr.Expr):  #
        if gridView is None:
            _, coeff_ = extract_arguments_and_coefficients(indicator)
            gridView = [c.grid for c in coeff_ if hasattr(c, "grid")]
            gridView += [c.gridView for c in coeff_ if hasattr(c, "gridView")]
            if len(gridView) == 0:
                raise ValueError(
                    "if a ufl expression is passed as indicator then the 'gridView' must also be provided"
                )
            gridView = gridView[0]
        indicator = expression2GF(gridView, indicator, 0)
    if gridView is None:
        gridView = indicator.gridView
    try:
        if not gridView.canAdapt:
            raise AttributeError(
                "indicator function must be over grid view that supports adaptation"
            )
    except AttributeError:
        raise AttributeError(
            "indicator function must be over grid view that supports adaptation"
        )
    if maxLevel == None:
        maxLevel = -1
    return gridView.mark(indicator, refineTolerance, coarsenTolerance,
                         minLevel, maxLevel)
Esempio n. 2
0
def _uflToExpr(grid, order, f):
    if not ufl: return f
    if isinstance(f, list) or isinstance(f, tuple):
        if isinstance(f[0], ufl.core.expr.Expr):
            f = ufl.as_vector(f)
    if isinstance(f, GridFunction):
        return f
    if isinstance(f, ufl.core.expr.Expr):
        return expression2GF(grid, f, order).as_ufl()
    else:
        return f
Esempio n. 3
0
def dfInterpolate(self, f):
    if isinstance(f, list) or isinstance(f, tuple):
        if isinstance(f[0], ufl.core.expr.Expr):
            f = ufl.as_vector(f)
    dimExpr = 0
    if isinstance(f, GridFunction):
        func = f.gf
        dimExpr = func.dimRange
    elif isinstance(f, ufl.core.expr.Expr):
        func = expression2GF(self.space.gridView, f, self.space.order).as_ufl()
        if func.ufl_shape == ():
            dimExpr = 1
        else:
            dimExpr = func.ufl_shape[0]
    else:
        try:
            gl = len(inspect.getargspec(f)[0])
            func = None
        except TypeError:
            func = f
            if isinstance(func, int) or isinstance(func, float):
                dimExpr = 1
            else:
                dimExpr = len(func)
        if func is None:
            if gl == 1:  # global function
                func = function.globalFunction(self.space.gridView, "tmp",
                                               self.space.order, f).gf
            elif gl == 2:  # local function
                func = function.localFunction(self.space.gridView, "tmp",
                                              self.space.order, f).gf
            elif gl == 3:  # local function with self argument (i.e. from @gridFunction)
                func = function.localFunction(self.space.gridView, "tmp",
                                              self.space.order,
                                              lambda en, x: f(en, x)).gf
            dimExpr = func.dimRange

    if dimExpr == 0:
        raise AttributeError("can not determine if expression shape"\
                " fits the space's range dimension")
    elif dimExpr != self.space.dimRange:
        raise AttributeError("trying to interpolate an expression"\
            " of size "+str(dimExpr)+" into a space with range dimension = "\
            + str(self.space.dimRange))

    try:
        # API GridView: assert func.gridView == self.gridView, "can only interpolate with same grid views"
        assert func.gridView == self.gridView, "can only interpolate with same grid views"
        assert func.dimRange == self.dimRange, "range dimension mismatch"
    except AttributeError:
        pass
    return self._interpolate(func)
Esempio n. 4
0
def plotComponents(solution, figure=None, level=0, show=None, gridLines="black",
        onlyContours=False, contours=None, contourWidth=2, contourColor="black",
        xlim=None, ylim=None, clim=None, cmap=None,
        block=globalBlock, grid=None, colorbar=None):
    if disable: return
    try:
        grid = solution.gridView
    except AttributeError:
        if isinstance(solution, Expr):
            assert grid, "need to provide a named grid argument to plot a ufl expression directly"
            solution = expression2GF(grid,solution,1)
        else:
            grid = solution
            solution = None
    if not grid.dimWorld == 2 and solution is None:
        print("inline plotting of grid only available for 2d grids")
        return

    if not show:
        show = range(solution.dimRange)

    if figure is None:
        figure = pyplot.figure()
        newFig = True
    else:
        newFig = False
    if (gridLines is not None) and (gridLines != ""):
        offset = 1
    else:
        offset = 0
    subfig = 101+(len(show)+offset)*10

    # first the grid if required
    if (gridLines is not None) and (gridLines != ""):
        pyplot.subplot(subfig)
        _plotPointData(figure,grid,None,level,gridLines,0.2,False,
                onlyContours, contours, contourWidth, contourColor,
                xlim,ylim,clim,cmap,colorbar)

    # add the data
    for p in show:
        pyplot.subplot(subfig+offset+p)
        _plotPointData(figure,grid,solution[p],level,"",0.2,False,
                onlyContours, contours, contourWidth, contourColor,
                xlim,ylim,clim,cmap,colorbar)

    if newFig and block:
        pyplot.show(block=block)
Esempio n. 5
0
def plotPointData(solution, figure=None, linewidth=0.1,
        level=0, gridLines="black", vectors=False,
        onlyContours=False, contours=None, contourWidth=2, contourColor="black",
        xlim=None, ylim=None, clim=None, cmap=None,
        colorbar="vertical", grid=None, triplot=False,
        block=globalBlock,
        logscale=False, ticks=11):
    if disable: return
    try:
        grid = solution.gridView
    except AttributeError:
        if isinstance(solution, list) or isinstance(solution,tuple):
            solution = as_vector(solution)
        if isinstance(solution, Expr):
            assert grid, "need to provide a named grid argument to plot a ufl expression directly"
            solution = expression2GF(grid, solution, 1)
        else:
            grid = solution
            solution = None
    if not grid.dimWorld == 2 and solution is None:
        print("inline plotting of grid only available for 2d grids")
        return

    if figure is None:
        figure = pyplot.figure()
        newFig = True
    else:
        try:
            subPlot = figure[1]
            figure = figure[0]

            if isinstance(subPlot, pyplot.Axes):
                pyplot.sca(subPlot)
            else:
                pyplot.subplot(subPlot)
        except:
            pass
        newFig = False
    _plotPointData(figure, grid, solution, level, gridLines, linewidth,
                    vectors, onlyContours, contours, contourWidth, contourColor,
                    xlim, ylim, clim, cmap, colorbar, triplot,
                    logscale, ticks)

    if newFig and block:
        pyplot.show(block=block)
Esempio n. 6
0
    "newton.linear.preconditioning.method": "sor",
    "newton.verbose": True,
    "newton.linear.verbose": True
}
scheme = solutionScheme(a_im == a_ex,
                        space,
                        solver="gmres",
                        parameters=solverParameters)

# <markdowncell>
# We set up the adaptive method. We start with a marking strategy based on the value of the gradient of the phase field variable.

# <codecell>
from dune.ufl import expression2GF
indicator = expression2GF(gridView,
                          dot(grad(u_h[0]), grad(u_h[0])),
                          0,
                          name="indicator")
# <markdowncell>
# We do the initial refinement of the grid.

# <codecell>
maxLevel = 9
startLevel = 4
hgrid = gridView.hierarchicalGrid
hgrid.globalRefine(startLevel)
for i in range(startLevel, maxLevel):
    fem.mark(indicator, 1.4, 1.2, 0, maxLevel)
    fem.adapt(u_h)
    fem.loadBalance(u_h)
    u_h.interpolate(initial_gf)
Esempio n. 7
0
# <markdowncell>
# **Note**: the coordinates returned are always in the interval $[0,1]$ so
# if physical coordinates are required, they need to be rescaled.
# Also, function values returned by the `sample` function
# are always of a `FieldVector` type, so that even for a scalar example
# a `v[i]` is a vector of dimension one, so that `y[i]=v[i][0]` has to be
# used.
#
# A mentioned above any grid function can be passed in as argument to the
# `sample` function. So for example plotting $|\nabla u_h|$ is straight
# forward using the corresponding ufl expression. Since in this case
# automatic conversion from the ufl expression (available for example in the
# plotting function) to a grid function, we need to do this explicitly:
# <codecell>
from dune.ufl import expression2GF
absGrad = expression2GF(gridView3d, sqrt(dot(grad(uh3d), grad(uh3d))), 2)
p, v = algorithm.run('sample', 'utility.hh', absGrad, x0, x1, 100)
for i in range(len(x)):
    y[i] = v[i][0]
pyplot.plot(x, y)
pyplot.show()

# <markdowncell>
# Similar we can plot both partial derivatives of the solution over the
# given line:
# <codecell>
from dune.ufl import expression2GF
absGrad = expression2GF(gridView3d, grad(uh3d), 2)
p, v = algorithm.run('sample', 'utility.hh', absGrad, x0, x1, 100)
dx, dy = numpy.zeros(len(p)), numpy.zeros(len(p))
for i in range(len(x)):
Esempio n. 8
0
# .. literalinclude:: laplace-dwr.hh
#
# <codecell>

from dune.fem.scheme import galerkin as solutionScheme
spaceZ = solutionSpace(uh.space.grid, order=order + 1)
u = TrialFunction(spaceZ)
v = TestFunction(spaceZ)
x = SpatialCoordinate(spaceZ)
a = dot(grad(u), grad(v)) * dx
dual = solutionScheme([a == 0, DirichletBC(spaceZ, 0)], solver="cg")
z = spaceZ.interpolate(0, name="dual")
zh = uh.copy(name="dual_h")
point = common.FieldVector([0.4, 0.4])
pointFunctional = z.copy("dual_rhs")
eh = expression2GF(uh.space.grid, abs(exact - uh), order=order + 1)
computeFunctional = algorithm.load("pointFunctional", "laplace-dwr.hh", point,
                                   pointFunctional, eh)

# <markdowncell>
# <codecell>

from dune.fem.space import finiteVolume as estimatorSpace
from dune.fem.operator import galerkin as estimatorOp

fvspace = estimatorSpace(uh.space.grid)
estimate = fvspace.interpolate([0], name="estimate")

u = TrialFunction(uh.space.as_ufl())
v = TestFunction(fvspace)
n = FacetNormal(fvspace.cell())
Esempio n. 9
0
op = create.operator("galerkin", inner(jump(u),jump(v))*dS, spc)
w = spc.interpolate([0],name="tmp")
op(uh, w)
dgError = [ math.sqrt( integrate(grid,(uh[0]-exact[0])**2,order=7) ),
            math.sqrt( integrate(grid,inner(grad(uh[0]-exact[0]),grad(uh[0]-exact[0])),order=7)\
            + w.scalarProductDofs(uh)) ]
l2Errors = [dgError[0]]
h1Errors = [dgError[1]]

zh = spc.interpolate([0],name="dual_h")
dualOp = create.scheme("galerkin", [adjoint(a)==0],
                 spc, solver="cg",
                 parameters={"newton." + k: v for k, v in newtonParameter.items()})
pointFunctional = spc.interpolate([0],name="pointFunctional")
point = FieldVector([0.6,0.4])
errors = [ expression2GF(grid, exact-s, reconOrder) for s in solutions ]
dualErrors = algorithm.run('pointFunctional', 'pointfunctional.hh', point, pointFunctional, *errors)
dualOp.solve(target=zh, rhs=pointFunctional)
dualWeight.project(zh-zh)

for i in range(levels):
        if error[2][useEstimate] < tolerance:
            print("COMPLETED:",error[2][useEstimate],"<",tolerance)
            break
        marked = mark(estimate, error[2][useEstimate]/grid.size(0))
        print("elements marked:", marked,"/",grid.size(0),flush=True)
        if sum(marked)==0: break
        adapt(uh)
        loadBalance(uh)
        level += 1
    _, solutions, error = compute(uh)