Example #1
0
def test(model, spaceName, dimD, dimR, storage):
    # print("########################################")
    # print("#### ",spaceName,storage,dimD,dimR,flush=True)
    spaceD = create.space(spaceName,
                          grid,
                          dimRange=dimD,
                          order=1,
                          storage=storage)
    spaceR = create.space(spaceName,
                          grid,
                          dimRange=dimR,
                          order=1,
                          storage=storage)
    scheme = create.operator("galerkin", model, spaceD, spaceR)
    uD = create.function("discrete", spaceD, name=storage)
    uD.clear()
    start = time.time()
    for i in range(testLoop):
        A = linearOperator(scheme)  # , parameters={"petsc.blockedmode":False})
    end = time.time()
    # print( "setup+assembly:",(end-start)/testLoop, flush=True )
    start = time.time()
    for i in range(testLoop):
        jacobian(scheme, uD, A)
    end = time.time()
    # print( "assembly only: ",(end-start)/testLoop, flush=True )
    # sys.stdout.flush()

    try:
        import petsc4py
        from petsc4py import PETSc
        mat = A.as_petsc
        # print(mat.getInfo(), flush=True)
    except:
        pass
Example #2
0
def test(space):
    if test_numpy:
        numpySpace = create.space(space,
                                  grid,
                                  dimRange=1,
                                  order=1,
                                  storage='numpy')
        numpyScheme = create.scheme("galerkin", model, numpySpace)
        numpy_h = create.function("discrete", numpySpace, name="numpy")
        numpy_dofs = numpy_h.as_numpy
        # numpyScheme.solve(target = numpy_h)
        start = time.time()
        for i in range(testLoop):
            linOp = linearOperator(numpyScheme)
            numpyScheme.jacobian(numpy_h, linOp)
            numpy_mat = linOp.as_numpy
        end = time.time()
        # print( "numpy:", (end-start)/testLoop, flush=True )
        # sys.stdout.flush()
        numpy_coo = numpy_mat.tocoo()
        # for i,j,v in zip(numpy_coo.row,numpy_coo.col,numpy_coo.data):
        #     print(i,j,v)
        # print("****************************",flush=True)

    if test_istl:
        istlSpace = create.space(space,
                                 grid,
                                 dimRange=1,
                                 order=1,
                                 storage='istl')
        istlScheme = create.scheme("galerkin", model, istlSpace)
        istl_h = create.function("discrete", istlSpace, name="istl")
        istl_dofs = istl_h.as_istl
        # istlScheme.solve(target = istl_h)
        start = time.time()
        for i in range(testLoop):
            linOp = linearOperator(istlScheme)
            istlScheme.jacobian(istl_h, linOp)
            istl_mat = linOp.as_istl
        end = time.time()
        # print( "istl:", (end-start)/testLoop, flush=True )
        # sys.stdout.flush()
        # there is no way yet to go from istl to scipy - would be nice to have
        # istl_coo = istl_mat.tocoo()
        # for i,j,v in zip(eigen_coo.row,eigen_coo.col,eigen_coo.data):
        #     print(i,j,v)
        # print("****************************",flush=True)

    if test_petsc:
        import petsc4py
        from petsc4py import PETSc
        petsc4py.init(sys.argv)
        petscSpace = create.space(space,
                                  grid,
                                  dimRange=1,
                                  order=1,
                                  storage='petsc')
        petscScheme = create.scheme("galerkin", model, petscSpace)
        petsc_h = create.function("discrete", petscSpace, name="petsc")
        petsc_dofs = petsc_h.as_petsc
        # petscScheme.solve(target = petsc_h)
        linOp = linearOperator(petscScheme)
        petscScheme.jacobian(petsc_h, linOp)
        petsc_mat = linOp.as_petsc
        rptr, cind, vals = petsc_mat.getValuesCSR()
        petsc_coo = scipy.sparse.csr_matrix((vals, cind, rptr)).tocoo()
        start = time.time()
        for i in range(testLoop):
            linOp = linearOperator(petscScheme)
            petscScheme.jacobian(petsc_h, linOp)
            petsc_mat = linOp.as_petsc
        end = time.time()
        # print( "petsc:", (end-start)/testLoop, flush=True )
        # sys.stdout.flush()

        ksp = PETSc.KSP()
        ksp.create(PETSc.COMM_WORLD)
        ksp.setType("cg")
        # ksp.getPC().setType("icc")
        petsc_h.clear()
        res = petsc_h.copy()
        petscScheme(petsc_h, res)
        petscScheme.jacobian(petsc_h, linOp)
        petsc_mat = linOp.as_petsc
        ksp.setOperators(petsc_mat, petsc_mat)
        ksp.setFromOptions()
        ksp.solve(res.as_petsc, petsc_h.as_petsc)

        # print("****************************",flush=True)
        # print(petsc_mat.size, petsc_mat.getSize(), petsc_mat.getSizes())
        # print(petsc_mat.getType())
        # print(type(petsc_mat))
        # print(petscSpace.size)
        # print(petsc_mat.assembled)
        # rptr, cind, vals = petsc_mat.getValuesCSR()
        # petsc_coo = scipy.sparse.csr_matrix((vals,cind,rptr),shape=(100,100)).tocoo()
        # for i,j,v in zip(petsc_coo.row,petsc_coo.col,petsc_coo.data):
        #     print(i,j,v)

    if test_istl:
        try:  # istl_coo does not exist
            assert (istl_coo.row == numpy_coo.row).all()
            assert (istl_coo.col == numpy_coo.col).all()
            assert np.allclose(istl_coo.data, numpy_coo.data)
        except:
            # print("issue between istl and numpy matrices")
            pass
    if test_petsc:
        try:
            assert (petsc_coo.row == numpy_coo.row).all()
            assert (petsc_coo.col == numpy_coo.col).all()
            assert np.allclose(petsc_coo.data, numpy_coo.data)
        except:
            # print("issue between petsc and numpy matrices")
            pass
