class AnisotropicLens: dimWorld = 2 domain = cartesianDomain([0, 0.39], [0.9, 0.65], [15, 4]) x = SpatialCoordinate(triangle) g = [ 0, ] * dimWorld g[dimWorld - 1] = -9.810 # [m/s^2] g = as_vector(g) r_w = 1000. # [Kg/m^3] mu_w = 1.e-3 # [Kg/m s] r_n = 1460. # [Kg/m^3] mu_n = 9.e-4 # [Kg/m s] lens = lambda x, a, b: (a - b) * (conditional( abs(x[1] - 0.49) < 0.03, 1., 0.) * conditional( abs(x[0] - 0.45) < 0.11, 1., 0.)) + b p_c = brooksCorey Kdiag = lens(x, 6.64 * 1e-14, 1e-10) # [m^2] Koff = lens(x, 0, -5e-11) # [m^2] K = as_matrix([[Kdiag, Koff], [Koff, Kdiag]]) Phi = lens(x, 0.39, 0.40) # [-] s_wr = lens(x, 0.10, 0.12) # [-] s_nr = lens(x, 0.00, 0.00) # [-] theta = lens(x, 2.00, 2.70) # [-] pd = lens(x, 5000., 755.) # [Pa] #### initial conditions p_w0 = (0.65 - x[1]) * 9810. # hydrostatic pressure s_n0 = 0 # fully saturated # boundary conditions inflow = conditional(abs(x[0] - 0.45) < 0.06, 1., 0.) * conditional( abs(x[1] - 0.65) < 1e-8, 1., 0.) J_n = -5.137 * 1e-5 J_w = 1e-20 dirichlet = conditional(abs(x[0]) < 1e-8, 1., 0.) + conditional( abs(x[0] - 0.9) < 1e-8, 1., 0.) p_wD = p_w0 s_nD = s_n0 q_n = 0 q_w = 0 useCutOff = False
import dune.geometry geometryType = dune.geometry.simplex(2) referenceElement = dune.geometry.referenceElement(geometryType) print("\t".join(str(c) for c in referenceElement.corners)) for p in dune.geometry.quadratureRule(geometryType, 3): print(p.position, p.weight) # <markdowncell> # # Grid Construction and Basic Interface # We now move on to the Dune-Grid module. First let us discuss different # possibilities of constructing a grid. # <codecell> from dune.grid import cartesianDomain, yaspGrid domain = cartesianDomain([0, 0], [1, 0.25], [15, 4]) yaspView = yaspGrid(domain) yaspView.plot() yaspView.hierarchicalGrid.globalRefine() yaspView.plot() pyplot.show() # <markdowncell> # Let's visualize the grid and then globally refine it once # <codecell> from dune.alugrid import aluConformGrid aluView = aluConformGrid(domain) aluView.plot() aluView.hierarchicalGrid.globalRefine()
[[0.0, 0.5, 0.0], [-0.1, 0.1, 0.0], [-0.5, 0.0, 0.0 ], [-0.1, -0.1, 0.0], [0.0, -0.5, 0.0], [0.1, -0.1, 0.0], [0.5, 0.0, 0.0], [0.1, 0.1, 0.0]], lcar=0.05) axis = [0, 0, 1] geom.extrude(poly, translation_axis=axis, rotation_axis=axis, point_on_axis=[0, 0, 0], angle=2.0 / 6.0 * numpy.pi) mesh = pygmsh.generate_mesh(geom, verbose=False) points, cells = mesh.points, mesh.cells domain3d = {"vertices": points, "simplices": cells["tetra"]} except ImportError: # pygmsh not installed - use a simple cartesian domain from dune.grid import cartesianDomain domain3d = cartesianDomain([-0.25, -0.25, 0], [0.25, 0.25, 1], [30, 30, 60]) from dune.alugrid import aluSimplexGrid as leafGridView3d gridView3d = leafGridView3d(domain3d) # <markdowncell> # As before we solve a simple Laplace problem # <codecell> from dune.fem.space import lagrange as solutionSpace from dune.fem.scheme import galerkin as solutionScheme from ufl import TrialFunction, TestFunction, SpatialCoordinate, dot, grad, dx, conditional, sqrt space3d = solutionSpace(gridView3d, order=1) u = TrialFunction(space3d) v = TestFunction(space3d) x = SpatialCoordinate(space3d)
matplotlib.rc('image', cmap='jet') from matplotlib import pyplot 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")
import math from ufl import * 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])
from __future__ import print_function, unicode_literals import time, math, numpy, ufl import dune, dune.create from dune.generator import algorithm from dune.grid import cartesianDomain, yaspGrid domain = cartesianDomain([0, 0], [1, 0.25], [12, 3]) yaspView = yaspGrid(domain) x = ufl.SpatialCoordinate(ufl.triangle) function = ufl.as_vector([ufl.cos(2 * ufl.pi / (0.3 + x[0] * x[1]))]) # function = dune.create.function("global",gridview=yaspView, name="gl",order=5, # value=lambda x: [math.cos(2*math.pi/(0.3+x[0]*x[1]))] ) space = dune.create.space("lagrange", yaspView, order=1, dimRange=1) uh = space.interpolate(function, name="uh") error = dune.create.function("ufl", gridView=yaspView, name="error", order=5, ufl=uh - function, virtualize=True) rules = dune.geometry.quadratureRules(5) if False: # dune.fem type grid functions don't yet have vectorization support start = time.time() l2norm2 = 0 for e in yaspView.elements: hatxs, hatws = rules(e.type).get() weights = hatws * e.geometry.integrationElement(hatxs)
import sys import time from dune.grid import structuredGrid, cartesianDomain from dune.fem.view import adaptiveLeafGridView as gridView dim = sys.argv[1] if dim == "2": # 2d structured grid grid = structuredGrid([0, 0], [1, 1], [4, 4]) try: from dune.alugrid import aluConformGrid, aluSimplexGrid, aluCubeGrid domain = cartesianDomain([0, 0], [1, 1], [4, 4]) # 2d alu conform grid grid = gridView(aluConformGrid(domain)) # 2d alu simplex grid grid = gridView(aluSimplexGrid(domain)) # 2d alu cube grid grid = gridView(aluCubeGrid(domain)) except ImportError: print("Cannot import module dune-alugrid, skipping grid creation!") elif dim == "3": # 3d structured grid grid = structuredGrid([0, 0, 0], [1, 1, 1], [4, 4, 4]) try: from dune.alugrid import aluConformGrid, aluSimplexGrid, aluCubeGrid domain = cartesianDomain([0, 0, 0], [1, 1, 1], [4, 4, 4])
import dune.create as create 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)
# <codecell> import matplotlib matplotlib.rc('image', cmap='jet') import dune.fem as fem from dune.grid import cartesianDomain from dune.alugrid import aluConformGrid as leafGridView from dune.fem.view import adaptiveLeafGridView as adaptiveGridView from dune.fem.space import lagrange as solutionSpace order = 1 dimDomain = 2 # we are solving this in 2D dimRange = 2 # we have a system with two unknowns domain = cartesianDomain([4, 4], [8, 8], [3, 3]) gridView = adaptiveGridView(leafGridView(domain)) space = solutionSpace(gridView, dimRange=dimRange, order=order, storage="fem") # <markdowncell> # We want to solve the following system of equations of variables $\phi$ (phase field) and $T$ (temperature field) # # \begin{equation} # \begin{aligned} # \tau \frac{\partial \phi}{\partial t} &= \nabla \cdot D \nabla \phi + \phi(1-\phi)m(\phi, T), \\ # \frac{\partial T}{\partial t} &= D_T \nabla^2 T + \frac{\partial \phi}{\partial t}, # \end{aligned} # \end{equation} # # where $D_T$ = 2.25, m is given by #
inner, dot, div, grad, dx, as_vector, transpose, Identity from dune.ufl import Constant, DirichletBC from dune.fem.space import lagrange as lagrangeSpace from dune.fem.operator import galerkin as galerkinOperator from dune.fem.operator import linear as linearOperator from dune.fem.scheme import galerkin as galerkinScheme from dune.fem import parameter parameter.append({"fem.verboserank": 0}) order = 2 # Note: structuredGrid fails in precon step! # grid = structuredGrid([0,0],[3,1],[30,10]) from dune.alugrid import aluCubeGrid as leafGridView grid = leafGridView( cartesianDomain([0,0],[3,1],[30,10]) ) spcU = lagrangeSpace(grid, dimRange=grid.dimension, order=order, storage="petsc") spcP = lagrangeSpace(grid, dimRange=1, order=order-1, storage="petsc") cell = spcU.cell() x = SpatialCoordinate(cell) mu = Constant(0.1, "mu") nu = Constant(0.01, "nu") u = TrialFunction(spcU) v = TestFunction(spcU) p = TrialFunction(spcP) q = TestFunction(spcP) exact_u = as_vector( [x[1] * (1.-x[1]), 0] ) exact_p = as_vector( [ (-2*x[0] + 2)*mu ] ) f = as_vector( [0,]*grid.dimension )
from __future__ import print_function, division from ufl import as_vector, grad, cos, pi, SpatialCoordinate, triangle from dune.grid import structuredGrid, cartesianDomain from dune.fem.space import lagrange from dune.alugrid import aluConformGrid as gridManager grid = gridManager(cartesianDomain([0, 0], [1, 1], [16, 16])) # grid = structuredGrid([0, 0], [1, 1], [16, 16]) space = lagrange(grid, dimRange=1, order=1) x = SpatialCoordinate(triangle) exact = as_vector([cos(2. * pi * x[0]) * cos(2. * pi * x[1])]) solution = space.interpolate(exact, name="solution") test = space.interpolate(solution[0], name="tmp") test = space.interpolate(grad(solution)[0, 0], name="tmp")
def newGridView(N=4): return leafGridView([-1, -1], [1, 1], [N, N]) ctor = cartesianDomain([-1, -1], [1, 1], [N, N]) return leafGridView(ctor)
# Now we define the model starting with the exact solution: # <codecell> u = TrialFunction(uflSpace) v = TestFunction(uflSpace) a = (diffCoeff * inner(grad(u), grad(v)) + massCoeff * dot(u, v)) * dx # finally the right hand side and the boundary conditions b = (-div(diffCoeff * grad(exact[0])) + massCoeff * exact[0]) * v[0] * dx dbc = [dune.ufl.DirichletBC(uflSpace, exact, i + 1) for i in range(4)] # <markdowncell> # Now we define a grid build up of voronoi cells around $50$ random points # <codecell> constructor = cartesianDomain([-0.5, -0.5], [1, 1], [10, 10]) polyGrid = create.grid( "polygrid", voronoiCells(constructor, 50, "voronoiseeds", True, lloyd=100)) # <markdowncell> # In general we can construct a `polygrid` by providing a dictionary with # the `vertices` and the `polygons`. The `voronoiCells` function creates # such a dictonary using random seeds to generate voronoi cells which are # cut off using the provided `cartesianDomain`. The seeds can be # provided as list of points as second argument: # ``` # voronoiCells(constructor, towers, fileName=None, load=False): # ``` # If a `fileName` is provided the seeds will be written to disc and loaded # from that file is `load=True`. As an example the output of # `voronoiCells(constructor,5)` is
return l2norm2; } """ def testCppQuad(view, rules, error): algo = algorithm.load('l2norm2', io.StringIO(code), view, rules, error) start = time.time() l2norm2 = algo(view, rules, error) # print("C++:",math.sqrt(l2norm2),flush=True) # print("time used:", round(time.time()-start,2),flush=True) return l2norm2 if __name__ == "__main__": domain = cartesianDomain([0, 0], [1, 1], [50, 50]) view = gridView(domain) @dune.grid.gridFunction(view) def function(x): return numpy.cos(numpy.pi * x[0]) * numpy.cos(numpy.pi * x[1]) def interpolate(grid): mapper = grid.mapper({dune.geometry.vertex: 1}) data = numpy.zeros(mapper.size) for v in grid.vertices: data[mapper.index(v)] = function(v.geometry.center) return mapper, data mapper, data = interpolate(view)
# Before anything else let us set up the grid and the function space. We use the default DoF storage available in ```dune-fem``` - this can be changed for example to ```istl``` or ```petsc```. # <codecell> import time import dune.fem as fem from dune.grid import cartesianDomain from dune.alugrid import aluConformGrid as leafGridView from dune.fem.view import adaptiveLeafGridView as adaptiveGridView from dune.fem.space import lagrange as solutionSpace fem.parameter.append({"fem.verboserank": -1}) order = 1 dimDomain = 2 # we are solving this in 2D dimRange = 2 # we have a system with two unknowns domain = cartesianDomain( [4, 4], [8, 8], [40, 40]) # fails with 20x20 in adapt due to petsc error gridView = adaptiveGridView(leafGridView(domain, dimgrid=dimDomain)) space = solutionSpace(gridView, dimRange=dimRange, order=order, storage="petscadapt") # <markdowncell> # We want to solve the following system of equations of variables $\phi$ (phase field) and $T$ (temperature field) # # \begin{gather*} # \tau \frac{\partial \phi}{\partial t} = \nabla \cdot D \nabla \phi + \phi(1-\phi)m(\phi, T), \\ # \frac{\partial T}{\partial t} = D_T \nabla^2 T + \frac{\partial \phi}{\partial t}, # \end{gather*} # # where $D_T$ = 2.25, m is given by
from ufl import SpatialCoordinate, dot from dune.grid import cartesianDomain from dune.alugrid import aluConformGrid as leafGridView from dune.fem.view import filteredGridView from dune.fem.space import lagrange gridView = leafGridView( cartesianDomain([0,0],[1,1],[16,16]) ) filteredView = filteredGridView(gridView, lambda e: e.geometry.center.two_norm > 0.5, domainId=1) space = lagrange(filteredView, order=2) x = SpatialCoordinate(space) solution = space.interpolate(dot(x,x),name="solution") solution.plot() print("number of dofs:", solution.size,\ "integral over filtered domain",solution.integrate()) filteredView = filteredGridView(gridView, lambda e: e.geometry.center.two_norm < 0.5, domainId=1, useFilteredIndexSet=True) space = lagrange(filteredView, order=2) x = SpatialCoordinate(space) solution = space.interpolate(dot(x,x),name="solution") solution.plot() print("number of dofs:", solution.size,\ "integral over filtered domain",solution.integrate()) space = lagrange(gridView, order=2) solution = space.interpolate(dot(x,x),name="solution") solution.plot() print("number of dofs:", solution.size,\ "integral over filtered domain",solution.integrate())
self.cppTypeName = name self.cppIncludes = includes scalarTypeName = "GridViewFunction" vectorTypeName = "std::vector<GridViewFunction>" callScalar = algorithm.load('callScalar', io.StringIO(code), CppTypeInfo(scalarTypeName, [])) callVector = algorithm.load('callVector', io.StringIO(code), CppTypeInfo(vectorTypeName, [])) # number of grid elements (in one direction) gridSize = 4 # create a YaspGrid of the unit square domain = cartesianDomain([0, 0], [1, 1], [gridSize, gridSize]) grid = yaspGrid(domain, dimgrid=2) # create a nodal Lagrange FE basis of order 1 and order 2 basis1 = dune.functions.defaultGlobalBasis(grid, dune.functions.Lagrange(order=1)) basis2 = dune.functions.defaultGlobalBasis(grid, dune.functions.Lagrange(order=2)) # create a DOF vectors N1 = len(basis1) x1 = np.ndarray(N1) N2 = len(basis2) x2 = np.ndarray(N2)