def initialize(self, V, Q, PS, D): super(Problem, self).initialize(V, Q, PS, D) print("IC type: " + self.ic) print("Velocity scale factor = %4.2f" % self.factor) reynolds = 728.761 * self.factor # TODO modify by nu_factor print("Computing with Re = %f" % reynolds) # set constants for self.area = assemble(interpolate(Expression("1.0"), Q) * self.dsIn) # inflow area if self.doErrControl: self.solution = interpolate( Expression(("0.0", "0.0", "factor*(1081.48-43.2592*(x[0]*x[0]+x[1]*x[1]))"), factor=self.factor), self.vSpace) print("Prepared analytic solution.") # womersley = steady + e^iCt, e^iCt has average 0 self.pg_normalization_factor.append(womersleyBC.average_analytic_pressure_grad(self.factor)) self.p_normalization_factor.append(norm( interpolate(womersleyBC.average_analytic_pressure_expr(self.factor), self.pSpace), norm_type='L2')) self.vel_normalization_factor.append(norm( interpolate(womersleyBC.average_analytic_velocity_expr(self.factor), self.vSpace), norm_type='L2')) print('Normalisation factors (vel, p, pg):', self.vel_normalization_factor[0], self.p_normalization_factor[0], self.pg_normalization_factor[0])
def test_WeightedGradient(): mesh = UnitSquareMesh(4, 4) V = FunctionSpace(mesh, 'CG', 1) u = interpolate(Expression("x[0]+2*x[1]"), V) wx = weighted_gradient_matrix(mesh, 0) du = Function(V) du.vector()[:] = wx * u.vector() nose.tools.assert_almost_equal(du.vector().min(), 1.) wy = weighted_gradient_matrix(mesh, 1) du.vector()[:] = wy * u.vector() nose.tools.assert_almost_equal(du.vector().min(), 2.) mesh = UnitCubeMesh(4, 4, 4) V = FunctionSpace(mesh, 'CG', 1) u = interpolate(Expression("x[0]+2*x[1]+3*x[2]"), V) du = Function(V) wx = weighted_gradient_matrix(mesh, (0, 1, 2)) du.vector()[:] = wx[0] * u.vector() nose.tools.assert_almost_equal(du.vector().min(), 1.) du.vector()[:] = wx[1] * u.vector() nose.tools.assert_almost_equal(du.vector().min(), 2.) du.vector()[:] = wx[2] * u.vector() nose.tools.assert_almost_equal(du.vector().min(), 3.) #if __name__ == '__main__': #nose.run(defaultTest=__name__)
def cyclic3D(u): """ Symmetrize with respect to (xyz) cycle. """ try: nrm = np.linalg.norm(u.vector()) V = u.function_space() assert V.mesh().topology().dim() == 3 mesh1 = Mesh(V.mesh()) mesh1.coordinates()[:, :] = mesh1.coordinates()[:, [1, 2, 0]] W1 = FunctionSpace(mesh1, 'CG', 1) # testing if symmetric bc = DirichletBC(V, 1, DomainBoundary()) test = Function(V) bc.apply(test.vector()) test = interpolate(Function(W1, test.vector()), V) assert max(test.vector()) - min(test.vector()) < 1.1 v1 = interpolate(Function(W1, u.vector()), V) mesh2 = Mesh(mesh1) mesh2.coordinates()[:, :] = mesh2.coordinates()[:, [1, 2, 0]] W2 = FunctionSpace(mesh2, 'CG', 1) v2 = interpolate(Function(W2, u.vector()), V) pr = project(u+v1+v2) assert np.linalg.norm(pr.vector())/nrm > 0.01 return pr except: print "Cyclic symmetrization failed!" return u
def initialize(self, V, Q, PS, D): super(Problem, self).initialize(V, Q, PS, D) print("IC type: " + self.ic) print("Velocity scale factor = %4.2f" % self.factor) reynolds = 728.761 * self.factor # TODO modify by nu_factor print("Computing with Re = %f" % reynolds) self.v_in = Function(V) print('Initializing error control') self.load_precomputed_bessel_functions(PS) self.solution = self.assemble_solution(0.0) # set constants for self.area = assemble(interpolate(Expression("1.0"), Q) * self.dsIn) # inflow area # womersley = steady + e^iCt, e^iCt has average 0 self.pg_normalization_factor.append(womersleyBC.average_analytic_pressure_grad(self.factor)) self.p_normalization_factor.append(norm( interpolate(womersleyBC.average_analytic_pressure_expr(self.factor), self.pSpace), norm_type='L2')) self.vel_normalization_factor.append(norm( interpolate(womersleyBC.average_analytic_velocity_expr(self.factor), self.vSpace), norm_type='L2')) # print('Normalisation factors (vel, p, pg):', self.vel_normalization_factor[0], self.p_normalization_factor[0], # self.pg_normalization_factor[0]) one = (interpolate(Expression('1.0'), Q)) self.outflow_area = assemble(one*self.dsOut) print('Outflow area:', self.outflow_area)
def test_StatisticsProbe_segregated_3D(V3_self): u0 = interpolate(Expression('x[0]'), V3_self) v0 = interpolate(Expression('x[1]'), V3_self) w0 = interpolate(Expression('x[2]'), V3_self) x = array([0.5, 0.25, 0.25]) p = StatisticsProbe(x, V3_self, True) for i in range(5): p(u0, v0, w0) assert p.number_of_evaluations() == 5 assert p.value_size() == 9 mean = p.mean() var = p.variance() assert round(p[0][0] - 2.5, 7) == 0 assert round(p[0][4] - 0.3125, 7) == 0 assert round(p[1][0] - 0.5, 7) == 0 assert round(p[1][1] - 0.25, 7) == 0 assert round(p[1][2] - 0.25, 7) == 0 assert round(mean[0] - 0.5, 7) == 0 assert round(mean[1] - 0.25, 7) == 0 assert round(mean[2] - 0.25, 7) == 0 assert round(var[0] - 0.25, 7) == 0 assert round(var[1] - 0.0625, 7) == 0 assert round(var[2] - 0.0625, 7) == 0 assert round(var[3] - 0.125, 7) == 0 assert round(var[4] - 0.125, 7) == 0
def setup_forms(self, old_solver): prob = self.prob if old_solver is not None: self.old_vel = dfn.interpolate(old_solver.old_vel, prob.v_fnc_space) self.cur_vel = dfn.interpolate(old_solver.cur_vel, prob.v_fnc_space) else: self.old_vel = dfn.Function(prob.v_fnc_space) self.cur_vel = dfn.Function(prob.v_fnc_space) # Assemble matrices from variational forms. Ax = Ls self.a = dfn.inner(dfn.grad(prob.v), dfn.grad(prob.vt)) * dfn.dx self.A = dfn.assemble(self.a) if params['bcs'] is 'test': self.bcs = get_test_bcs(prob.v_fnc_space, test_bc) else: self.bcs = get_normal_bcs(prob.v_fnc_space, test_bc) # For the gradient term in the stress update self.l_elastic = self.dt * self.mu * \ dfn.inner(dfn.grad(prob.v), prob.St) * dfn.dx self.L_elastic = dfn.assemble(self.l_elastic)
def apply(self, pc, x, y): ysave = x.duplicate() f = HiptmairSetup.BCapply(self.Fspace[0],self.BC[0],x,"dolfin") fVec = interpolate(f,self.Fspace[2]) self.BC[2].apply(fVec.vector()) uVec = HiptmairSetup.FuncToPETSc(fVec) u = uVec.duplicate() self.kspVector.solve(uVec, u) f = HiptmairSetup.BCapply(self.Fspace[2],self.BC[2],u,"dolfin") fMag = interpolate(f,self.Fspace[0]) self.BC[0].apply(fMag.vector()) xVec = HiptmairSetup.FuncToPETSc(fMag) xMag = HiptmairSetup.BCapply(self.Fspace[0],self.BC[0],x) uGrad = HiptmairSetup.TransGradOp(self.kspMass,self.B,xMag) xLag = HiptmairSetup.BCapply(self.Fspace[1],self.BC[1],uGrad) u = uGrad.duplicate() self.kspScalar.solve(xLag, u) uGrad = HiptmairSetup.BCapply(self.Fspace[1],self.BC[1],u) uGrad1 = HiptmairSetup.GradOp(self.kspMass,self.B,uGrad) xMag = HiptmairSetup.BCapply(self.Fspace[0],self.BC[0],uGrad1) xx = x.duplicate() xx.pointwiseMult(self.diag, x) # print xVec.array, xMag.array # sss y.array = xx.array+xVec.array+xMag.array
def initialize(self, V, Q, PS, D): super(Problem, self).initialize(V, Q, PS, D) print("IC type: " + self.ic) print("Velocity scale factor = %4.2f" % self.factor) reynolds = 728.761 * self.factor print("Computing with Re = %f" % reynolds) # set constants for self.area = assemble(interpolate(Expression("1.0"), Q) * self.dsIn) # inflow area self.solution = interpolate(Expression(("0.0", "0.0", "factor*(1081.48-43.2592*(x[0]*x[0]+x[1]*x[1]))"), factor=self.factor), self.vSpace) analytic_pressure = womersleyBC.average_analytic_pressure_expr(self.factor) self.sol_p = interpolate(analytic_pressure, self.pSpace) self.analytic_gradient = womersleyBC.average_analytic_pressure_grad(self.factor) self.analytic_pressure_norm = norm(self.sol_p, norm_type='L2') self.analytic_v_norm_L2 = norm(self.solution, norm_type='L2') self.analytic_v_norm_H1 = norm(self.solution, norm_type='H1') self.analytic_v_norm_H1w = sqrt(assemble((inner(grad(self.solution), grad(self.solution)) + inner(self.solution, self.solution)) * self.dsWall)) print("Prepared analytic solution.") self.pg_normalization_factor.append(womersleyBC.average_analytic_pressure_grad(self.factor)) self.p_normalization_factor.append(self.analytic_pressure_norm) self.vel_normalization_factor.append(norm(self.solution, norm_type='L2')) print('Normalisation factors (vel, p, pg):', self.vel_normalization_factor[0], self.p_normalization_factor[0], self.pg_normalization_factor[0]) one = (interpolate(Expression('1.0'), Q)) self.outflow_area = assemble(one*self.dsOut) print('Outflow area:', self.outflow_area)
def test_StatisticsProbes_segregated_2D(): mesh = UnitSquareMesh(4, 4) V = FunctionSpace(mesh, 'CG', 1) u0 = interpolate(Expression('x[0]'), V) v0 = interpolate(Expression('x[1]'), V) x = array([[0.5, 0.25], [0.4, 0.4], [0.3, 0.3]]) probes = StatisticsProbes(x.flatten(), V, True) for i in range(5): probes(u0, v0) id0, p = probes[0] if len(p) > 0: assert p.number_of_evaluations() == 5 assert p.value_size() == 5 mean = p.mean() var = p.variance() nose.tools.assert_almost_equal(p[0][0], 2.5) nose.tools.assert_almost_equal(p[0][4], 0.625) nose.tools.assert_almost_equal(p[1][0], 0.5) nose.tools.assert_almost_equal(p[1][1], 0.25) nose.tools.assert_almost_equal(mean[0], 0.5) nose.tools.assert_almost_equal(mean[1], 0.25) nose.tools.assert_almost_equal(var[0], 0.25) nose.tools.assert_almost_equal(var[1], 0.0625) nose.tools.assert_almost_equal(var[2], 0.125)
def test_StatisticsProbe_segregated_2D(): mesh = UnitSquareMesh(mpi_comm_self(), 4, 4) V = FunctionSpace(mesh, 'CG', 1) u0 = interpolate(Expression('x[0]'), V) v0 = interpolate(Expression('x[1]'), V) x = array([0.5, 0.25]) p = StatisticsProbe(x, V, True) for i in range(5): p(u0, v0) assert p.number_of_evaluations() == 5 assert p.value_size() == 5 mean = p.mean() var = p.variance() nose.tools.assert_almost_equal(p[0][0], 2.5) nose.tools.assert_almost_equal(p[0][4], 0.625) nose.tools.assert_almost_equal(p[1][0], 0.5) nose.tools.assert_almost_equal(p[1][1], 0.25) nose.tools.assert_almost_equal(mean[0], 0.5) nose.tools.assert_almost_equal(mean[1], 0.25) nose.tools.assert_almost_equal(var[0], 0.25) nose.tools.assert_almost_equal(var[1], 0.0625) nose.tools.assert_almost_equal(var[2], 0.125)
def test_fenics_vector(): def mult_assemble(a, basis): return MultiplicationOperator(a(0), basis) mean_func = ConstFunction(2) a = [ConstFunction(3), ConstFunction(4)] rvs = [UniformRV(), NormalRV(mu=0.5)] coeff_field = ListCoefficientField(mean_func, a, rvs) A = MultiOperator(coeff_field, mult_assemble) mis = [Multiindex([0]), Multiindex([1]), Multiindex([0, 1]), Multiindex([0, 2])] mesh = UnitSquare(4, 4) fs = FunctionSpace(mesh, "CG", 4) F = [interpolate(Expression("*".join(["x[0]"] * i)), fs) for i in range(1, 5)] vecs = [FEniCSVector(f) for f in F] w = MultiVectorWithProjection() for mi, vec in zip(mis, vecs): w[mi] = vec v = A * w L = LegendrePolynomials(normalised=True) H = StochasticHermitePolynomials(mu=0.5, normalised=True) ex0 = Expression("2*x[0] + 3*(l01*x[0]*x[0]-l00*x[0]) + 4*(h01*x[0]*x[0]*x[0]-h00*x[0])", l01=L.get_beta(0)[1], l00=L.get_beta(0)[0], h01=H.get_beta(0)[1], h00=H.get_beta(0)[0]) vec0 = FEniCSVector(interpolate(ex0, fs)) assert_almost_equal(v[mis[0]].array, vec0.array) # ====================================================================== # test with different meshes # ====================================================================== N = len(mis) meshes = [UnitSquare(i + 3, i + 3) for i in range(N)] fss = [FunctionSpace(mesh, "CG", 4) for mesh in meshes] F = [interpolate(Expression("*".join(["x[0]"] * (i + 1))), fss[i]) for i in range(N)] vecs = [FEniCSVector(f) for f in F] w = MultiVectorWithProjection() for mi, vec in zip(mis, vecs): w[mi] = vec v = A * w L = LegendrePolynomials(normalised=True) H = StochasticHermitePolynomials(mu=0.5, normalised=True) ex0 = Expression("2*x[0] + 3*(l01*x[0]*x[0]-l00*x[0]) + 4*(h01*x[0]*x[0]*x[0]-h00*x[0])", l01=L.get_beta(0)[1], l00=L.get_beta(0)[0], h01=H.get_beta(0)[1], h00=H.get_beta(0)[0]) ex2 = Expression("2*x[0]*x[0]*x[0] + 4*(h11*x[0]*x[0]*x[0]*x[0] - h10*x[0]*x[0]*x[0] + h1m1*x[0])", h11=H.get_beta(1)[1], h10=H.get_beta(1)[0], h1m1=H.get_beta(1)[-1]) vec0 = FEniCSVector(interpolate(ex0, fss[0])) vec2 = FEniCSVector(interpolate(ex2, fss[2])) assert_almost_equal(v[mis[0]].array, vec0.array) assert_almost_equal(v[mis[2]].array, vec2.array)
def neumann_elasticity_data(): ''' Return: a bilinear form in the neumann elasticity problem L linear form in therein V function space, where a, L are defined bc homog. dirichlet conditions for case where we want pos. def problem z list of orthonormal vectors in the nullspace of A that form basis of ker(A) ''' mesh = UnitSquareMesh(40, 40) V = VectorFunctionSpace(mesh, 'CG', 1) u = TrialFunction(V) v = TestFunction(V) f = Expression(('sin(pi*x[0])', 'cos(pi*x[1])')) epsilon = lambda u: sym(grad(u)) # Material properties E, nu = 10.0, 0.3 mu, lmbda = Constant(E/(2*(1 + nu))), Constant(E*nu/((1 + nu)*(1 - 2*nu))) sigma = lambda u: 2*mu*epsilon(u) + lmbda*tr(epsilon(u))*Identity(2) a = inner(sigma(u), epsilon(v))*dx L = inner(f, v)*dx # Zero stress bc = DirichletBC(V, Constant((0, 0)), DomainBoundary()) z0 = interpolate(Constant((1, 0)), V).vector() normalize(z0, 'l2') z1 = interpolate(Constant((0, 1)), V).vector() normalize(z1, 'l2') X = mesh.coordinates().reshape((-1, 2)) c0, c1 = np.sum(X, axis=0)/len(X) z2 = interpolate(Expression(('x[1]-c1', '-(x[0]-c0)'), c0=c0, c1=c1), V).vector() normalize(z2, 'l2') z = [z0, z1, z2] # Check that this is orthonormal basis I = np.zeros((3, 3)) for i, zi in enumerate(z): for j, zj in enumerate(z): I[i, j] = zi.inner(zj) print I print la.norm(I-np.eye(3)) assert la.norm(I-np.eye(3)) < 1E-13 return a, L, V, bc, z
def setUp(self): self.mesh = dolfin.UnitCube(3,3,3) self.V = dolfin.FunctionSpace(self.mesh, "Nedelec 1st kind H(curl)", 3) self.u_r = dolfin.interpolate( dolfin.Expression(('0','0', '2*x[2]')), self.V) self.u_i = dolfin.interpolate( dolfin.Expression(('0','0', '-x[2]*x[2]')), self.V) self.x = self.u_r.vector().array() + 1j*self.u_i.vector().array() self.DUT = ComplexVoltageAlongLine(self.V) self.DUT.set_dofs(self.x)
def test_compute_flux(): f = df.interpolate(df.Constant((1, 0, 0)), VV) assert abs(compute_flux(f, mesh2d) - 1) < tol f = df.interpolate(df.Constant((1, 0, 1)), VV) assert abs(compute_flux(f, mesh2d) - 1) < tol f = df.interpolate(df.Constant((0.5, 0, 1)), VV) assert abs(compute_flux(f, mesh2d) - 0.5) < tol f = df.interpolate(df.Constant((0, 0, 1)), VV) assert abs(compute_flux(f, mesh2d) - 0) < tol
def test_StatisticsProbes_segregated_2D(V2): u0 = interpolate(Expression('x[0]', degree=1), V2) v0 = interpolate(Expression('x[1]', degree=1), V2) x = array([[0.5, 0.25], [0.4, 0.4], [0.3, 0.3]]) probes = StatisticsProbes(x.flatten(), V2, True) for i in range(5): probes(u0, v0) p = probes.array() if MPI.rank(mpi_comm_world()) == 0: assert round(p[0,0] - 2.5, 7) == 0 assert round(p[0,4] - 0.625, 7) == 0
def get_initial_conditions(self, function_list): out = [] for d in function_list: if d['type'] == 'v': f = Function(self.vSpace) if self.ic == 'correct': f = interpolate(Expression(("0.0", "0.0", "factor*(1081.48-43.2592*(x[0]*x[0]+x[1]*x[1]))"), factor=self.factor), self.vSpace) if d['type'] == 'p': f = Function(self.pSpace) if self.ic == 'correct': f = interpolate(womersleyBC.average_analytic_pressure_expr(self.factor), self.pSpace) out.append(f) return out
def test_StatisticsProbes_segregated_3D(V3): u0 = interpolate(Expression('x[0]', degree=1), V3) v0 = interpolate(Expression('x[1]', degree=1), V3) w0 = interpolate(Expression('x[2]', degree=1), V3) x = array([[0.5, 0.25, 0.25], [0.4, 0.4, 0.4], [0.3, 0.3, 0.3]]) probes = StatisticsProbes(x.flatten(), V3, True) for i in range(5): probes(u0, v0, w0) p = probes.array() if MPI.rank(MPI.comm_world) == 0: assert round(p[0,0] - 2.5, 7) == 0 assert round(p[0,4] - 0.3125, 7) == 0
def symmetrize(u, d, sym): """ Symmetrize function u. """ if len(d) == 3: # three dimensions -> cycle XYZ return cyclic3D(u) elif len(d) >= 4: # four dimensions -> rotations in 2D return rotational(u, d[-1]) nrm = np.linalg.norm(u.vector()) V = u.function_space() mesh = Mesh(V.mesh()) # test if domain is symmetric using function equal 0 inside, 1 on boundary # extrapolation will force large values if not symmetric since the flipped # domain is different bc = DirichletBC(V, 1, DomainBoundary()) test = Function(V) bc.apply(test.vector()) if len(d) == 2: # two dimensions given: swap dimensions mesh.coordinates()[:, d] = mesh.coordinates()[:, d[::-1]] else: # one dimension given: reflect mesh.coordinates()[:, d[0]] *= -1 # FIXME functionspace takes a long time to construct, maybe copy? W = FunctionSpace(mesh, 'CG', 1) try: # testing test = interpolate(Function(W, test.vector()), V) # max-min should be around 1 if domain was symmetric # may be slightly above due to boundary approximation assert max(test.vector()) - min(test.vector()) < 1.1 v = interpolate(Function(W, u.vector()), V) if sym: # symmetric pr = project(u+v) else: # antisymmetric pr = project(u-v) # small solution norm most likely means that symmetrization gives # trivial function assert np.linalg.norm(pr.vector())/nrm > 0.01 return pr except: # symmetrization failed for some reason print "Symmetrization " + str(d) + " failed!" return u
def test_Probes_vectorfunctionspace_2D(): mesh = UnitSquareMesh(4, 4) V = VectorFunctionSpace(mesh, 'CG', 1) u0 = interpolate(Expression(('x[0]', 'x[1]')), V) x = array([[0.5, 0.5], [0.4, 0.4], [0.3, 0.3]]) p = Probes(x.flatten(), V) # Probe twice p(u0) p(u0) # Check both snapshots p0 = p.array(N=0) if MPI.rank(mpi_comm_world()) == 0: nose.tools.assert_almost_equal(p0[0, 0], 0.5) nose.tools.assert_almost_equal(p0[1, 1], 0.4) nose.tools.assert_almost_equal(p0[2, 1], 0.3) p0 = p.array(N=1) if MPI.rank(mpi_comm_world()) == 0: nose.tools.assert_almost_equal(p0[0, 0], 0.5) nose.tools.assert_almost_equal(p0[1, 0], 0.4) nose.tools.assert_almost_equal(p0[2, 1], 0.3) p0 = p.array(filename='dumpvector2D') if MPI.rank(mpi_comm_world()) == 0: nose.tools.assert_almost_equal(p0[0, 0, 0], 0.5) nose.tools.assert_almost_equal(p0[1, 1, 1], 0.4) nose.tools.assert_almost_equal(p0[2, 0, 1], 0.3) f = open('dumpvector2D_all.probes', 'r') p1 = load(f) nose.tools.assert_almost_equal(p1[0, 0, 0], 0.5) nose.tools.assert_almost_equal(p1[1, 1, 0], 0.4) nose.tools.assert_almost_equal(p1[2, 1, 1], 0.3)
def u_exact(self,t): """ Routine to compute the exact solution at time t Args: t: current time Returns: exact solution """ w = df.Expression('r*(1-pow(tanh(r*((0.75-4) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25-4))),2)) - \ r*(1-pow(tanh(r*((0.75-3) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25-3))),2)) - \ r*(1-pow(tanh(r*((0.75-2) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25-2))),2)) - \ r*(1-pow(tanh(r*((0.75-1) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25-1))),2)) - \ r*(1-pow(tanh(r*((0.75-0) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25-0))),2)) - \ r*(1-pow(tanh(r*((0.75+1) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25+1))),2)) - \ r*(1-pow(tanh(r*((0.75+2) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25+2))),2)) - \ r*(1-pow(tanh(r*((0.75+3) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25+3))),2)) - \ r*(1-pow(tanh(r*((0.75+4) - x[1])),2)) + r*(1-pow(tanh(r*(x[1] - (0.25+4))),2)) - \ d*2*a*cos(2*a*(x[0]+0.25))',d=self.delta,r=self.rho,a=np.pi,degree=self.order) me = fenics_mesh(self.V) me.values = df.interpolate(w,self.V) # df.plot(me.values) # df.interactive() # exit() return me
def RunAcoustic(q): Nxy = 100 tf = 0.1 # Final time direction = 0 u0_expr = Expression("100*pow(x[i]-.25,2)*pow(x[i]-0.75,2)*(x[i]<=0.75)*(x[i]>=0.25)", i=direction) class LeftRight(SubDomain): def inside(self, x, on_boundary): return (x[direction] < 1e-16 or x[direction] > 1.0 - 1e-16) and on_boundary h = 1.0 / Nxy mesh = UnitSquareMesh(Nxy, Nxy, "crossed") V = FunctionSpace(mesh, "Lagrange", q) Vl = FunctionSpace(mesh, "Lagrange", 1) Dt = h / (q * 10.0) Wave = AcousticWave({"V": V, "Vl": Vl, "Vr": Vl}) Wave.verbose = True Wave.lump = True Wave.set_abc(mesh, LeftRight()) Wave.update( { "lambda": 1.0, "rho": 1.0, "t0": 0.0, "tf": tf, "Dt": Dt, "u0init": interpolate(u0_expr, V), "utinit": Function(V), } ) sol, tmp = Wave.solve()
def test_Probes_vectorfunctionspace_3D(VF3, dirpath): u0 = interpolate(Expression(('x[0]', 'x[1]', 'x[2]'), degree=1), VF3) x = array([[0.5, 0.5, 0.5], [0.4, 0.4, 0.4], [0.3, 0.3, 0.3]]) p = Probes(x.flatten(), VF3) # Probe twice p(u0) p(u0) # Check both snapshots p0 = p.array(N=0) if MPI.rank(MPI.comm_world) == 0: assert round(p0[0, 0] - 0.5, 7) == 0 assert round(p0[1, 1] - 0.4, 7) == 0 assert round(p0[2, 2] - 0.3, 7) == 0 p0 = p.array(N=1) if MPI.rank(MPI.comm_world) == 0: assert round(p0[0, 0] - 0.5, 7) == 0 assert round(p0[1, 1] - 0.4, 7) == 0 assert round(p0[2, 2] - 0.3, 7) == 0 p0 = p.array(filename=dirpath+'dumpvector3D') if MPI.rank(MPI.comm_world) == 0: assert round(p0[0, 0, 0] - 0.5, 7) == 0 assert round(p0[1, 1, 0] - 0.4, 7) == 0 assert round(p0[2, 1, 0] - 0.3, 7) == 0 p1 = load(dirpath+'dumpvector3D_all.npy') assert round(p1[0, 0, 0] - 0.5, 7) == 0 assert round(p1[1, 1, 0] - 0.4, 7) == 0 assert round(p1[2, 1, 1] - 0.3, 7) == 0
def test_Probes_vectorfunctionspace_2D(VF2, dirpath): u0 = interpolate(Expression(('x[0]', 'x[1]')), VF2) x = array([[0.5, 0.5], [0.4, 0.4], [0.3, 0.3]]) p = Probes(x.flatten(), VF2) # Probe twice p(u0) p(u0) # Check both snapshots p0 = p.array(N=0) if MPI.rank(mpi_comm_world()) == 0: assert round(p0[0, 0] - 0.5, 7) == 0 assert round(p0[1, 1] - 0.4, 7) == 0 assert round(p0[2, 1] - 0.3, 7) == 0 p0 = p.array(N=1) if MPI.rank(mpi_comm_world()) == 0: assert round(p0[0, 0] - 0.5, 7) == 0 assert round(p0[1, 0] - 0.4, 7) == 0 assert round(p0[2, 1] - 0.3, 7) == 0 p0 = p.array(filename=dirpath+'dumpvector2D') if MPI.rank(mpi_comm_world()) == 0: assert round(p0[0, 0, 0] - 0.5, 7) == 0 assert round(p0[1, 1, 1] - 0.4, 7) == 0 assert round(p0[2, 0, 1] - 0.3, 7) == 0 f = open(dirpath+'dumpvector2D_all.probes', 'r') p1 = load(f) assert round(p1[0, 0, 0] - 0.5, 7) == 0 assert round(p1[1, 1, 0] - 0.4, 7) == 0 assert round(p1[2, 1, 1] - 0.3, 7) == 0
def mplot_expression(ax, f, mesh, **kwargs): # TODO: Can probably avoid creating the function space here by # restructuring mplot_function a bit so it can handle Expression # natively V = create_cg1_function_space(mesh, f.ufl_shape) g = dolfin.interpolate(f, V) return mplot_function(ax, g, **kwargs)
def get_distance_function(config, domains): V = dolfin.FunctionSpace(config.domain.mesh, "CG", 1) v = dolfin.TestFunction(V) d = dolfin.TrialFunction(V) sol = dolfin.Function(V) s = dolfin.interpolate(Constant(1.0), V) domains_func = dolfin.Function(dolfin.FunctionSpace(config.domain.mesh, "DG", 0)) domains_func.vector().set_local(domains.array().astype(numpy.float)) def boundary(x): eps_x = config.params["turbine_x"] eps_y = config.params["turbine_y"] min_val = 1 for e_x, e_y in [(-eps_x, 0), (eps_x, 0), (0, -eps_y), (0, eps_y)]: try: min_val = min(min_val, domains_func((x[0] + e_x, x[1] + e_y))) except RuntimeError: pass return min_val == 1.0 bc = dolfin.DirichletBC(V, 0.0, boundary) # Solve the diffusion problem with a constant source term log(INFO, "Solving diffusion problem to identify feasible area ...") a = dolfin.inner(dolfin.grad(d), dolfin.grad(v)) * dolfin.dx L = dolfin.inner(s, v) * dolfin.dx dolfin.solve(a == L, sol, bc) return sol
def update_time(self, actual_time, step_number): super(Problem, self).update_time(actual_time, step_number) if self.actual_time > 0.5 and int(round(self.actual_time * 1000)) % 1000 == 0: self.isWholeSecond = True seconds = int(round(self.actual_time)) self.second_list.append(seconds) self.N1 = seconds*self.stepsInSecond self.N0 = (seconds-1)*self.stepsInSecond else: self.isWholeSecond = False self.solution = self.assemble_solution(self.actual_time) # Update boundary condition self.tc.start('updateBC') self.v_in.assign(self.solution) self.tc.end('updateBC') # construct analytic pressure (used for computing pressure and force errors) self.tc.start('analyticP') analytic_pressure = womersleyBC.analytic_pressure(self.factor, self.actual_time) self.sol_p = interpolate(analytic_pressure, self.pSpace) self.tc.end('analyticP') self.tc.start('analyticVnorms') self.analytic_v_norm_L2 = norm(self.solution, norm_type='L2') self.analytic_v_norm_H1 = norm(self.solution, norm_type='H1') self.analytic_v_norm_H1w = sqrt(assemble((inner(grad(self.solution), grad(self.solution)) + inner(self.solution, self.solution)) * self.dsWall)) self.listDict['av_norm_L2']['list'].append(self.analytic_v_norm_L2) self.listDict['av_norm_H1']['list'].append(self.analytic_v_norm_H1) self.listDict['av_norm_H1w']['list'].append(self.analytic_v_norm_H1w) self.tc.end('analyticVnorms')
def neumann_poisson_data(): ''' Return: a bilinear form in the neumann poisson problem L linear form in therein V function space, where a, L are defined bc homog. dirichlet conditions for case where we want pos. def problem z list of orthonormal vectors in the nullspace of A that form basis of ker(A) ''' mesh = UnitSquareMesh(40, 40) V = FunctionSpace(mesh, 'CG', 1) u = TrialFunction(V) v = TestFunction(V) f = Expression('x[0]+x[1]') a = inner(grad(u), grad(v))*dx L = inner(f, v)*dx bc = DirichletBC(V, Constant(0), DomainBoundary()) z0 = interpolate(Constant(1), V).vector() normalize(z0, 'l2') print '%16E' % z0.norm('l2') assert abs(z0.norm('l2')-1) < 1E-13 return a, L, V, bc, [z0]
def test_matrixization(): def mult_assemble(a, basis): return MultiplicationOperator(a(0), basis) mean_func = ConstFunction(2) a = [ConstFunction(3), ConstFunction(4)] rvs = [UniformRV(), NormalRV(mu=0.5)] coeff_field = ListCoefficientField(mean_func, a, rvs) A = MultiOperator(coeff_field, mult_assemble) mis = [Multiindex([0]), # Multiindex([1]), # Multiindex([0, 1]), Multiindex([0, 2])] mesh = UnitSquare(1, 1) fs = FunctionSpace(mesh, "CG", 2) F = [interpolate(Expression("*".join(["x[0]"] * i)), fs) for i in range(1, 5)] vecs = [FEniCSVector(f) for f in F] w = MultiVector() for mi, vec in zip(mis, vecs): w[mi] = vec P = w.to_euclidian_operator Q = w.from_euclidian_operator Pw = P.apply(w) assert type(Pw) == np.ndarray and len(Pw) == sum((v for v in w.dim.values())) QPw = Q.apply(Pw) assert w.active_indices() == QPw.active_indices() for mu in w.active_indices(): assert_equal(w[mu].array, QPw[mu].array) A_linear = P * A * Q A_mat = evaluate_operator_matrix(A_linear)
def les_setup(u_, mesh, KineticEnergySGS, assemble_matrix, CG1Function, nut_krylov_solver, bcs, **NS_namespace): """ Set up for solving the Kinetic Energy SGS-model. """ DG = FunctionSpace(mesh, "DG", 0) CG1 = FunctionSpace(mesh, "CG", 1) dim = mesh.geometry().dim() delta = Function(DG) delta.vector().zero() delta.vector().axpy(1.0, assemble(TestFunction(DG)*dx)) delta.vector().set_local(delta.vector().array()**(1./dim)) delta.vector().apply('insert') Ck = KineticEnergySGS["Ck"] ksgs = interpolate(Constant(1E-7), CG1) bc_ksgs = DirichletBC(CG1, 0, "on_boundary") A_mass = assemble_matrix(TrialFunction(CG1)*TestFunction(CG1)*dx) nut_form = Ck * delta * sqrt(ksgs) bcs_nut = derived_bcs(CG1, bcs['u0'], u_) nut_ = CG1Function(nut_form, mesh, method=nut_krylov_solver, bcs=bcs_nut, bounded=True, name="nut") At = Matrix() bt = Vector(nut_.vector()) ksgs_sol = KrylovSolver("bicgstab", "additive_schwarz") ksgs_sol.parameters["preconditioner"]["structure"] = "same_nonzero_pattern" ksgs_sol.parameters["error_on_nonconvergence"] = False ksgs_sol.parameters["monitor_convergence"] = False ksgs_sol.parameters["report"] = False del NS_namespace return locals()
def test_GaussDivergence(): mesh = UnitSquareMesh(4, 4) V = VectorFunctionSpace(mesh, 'CG', 1) u = interpolate(Expression(('x[0]', 'x[1]')), V) divu = gauss_divergence(u) DIVU = divu.vector().array() point_0 = all(abs(DIVU - 2.) < 1E-13) nose.tools.assert_equal(point_0, True) mesh = UnitCubeMesh(4, 4, 4) V = VectorFunctionSpace(mesh, 'CG', 1) u = interpolate(Expression(('2*x[0]', '2*x[1]', '2*x[2]')), V) divu = gauss_divergence(u) DIVU = divu.vector().array() point_0 = all(abs(DIVU - 6.) < 1E-13) nose.tools.assert_equal(point_0, True)
from dolfin import (Constant, DirichletBC, Function, FunctionSpace, Point, RectangleMesh, TestFunction, dx, grad, inner, interactive, near, plot, solve, assign, interpolate, Expression, dot) v = Constant((1.0, 0.0)) def left(x, on_boundary): return on_boundary and near(x[0], 0.0) mesh = RectangleMesh(Point(0.0, 0.0), Point(1.0, 1.0), 50, 50) dt = 0.001 S = FunctionSpace(mesh, 'CG', 1) T = Function(S) T0 = interpolate(Expression("1.0 / (10.0 * x[0] + 1.0)"), S) T_t = TestFunction(S) r = (T_t * ((T - T0) + dt * dot(v, grad(T)))) * dx bc1 = DirichletBC(S, 1.0, left) t = 0.0 while t <= 1.0: solve(r == 0, T, [bc1]) assign(T0, T) plot(T, mesh) t += dt
from dolfin import UnitSquareMesh, Expression, FunctionSpace, interpolate, File from dolfin import XDMFFile, inner, grad, dx, assemble from interpreter import Eval # Build a monomial basis for x, y, x**2, xy, y**2, ... try: from pydmd import DMD # https://github.com/mathLab/PyDMD except ImportError: from xcalc.dmdbase import DMD deg = 4 mesh = UnitSquareMesh(3, 3) V = FunctionSpace(mesh, 'CG', 1) f = interpolate(Expression('x[0]+x[1]', degree=1), V).vector().get_local() A = np.diag(np.random.rand(V.dim())) basis = [] for i in range(deg): for j in range(deg): f = A.dot(f) Af = Function(V); Af.vector().set_local(f) basis.append(Af) # NOTE: skipping 1 bacause Eval of it is not a Function dmd_ = DMD(svd_rank=-1, exact=False) energy, pod_basis = dmd(basis[1:], dmd_) print np.linalg.norm(dmd_.snapshots - dmd_.reconstructed_data.real) print len(pod_basis), len(basis[1:])
def initial_phasefield(Lx, R, eps, function_space): expr_str = "-2.*((-tanh((x[0]-(2+2*R))/(sqrt(2)*eps))+tanh((x[0]-(Lx-2*R-2))/(sqrt(2)*eps))) +0.5) " #expr_str = "+tanh((x[0]-(2+2*R))/(sqrt(2)*eps))" phi_init_expr = df.Expression(expr_str, Lx=Lx, R=R, eps=eps, degree=2) phi_init = df.interpolate(phi_init_expr, function_space.collapse()) return phi_init
def test_interpolation_jit_rank1(W): f = Expression(("1.0", "1.0", "1.0"), degree=0) w = interpolate(f, W) x = w.vector() assert abs(x.get_local()).max() == 1 assert abs(x.get_local()).min() == 1
double R = sqrt(pow(x[0],2)+pow(x[1],2)); double phi = atan2(x[1],x[0]); double d_0 = C_9 + C_2*cyl_bessel_k(0, R*lambda_2/tau) + C_8*cyl_bessel_i(0, R*lambda_2/tau); double d = - (10*A_1 * pow(R,2))/(27*tau) + (4*C_4*R)/(tau) - (2*C_5*tau)/R + C_14*cyl_bessel_k(1, R*lambda_2/tau) + C_15* cyl_bessel_i(1, R*lambda_2/tau); values[0] = d_0 + cos(phi) * d; } // The data stored in mesh functions double R; }; PYBIND11_MODULE(SIGNATURE, m) { py::class_<Pressure, std::shared_ptr<Pressure>, dolfin::Expression> (m, "Pressure") .def(py::init<>()); } """ c = df.CompiledExpression(df.compile_cpp_code(p_code).Pressure(), degree=1) print(2 * c([1, 1])) p_i = df.interpolate(c, V) df.plot(p_i) file = df.File("out.pvd") file.write(p_i)
def value_shape(self): return () class InitialData(UserExpression): def eval(self, value, x): value[0] = stats.uniform.pdf(x[0], 0, 1) \ + (1 + math.sin(40 * x[0] + math.cos(40 * x[0]))) / 10 def value_shape(self): return () f0 = DoubleHat(degree=1) # f0 = InitialData(degree=1) f0 = interpolate(f0, V) # Compute transport f = transport1d(v, np.zeros_like(v), f0.vector().get_local()) # Normalise to [0, 1]. f = np.array(f, dtype=float) f = (f - f.min()) / (f.max() - f.min()) # Add some noise. # f = f + 0.05 * np.random.randn(m + 1, n) # Check continuity equation for rho. def flux(v, f): return f * v
def set_D_with_protein(setup): meshp = setup.geo.mesh # mesh WITH protein x0 = np.array(setup.geop.x0) dim = setup.phys.dim x0 = x0 if dim == 3 else x0[::2] r0 = setup.geop.rMolecule rion = 0.11 # load diffusivity on mesh without protein functions, mesh = fields.get_functions(**setup.solverp.diffusivity_data) dist = functions["dist"] D0 = functions["D"] # evaluate dist, D on meshp nodes Vp = dolfin.FunctionSpace(meshp, "CG", 1) VVp = dolfin.VectorFunctionSpace(meshp, "CG", 1) distp_ = dolfin.interpolate(dist, Vp) D0p_ = dolfin.interpolate(D0, VVp) distp = distp_.vector()[dolfin.vertex_to_dof_map(Vp)] D0p = D0p_.vector()[dolfin.vertex_to_dof_map(VVp)] D0p = np.column_stack([D0p[i::dim] for i in range(dim)]) x = meshp.coordinates() # probes = Probes(x.flatten(), V) # probes(dist) # distp = probes.array(0) # # probes_ = Probes(x.flatten(), VV) # probes_(D0) # D0p = probes_.array(0) # first create (N,3,3) array from D0 (N,3) N = len(D0p) Da = np.zeros((N, dim, dim)) i3 = np.array(range(dim)) Da[:, i3, i3] = D0p # modify (N,3,3) array to include protein interaction R = x - x0 r = np.sqrt(np.sum(R**2, 1)) overlap = r < rion + r0 near = ~overlap & (r - r0 < distp) h = np.maximum(r[near] - r0, rion) eps = 1e-2 D00 = setup.phys.D Dt = np.zeros_like(r) Dn = np.zeros_like(r) Dt[overlap] = eps Dn[overlap] = eps Dt[near] = diff.Dt_plane(h, rion) Dn[near] = diff.Dn_plane(h, rion, N=20) # D(R) = Dn(h) RR^T + Dt(h) (I - RR^T) where R is normalized R0 = R / (r[:, None] + 1e-100) RR = (R0[:, :, None] * R0[:, None, :]) I = np.zeros((N, dim, dim)) I[:, i3, i3] = 1. Dpp = Dn[:, None, None] * RR + Dt[:, None, None] * (I - RR) Da[overlap | near] = D00 * Dpp[overlap | near] # assign final result to dolfin P1 TensorFunction VVV = dolfin.TensorFunctionSpace(meshp, "CG", 1, shape=(dim, dim)) D = dolfin.Function(VVV) v2d = dolfin.vertex_to_dof_map(VVV) Dv = D.vector() for k, (i, j) in enumerate(product(i3, i3)): Dv[np.ascontiguousarray(v2d[k::dim**2])] = np.ascontiguousarray(Da[:, i, j]) setup.phys.update(Dp=D, Dm=D) #embed() return D
def generate_initial_condition(mesh, county_geom, total_pop, infected_cases, recovered_cases, deceased_cases, infected_total_state, deceased_state, save_path='./', transmit_rate=1.16, date=None, FE_polynomial=1, save_numpy=True, save_vtu=True): # Define function space and all functions Vu = dl.FunctionSpace(mesh, "Lagrange", FE_polynomial) u = [dl.Function(Vu) for i in range(5)] # Determine the day index based on the given date if date is None: day_index = 0 else: validate_date(date) d0 = datetime.strptime("2020-03-06", "%Y-%m-%d") d1 = datetime.strptime(date, "%Y-%m-%d") day_index = abs((d1 - d0)).days # Determine the infected and deseased data on the given date infected_pop = infected_cases[day_index, :] deceased_pop = deceased_cases[day_index, :] recovered_pop = recovered_cases[day_index, :] active_infected_pop = infected_pop - deceased_pop - recovered_pop susceptible_pop = total_pop - transmit_rate * active_infected_pop - deceased_pop - recovered_pop - active_infected_pop # Interpolate initial conditions of the deceased/recovered/infected density based on the total cases deceased_pop_ic = seird_ic(county_geom, deceased_pop) u[DE] = dl.interpolate(deceased_pop_ic, Vu) recovered_pop_ic = seird_ic(county_geom, recovered_pop) u[RE] = dl.interpolate(recovered_pop_ic, Vu) active_infected_pop_ic = seird_ic(county_geom, active_infected_pop) u[IN] = dl.interpolate(active_infected_pop_ic, Vu) exposed_pop_ic = seird_ic(county_geom, transmit_rate * active_infected_pop) u[EX] = dl.interpolate(exposed_pop_ic, Vu) susceptible_pop_ic = seird_ic(county_geom, susceptible_pop) u[SU] = dl.interpolate(susceptible_pop_ic, Vu) r1 = deceased_state[day_index] / (10000 * dl.assemble(u[DE] * dl.dx)) print(r1) u[DE] = dl.project(r1 * u[DE], Vu) r2 = (infected_total_state[day_index] - deceased_state[day_index]) / (10000 * dl.assemble( (u[IN] + u[RE]) * dl.dx)) print(r2) u[IN] = dl.project(r2 * u[IN], Vu) u[RE] = dl.project(r2 * u[RE], Vu) names = ["susceptible", "exposed", "infected", "recovered", "deceased"] for i in range(5): print(names[i] + ": ", dl.assemble(10000 * u[i] * dl.dx)) if save_numpy: for i in range(5): np.save(save_path + names[i] + '_ic.npy', u[i].vector().get_local()) if save_vtu: for i in range(5): file = dl.File(save_path + names[i] + '_ic.pvd', "compressed") file << u[i]
c0 = 0.0 # Create mesh and function spaces. m, n = 40, 100 mesh = UnitSquareMesh(m - 1, n - 1) V = dh.create_function_space(mesh, 'default') W = dh.create_function_space(mesh, 'periodic') # Run experiments with decaying data. f = f_decay(degree=2) ft = f_decay_t(degree=1) fx = f_decay_x(degree=1) datastr = DecayingData().string() # Interpolate function. fa = interpolate(f, V) fa = dh.funvec2img(fa.vector().get_local(), m, n) fa_pb = interpolate(f, W) fa_pb = dh.funvec2img_pb(fa_pb.vector().get_local(), m, n) v, res, fun = cm1d_exp_pb(m, n, f, ft, fx, alpha0, alpha1) saveresults(resultpath, 'decay_cm1d_l2h1_exp_pb', 'l2h1', fa_pb, v) v, k, res, fun, converged = cmscr1d_exp_pb(m, n, f, ft, fx, alpha0, alpha1, alpha2, alpha3, beta) saveresults(resultpath, 'decay_cmscr1d_l2h1h1cr_exp_pb', 'l2h1h1cr', fa_pb, v, k, (c0 - fa_pb) / tau) # The next example shows that for the initial concentration used in the
saveresults(resultpath, 'analytic_example_decay_cmscr1d_l2h1h1cr_img', 'l2h1h1cr', f, v, k, (c0 - f) / tau) v, k, res, fun, converged = cmscr1d_img_pb(f, alpha0, alpha1, alpha2, alpha3, beta, 'mesh') saveresults(resultpath, 'analytic_example_decay_cmscr1d_l2h1h1cr_img_pb', 'l2h1h1cr', f, v, k, (c0 - f) / tau) # Run experiments with constant data. f = f_const(degree=2) ft = f_const_t(degree=1) fx = f_const_x(degree=1) datastr = ConstantData().string() # Interpolate function. fa = interpolate(f, V) fa = dh.funvec2img(fa.vector().get_local(), m, n) fa_pb = interpolate(f, W) fa_pb = dh.funvec2img_pb(fa_pb.vector().get_local(), m, n) v, res, fun = of1d_exp(m, n, f, ft, fx, alpha0, alpha1) saveresults(resultpath, 'analytic_example_const_of1d_l2h1_exp', 'l2h1', fa, v) v, res, fun = of1d_exp_pb(m, n, f, ft, fx, alpha0, alpha1) saveresults(resultpath, 'analytic_example_const_of1d_l2h1_exp_pb', 'l2h1', fa_pb, v) v, res, fun = cm1d_exp(m, n, f, ft, fx, alpha0, alpha1) saveresults(resultpath, 'analytic_example_const_cm1d_l2h1_exp', 'l2h1', fa, v)
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) cg = normalizedcrossgradient(VV, {'eps': 0.0}) a = dl.interpolate(dl.Expression('x[0]*x[0]', degree=10), V) b = dl.interpolate(dl.Expression('x[1]*x[1]', degree=10), V)
def __init__(self, Vh, gamma, delta, Theta=None, mean=None, rel_tol=1e-12, max_iter=1000): """ Construct the Prior model. Input: - Vh: the finite element space for the parameter - gamma and delta: the coefficient in the PDE - Theta: the s.p.d. tensor for anisotropic diffusion of the pde - mean: the prior mean """ assert delta != 0., "Intrinsic Gaussian Prior are not supported" self.Vh = Vh trial = dl.TrialFunction(Vh) test = dl.TestFunction(Vh) if Theta == None: varfL = dl.inner(dl.nabla_grad(trial), dl.nabla_grad(test)) * dl.dx else: varfL = dl.inner(Theta * dl.grad(trial), dl.grad(test)) * dl.dx varfM = dl.inner(trial, test) * dl.dx self.M = dl.assemble(varfM) self.Msolver = dl.PETScKrylovSolver("cg", "jacobi") self.Msolver.set_operator(self.M) self.Msolver.parameters["maximum_iterations"] = max_iter self.Msolver.parameters["relative_tolerance"] = rel_tol self.Msolver.parameters["error_on_nonconvergence"] = True self.Msolver.parameters["nonzero_initial_guess"] = False self.A = dl.assemble(gamma * varfL + delta * varfM) self.Asolver = dl.PETScKrylovSolver("cg", amg_method()) self.Asolver.set_operator(self.A) self.Asolver.parameters["maximum_iterations"] = max_iter self.Asolver.parameters["relative_tolerance"] = rel_tol self.Asolver.parameters["error_on_nonconvergence"] = True self.Asolver.parameters["nonzero_initial_guess"] = False old_qr = dl.parameters["form_compiler"]["quadrature_degree"] dl.parameters["form_compiler"]["quadrature_degree"] = -1 qdegree = 2 * Vh._ufl_element.degree() metadata = {"quadrature_degree": qdegree} if dlversion() >= (2017, 1, 0): representation_old = dl.parameters["form_compiler"][ "representation"] dl.parameters["form_compiler"]["representation"] = "quadrature" if dlversion() <= (1, 6, 0): Qh = dl.FunctionSpace(Vh.mesh(), 'Quadrature', qdegree) else: element = dl.FiniteElement("Quadrature", Vh.mesh().ufl_cell(), qdegree, quad_scheme="default") Qh = dl.FunctionSpace(Vh.mesh(), element) ph = dl.TrialFunction(Qh) qh = dl.TestFunction(Qh) Mqh = dl.assemble(ph * qh * dl.dx(metadata=metadata)) ones = dl.interpolate(dl.Constant(1.), Qh).vector() dMqh = Mqh * ones Mqh.zero() dMqh.set_local(ones.array() / np.sqrt(dMqh.array())) Mqh.set_diagonal(dMqh) MixedM = dl.assemble(ph * test * dl.dx(metadata=metadata)) self.sqrtM = MatMatMult(MixedM, Mqh) dl.parameters["form_compiler"]["quadrature_degree"] = old_qr if dlversion() >= (2017, 1, 0): dl.parameters["form_compiler"][ "representation"] = representation_old self.R = _BilaplacianR(self.A, self.Msolver) self.Rsolver = _BilaplacianRsolver(self.Asolver, self.M) self.mean = mean if self.mean is None: self.mean = dl.Vector() self.init_vector(self.mean, 0)
def test_interpolation_jit_rank0(V): f = Expression("1.0", degree=0) w = interpolate(f, V) x = w.vector() assert MPI.max(MPI.comm_world, abs(x.get_local()).max()) == 1 assert MPI.min(MPI.comm_world, abs(x.get_local()).min()) == 1
def __init__(self, Vh, gamma, delta, locations, m_true, Theta=None, pen=1e1, order=2, rel_tol=1e-12, max_iter=1000): """ Construct the Prior model. Input: - Vh: the finite element space for the parameter - gamma and delta: the coefficient in the PDE - locations: the points x_i at which we assume to know the true value of the parameter - m_true: the true model - Theta: the s.p.d. tensor for anisotropic diffusion of the pde - pen: a penalization parameter for the mollifier """ assert delta != 0. or pen != 0, "Intrinsic Gaussian Prior are not supported" self.Vh = Vh trial = dl.TrialFunction(Vh) test = dl.TestFunction(Vh) if Theta == None: varfL = dl.inner(dl.nabla_grad(trial), dl.nabla_grad(test)) * dl.dx else: varfL = dl.inner(Theta * dl.grad(trial), dl.grad(test)) * dl.dx varfM = dl.inner(trial, test) * dl.dx self.M = dl.assemble(varfM) self.Msolver = dl.PETScKrylovSolver("cg", "jacobi") self.Msolver.set_operator(self.M) self.Msolver.parameters["maximum_iterations"] = max_iter self.Msolver.parameters["relative_tolerance"] = rel_tol self.Msolver.parameters["error_on_nonconvergence"] = True self.Msolver.parameters["nonzero_initial_guess"] = False #mfun = Mollifier(gamma/delta, dl.inv(Theta), order, locations) mfun = dl.Expression(code_Mollifier, degree=Vh.ufl_element().degree() + 2) mfun.l = gamma / delta mfun.o = order mfun.theta0 = 1. / Theta.theta0 mfun.theta1 = 1. / Theta.theta1 mfun.alpha = Theta.alpha for ii in range(locations.shape[0]): mfun.addLocation(locations[ii, 0], locations[ii, 1]) varfmo = mfun * dl.inner(trial, test) * dl.dx MO = dl.assemble(pen * varfmo) self.A = dl.assemble(gamma * varfL + delta * varfM + pen * varfmo) self.Asolver = dl.PETScKrylovSolver("cg", amg_method()) self.Asolver.set_operator(self.A) self.Asolver.parameters["maximum_iterations"] = max_iter self.Asolver.parameters["relative_tolerance"] = rel_tol self.Asolver.parameters["error_on_nonconvergence"] = True self.Asolver.parameters["nonzero_initial_guess"] = False old_qr = dl.parameters["form_compiler"]["quadrature_degree"] dl.parameters["form_compiler"]["quadrature_degree"] = -1 qdegree = 2 * Vh._ufl_element.degree() metadata = {"quadrature_degree": qdegree} if dlversion() >= (2017, 1, 0): representation_old = dl.parameters["form_compiler"][ "representation"] dl.parameters["form_compiler"]["representation"] = "quadrature" if dlversion() <= (1, 6, 0): Qh = dl.FunctionSpace(Vh.mesh(), 'Quadrature', qdegree) else: element = dl.FiniteElement("Quadrature", Vh.mesh().ufl_cell(), qdegree, quad_scheme="default") Qh = dl.FunctionSpace(Vh.mesh(), element) ph = dl.TrialFunction(Qh) qh = dl.TestFunction(Qh) Mqh = dl.assemble(ph * qh * dl.dx(metadata=metadata)) ones = dl.interpolate(dl.Constant(1.), Qh).vector() dMqh = Mqh * ones Mqh.zero() dMqh.set_local(ones.array() / np.sqrt(dMqh.array())) Mqh.set_diagonal(dMqh) MixedM = dl.assemble(ph * test * dl.dx(metadata=metadata)) self.sqrtM = MatMatMult(MixedM, Mqh) dl.parameters["form_compiler"]["quadrature_degree"] = old_qr if dlversion() >= (2017, 1, 0): dl.parameters["form_compiler"][ "representation"] = representation_old self.R = _BilaplacianR(self.A, self.Msolver) self.Rsolver = _BilaplacianRsolver(self.Asolver, self.M) rhs = dl.Vector() self.mean = dl.Vector() self.init_vector(rhs, 0) self.init_vector(self.mean, 0) MO.mult(m_true, rhs) self.Asolver.solve(self.mean, rhs)
def mplot_expression(ax, f, mesh, **kwargs): # TODO: Can probably avoid creating the function space here by restructuring # mplot_function a bit so it can handle Expression natively V = create_cg1_function_space(mesh, f.ufl_shape) g = dolfin.interpolate(f, V) return mplot_function(ax, g, **kwargs)
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))
def mplot_function(ax, f, **kwargs): mesh = f.function_space().mesh() gdim = mesh.geometry().dim() tdim = mesh.topology().dim() # Extract the function vector in a way that also works for # subfunctions try: fvec = f.vector() except RuntimeError: fspace = f.function_space() try: fspace = fspace.collapse() except RuntimeError: return fvec = dolfin.interpolate(f, fspace).vector() if fvec.size() == mesh.num_cells(): # DG0 cellwise function C = fvec.get_local( ) # NB! Assuming here dof ordering matching cell numbering if gdim == 2 and tdim == 2: return ax.tripcolor(mesh2triang(mesh), C, **kwargs) elif gdim == 3 and tdim == 2: # surface in 3d # FIXME: Not tested, probably broken xy = mesh.coordinates() shade = kwargs.pop("shade", True) return ax.plot_trisurf(mesh2triang(mesh), xy[:, 2], C, shade=shade, **kwargs) elif gdim == 1 and tdim == 1: x = mesh.coordinates()[:, 0] nv = len(x) # Insert duplicate points to get piecewise constant plot xp = np.zeros(2 * nv - 2) xp[0] = x[0] xp[-1] = x[-1] xp[1:2 * nv - 3:2] = x[1:-1] xp[2:2 * nv - 2:2] = x[1:-1] Cp = np.zeros(len(xp)) Cp[0:len(Cp) - 1:2] = C Cp[1:len(Cp):2] = C return ax.plot(xp, Cp, *kwargs) # elif tdim == 1: # FIXME: Plot embedded line else: raise AttributeError( 'Matplotlib plotting backend only supports 2D mesh for scalar functions.' ) elif f.value_rank() == 0: # Scalar function, interpolated to vertices # TODO: Handle DG1? C = f.compute_vertex_values(mesh) if gdim == 2 and tdim == 2: mode = kwargs.pop("mode", "contourf") if mode == "contourf": levels = kwargs.pop("levels", 40) return ax.tricontourf(mesh2triang(mesh), C, levels, **kwargs) elif mode == "color": shading = kwargs.pop("shading", "gouraud") return ax.tripcolor(mesh2triang(mesh), C, shading=shading, **kwargs) elif mode == "warp": from matplotlib import cm cmap = kwargs.pop("cmap", cm.jet) linewidths = kwargs.pop("linewidths", 0) return ax.plot_trisurf(mesh2triang(mesh), C, cmap=cmap, linewidths=linewidths, **kwargs) elif mode == "wireframe": return ax.triplot(mesh2triang(mesh), **kwargs) elif mode == "contour": return ax.tricontour(mesh2triang(mesh), C, **kwargs) elif gdim == 3 and tdim == 2: # surface in 3d # FIXME: Not tested from matplotlib import cm cmap = kwargs.pop("cmap", cm.jet) return ax.plot_trisurf(mesh2triang(mesh), C, cmap=cmap, **kwargs) elif gdim == 3 and tdim == 3: # Volume # TODO: Isosurfaces? # Vertex point cloud X = [mesh.coordinates()[:, i] for i in range(gdim)] return ax.scatter(*X, c=C, **kwargs) elif gdim == 1 and tdim == 1: x = mesh.coordinates()[:, 0] ax.set_aspect('auto') p = ax.plot(x, C, **kwargs) # Setting limits for Line2D objects # Must be done after generating plot to avoid ignoring function # range if no vmin/vmax are supplied vmin = kwargs.pop("vmin", None) vmax = kwargs.pop("vmax", None) ax.set_ylim([vmin, vmax]) return p # elif tdim == 1: # FIXME: Plot embedded line else: raise AttributeError( 'Matplotlib plotting backend only supports 2D mesh for scalar functions.' ) elif f.value_rank() == 1: # Vector function, interpolated to vertices w0 = f.compute_vertex_values(mesh) nv = mesh.num_vertices() if len(w0) != gdim * nv: raise AttributeError( 'Vector length must match geometric dimension.') X = mesh.coordinates() X = [X[:, i] for i in range(gdim)] U = [w0[i * nv:(i + 1) * nv] for i in range(gdim)] # Compute magnitude C = U[0]**2 for i in range(1, gdim): C += U[i]**2 C = np.sqrt(C) mode = kwargs.pop("mode", "glyphs") if mode == "glyphs": args = X + U + [C] if gdim == 3: length = kwargs.pop("length", 0.1) return ax.quiver(*args, length=length, **kwargs) else: return ax.quiver(*args, **kwargs) elif mode == "displacement": Xdef = [X[i] + U[i] for i in range(gdim)] import matplotlib.tri as tri if gdim == 2 and tdim == 2: # FIXME: Not tested triang = tri.Triangulation(Xdef[0], Xdef[1], mesh.cells()) shading = kwargs.pop("shading", "flat") return ax.tripcolor(triang, C, shading=shading, **kwargs) else: # Return gracefully to make regression test pass without vtk cpp.warning('Matplotlib plotting backend does not support ' 'displacement for %d in %d. Continuing without ' 'plotting...' % (tdim, gdim)) return
#mesh = dl.UnitSquareMesh(nx, ny) nx = 100 ny = 20 mesh = dl.RectangleMesh(dl.Point(0, 0),dl.Point(8,0.5),nx,ny, "right") rank = dl.MPI.rank(mesh.mpi_comm()) nproc = dl.MPI.size(mesh.mpi_comm()) Vh2 = dl.VectorFunctionSpace(mesh, 'Lagrange', 1) Vh1 = dl.FunctionSpace(mesh, 'Lagrange', 1) Vh = [Vh2, Vh1, Vh2] prior = BiLaplacianPrior(Vh[PARAMETER], gamma=4e-1, delta=1e-1) model = Elasticity(mesh, Vh, prior) m0 = dl.interpolate(dl.Expression("x[0] + 2.2", element=Vh[PARAMETER].ufl_element()), Vh[PARAMETER]) modelVerify(model, m0.vector(), is_quadratic = False, verbose = (rank==0)) m0 = dl.interpolate(dl.Constant(1.0),Vh[PARAMETER]) parameters = ReducedSpaceNewtonCG_ParameterList() parameters["rel_tolerance"] = 1e-12 parameters["abs_tolerance"] = 1e-12 parameters["max_iter"] = 50 parameters["globalization"] = "LS" parameters["GN_iter"] = 6 if rank != 0: parameters["print_level"] = -1 solver = ReducedSpaceNewtonCG(model, parameters)
exit() def load_force_field(): forces, mesh, meta = nanopores.load_vector_functions(FNAME) #mesh = forces["F"].function_space().mesh() return forces["F"], forces["Fel"], forces["Fdrag"], mesh F, Fel, Fdrag, mesh = load_force_field() geo, phys = Howorka.setup2D(mesh=mesh, z0=None, **PARAMS) submesh = geo.submesh("fluid") mesh = submesh geo, phys = Howorka.setup2D(mesh=mesh, z0=None, **PARAMS) V = dolfin.FunctionSpace(mesh, "CG", 1) VV = dolfin.VectorFunctionSpace(mesh, "CG", 1) F = dolfin.interpolate(F, VV) Fel = dolfin.interpolate(Fel, VV) Fdrag = dolfin.interpolate(Fdrag, VV) v2d = dolfin.vertex_to_dof_map(V) coord = mesh.coordinates() # numpy array of 2-1 arrays def function_from_values(values): u = dolfin.Function(V) u.vector()[v2d] = numpy.array(values) return u def function_from_lambda(f): values = [f(x) for x in coord] return function_from_values(values) N = 10. # number of molecules to diffuse
def __init__(self, Vh_STATE, Vhs, bcs0, datafile, dx=dl.dx): self.dx = dx x, y, U, V, uu, vv, ww, uv, k = np.loadtxt(datafile, skiprows=2, unpack=True) u_fun_mean = VelocityDNS(x=x, y=y, U=U, V=V, symmetrize=True, coflow=0.) u_fun_data = VelocityDNS(x=x, y=y, U=U, V=V, symmetrize=False, coflow=0.) u_mean = dl.interpolate(u_fun_mean, Vhs[0]) u_data = dl.interpolate(u_fun_data, Vhs[0]) q_order = dl.parameters["form_compiler"]["quadrature_degree"] dl.parameters["form_compiler"]["quadrature_degree"] = 6 noise_var_u = dl.assemble( dl.inner(u_fun_data - u_mean, u_fun_data - u_mean) * self.dx, form_compiler_parameters=dl.parameters["form_compiler"]) dl.parameters["form_compiler"]["quadrature_degree"] = q_order noise_var_u = 1.e-3 mpi_comm = Vh_STATE.mesh().mpi_comm() rank = dl.MPI.rank(mpi_comm) if rank == 0: print "Noise Variance = {0}".format(noise_var_u) if Vh_STATE.num_sub_spaces() == 2: u_trial, p_trial = dl.TrialFunctions(Vh_STATE) u_test, p_test = dl.TestFunctions(Vh_STATE) elif Vh_STATE.num_sub_spaces() == 3: u_trial, p_trial, g_trial = dl.TrialFunctions(Vh_STATE) u_test, p_test, g_test = dl.TestFunctions(Vh_STATE) else: raise InputError() Wform = dl.Constant(1. / noise_var_u) * dl.inner(u_trial, u_test) * self.dx self.W = dl.assemble(Wform) dummy = dl.Vector() self.W.init_vector(dummy, 0) [bc.zero(self.W) for bc in bcs0] Wt = Transpose(self.W) [bc.zero(Wt) for bc in bcs0] self.W = Transpose(Wt) xfun = dl.Function(Vh_STATE) assigner = dl.FunctionAssigner(Vh_STATE, Vhs) if Vh_STATE.num_sub_spaces() == 2: assigner.assign(xfun, [u_data, dl.Function(Vhs[1])]) elif Vh_STATE.num_sub_spaces() == 3: assigner.assign( xfun, [u_data, dl.Function(Vhs[1]), dl.Function(Vhs[2])]) self.d = xfun.vector()
geo = head.getCollection() geo.add(face) geo.add(nose, add_boundaries=False) geo.add(eyes, add_boundaries=False) geo.generateMesh(0.2) geo.writeMesh('face') filea = io.H5File('face', 'r') print('a cell attributes:', filea.cell_attributes) print('a facet attributes:', filea.facet_attributes) domains = filea.read_attribute('domains') boundaries = filea.read_attribute('boundaries') space = dolfin.FunctionSpace(filea.mesh, 'CG', 1) functiona = dolfin.interpolate(dolfin.Expression('x[0]', degree=1), space) functionb = dolfin.interpolate(dolfin.Expression('x[0]*x[1]', degree=1), space) vspace = dolfin.VectorFunctionSpace(filea.mesh, 'CG', 1) vfunctiona = dolfin.interpolate(dolfin.Expression(('x[0]', '0'), degree=1), vspace) vfunctionb = dolfin.interpolate(dolfin.Expression(('x[1]', '-x[0]'), degree=1), vspace) filea.close() fileb = io.H5File('face_copy', 'w') fileb.set_mesh(filea.mesh) fileb.add_attribute(domains, 'domains_copy') fileb.add_attribute(boundaries, 'boundaries_copy') fileb.add_function_group([functiona, functionb], 'scalars', scale_to_one=True) fileb.add_function_group([vfunctiona, vfunctionb], 'vectors') print('b cell attributes:', fileb.cell_attributes)
def main(): parser = argparse.ArgumentParser(description="Average various files") parser.add_argument("-l", "--list", nargs="+", help="List of folders", required=True) parser.add_argument("-f", "--fields", nargs="+", default=None, help="Sought fields") parser.add_argument("-t", "--time", type=float, default=0, help="Time") parser.add_argument("--show", action="store_true", help="Show") parser.add_argument("-R", "--radius", type=float, default=None, help="Radial distance") args = parser.parse_args() tss = [] for folder in args.list: ts = InterpolatedTimeSeries(folder, sought_fields=args.fields) tss.append(ts) Ntss = len(tss) all_fields_ = [] for ts in tss: all_fields_.append(set(ts.fields)) all_fields = list(set.intersection(*all_fields_)) if args.fields is None: fields = all_fields else: fields = list(set.intersection(set(args.fields), set(all_fields))) f_in = [] for ts in tss: f_in.append(ts.functions()) # Using the first timeseries to define the spaces # Could be redone to e.g. a finer, structured mesh. # ref_mesh = tss[0].mesh ref_spaces = dict([(field, f.function_space()) for field, f in f_in[0].items()]) if "psi" not in fields: exit("No psi") var_names = ["t", "s"] index_names = ["tt", "st", "ss"] index_numbers = [0, 1, 4] dim_names = ["x", "y", "z"] # Loading geometry rad_t = [] rad_s = [] g_ab = [] gab = [] for ts in tss: # Should compute these from the curvature tensor rad_t.append( df.interpolate(df.Expression("x[0]", degree=2), ts.function_space)) rad_s.append( df.interpolate(df.Expression("x[1]", degree=2), ts.function_space)) # g_loc = [ts.function(name) for name in ["gtt", "gst", "gss"]] # g_inv_loc = [ts.function(name) for name in ["g_tt", "g_st", "g_ss"]] gab_loc = dict([(idx, ts.function("g{}".format(idx))) for idx in index_names]) g_ab_loc = dict([(idx, ts.function("g_{}".format(idx))) for idx in index_names]) for idx, ij in zip(index_names, index_numbers): # for ij in range(3): # ts.set_val(g_loc[ij], ts.g[:, ij]) # ts.set_val(g_inv_loc[ij], ts.g_inv[:, ij]) ts.set_val(g_ab_loc[idx], ts.g_ab[:, ij]) # Could compute the gab locally instead of loading ts.set_val(gab_loc[idx], ts.gab[:, ij]) g_ab_loc["ts"] = g_ab_loc["st"] gab_loc["ts"] = gab_loc["st"] g_ab.append(g_ab_loc) gab.append(gab_loc) costheta = df.Function(ref_spaces["psi"], name="costheta") for its, (ts, g_ab_loc, gab_loc) in enumerate(zip(tss, g_ab, gab)): if args.time is not None: step, time = get_step_and_info(ts, args.time) g_ab_ = to_vector(g_ab_loc) gab_ = to_vector(gab_loc) ts.update(f_in[its]["psi"], "psi", step) psi = f_in[its]["psi"] psi_t = df.project(psi.dx(0), ts.function_space) psi_s = df.project(psi.dx(1), ts.function_space) gp_t = psi_t.vector().get_local() gp_s = psi_s.vector().get_local() # gtt, gst, gss = [g_ij.vector().get_local() for g_ij in g[its]] # g_tt, g_st, g_ss = [g_ij.vector().get_local() for g_ij in g_inv[its]] gtt = gab_["tt"] gst = gab_["ts"] gss = gab_["ss"] g_tt = g_ab_["tt"] g_st = g_ab_["ts"] g_ss = g_ab_["ss"] rht = rad_t[its].vector().get_local() rhs = rad_s[its].vector().get_local() rh_norm = np.sqrt(g_tt * rht**2 + g_ss * rhs**2 + 2 * g_st * rht * rhs) gp_norm = np.sqrt(gtt * gp_t**2 + gss * gp_s**2 + 2 * gst * gp_t * gp_s) costheta_loc = ts.function("costheta") # abs(cos(theta)): costheta_loc.vector()[:] = abs( (rht * gp_t + rhs * gp_s) / (rh_norm * gp_norm + 1e-8)) # cos(theta)**2: #costheta_loc.vector()[:] = ((rht*gp_t + rhs*gp_s)/(rh_norm*gp_norm+1e-8))**2 # sin(theta): #costheta_loc.vector()[:] = np.sin(np.arccos((rht*gp_t + rhs*gp_s)/(rh_norm*gp_norm+1e-8))) # sin(theta)**2: # costheta_loc.vector()[:] = np.sin(np.arccos((rht*gp_t + rhs*gp_s)/(rh_norm*gp_norm+1e-8)))**2 # abs(theta): #costheta_loc.vector()[:] = abs(np.arccos((rht*gp_t + rhs*gp_s)/(rh_norm*gp_norm+1e-8))) costheta_intp = interpolate_nonmatching_mesh(costheta_loc, ref_spaces["psi"]) costheta.vector()[:] += costheta_intp.vector().get_local() / Ntss dump_xdmf(costheta) if args.show: JET = plt.get_cmap('jet') RYB = plt.get_cmap('RdYlBu') RYB_r = plt.get_cmap('RdYlBu_r') mgm = plt.get_cmap('magma') fig, ax = plt.subplots() fig.set_size_inches(4.7, 4.7) rc('text', usetex=True) rc('font', **{'family': 'serif', 'serif': ['Palatino']}) # First, dump a hires PNG version of the data: plot = df.plot(costheta, cmap=mgm) plt.axis('off') plt.savefig('anglogram_hires.png', format="png", bbox_inches='tight', pad_inches=0, dpi=500) mainfs = 10 # Fontsize titlefs = 12 # Fontsize #plt.set_cmap('jet') #cbar = fig.colorbar(plot, ticks=[0, 0.5, 1], orientation='vertical') #cbar.ax.set_yticklabels(['Radial', 'Intermediate', 'Azimuthal']) #cbar = fig.colorbar(plot, ticks=[0, 0.5, 0.95], orientation='horizontal', fraction=0.046, pad=0.04) #cbar = fig.colorbar(plot, ticks=[0, 0.5, 0.995], orientation='horizontal', fraction=0.046, pad=0.04) cbar = fig.colorbar(plot, ticks=[0, 0.5, 0.9995], orientation='horizontal', fraction=0.046, pad=0.04) cbar.ax.set_xticklabels(['Radial', 'Intermediate', 'Azimuthal']) #ax.set_title('Stripe orientation -- $\\cos^2(\\theta)$', fontsize=mainfs) #ax.set_title(r'Stripe orientation -- $\cos^2(\theta)$') plt.text(0.5, 1.05, r'Stripe orientation -- $\left\vert\cos(\theta)\right\vert$', fontsize=titlefs, horizontalalignment='center', transform=ax.transAxes) #ax.set_title('Stripe orientation', fontsize=mainfs) #plt.text(0.2, 0.2, '$\\textcolor{red}{\\mathbf{p}(u,w,\\xi)}=\\textcolor{blue}{\\tilde{\\mathbf{p}}(u,w)} + \\xi \\tilde{\\mathbf{n}}(u,w)$', fontsize=mainfs) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) #plt.show() plt.savefig('anglogram.pdf', format="pdf", bbox_inches='tight', pad_inches=0) #plt.axis('on') #ax.get_xaxis().set_visible(True) #ax.get_yaxis().set_visible(True) #plt.colorbar(plot) #plt.show() if args.radius is not None and args.radius > 0: Nr, Nphi = 256, 256 r_lin = np.linspace(0., args.radius, Nr) phi_lin = np.linspace(0, 2 * np.pi, Nphi, endpoint=False) R, Phi = np.meshgrid(r_lin, phi_lin) r = R.reshape((Nr * Nphi, 1)) phi = Phi.reshape((Nr * Nphi, 1)) xy = np.hstack((r * np.cos(phi), r * np.sin(phi))) pts = xy.flatten() probes = Probes(pts, ref_spaces["psi"]) probes(costheta) ct = probes.array() CT = ct.reshape(R.shape) g_r = CT.mean(axis=0) g_phi = CT.mean(axis=1) plt.figure() plt.plot(r_lin, g_r) plt.ylabel("g(r)") plt.xlabel("r") plt.figure() plt.plot(phi_lin, g_phi) plt.xlabel("phi") plt.ylabel("g(phi)") plt.show()
def interpolate(self, f): ''' Interpolate other ii_Function/ntuple of interpolable things into self. ''' assert len(self) == len(f) [fi.assign(df.interpolate(f, fi.function_space())) for fi in self]
def __init__(self, fileName, timeEnd, timeStep, average=False): fc.set_log_active(False) self.times = [] self.BB = [] self.HH = [] self.TD = [] self.TB = [] self.TX = [] self.TY = [] self.TZ = [] self.us = [] self.ub = [] ########################################################## ################ MESH ################# ########################################################## # TODO: Probably do not have to save then open mesh self.mesh = df.Mesh() self.inFile = fc.HDF5File(self.mesh.mpi_comm(), fileName, "r") self.inFile.read(self.mesh, "/mesh", False) ######################################################### ################# FUNCTION SPACES ##################### ######################################################### self.E_Q = df.FiniteElement("CG", self.mesh.ufl_cell(), 1) self.Q = df.FunctionSpace(self.mesh, self.E_Q) self.E_V = df.MixedElement(self.E_Q, self.E_Q, self.E_Q) self.V = df.FunctionSpace(self.mesh, self.E_V) self.assigner_inv = fc.FunctionAssigner([self.Q, self.Q, self.Q], self.V) self.assigner = fc.FunctionAssigner(self.V, [self.Q, self.Q, self.Q]) self.U = df.Function(self.V) self.dU = df.TrialFunction(self.V) self.Phi = df.TestFunction(self.V) self.u, self.u2, self.H = df.split(self.U) self.phi, self.phi1, self.xsi = df.split(self.Phi) self.un = df.Function(self.Q) self.u2n = df.Function(self.Q) self.zero_sol = df.Function(self.Q) self.Bhat = df.Function(self.Q) self.H0 = df.Function(self.Q) self.A = df.Function(self.Q) if average: self.inFile.read(self.Bhat.vector(), "/bedAvg", True) self.inFile.read(self.A.vector(), "/smbAvg", True) self.inFile.read(self.H0.vector(), "/thicknessAvg", True) else: self.inFile.read(self.Bhat.vector(), "/bed", True) self.inFile.read(self.A.vector(), "/smb", True) self.inFile.read(self.H0.vector(), "/thickness", True) self.Hmid = theta * self.H + (1 - theta) * self.H0 self.B = softplus(self.Bhat, -rho / rho_w * self.Hmid, alpha=0.2) # Is not the bed, it is the lower surface self.S = self.B + self.Hmid self.width = df.interpolate(Width(degree=2), self.Q) self.strs = Stresses(self.U, self.Hmid, self.H0, self.H, self.width, self.B, self.S, self.Phi) self.R = -(self.strs.tau_xx + self.strs.tau_xz + self.strs.tau_b + self.strs.tau_d + self.strs.tau_xy) * df.dx ############################################################################# ######################## MASS CONSERVATION ################################ ############################################################################# self.h = df.CellSize(self.mesh) self.D = self.h * abs(self.U[0]) / 2. self.area = self.Hmid * self.width self.mesh_min = self.mesh.coordinates().min() self.mesh_max = self.mesh.coordinates().max() # Define boundaries self.ocean = df.FacetFunctionSizet(self.mesh, 0) self.ds = fc.ds(subdomain_data=self.ocean) # THIS DS IS FROM FENICS! border integral for f in df.facets(self.mesh): if df.near(f.midpoint().x(), self.mesh_max): self.ocean[f] = 1 if df.near(f.midpoint().x(), self.mesh_min): self.ocean[f] = 2 self.R += ((self.H - self.H0) / dt * self.xsi \ - self.xsi.dx(0) * self.U[0] * self.Hmid \ + self.D * self.xsi.dx(0) * self.Hmid.dx(0) \ - (self.A - self.U[0] * self.H / self.width * self.width.dx(0)) \ * self.xsi) * df.dx + self.U[0] * self.area * self.xsi * self.ds(1) \ - self.U[0] * self.area * self.xsi * self.ds(0) ##################################################################### ######################### SOLVER SETUP ########################### ##################################################################### # Bounds self.l_thick_bound = df.project(Constant(thklim), self.Q) self.u_thick_bound = df.project(Constant(1e4), self.Q) self.l_v_bound = df.project(-10000.0, self.Q) self.u_v_bound = df.project(10000.0, self.Q) self.l_bound = df.Function(self.V) self.u_bound = df.Function(self.V) self.assigner.assign(self.l_bound, [self.l_v_bound] * 2 + [self.l_thick_bound]) self.assigner.assign(self.u_bound, [self.u_v_bound] * 2 + [self.u_thick_bound]) # This should set the velocity at the divide (left) to zero self.dbc0 = df.DirichletBC(self.V.sub(0), 0, lambda x, o: df.near(x[0], self.mesh_min) and o) # Set the velocity on the right terminus to zero self.dbc1 = df.DirichletBC(self.V.sub(0), 0, lambda x, o: df.near(x[0], self.mesh_max) and o) # overkill? self.dbc2 = df.DirichletBC(self.V.sub(1), 0, lambda x, o: df.near(x[0], self.mesh_max) and o) # set the thickness on the right edge to thklim self.dbc3 = df.DirichletBC(self.V.sub(2), thklim, lambda x, o: df.near(x[0], self.mesh_max) and o) # Define variational solver for the mass-momentum coupled problem self.J = df.derivative(self.R, self.U, self.dU) self.coupled_problem = df.NonlinearVariationalProblem(self.R, self.U, bcs=[self.dbc0, self.dbc1, self.dbc3], \ J=self.J) self.coupled_problem.set_bounds(self.l_bound, self.u_bound) self.coupled_solver = df.NonlinearVariationalSolver(self.coupled_problem) # Acquire the optimizations in fenics_optimizations set_solver_options(self.coupled_solver) self.t = 0 self.timeEnd = float(timeEnd) self.dtFloat = float(timeStep) self.inFile.close()
def method(ts, time=None, step=0, show=False, save_fig=False, **kwargs): """ Compare to analytic reference expression at given timestep. This is done by importing the function "reference" in the problem module. """ info_cyan("Comparing to analytic reference at given time or step.") step, time = get_step_and_info(ts, time, step) parameters = ts.get_parameters(time=time) problem = parameters.get("problem", "intrusion_bulk") try: module = importlib.import_module("problems.{}".format(problem)) reference = module.reference except: info_error("No analytic reference available.") ref_exprs = reference(t=time, **parameters) info("Comparing to analytic solution.") info_split("Problem:", "{}".format(problem)) info_split("Time:", "{}".format(time)) f = ts.functions(ref_exprs.keys()) err = dict() f_int = dict() f_ref = dict() for field in ref_exprs.keys(): el = f[field].function_space().ufl_element() degree = el.degree() if bool(el.value_size() != 1): W = df.VectorFunctionSpace(ts.mesh, "CG", degree + 3) else: W = df.FunctionSpace(ts.mesh, "CG", degree + 3) err[field] = df.Function(W) f_int[field] = df.Function(W) f_ref[field] = df.Function(W) for field, ref_expr in ref_exprs.items(): ref_expr.t = time # Update numerical solution f ts.update(f[field], field, step) # Interpolate f to higher space f_int[field].assign( df.interpolate(f[field], f_int[field].function_space())) # Interpolate f_ref to higher space f_ref[field].assign( df.interpolate(ref_expr, f_ref[field].function_space())) err[field].vector()[:] = (f_int[field].vector().get_local() - f_ref[field].vector().get_local()) if show or save_fig: # Interpolate the error to low order space for visualisation. err_int = df.interpolate(err[field], f[field].function_space()) err_arr = ts.nodal_values(err_int) label = "Error in " + field if rank == 0: save_fig_file = None if save_fig: save_fig_file = os.path.join( ts.plots_folder, "error_{}_time{}_analytic.png".format(field, time)) plot_any_field(ts.nodes, ts.elems, err_arr, save=save_fig_file, show=show, label=label) save_file = os.path.join(ts.analysis_folder, "errornorms_time{}_analytic.dat".format(time)) compute_norms(err, save=save_file)
rank = dl.MPI.rank(mesh.mpi_comm()) nproc = dl.MPI.size(mesh.mpi_comm()) if rank == 0: print( sep, "Set up the mesh and finite element spaces.\n","Compute wind velocity", sep ) Vh = dl.FunctionSpace(mesh, "Lagrange", 2) ndofs = Vh.dim() if rank == 0: print( "Number of dofs: {0}".format( ndofs ) ) if rank == 0: print( sep, "Set up Prior Information and model", sep ) ic_expr = dl.Expression('min(0.5,exp(-100*(pow(x[0]-0.35,2) + pow(x[1]-0.7,2))))', element=Vh.ufl_element()) true_initial_condition = dl.interpolate(ic_expr, Vh).vector() gamma = 1. delta = 8. prior = BiLaplacianPrior(Vh, gamma, delta, robin_bc=True) if rank == 0: print( "Prior regularization: (delta - gamma*Laplacian)^order: delta={0}, gamma={1}, order={2}".format(delta, gamma,2) ) prior.mean = dl.interpolate(dl.Constant(0.25), Vh).vector() t_init = 0. t_final = 4. t_1 = 1. dt = .1
expr_scalar = Expression("1+x[0]", degree=1) expr_vector = Expression(("1+x[0]", "x[1]-2"), degree=1) mesh = UnitSquareMesh(12,12) submesh = UnitSquareMesh(6,6) submesh.coordinates()[:] /= 2.0 submesh.coordinates()[:] += 0.2 Q = FunctionSpace(mesh, "CG", 1) V = VectorFunctionSpace(mesh, "CG", 1) Q_sub = FunctionSpace(submesh, "CG", 1) V_sub = VectorFunctionSpace(submesh, "CG", 1) u = interpolate(expr_scalar, Q) v = interpolate(expr_vector, V) u_sub = interpolate(expr_scalar, Q_sub) v_sub = interpolate(expr_vector, V_sub) from fenicstools import interpolate_nonmatching_mesh u_sub2 = interpolate_nonmatching_mesh(u, Q_sub) v_sub2 = interpolate_nonmatching_mesh(v, V_sub) print errornorm(u_sub, u_sub2) print errornorm(v_sub, v_sub2)
def test_interpolation_mismatch_rank1(W): f = Expression(("1.0", "1.0"), degree=0) with pytest.raises(RuntimeError): interpolate(f, W)
x = [utrue, mtrue, None] pde.solveFwd(x[STATE], x, 1e-9) misfit.B.mult(x[STATE], misfit.d) rel_noise = 0.01 MAX = misfit.d.norm("linf") noise_std_dev = rel_noise * MAX parRandom.normal_perturb(noise_std_dev, misfit.d) misfit.noise_variance = noise_std_dev * noise_std_dev model = Model(pde, prior, misfit) if rank == 0: print(sep, "Test the gradient and the Hessian of the model", sep) m0 = dl.interpolate( dl.Expression("sin(x[0])", element=Vh[PARAMETER].ufl_element()), Vh[PARAMETER]) modelVerify(model, m0.vector(), 1e-12, is_quadratic=False, verbose=(rank == 0)) if rank == 0: print(sep, "Find the MAP point", sep) m = prior.mean.copy() parameters = ReducedSpaceNewtonCG_ParameterList() parameters["rel_tolerance"] = 1e-9 parameters["abs_tolerance"] = 1e-12 parameters["max_iter"] = 25 parameters["inner_rel_tolerance"] = 1e-15
d = 4 # FE order # Get mesh and function space (CG or DG) mesh = df.UnitIntervalMesh(N) V = df.FunctionSpace(mesh, "CG", d) # V = df.FunctionSpace(mesh, "DG", d) # Build mass matrix u = df.TrialFunction(V) v = df.TestFunction(V) a_M = u * v * df.dx M = df.assemble(a_M) # Create vector with sine function u0 = df.Expression('sin(k*pi*x[0])', pi=np.pi, k=k, degree=d) w = df.interpolate(u0, V) # Apply mass matrix to this vector Mw = df.Function(V) M.mult(w.vector(), Mw.vector()) # Do FFT to get the frequencies fw = np.fft.fft(w.vector()[:]) fMw = np.fft.fft(Mw.vector()[:]) # Shift to have zero frequency in the middle of the plot fw2 = np.fft.fftshift(fw) fMw2 = np.fft.fftshift(fMw) fw2 /= np.amax(abs(fw2)) fMw2 /= np.amax(abs(fMw2))