Example #3
0
    q_n = 0
    q_w = 0

    useCutOff = False


P = AnisotropicLens()

# <markdowncell>
# Setup grid, discrete spaces and functions

# <codecell>
grid = create.view("adaptive", "ALUCube", P.domain, dimgrid=2)

if coupled:
    spc = create.space("dglegendrehp", grid, dimRange=2, order=maxOrder)
else:
    spc1 = create.space("dglegendrehp", grid, dimRange=1, order=maxOrder)
    spc = create.space("product", spc1, spc1, components=["p", "s"])

solution = spc.interpolate([0, 0], name="solution")
solution_old = spc.interpolate([0, 0], name="solution_old")
sol_pm1 = spc.interpolate([0, 0], name="sol_pm1")
intermediate = spc.interpolate([0, 0], name="iterate")
persistentDF = [solution, solution_old, intermediate]

fvspc = create.space("finitevolume", grid, dimRange=1, storage="fem")
estimate = fvspc.interpolate([0], name="estimate")
estimate_pm1 = fvspc.interpolate([0], name="estimate-pm1")

# <markdowncell>
Example #4
0
import numpy
from dune.fem.plotting import plotPointData as plot
import dune.create as create
from dune.grid import structuredGrid
from dune.istl import blockVector
import ufl

g = structuredGrid([0, 0], [1, 1], [2, 3])

s = create.space("lagrange", g, dimRange=2, storage="istl")
f1 = s.interpolate(expr=[2, 1], name="tmp")
dofs = blockVector(int(s.size / s.localBlockSize), s.localBlockSize)
# f2 = s.function("tmp", expr=[2,1], dofVector=dofs)
f2 = s.function("tmp", dofVector=dofs)
f2.interpolate([2, 1])
assert all([(d1 - d2).two_norm == 0 for d1, d2 in zip(dofs, f1.as_istl)])
assert all([(d1 - d2).two_norm == 0 for d1, d2 in zip(dofs, f2.as_istl)])
operator = create.operator(
    "galerkin",
    ufl.dot(ufl.TrialFunction(s), ufl.TestFunction(s)) * ufl.dx)
