def get_mesh(dim): if dim == 2: return df.UnitSquareMesh(2, 2) elif dim == 3: return df.UnitCubeMesh(2, 2, 2)
# Defines some hyper parameters, Number of temperatures, N samples, etc. # #--------------------------------------------------------------------- # Number of runs Nruns = 1 N = int(4 * 10**3) #number of samples N_temp = 4 #number of temperatures Ns = 1 #How often do we swap Nx = 28 Ny = 28 mesh = dl.UnitSquareMesh(Nx, Ny) PRIOR = prior.prior_measure(mesh) z0 = PRIOR.sample(exp=False) p = len(z0) X = np.zeros([N, p, N_temp]) #prealloactes y = np.zeros([N_temp, p]) #preallocates proposals bt = np.zeros([N, N_temp]) T0 = 100.0**(1.0 / 3.0) beta = np.array(T0**np.arange(0, N_temp)) beta_original = np.copy(beta) x0 = np.zeros((p, N_temp)) for i in range(N_temp): x0[:, i] = PRIOR.sample(exp=False)
def __init__(self, tfml_file, system_name='magma', p_name='Pressure', f_name='Porosity', c_name='c', n_name='n', m_name='m', d_name='d', N_name='N', h_squared_name='h_squared', x0_name='x0'): """read the tfml_file and use libspud to populate the internal parameters c: wavespeed n: permeability exponent m: bulk viscosity exponent d: wave dimension N: number of collocation points x0: coordinate wave peak h_squared: the size of the system in compaction lengths squared (h/delta)**2 """ # initialize libspud and extract parameters libspud.clear_options() libspud.load_options(tfml_file) # get model dimension self.dim = libspud.get_option("/geometry/dimension") self.system_name = system_name # get solitary wave parameters path = "/system::" + system_name + "/coefficient::" scalar_value = "/type::Constant/rank::Scalar/value::WholeMesh/constant" vector_value = "/type::Constant/rank::Vector/value::WholeMesh/constant::dim" c = libspud.get_option(path + c_name + scalar_value) n = int(libspud.get_option(path + n_name + scalar_value)) m = int(libspud.get_option(path + m_name + scalar_value)) d = float(libspud.get_option(path + d_name + scalar_value)) N = int(libspud.get_option(path + N_name + scalar_value)) self.h = np.sqrt( libspud.get_option(path + h_squared_name + scalar_value)) self.x0 = np.array(libspud.get_option(path + x0_name + vector_value)) self.swave = SolitaryWave(c, n, m, d, N) self.rmax = self.swave.r[-1] self.tfml_file = tfml_file # check that d <= dim assert (d <= self.dim) # sort out appropriate index for calculating distance r if d == 1: self.index = [self.dim - 1] else: self.index = range(0, int(d)) # check that the origin point is the correct dimension assert (len(self.x0) == self.dim) #read in information for constructing Function space and dolfin objects # get the mesh parameters and reconstruct the mesh meshtype = libspud.get_option("/geometry/mesh/source[0]/name") if meshtype == 'UnitSquare': number_cells = libspud.get_option( "/geometry/mesh[0]/source[0]/number_cells") diagonal = libspud.get_option( "/geometry/mesh[0]/source[0]/diagonal") mesh = df.UnitSquareMesh(number_cells[0], number_cells[1], diagonal) elif meshtype == 'Rectangle': x0 = libspud.get_option( "/geometry/mesh::Mesh/source::Rectangle/lower_left") x1 = libspud.get_option( "/geometry/mesh::Mesh/source::Rectangle/upper_right") number_cells = libspud.get_option( "/geometry/mesh::Mesh/source::Rectangle/number_cells") diagonal = libspud.get_option( "/geometry/mesh[0]/source[0]/diagonal") mesh = df.RectangleMesh(x0[0], x0[1], x1[0], x1[1], number_cells[0], number_cells[1], diagonal) elif meshtype == 'UnitCube': number_cells = libspud.get_option( "/geometry/mesh[0]/source[0]/number_cells") mesh = df.UnitCubeMesh(number_cells[0], number_cells[1], number_cells[2]) elif meshtype == 'Box': x0 = libspud.get_option( "/geometry/mesh::Mesh/source::Box/lower_back_left") x1 = libspud.get_option( "/geometry/mesh::Mesh/source::Box/upper_front_right") number_cells = libspud.get_option( "/geometry/mesh::Mesh/source::Box/number_cells") mesh = df.BoxMesh(x0[0], x0[1], x0[2], x1[0], x1[1], x1[2], number_cells[0], number_cells[1], number_cells[2]) elif meshtype == 'UnitInterval': number_cells = libspud.get_option( "/geometry/mesh::Mesh/source::UnitInterval/number_cells") mesh = df.UnitIntervalMesh(number_cells) elif meshtype == 'Interval': number_cells = libspud.get_option( "/geometry/mesh::Mesh/source::Interval/number_cells") left = libspud.get_option( "/geometry/mesh::Mesh/source::Interval/left") right = libspud.get_option( "/geometry/mesh::Mesh/source::Interval/right") mesh = df.IntervalMesh(number_cells, left, right) elif meshtype == 'File': mesh_filename = libspud.get_option( "/geometry/mesh::Mesh/source::File/file") print "tfml_file = ", self.tfml_file, "mesh_filename=", mesh_filename mesh = df.Mesh(mesh_filename) else: df.error("Error: unknown mesh type " + meshtype) #set the functionspace for n-d solitary waves path = "/system::" + system_name + "/field::" p_family = libspud.get_option(path + p_name + "/type/rank/element/family") p_degree = libspud.get_option(path + p_name + "/type/rank/element/degree") f_family = libspud.get_option(path + f_name + "/type/rank/element/family") f_degree = libspud.get_option(path + f_name + "/type/rank/element/degree") pe = df.FiniteElement(p_family, mesh.ufl_cell(), p_degree) ve = df.FiniteElement(f_family, mesh.ufl_cell(), f_degree) e = pe * ve self.functionspace = df.FunctionSpace(mesh, e) #work out the order of the fields for i in xrange( libspud.option_count("/system::" + system_name + "/field")): name = libspud.get_option("/system::" + system_name + "/field[" + ` i ` + "]/name") if name == f_name: self.f_index = i if name == p_name: self.p_index = i
import dolfin as dl mesh = dl.UnitSquareMesh(10, 10) V1 = dl.VectorFunctionSpace(mesh, "CG", 2) V2 = dl.FunctionSpace(mesh, "CG", 1) V3 = dl.FunctionSpace(mesh, "CG", 1) V = dl.MixedFunctionSpace([V1, V2, V3]) f1 = dl.Expression(("A + B*x[1]*(1-x[1])", "0."), A=1., B=1.) f2 = dl.Expression("A*x[0]", A=1.) f3 = dl.Expression("A", A=-3.) F1, F2, F3 = [ dl.interpolate(fi, Vi) for fi, Vi in zip((f1, f2, f3), (V1, V2, V3)) ] assigner = dl.FunctionAssigner(V, [V1, V2, V3]) state = dl.Function(V) assigner.assign(state, [F1, F2, F3]) print "|| state ||^2_L^(2) = ", dl.assemble(dl.inner(state, state) * dl.dx) dl.plot(state.sub(0)) dl.plot(state.sub(1)) dl.plot(state.sub(2)) dl.interactive()
def _discretize_fenics(): # assemble system matrices - FEniCS code ######################################## import dolfin as df # discrete function space mesh = df.UnitSquareMesh(GRID_INTERVALS, GRID_INTERVALS, 'crossed') V = df.FunctionSpace(mesh, 'Lagrange', FENICS_ORDER) u = df.TrialFunction(V) v = df.TestFunction(V) # data functions bottom_diffusion = df.Expression('(x[0] > 0.45) * (x[0] < 0.55) * (x[1] < 0.7) * 1.', element=df.FunctionSpace(mesh, 'DG', 0).ufl_element()) top_diffusion = df.Expression('(x[0] > 0.35) * (x[0] < 0.40) * (x[1] > 0.3) * 1. +' '(x[0] > 0.60) * (x[0] < 0.65) * (x[1] > 0.3) * 1.', element=df.FunctionSpace(mesh, 'DG', 0).ufl_element()) initial_data = df.Expression('(x[0] > 0.45) * (x[0] < 0.55) * (x[1] < 0.7) * 10.', element=df.FunctionSpace(mesh, 'DG', 0).ufl_element()) neumann_data = df.Expression('(x[0] > 0.45) * (x[0] < 0.55) * 1000.', element=df.FunctionSpace(mesh, 'DG', 0).ufl_element()) # assemble matrices and vectors l2_mat = df.assemble(df.inner(u, v) * df.dx) l2_0_mat = l2_mat.copy() h1_mat = df.assemble(df.inner(df.nabla_grad(u), df.nabla_grad(v)) * df.dx) h1_0_mat = h1_mat.copy() mat0 = h1_mat.copy() mat0.zero() bottom_mat = df.assemble(bottom_diffusion * df.inner(df.nabla_grad(u), df.nabla_grad(v)) * df.dx) top_mat = df.assemble(top_diffusion * df.inner(df.nabla_grad(u), df.nabla_grad(v)) * df.dx) u0 = df.project(initial_data, V).vector() f = df.assemble(neumann_data * v * df.ds) # boundary treatment def dirichlet_boundary(x, on_boundary): tol = 1e-14 return on_boundary and (abs(x[0]) < tol or abs(x[0] - 1) < tol or abs(x[1] - 1) < tol) bc = df.DirichletBC(V, df.Constant(0.), dirichlet_boundary) bc.apply(l2_0_mat) bc.apply(h1_0_mat) bc.apply(mat0) bc.zero(bottom_mat) bc.zero(top_mat) bc.apply(f) bc.apply(u0) # wrap everything as a pyMOR model ################################## from pymor.bindings.fenics import FenicsVectorSpace, FenicsMatrixOperator, FenicsVisualizer fom = InstationaryModel( T=1., initial_data=FenicsVectorSpace(V).make_array([u0]), operator=LincombOperator([FenicsMatrixOperator(mat0, V, V), FenicsMatrixOperator(h1_0_mat, V, V), FenicsMatrixOperator(bottom_mat, V, V), FenicsMatrixOperator(top_mat, V, V)], [1., 1., 100. - 1., ExpressionParameterFunctional('top - 1.', {'top': 0})]), rhs=VectorOperator(FenicsVectorSpace(V).make_array([f])), mass=FenicsMatrixOperator(l2_0_mat, V, V, name='l2'), products={'l2': FenicsMatrixOperator(l2_mat, V, V, name='l2'), 'l2_0': FenicsMatrixOperator(l2_0_mat, V, V, name='l2_0'), 'h1': FenicsMatrixOperator(h1_mat, V, V, name='h1'), 'h1_0_semi': FenicsMatrixOperator(h1_0_mat, V, V, name='h1_0_semi')}, time_stepper=ImplicitEulerTimeStepper(nt=NT), parameter_space=CubicParameterSpace({'top': 0}, minimum=1, maximum=100.), visualizer=FenicsVisualizer(FenicsVectorSpace(V)) ) return fom
NOISE = True PLOTTS = False FDGRAD = False ALL = False nbtest = 5 ############## Nxy, Dt, fpeak, t0, t1, t2, tf = loadparameters(TRANSMISSION) h = 1. / Nxy if PRINT: print 'Nxy={} (h={}), Dt={}, fpeak={}, t0,t1,t2,tf={}'.format(\ Nxy, h, Dt, fpeak, [t0,t1,t2,tf]) # Define PDE: # dist is in [km] mesh = dl.UnitSquareMesh(mpicomm_local, Nxy, Nxy) X, Y = 1, 1 # shall not be changed Vl = dl.FunctionSpace(mesh, 'Lagrange', 1) # Source term: Ricker = RickerWavelet(fpeak, 1e-6) r = 2 # polynomial degree for state and adj V = dl.FunctionSpace(mesh, 'Lagrange', r) if TRANSMISSION: y_src = 0.1 else: y_src = 1.0 #Pt = PointSources(V, [[0.1,y_src], [0.25,y_src], [0.4,y_src],\ #[0.6,y_src], [0.75,y_src], [0.9,y_src]]) Pt = PointSources(V, [[0.1, y_src], [0.4, y_src], [0.6, y_src], [0.9, y_src]]) srcv = dl.Function(V).vector()
""" import pyamg ############################################################ # Part I: Setup problem with Dolfin try: import dolfin as dfn except ImportError: raise ImportError('Problem with Dolfin Installation') dfn.parameters['linear_algebra_backend'] = 'Eigen' # Define mesh, function space mesh = dfn.UnitSquareMesh(75, 35) V = dfn.FunctionSpace(mesh, "CG", 1) # Define basis and bilinear form u = dfn.TrialFunction(V) v = dfn.TestFunction(V) a = dfn.dot(dfn.grad(v), dfn.grad(u)) * dfn.dx f = dfn.Expression( '500.0 * exp(-(pow(x[0] - 0.5, 2) + pow(x[1] - 0.5, 2)) / 0.02)', degree=1) L = v * f * dfn.dx # Define Dirichlet boundary (x = 0 or x = 1) class DirichletBoundary(dfn.SubDomain): def inside(self, x, on_boundary):
def test1(): """ Test whether SingleRegularization returns same output as underlying regularization """ mesh = dl.UnitSquareMesh(40, 40) Vm = dl.FunctionSpace(mesh, 'CG', 1) VmVm = createMixedFS(Vm, Vm) ab = dl.Function(VmVm) xab = dl.Function(VmVm) x = dl.Function(Vm) regul = LaplacianPrior({'Vm': Vm, 'gamma': 1e-4, 'beta': 1e-4}) regula = LaplacianPrior({'Vm': Vm, 'gamma': 1e-4, 'beta': 1e-4}) jointregula = SingleRegularization(regula, 'a') regulb = LaplacianPrior({'Vm': Vm, 'gamma': 1e-4, 'beta': 1e-4}) jointregulb = SingleRegularization(regulb, 'b') for ii in range(4): #ab.vector()[:] = (ii+1.0)*np.random.randn(2*Vm.dim()) ab = dl.interpolate(dl.Expression(('sin(nn*pi*x[0])*sin(nn*pi*x[1])', 'sin(nn*pi*x[0])*sin(nn*pi*x[1])'),\ nn=ii+1, degree=10), VmVm) a, b = ab.split(deepcopy=True) print '\nTest a' costregul = regul.cost(a) costjoint = jointregula.costab(a, b) print 'cost={}, diff={}'.format(costregul, np.abs(costregul - costjoint)) gradregul = regul.grad(a) gradjoint = jointregula.gradab(a, b) xab.vector().zero() xab.vector().axpy(1.0, gradjoint) ga, gb = xab.split(deepcopy=True) gan = ga.vector().norm('l2') gbn = gb.vector().norm('l2') diffn = (gradregul - ga.vector()).norm('l2') print '|ga|={}, diff={}, |gb|={}'.format(gan, diffn, gbn) regul.assemble_hessian(a) jointregula.assemble_hessianab(a, b) Hvregul = regul.hessian(a.vector()) Hvjoint = jointregula.hessianab(a.vector(), b.vector()) xab.vector().zero() xab.vector().axpy(1.0, Hvjoint) Ha, Hb = xab.split(deepcopy=True) Han = Ha.vector().norm('l2') Hbn = Hb.vector().norm('l2') diffn = (Hvregul - Ha.vector()).norm('l2') print '|Ha|={}, diff={}, |Hb|={}'.format(Han, diffn, Hbn) solvera = regul.getprecond() solveraiter = solvera.solve(x.vector(), a.vector()) solverab = jointregula.getprecond() solverabiter = solverab.solve(xab.vector(), ab.vector()) xa, xb = xab.split(deepcopy=True) diffn = (x.vector() - xa.vector()).norm('l2') diffbn = (b.vector() - xb.vector()).norm('l2') xan = xa.vector().norm('l2') xbn = xb.vector().norm('l2') print '|xa|={}, diff={}'.format(xan, diffn) print '|xb|={}, diff={}'.format(xbn, diffbn) print 'iter={}, diff={}'.format(solveraiter, np.abs(solveraiter - solverabiter)) print 'Test b' costregul = regul.cost(b) costjoint = jointregulb.costab(a, b) print 'cost={}, diff={}'.format(costregul, np.abs(costregul - costjoint)) gradregul = regul.grad(b) gradjoint = jointregulb.gradab(a, b) xab.vector().zero() xab.vector().axpy(1.0, gradjoint) ga, gb = xab.split(deepcopy=True) gan = ga.vector().norm('l2') gbn = gb.vector().norm('l2') diffn = (gradregul - gb.vector()).norm('l2') print '|gb|={}, diff={}, |ga|={}'.format(gbn, diffn, gan) regul.assemble_hessian(b) jointregulb.assemble_hessianab(a, b) Hvregul = regul.hessian(b.vector()) Hvjoint = jointregulb.hessianab(a.vector(), b.vector()) xab.vector().zero() xab.vector().axpy(1.0, Hvjoint) Ha, Hb = xab.split(deepcopy=True) Han = Ha.vector().norm('l2') Hbn = Hb.vector().norm('l2') diffn = (Hvregul - Hb.vector()).norm('l2') print '|Hb|={}, diff={}, |Ha|={}'.format(Hbn, diffn, Han) solverb = regul.getprecond() solverbiter = solverb.solve(x.vector(), b.vector()) solverab = jointregulb.getprecond() solverabiter = solverab.solve(xab.vector(), ab.vector()) xa, xb = xab.split(deepcopy=True) diffn = (x.vector() - xb.vector()).norm('l2') diffan = (a.vector() - xa.vector()).norm('l2') xan = xa.vector().norm('l2') xbn = xb.vector().norm('l2') print '|xb|={}, diff={}'.format(xbn, diffn) print '|xa|={}, diff={}'.format(xan, diffan) print 'iter={}, diff={}'.format(solverbiter, np.abs(solverbiter - solverabiter))
from fenicstools.objectivefunctional import ObjFctalElliptic from fenicstools.plotfenics import PlotFenics from fenicstools.prior import LaplacianPrior from fenicstools.regularization import TV, TVPD from fenicstools.observationoperator import ObsPointwise from fenicstools.optimsolver import checkgradfd_med, checkhessfd_med mpicomm = mpi_comm_world() mpirank = MPI.rank(mpicomm) mpisize = MPI.size(mpicomm) PLOT = False CHECK = True mesh = dl.UnitSquareMesh(150, 150) V = dl.FunctionSpace(mesh, 'Lagrange', 2) # space for state and adjoint variables Vm = dl.FunctionSpace(mesh, 'Lagrange', 1) # space for medium parameter Vme = dl.FunctionSpace(mesh, 'Lagrange', 1) # sp for target med param def u0_boundary(x, on_boundary): return on_boundary u0 = dl.Constant("0.0") bc = dl.DirichletBC(V, u0, u0_boundary) mtrue_exp = \ dl.Expression('1.0 + 7.0*(x[0]<=0.8)*(x[0]>=0.2)*(x[1]<=0.8)*(x[1]>=0.2)')
def QoI_FEM(lam1,lam2,pointa,pointb,gridx,gridy,p): aa = pointa[0] bb = pointb[0] cc = pointa[1] dd = pointb[1] mesh = fn.UnitSquareMesh(gridx, gridy) V = fn.FunctionSpace(mesh, "Lagrange", p) # Define diffusion tensor (here, just a scalar function) and parameters A = fn.Expression((('exp(lam1)','a'), ('a','exp(lam2)')), a = fn.Constant(0.0), lam1 = lam1, lam2 = lam2, degree=3) u_exact = fn.Expression("sin(lam1*pi*x[0])*cos(lam2*pi*x[1])", lam1 = lam1, lam2 = lam2, degree=2+p) # Define the mix of Neumann and Dirichlet BCs class LeftBoundary(fn.SubDomain): def inside(self, x, on_boundary): return (x[0] < fn.DOLFIN_EPS) class RightBoundary(fn.SubDomain): def inside(self, x, on_boundary): return (x[0] > 1.0 - fn.DOLFIN_EPS) class TopBoundary(fn.SubDomain): def inside(self, x, on_boundary): return (x[1] > 1.0 - fn.DOLFIN_EPS) class BottomBoundary(fn.SubDomain): def inside(self, x, on_boundary): return (x[1] < fn.DOLFIN_EPS) # Create a mesh function (mf) assigning an unsigned integer ('uint') # to each edge (which is a "Facet" in 2D) mf = fn.MeshFunction('size_t', mesh, 1) mf.set_all(0) # initialize the function to be zero # Setup the boundary classes that use Neumann boundary conditions NTB = TopBoundary() # instatiate NTB.mark(mf, 1) # set all values of the mf to be 1 on this boundary NBB = BottomBoundary() NBB.mark(mf, 2) # set all values of the mf to be 2 on this boundary NRB = RightBoundary() NRB.mark(mf, 3) # Define Dirichlet boundary conditions Gamma_0 = fn.DirichletBC(V, u_exact, LeftBoundary()) bcs = [Gamma_0] # Define data necessary to approximate exact solution f = ( fn.exp(lam1)*(lam1*fn.pi)**2 + fn.exp(lam2)*(lam2*fn.pi)**2 ) * u_exact #g1:#pointing outward unit normal vector, pointing upaward (0,1) g1 = fn.Expression("-exp(lam2)*lam2*pi*sin(lam1*pi*x[0])*sin(lam2*pi*x[1])", lam1=lam1, lam2=lam2, degree=2+p) #g2:pointing downward (0,1) g2 = fn.Expression("exp(lam2)*lam2*pi*sin(lam1*pi*x[0])*sin(lam2*pi*x[1])", lam1=lam1, lam2=lam2, degree=2+p) g3 = fn.Expression("exp(lam1)*lam1*pi*cos(lam1*pi*x[0])*cos(lam2*pi*x[1])", lam1=lam1, lam2=lam2, degree=2+p) fn.ds = fn.ds(subdomain_data=mf) # Define variational problem u = fn.TrialFunction(V) v = fn.TestFunction(V) a = fn.inner(A*fn.grad(u), fn.grad(v))*fn.dx L = f*v*fn.dx + g1*v*fn.ds(1) + g2*v*fn.ds(2) + g3*v*fn.ds(3) #note the 1, 2 and 3 correspond to the mf # Compute solution u = fn.Function(V) fn.solve(a == L, u, bcs) psi = AvgCharFunc([aa, bb, cc, dd], degree=0) Q = fn.assemble(fn.project(psi * u, V) * fn.dx) return Q
def get_mesh(N) -> df.Mesh: """Create the mesh.""" mesh = df.UnitSquareMesh(N, N) return mesh
import dolfin as dl import numpy as np from fenicstools.jointregularization import normalizedcrossgradient from fenicstools.miscfenics import setfct, createMixedFS from hippylib.linalg import vector2Function print 'Check exact results (cost only):' print 'Test 1' err = 1.0 N = 10 while err > 1e-6: N = 2 * N mesh = dl.UnitSquareMesh(N, N) V = dl.FunctionSpace(mesh, 'Lagrange', 1) VV = createMixedFS(V, V) cg = normalizedcrossgradient(VV, {'eps': 0.0}) a = dl.interpolate(dl.Expression('x[0]', degree=10), V) b = dl.interpolate(dl.Expression('x[1]', degree=10), V) ncg = cg.costab(a, b) err = np.abs(ncg - 0.5) / 0.5 print 'N={}, ncg(x,y)={:.6f}, err={:.3e}'.format(N, ncg, err) print 'Test 2' err = 1.0 N = 10 while err > 1e-6: N = 2 * N mesh = dl.UnitSquareMesh(N, N) V = dl.FunctionSpace(mesh, 'Lagrange', 2) VV = createMixedFS(V, V)
entity_map[edim][cell.index()] = the_entity.pop() assert not any(v is None for v in entity_map[0]) assert not any(v is None for v in entity_map[edim]) return entity_map # ------------------------------------------------------------------- if __name__ == '__main__': # Embedding map n0, dt0 = None, None for n in [8, 16, 32, 64, 128, 256, 512]: mesh = df.UnitSquareMesh(n, n) emesh = df.BoundaryMesh(mesh, 'exterior') time = df.Timer('map') time.start() mapping = build_embedding_map(emesh, mesh, tol=1E-14) dt = time.stop() mesh_x = mesh.coordinates() emesh_x = emesh.coordinates() assert max( np.linalg.norm(ex - mesh_x[to]) for ex, to in zip(emesh_x, mapping[0])) < 1E-14 assert max(
import dolfin as df mesh1 = df.UnitSquareMesh(2, 2) mesh2 = df.UnitSquareMesh(2, 2) V1 = df.FunctionSpace(mesh1, "CG", 1) V2 = df.FunctionSpace(mesh2, "CG", 1) u1 = df.Function(V1) v1 = df.TestFunction(V1) u2 = df.Function(V2) v2 = df.TestFunction(V2) u3 = df.Function(V2) u1.vector()[0] = 1 u3.vector()[:] = u1.vector()[:] u1.vector()[0] = 2 print(u1.vector()[0], u3.vector()[0]) df.assemble(-1.0 * df.inner(df.grad(u1), df.grad(v1)) * df.dx) df.assemble(-1.0 * df.inner(df.grad(u2), df.grad(v2)) * df.dx) df.assemble(-1.0 * df.inner(df.grad(u3), df.grad(v2)) * df.dx)
def drivcav_fems(N, vdgree=2, pdgree=1, scheme=None, bccontrol=None): """dictionary for the fem items of the (unit) driven cavity Parameters ---------- N : int mesh parameter for the unitsquare (N gives 2*N*N triangles) vdgree : int, optional polynomial degree of the velocity basis functions, defaults to 2 pdgree : int, optional polynomial degree of the pressure basis functions, defaults to 1 scheme : {None, 'CR', 'TH'} the finite element scheme to be applied, 'CR' for Crouzieux-Raviart,\ 'TH' for Taylor-Hood, overrides `pdgree`, `vdgree`, defaults to `None` bccontrol : boolean, optional whether to consider boundary control via penalized Robin \ defaults to false. TODO: not implemented yet but we need it here \ for consistency Returns ------- femp : a dict of problem FEM description with the keys: * `V`: FEM space of the velocity * `Q`: FEM space of the pressure * `diribcs`: list of the (Dirichlet) boundary conditions * `fv`: right hand side of the momentum equation * `fp`: right hand side of the continuity equation * `charlen`: characteristic length of the setup * `odcoo`: dictionary with the coordinates of the domain of \ observation * `cdcoo`: dictionary with the coordinates of the domain of \ control """ mesh = dolfin.UnitSquareMesh(N, N) if scheme == 'CR': # print 'we use Crouzieux-Raviart elements !' V = dolfin.VectorFunctionSpace(mesh, "CR", 1) Q = dolfin.FunctionSpace(mesh, "DG", 0) if scheme == 'TH': # print 'we use Taylor-Hood elements !' V = dolfin.VectorFunctionSpace(mesh, "CG", 2) Q = dolfin.FunctionSpace(mesh, "CG", 1) else: V = dolfin.VectorFunctionSpace(mesh, "CG", vdgree) Q = dolfin.FunctionSpace(mesh, "CG", pdgree) # Boundaries def top(x, on_boundary): return x[1] > 1.0 - dolfin.DOLFIN_EPS def leftbotright(x, on_boundary): return (x[0] > 1.0 - dolfin.DOLFIN_EPS or x[1] < dolfin.DOLFIN_EPS or x[0] < dolfin.DOLFIN_EPS) # No-slip boundary condition for velocity noslip = dolfin.Constant((0.0, 0.0)) bc0 = dolfin.DirichletBC(V, noslip, leftbotright) # Boundary condition for velocity at the lid lid = dolfin.Constant(("1", "0.0")) bc1 = dolfin.DirichletBC(V, lid, top) # Collect boundary conditions diribcs = [bc0, bc1] # rhs of momentum eqn fv = dolfin.Constant((0.0, 0.0)) # rhs of the continuity eqn fp = dolfin.Constant(0.0) dfems = dict(V=V, Q=Q, diribcs=diribcs, fv=fv, fp=fp, uspacedep=0, charlen=1.0) # domains of observation and control odcoo = dict(xmin=0.45, xmax=0.55, ymin=0.5, ymax=0.7) cdcoo = dict(xmin=0.4, xmax=0.6, ymin=0.2, ymax=0.3) dfems.update(dict(cdcoo=cdcoo, odcoo=odcoo)) return dfems
# (c) 2016 Gregor Mitscha-Baude "provide simple dolfin classes for code inspection" import dolfin mesh = dolfin.UnitSquareMesh(10, 10) V = dolfin.FunctionSpace(mesh, "CG", 1) u = dolfin.TrialFunction(V) v = dolfin.TestFunction(V) a = dolfin.inner(dolfin.grad(u), dolfin.grad(v)) * dolfin.dx L = dolfin.Constant(1.) * v * dolfin.dx u = dolfin.Function(V)
def _discretize_fenics(xblocks, yblocks, grid_num_intervals, element_order): # assemble system matrices - FEniCS code ######################################## import dolfin as df mesh = df.UnitSquareMesh(grid_num_intervals, grid_num_intervals, 'crossed') V = df.FunctionSpace(mesh, 'Lagrange', element_order) u = df.TrialFunction(V) v = df.TestFunction(V) diffusion = df.Expression('(lower0 <= x[0]) * (open0 ? (x[0] < upper0) : (x[0] <= upper0)) *' '(lower1 <= x[1]) * (open1 ? (x[1] < upper1) : (x[1] <= upper1))', lower0=0., upper0=0., open0=0, lower1=0., upper1=0., open1=0, element=df.FunctionSpace(mesh, 'DG', 0).ufl_element()) def assemble_matrix(x, y, nx, ny): diffusion.user_parameters['lower0'] = x/nx diffusion.user_parameters['lower1'] = y/ny diffusion.user_parameters['upper0'] = (x + 1)/nx diffusion.user_parameters['upper1'] = (y + 1)/ny diffusion.user_parameters['open0'] = (x + 1 == nx) diffusion.user_parameters['open1'] = (y + 1 == ny) return df.assemble(df.inner(diffusion * df.nabla_grad(u), df.nabla_grad(v)) * df.dx) mats = [assemble_matrix(x, y, xblocks, yblocks) for x in range(xblocks) for y in range(yblocks)] mat0 = mats[0].copy() mat0.zero() h1_mat = df.assemble(df.inner(df.nabla_grad(u), df.nabla_grad(v)) * df.dx) l2_mat = df.assemble(u * v * df.dx) f = df.Constant(1.) * v * df.dx F = df.assemble(f) bc = df.DirichletBC(V, 0., df.DomainBoundary()) for m in mats: bc.zero(m) bc.apply(mat0) bc.apply(h1_mat) bc.apply(F) # wrap everything as a pyMOR model ################################## # FEniCS wrappers from pymor.bindings.fenics import FenicsVectorSpace, FenicsMatrixOperator, FenicsVisualizer # generic pyMOR classes from pymor.models.basic import StationaryModel from pymor.operators.constructions import LincombOperator, VectorOperator from pymor.parameters.functionals import ProjectionParameterFunctional from pymor.parameters.spaces import CubicParameterSpace # define parameter functionals (same as in pymor.analyticalproblems.thermalblock) def parameter_functional_factory(x, y): return ProjectionParameterFunctional(component_name='diffusion', component_shape=(yblocks, xblocks), index=(yblocks - y - 1, x), name=f'diffusion_{x}_{y}') parameter_functionals = tuple(parameter_functional_factory(x, y) for x in range(xblocks) for y in range(yblocks)) # wrap operators ops = [FenicsMatrixOperator(mat0, V, V)] + [FenicsMatrixOperator(m, V, V) for m in mats] op = LincombOperator(ops, (1.,) + parameter_functionals) rhs = VectorOperator(FenicsVectorSpace(V).make_array([F])) h1_product = FenicsMatrixOperator(h1_mat, V, V, name='h1_0_semi') l2_product = FenicsMatrixOperator(l2_mat, V, V, name='l2') # build model visualizer = FenicsVisualizer(FenicsVectorSpace(V)) parameter_space = CubicParameterSpace(op.parameter_type, 0.1, 1.) fom = StationaryModel(op, rhs, products={'h1_0_semi': h1_product, 'l2': l2_product}, parameter_space=parameter_space, visualizer=visualizer) return fom
import sys, os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import dolfin import numpy import sa_thesis import sa_thesis.helpers.io as io import sa_thesis.computation.problems as problems mesh = dolfin.UnitSquareMesh(4, 4) domains = dolfin.MeshFunction('size_t', mesh, 2, 0) half = dolfin.AutoSubDomain(lambda xx, on: xx[0] > 0.5) half.mark(domains, 1) facets = dolfin.MeshFunction('size_t', mesh, 1, 0) left = dolfin.AutoSubDomain(lambda xx, on: on and dolfin.near(xx[0], 0)) right = dolfin.AutoSubDomain(lambda xx, on: on and dolfin.near(xx[0], 1)) front = dolfin.AutoSubDomain(lambda xx, on: on and dolfin.near(xx[1], 0)) back = dolfin.AutoSubDomain(lambda xx, on: on and dolfin.near(xx[1], 1)) left.mark(facets, 1) right.mark(facets, 2) front.mark(facets, 3) back.mark(facets, 4) h5file = io.H5File('square', 'w') h5file.set_mesh(mesh) h5file.add_attribute(domains, 'sides') problem = problems.PoissonProblem(mesh, domains=domains, facets=facets) ff = dolfin.Constant(-1.)
def _discretize_fenics(): # assemble system matrices - FEniCS code ######################################## import dolfin as df mesh = df.UnitSquareMesh(GRID_INTERVALS, GRID_INTERVALS, 'crossed') V = df.FunctionSpace(mesh, 'Lagrange', FENICS_ORDER) u = df.TrialFunction(V) v = df.TestFunction(V) diffusion = df.Expression( '(lower0 <= x[0]) * (open0 ? (x[0] < upper0) : (x[0] <= upper0)) *' '(lower1 <= x[1]) * (open1 ? (x[1] < upper1) : (x[1] <= upper1))', lower0=0., upper0=0., open0=0, lower1=0., upper1=0., open1=0, element=df.FunctionSpace(mesh, 'DG', 0).ufl_element()) def assemble_matrix(x, y, nx, ny): diffusion.user_parameters['lower0'] = x / nx diffusion.user_parameters['lower1'] = y / ny diffusion.user_parameters['upper0'] = (x + 1) / nx diffusion.user_parameters['upper1'] = (y + 1) / ny diffusion.user_parameters['open0'] = (x + 1 == nx) diffusion.user_parameters['open1'] = (y + 1 == ny) return df.assemble( df.inner(diffusion * df.nabla_grad(u), df.nabla_grad(v)) * df.dx) mats = [ assemble_matrix(x, y, XBLOCKS, YBLOCKS) for x in range(XBLOCKS) for y in range(YBLOCKS) ] mat0 = mats[0].copy() mat0.zero() h1_mat = df.assemble(df.inner(df.nabla_grad(u), df.nabla_grad(v)) * df.dx) f = df.Constant(1.) * v * df.dx F = df.assemble(f) bc = df.DirichletBC(V, 0., df.DomainBoundary()) for m in mats: bc.zero(m) bc.apply(mat0) bc.apply(h1_mat) bc.apply(F) # wrap everything as a pyMOR model ################################## # FEniCS wrappers from pymor.bindings.fenics import FenicsVectorSpace, FenicsMatrixOperator, FenicsVisualizer # define parameter functionals (same as in pymor.analyticalproblems.thermalblock) parameter_functionals = [ ProjectionParameterFunctional(component_name='diffusion', component_shape=(YBLOCKS, XBLOCKS), index=(YBLOCKS - y - 1, x)) for x in range(XBLOCKS) for y in range(YBLOCKS) ] # wrap operators ops = [FenicsMatrixOperator(mat0, V, V) ] + [FenicsMatrixOperator(m, V, V) for m in mats] op = LincombOperator(ops, [1.] + parameter_functionals) rhs = VectorOperator(FenicsVectorSpace(V).make_array([F])) h1_product = FenicsMatrixOperator(h1_mat, V, V, name='h1_0_semi') # build model visualizer = FenicsVisualizer(FenicsVectorSpace(V)) parameter_space = CubicParameterSpace(op.parameter_type, 0.1, 1.) fom = StationaryModel(op, rhs, products={'h1_0_semi': h1_product}, parameter_space=parameter_space, visualizer=visualizer) return fom
import numpy as np import dolfin as df from lib import openh5 mesh = df.UnitSquareMesh(10, 10) filename = 'file_mpi' functionspace = df.VectorFunctionSpace(mesh, 'CG', 1, 3) f = df.Function(functionspace) t_array = np.linspace(0, 1, 5) # Save data. sd = openh5(filename, functionspace, mode='w') sd.save_mesh() for t in t_array: f.assign(df.Constant((1 + t, 2, 3))) sd.write(f, 'f', t) sd.close()
prior.init_vector(mtrue, 0) prior.sample(noise, mtrue) return mtrue # define the PDE def pde_varf(u, m, p): return dl.exp(m) * dl.inner(dl.nabla_grad(u), dl.nabla_grad(p)) * dl.dx - dl.Constant(0.0) * p * dl.dx dl.set_log_active(False) sep = "\n" + "#" * 80 + "\n" ndim = 2 nx = 32 ny = 32 mesh = dl.UnitSquareMesh(dl.mpi_comm_self(), nx, ny) Vh2 = dl.FunctionSpace(mesh, 'Lagrange', 1) Vh1 = dl.FunctionSpace(mesh, 'Lagrange', 1) Vh = [Vh2, Vh1, Vh2] ndofs = [Vh[STATE].dim(), Vh[PARAMETER].dim(), Vh[ADJOINT].dim()] if rank == 0: print(sep, "Set up the mesh and finite element spaces", sep) print("Number of dofs: STATE={0}, PARAMETER={1}, ADJOINT={2}".format(*ndofs)) u_bdr = dl.Expression("x[1]", degree=1) u_bdr0 = dl.Constant(0.0) bc = dl.DirichletBC(Vh[STATE], u_bdr, u_boundary) bc0 = dl.DirichletBC(Vh[STATE], u_bdr0, u_boundary)
np.random.random((length, dim)) + np.random.random((length, dim)) * 1j) def block_vector_array_factory(length, dims, seed): return BlockVectorSpace( [NumpyVectorSpace(dim) for dim in dims]).from_numpy( numpy_vector_array_factory(length, sum(dims), seed).to_numpy()) if config.HAVE_FENICS: import dolfin as df from pymor.bindings.fenics import FenicsVectorSpace fenics_spaces = [ df.FunctionSpace(df.UnitSquareMesh(ni, ni), 'Lagrange', 1) for ni in [1, 10, 32, 100] ] def fenics_vector_array_factory(length, space, seed): V = FenicsVectorSpace(fenics_spaces[space]) U = V.zeros(length) dim = V.dim np.random.seed(seed) for v, a in zip(U._list, np.random.random((length, dim))): v.real_part.impl[:] = a if np.random.randint(2): UU = V.zeros(length) for v, a in zip(UU._list, np.random.random((length, dim))): v.real_part.impl[:] = a for u, uu in zip(U._list, UU._list):
print('[DONE]') print('Generating mesh.....', end='') if len(args.refinement) == 1: mesh_dims = args.refinement * args.dim else: if len(args.refinement) != args.dim: raise ValueError( "The number of refinement values must equal the number of dimensions." ) mesh_dims = args.refinement if args.dim == 1: mesh = dlf.UnitIntervalMesh(*mesh_dims) elif args.dim == 2: mesh = dlf.UnitSquareMesh(*mesh_dims) elif args.dim == 3: mesh = dlf.UnitCubeMesh(*mesh_dims) else: raise ValueError('Dimension %i is invalid!' % args.dim) print('[DONE]') # Region IDs ALL_ELSE = 0 LEFT = 1 RIGHT = 2 BOTTOM = 3 TOP = 4 BACK = 5 FRONT = 6
# Insert cell_map[cell.index()] = the_cell.pop() # Sanity assert not any(v is None for v in entity_map[0]) assert not any(v is None for v in entity_map[tdim]) # At this point we can build add the map emesh.parent_entity_map[mesh2.id()] = entity_map return emesh # ------------------------------------------------------------------- if __name__ == '__main__': mesh = df.UnitSquareMesh(4, 4) subdomains = df.MeshFunction('size_t', mesh, mesh.topology().dim(), 3) df.CompiledSubDomain('x[0] < 0.25+DOLFIN_EPS').mark(subdomains, 1) df.CompiledSubDomain('x[0] > 0.75-DOLFIN_EPS').mark(subdomains, 2) mesh1 = SubDomainMesh(subdomains, (1, 3)) mesh2 = SubDomainMesh(subdomains, (2, 3)) mesh12 = OverlapMesh(mesh1, mesh2) # FIXME: split the file! map1 = mesh12.parent_entity_map[mesh1.id()][2] map2 = mesh12.parent_entity_map[mesh2.id()][2] # Cell check out for c, c1, c2 in zip(df.cells(mesh12), map1, map2): assert df.near(c.midpoint().distance(df.Cell(mesh1, c1).midpoint()), 0, 1E-14) assert df.near(c.midpoint().distance(df.Cell(mesh2, c2).midpoint()), 0, 1E-14)
} double l; double c00; double c01; double c11; std::vector<double> locations; double o; }; ''' if __name__ == "__main__": dl.set_log_active(False) ndim = 2 nx = 64 ny = 64 mesh = dl.UnitSquareMesh(nx, ny) Vh = dl.FunctionSpace(mesh, "CG", 1) e = dl.Expression(cpp_mollifier) e.o = 2 e.l = math.pow(.2, e.o) e.c00 = 2. e.c01 = 0. e.c11 = .5 m = dl.interpolate(e, Vh) dl.plot(m) dl.interactive()
p = plot(u_r,title="{:d} -- {:2.2f}".format(i,eig)) return p if __name__ == "__main__": import dolfin import ufl import numpy as np import matplotlib.pyplot as plt dolfin.parameters["use_petsc_signal_handler"] = True dolfin.parameters["form_compiler"]["cpp_optimize"] = True dolfin.parameters["form_compiler"]["representation"] = "uflacs" n = 100 mesh = dolfin.UnitSquareMesh(n,n) V = dolfin.FunctionSpace(mesh,'CG',1) u = dolfin.Function(V) ut = dolfin.TestFunction(V) v = dolfin.TrialFunction(V) dx = dolfin.Measure("dx",domain=mesh) bc = dolfin.DirichletBC(V,0,"on_boundary") a_k = ufl.dot(ufl.grad(ut),ufl.grad(v))*dx a_m = ut*v*dx eig_solver = EigenSolver(a_k, a_m, u, [bc]) plt.savefig("operators.png") ncv, it = eig_solver.solve(10) eigs = eig_solver.get_eigenvalues(ncv) plt.figure() plt.plot(eigs,'o') plt.title("Eigenvalues")
""" Test different Krylov solver used to precondition NCG """ import dolfin as dl from fenicstools.miscfenics import createMixedFS from fenicstools.plotfenics import PlotFenics from fenicstools.jointregularization import crossgradient, normalizedcrossgradient from fenicstools.linalg.miscroutines import compute_eigfenics N = 40 mesh = dl.UnitSquareMesh(N,N) V = dl.FunctionSpace(mesh, 'CG', 1) mpirank = dl.MPI.rank(mesh.mpi_comm()) VV = createMixedFS(V, V) cg = crossgradient(VV) ncg = normalizedcrossgradient(VV) outdir = 'Output-CGvsNCG-' + str(N) + 'x' + str(N) + '/' plotfenics = PlotFenics(mesh.mpi_comm(), outdir) a1true = [ dl.interpolate(dl.Expression('log(10 - ' + '(x[0]>0.25)*(x[0]<0.75)*(x[1]>0.25)*(x[1]<0.75) * 8 )'), V), dl.interpolate(dl.Expression('log(10 - ' + '(x[0]>0.25)*(x[0]<0.75)*(x[1]>0.25)*(x[1]<0.75) * (' + '4*(x[0]<=0.5) + 8*(x[0]>0.5) ))'), V), dl.interpolate(dl.Expression('log(10 - ' + '(x[0]>0.25)*(x[0]<0.75)*(x[1]>0.25)*(x[1]<0.75) * (' + '4*(x[0]<=0.5) + 8*(x[0]>0.5) ))'), V),
import numpy as np import dolfin import dolfin_navier_scipy.dolfin_to_sparrays as dts import dolfin_navier_scipy.problem_setups as dnsps N = 2 femp = dnsps.drivcav_fems(N) mesh = dolfin.UnitSquareMesh(N, N) stokesmats = dts.get_stokessysmats(femp['V'], femp['Q']) # reduce the matrices by resolving the BCs (stokesmatsc, rhsd_stbc, invinds, bcinds, bcvals) = dts.condense_sysmatsbybcs(stokesmats, femp['diribcs']) fv = dolfin.Constant(('0', '1')) v = dolfin.interpolate(fv, femp['V']) invals = np.zeros(invinds.size) coorar, xinds, yinds, corvec = dts.get_dof_coors(femp['V']) icoorar, ixinds, iyinds, icorvec = dts.get_dof_coors(femp['V'], invinds=invinds) invals[ixinds] = icoorar[:, 0] # print coorar, xinds # print icoorar, ixinds # print v.vector().array()
import dolfin as dl import numpy as np import matplotlib.pyplot as plt from petsc4py import PETSc from fenicstools.linalg.miscroutines import gathermatrixrows, plotPETScmatrix, \ setupPETScmatrix, loadPETScmatrixfromfile #prefix = 'Hessian4.0-1src-1rcv/Hessian4.0_' prefix = 'Hessian4.0-5src-27rcv/Hessian4.0_' #prefix = 'Hessian8.0-5src-27rcv/Hessian8.0_' Nxy = 50 mysize = 16 # Set up PETSc matrix to store entire Hessian mesh = dl.UnitSquareMesh(Nxy, Nxy) Vm = dl.FunctionSpace(mesh, 'Lagrange', 1) listdofmap = Vm.dofmap().tabulate_all_coordinates(mesh).reshape((-1, 2)) np.savetxt(prefix + 'dof.txt', listdofmap) mpicomm = dl.mpi_comm_world() Hessian, _, _ = setupPETScmatrix(Vm, Vm, 'dense', mpicomm) # Get filenames and range of rows for each sub-piece filenames = [] rows = [] for myrank in range(mysize): a = myrank * (Vm.dim() / mysize) if myrank + 1 < mysize: b = (myrank + 1) * (Vm.dim() / mysize) + 5 else: b = Vm.dim()
def v_boundary(x, on_boundary): return on_boundary and (x[0] < dl.DOLFIN_EPS or x[0] > 1.0 - dl.DOLFIN_EPS) if __name__ == "__main__": dl.set_log_active(False) assert dlversion() >= (2016, 2, 0) world_comm = dl.mpi_comm_world() self_comm = dl.mpi_comm_self() ndim = 2 nx = 16 ny = 16 mesh = dl.UnitSquareMesh(self_comm, nx, ny) rank = dl.MPI.rank(world_comm) nproc = dl.MPI.size(world_comm) Vh2 = dl.FunctionSpace(mesh, 'Lagrange', 2) Vh1 = dl.FunctionSpace(mesh, 'Lagrange', 1) Vh = [Vh2, Vh1, Vh2] ndofs = [Vh[STATE].dim(), Vh[PARAMETER].dim(), Vh[ADJOINT].dim()] if rank == 0: print "Set up the mesh and finite element spaces" print "Number of dofs: STATE={0}, PARAMETER={1}, ADJOINT={2}".format( *ndofs) # Initialize Expressions