f1 = s.function("tmp", [2, 1],
                blockVector(s.size // s.localBlockSize, s.localBlockSize))
f2 = s.function("tmp", [2, 1],
                blockVector(s.size // s.localBlockSize, s.localBlockSize))
operator(f1, f2)

s = create.space("lagrange", g, dimRange=2, storage="numpy")
f1 = s.interpolate([2, 1], name="tmp")
dofs = numpy.ndarray(s.size)
f2 = s.function("tmp", [2, 1], dofs)
assert not (dofs - f1.as_numpy).any()
Example #5
0
from __future__ import print_function, division
import math
import numpy

from dune.grid import structuredGrid
import dune.create as create

grid = structuredGrid([0, 0], [1, 1], [10, 10])

fvspc = create.space("finitevolume", grid, dimRange=2, storage="numpy")
estimate = fvspc.interpolate([1, 1], name="estimate")

lf = estimate.localFunction(grid.elements.__next__())
y = lf.evaluate([0, 0])
assert y == (1, 1)
# print(y)

lf = estimate.setLocalContribution()
lf.bind(grid.elements.__next__())
y1, y2 = lf[0], lf[1]
assert y1 == 0 and y2 == 0
# print(y1,y2)
lf[0] = 10
y1, y2 = lf[0], lf[1]
assert y1 == 10 and y2 == 0
# print(y1,y2)
lf.unbind()

lf = estimate.localContribution("set")
lf.bind(grid.elements.__next__())
y1, y2 = lf[0], lf[1]
Example #6
0
    "istl.preconditioning.method": "ilu",
    "istl.preconditioning.iterations": 1,
    "istl.preconditioning.relaxation": 1
})

# set up grid

grid = create.grid("ALUSimplex", gridSelect, dimgrid=2, dimworld=3)
grid.hierarchicalGrid.globalRefine(2)
print("Number of elements:", grid.size(0))
print("Number of vertices:", grid.size(grid.dimension))

# set up a lagrange scalar space with polynomial order 2 over that grid
spc = create.space("Lagrange",
                   grid,
                   dimrange=grid.dimWorld,
                   order=order,
                   store="istl")

# non spherical initial surgface

uDimWorld = 6
positions = spc.interpolate(lambda x: surfaceOptions[case](x), name="position")
surface = create.view("geometry", positions)
SolutionSpace = create.space("Lagrange",
                             surface,
                             dimrange=uDimWorld,
                             order=order,
                             storage="istl")

if Graphics == 1:
Example #7
0
import numpy
from scipy.sparse import bmat, linalg
import dune.create as create
from dune.grid import cartesianDomain
from ufl import SpatialCoordinate, CellVolume, TrialFunction, TestFunction,\
                inner, dot, div, grad, dx, as_vector, transpose, Identity
from dune.ufl import Constant, DirichletBC
import dune.fem
from dune.fem.operator import linear as linearOperator

order = 2
grid = create.grid("ALUCube",
                   constructor=cartesianDomain([0, 0], [3, 1], [30, 10]))
spcU = create.space("lagrange",
                    grid,
                    dimRange=grid.dimension,
                    order=order,
                    storage="fem")
spcP = create.space("lagrange",
                    grid,
                    dimRange=1,
                    order=order - 1,
                    storage="fem")

cell = spcU.cell()
x = SpatialCoordinate(cell)
mu = Constant(0, "mu")
nu = Constant(0, "nu")
u = TrialFunction(spcU)
v = TestFunction(spcU)
p = TrialFunction(spcP)
Example #8
0
from dune.fem import spaceAdapt, adapt
from dune.grid import cartesianDomain, gridFunction
from dune.alugrid import aluConformGrid as leafGridView
from dune.fem.view import adaptiveLeafGridView as adaptiveGridView
from dune.fem import parameter, doerflerMark, globalRefine
from dune.fem.function import levelFunction
from dune.ufl import Space

import dune.create as create

parameter.append({"fem.verboserank": 0})

domain = cartesianDomain([0, 0], [1, 1], [16, 16])
grid = adaptiveGridView(leafGridView(domain))
space = create.space("lagrangehp", grid, maxOrder=4, storage="istl")

u = TrialFunction(space)
v = TestFunction(space)
x = SpatialCoordinate(space)
n = FacetNormal(space)
mu = 20 * 16
hT = MaxCellEdgeLength(space)
hS = avg(MaxFacetEdgeLength(space))
hs = MaxFacetEdgeLength(space)('+')

diffusiveFlux = lambda w, d: d
source = -sin(pi * x[0]) * sin(6 * pi * x[1])

a = (inner(diffusiveFlux(u, grad(u)), grad(v)) + source * v) * dx
a -= ( inner( outer(jump(u), n('+')), avg(diffusiveFlux(u,grad(v))) ) +\
Example #9
0
from ufl import *

import math
import dune.fem
from dune.fem.function import integrate
import dune.create as create
from dune.ufl import DirichletBC, Space

dimRange = 12  # needs to be >= 4, test with 4,8,11
grid = create.grid("ALUConform", "../data/mixed.dgf", dimgrid=2)

from ufl import SpatialCoordinate
uflSpace = dune.ufl.Space(2, dimRange)
x = SpatialCoordinate(uflSpace.cell())
from math import pi, log, sqrt
from ufl import cos, sin, as_vector
exact = as_vector(
    [sin(3 * pi * x[0]), x[1] * x[1], x[0] *
     x[0], cos(3. * pi * x[1])] + [0] * (dimRange - 4))
v1 = integrate(grid, exact, 5).two_norm

space = create.space("Lagrange", grid, dimRange=dimRange, order=1)
u = space.interpolate(exact, name="u")
v2 = integrate(grid, u, 5).two_norm

print(v1, v2, v1 - v2)
v3 = integrate(grid, inner(grad(u[11]), grad(u[11])), 5)
Example #10
0
from ufl import TestFunction, TrialFunction, SpatialCoordinate, triangle, exp,\
                dx, grad, inner, as_vector, replace, sqrt
from dune.ufl import Constant

parameter.append({"fem.verboserank": -1})

grid = structuredGrid([0, 0], [1, 1], [4, 4])

order = 2
dimR = 1
quadOrder = 2 * order + 3
spaceName = "lagrange"
#spaceName = "dgonb"
if use_codegen:
    space = create.space(spaceName, grid, dimRange=dimR, order=order,
                         interiorQuadratureOrders=[quadOrder, 2*order],\
                         skeletonQuadratureOrders=[quadOrder, 2*order, order, 2*order+1] )
else:
    space = create.space(spaceName, grid, dimRange=dimR, order=order)

x = SpatialCoordinate(space)

initial = 1 / 2 * (x[0]**2 + x[1]**2) - 1 / 3 * (x[0]**3 - x[1]**3) + 1

u_h = space.interpolate(as_vector([
    initial,
] * dimR), name='u_h')
u_h_n = u_h.copy(name="previous")

u = TrialFunction(space)
v = TestFunction(space)
Example #11
0
# print(vec, len(vec), vec[0], vec[0][0])
#set first element in first field vector equal to one
vec[0][0] = 2
# print(vec, len(vec), vec[0], vec[0][0])

#change element to 1
vec[0][0] = 1

assert (vec[0][0] == 1), "dune.istl blockvector not changing value correctly "
#now test with with other fieldvector created in dune=fempy

view = create.grid("yasp",
                   dune.grid.cartesianDomain([0, 0], [1, 1], [1, 1]),
                   dimgrid=2)

spc = create.space("Lagrange", view, dimRange=2, order=3, storage='istl')

#initialise all to 2
uh = spc.interpolate([2, 3], name="solution")

df = uh.as_istl
# print(df, len(df), df[0], df[0][0])
df[0][0] = 1
# print(df, len(df), df[0], df[0][0])

# print(uh.dofVector[0][0])

#reset equalt to one againt
assert (df[0][0] == 1), "blockvector from dune-fempy not changing correctly"
Example #12
0
    err = [inner(edf, edf), inner(grad(edf), grad(edf))]
    errors = [math.sqrt(e) for e in integrate(grid, err, order=8)]

    return df, errors, info


# <markdowncell>
# Finally we iterate over the requested methods and solve the problems

# <codecell>
fig = pyplot.figure(figsize=(10 * len(methods), 10))
figPos = 100 + 10 * len(methods) + 1
for i, m in enumerate(methods):
    space = create.space(m[1],
                         polyGrid,
                         order=order,
                         dimRange=1,
                         storage="istl",
                         **m[3])
    dfs, errors, info = compute(polyGrid, space, m[2], m[4])
    print("method:(",
          m[0],
          m[2],
          ")",
          "Size: ",
          space.size,
          "L^2: ",
          errors[0],
          "H^1: ",
          errors[1],
          info["linear_iterations"],
          flush=True)
Example #13
0
parameter.append({"fem.verboserank": 0})
newtonParameter = {
    "tolerance": 1e-7,
    "verbose": "false",
    "linear.absolutetol": 1e-8,
    "linear.reductiontol": 1e-8,
    "linear.preconditioning.method": "jacobi",
    "linear.preconditioning.iterations": 1,
    "linear.preconditioning.relaxation": 1.2,
    "linear.verbose": "false"
}

grid = create.grid("ALUConform",
                   cartesianDomain([0, 0], [1, 1], [10, 10]),
                   dimgrid=2)
spc = create.space("lagrange", grid, dimRange=1, order=2, storage="istl")

uflSpace = Space((grid.dimGrid, grid.dimWorld), 1)
u = TrialFunction(uflSpace)
v = TestFunction(uflSpace)
x = SpatialCoordinate(uflSpace.cell())
n = FacetNormal(uflSpace.cell())
mu = 1.
# he = MaxFacetEdgeLength(uflSpace.cell())('+') # this is wrong
# hT = MaxCellEdgeLength(uflSpace.cell())
hT = CellVolume(uflSpace.cell())
hF = FacetArea(uflSpace.cell())
# he = FacetArea(uflSpace.cell()) / Min( avg('+'), avg('-') )
heInv = hF / avg(hT)
exact = as_vector([cos(pi * x[0]) * cos(pi * x[1])])
Example #14
0
u = TrialFunction(uflSpace)
v = TestFunction(uflSpace)
x = SpatialCoordinate(uflSpace.cell())

from math import pi, log, sqrt
from ufl import cos, sin, as_vector, dx, ds, grad, inner
exact = as_vector(
    [sin(3 * pi * x[0]) * x[1] * x[1], x[0] * x[0] * cos(3. * pi * x[1])])
laplace = lambda u: grad(grad(u))[0, 0] + grad(grad(u))[1, 1]
f = as_vector([-laplace(exact[0]) + exact[0], -laplace(exact[1]) + exact[1]])
left = conditional(x[0] < 1e-5, 1, 0)
equation = inner(grad(u), grad(v)) * dx + inner(u,v) * dx - inner(f,v) * dx \
           + 3*pi*x[1]**2*v[0] * left*ds == 0

# spc = create.space("dgonb", grid, dimRange=dimRange, order=1)
spc = create.space("lagrange", grid, dimRange=dimRange, order=1)


def test(operator):
    model = [
        equation,
        DirichletBC(uflSpace, [None, x[0]**2], 2),  # bottom
        DirichletBC(uflSpace, [exact[0], None], 3),  # top
        DirichletBC(uflSpace, [None, None], 4),  # left
        DirichletBC(uflSpace, exact, 1)
    ]  # right
    parameters = {"newton." + k: v for k, v in newtonParameter.items()}

    scheme = create.scheme(operator, model, spc, parameters=parameters)
    solution = spc.interpolate([0, 0], name="solution")
    scheme.solve(target=solution)
Example #15
0
from dune.fem.function import integrate
import dune.create as create
from ufl import TestFunction, TrialFunction, SpatialCoordinate, triangle, exp,\
                dx, grad, inner, as_vector, replace, sqrt, dot,\
                derivative, action
from ufl.algorithms.apply_derivatives import apply_derivatives
from dune.fem.operator import linear as linearOperator

parameter.append({"fem.verboserank": -1})

grid = structuredGrid([0, 0], [1, 1], [40, 40])

order = 2
dimR = 2
spaceName = "lagrange"
space = create.space(spaceName, grid, dimRange=dimR, order=order)

arg = space.interpolate(as_vector([
    1,
] * dimR), name='arg')
destA = space.interpolate([
    0,
] * dimR, name='destA')  # note: this uses an efficient approach in C++
destB = space.interpolate(
    as_vector([
        0.,
    ] * dimR), name='destB'
)  # note: this needs to generate a ufl local function in the current implementation
destC = space.interpolate(as_vector([
    0,
] * dimR), name='destC')