from fenics import AutoSubDomain, DOLFIN_EPS, FunctionSpace, Mesh, \ set_log_active, FacetFunction, Constant, \ VectorFunctionSpace, MPI, mpi_comm_world import sys import numpy as np import time as timer from fenicstools import Probes # Local import from stress_tensor import * from common import * from weak_form import * # Set output from FEniCS set_log_active(False) # Set ut problem mesh = Mesh( path.join(rel_path, "mesh", "von_karman_street_FSI_structure_refine2.xml")) # Function space V = VectorFunctionSpace(mesh, "CG", 2) VV = V * V # Get the point [0.2,0.6] at the end of bar for coord in mesh.coordinates(): if coord[0] == 0.6 and (0.2 - DOLFIN_EPS <= coord[1] <= 0.2 + DOLFIN_EPS): #print coord break BarLeftSide = AutoSubDomain(lambda x: "on_boundary" and \
from varglas.data.data_factory import DataFactory from varglas.mesh.mesh_factory import MeshFactory from varglas.utilities import DataInput from varglas.model import Model from varglas.solvers import SteadySolver, TransientSolver from varglas.physical_constants import IceParameters from varglas.helper import default_nonlin_solver_params from fenics import set_log_active, parameters set_log_active(True) thklim = 50.0 vara = DataFactory.get_searise(thklim=thklim) mesh = MeshFactory.get_greenland_coarse() dsr = DataInput(vara, mesh=mesh) S = dsr.get_spline_expression('S') B = dsr.get_spline_expression('B') SMB = dsr.get_spline_expression('adot') T_s = dsr.get_spline_expression('T') q_geo = dsr.get_spline_expression('q_geo') U_ob = dsr.get_spline_expression('U_ob') Tn = vara['Tn']['map_data'] # create the model : model = Model() model.set_mesh(mesh) model.set_geometry(S, B, deform=True) model.set_parameters(IceParameters())
def solve_linear_pde( u_D_array, T, D=1, C1=0, num_r=100, min_r=0.001, tol=1e-14, degree=1, ): # disable logging set_log_active(False) num_t = len(u_D_array) dt = T / num_t # time step size mesh = IntervalMesh(num_r, min_r, 1) r = mesh.coordinates().flatten() r_args = np.argsort(r) V = FunctionSpace(mesh, "P", 1) # Define boundary conditions # Dirichlet condition at R def boundary_at_R(x, on_boundary): return on_boundary and near(x[0], 1, tol) D = Constant(D) u_D = Constant(u_D_array[0]) bc_at_R = DirichletBC(V, u_D, boundary_at_R) # Define initial values for free c c_0 = Expression("C1", C1=C1, degree=degree) c_n = interpolate(c_0, V) # Define variational problem c = TrialFunction(V) v = TestFunction(V) # define Constants r_squ = Expression("4*pi*pow(x[0],2)", degree=degree) F_tmp = (D * dt * inner(grad(c), grad(v)) * r_squ * dx + c * v * r_squ * dx - c_n * v * r_squ * dx) a, L = lhs(F_tmp), rhs(F_tmp) u = Function(V) data_c = np.zeros((num_t, len(r)), dtype=np.double) for n in range(num_t): u_D.assign(u_D_array[n]) # Compute solution solve(a == L, u, bc_at_R) data_c[n, :] = u.vector().vec().array c_n.assign(u) data_c = data_c[:, r_args[::-1]] r = r[r_args] return data_c, r
from varglas.model import Model from varglas.solvers import SteadySolver from varglas.physical_constants import IceParameters from varglas.helper import default_nonlin_solver_params from fenics import set_log_active, File, Expression, pi, \ sin, tan set_log_active(True) alpha = 0.1 * pi / 180 L = 40000 nx = 40 ny = 40 nz = 10 model = Model() model.generate_uniform_mesh(nx, ny, nz, xmin=0, xmax=L, ymin=0, ymax=L, generate_pbcs=True) Surface = Expression('- x[0] * tan(alpha)', alpha=alpha, element=model.Q.ufl_element()) Bed = Expression('- x[0] * tan(alpha) - 1000.0', alpha=alpha, element=model.Q.ufl_element()) Beta2 = Expression( '1000 + 1000 * sin(2*pi*x[0]/L) * sin(2*pi*x[1]/L)', alpha=alpha, L=L, element=model.Q.ufl_element()) model.set_geometry(Surface, Bed, deform=True) model.set_parameters(IceParameters()) model.calculate_boundaries()
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()
rng = np.random.default_rng(args.seed) # Define variables to be traced def trace_func(state): u, v = state.pos[0], state.pos[1 : 1 + dim_z] σ = generate_σ(u) z = prior_covar_sqrt @ v x = solution_func(v) return {"σ": σ, "z_mean": z.mean(), "z_std": z.std(), "z": z, "x": x} # Disable fenics logging to prevent interference with progress meter display fenics.set_log_active(False) logging.getLogger("UFL").setLevel(logging.WARNING) logging.getLogger("FFC").setLevel(logging.WARNING) # Disable runtime warnings to prevent interference with progress meter display warnings.filterwarnings("ignore", category=RuntimeWarning) # Run experiment constrained_system_kwargs = pde.construct_constrained_system_kwargs( y_obs=data["y_obs"], forward_func=forward_func, jacob_forward_func=jacob_forward_func, mhp_forward_func=mhp_forward_func, dim_y=dim_y,
def pme(ts, output_times, x_bins, sigma, fenics_nx=101, fenics_ny=2, fenics_dt=0.05): ''' Here "output_times" are in real, forwards-time units. ''' width = ts.metadata['SLiM']['user_metadata']['WIDTH'][0] height = ts.metadata['SLiM']['user_metadata']['HEIGHT'][0] K = ts.metadata['SLiM']['user_metadata']['K'][0] theta = ts.metadata['SLiM']['user_metadata']['THETA'][0] slim_dt = ts.metadata['SLiM']['user_metadata']['DT'][0] step_ago = ts.metadata['SLiM']['generation'] - np.min(output_times) / slim_dt - 1 init_xy = np.array([ ts.individual(i).location[:2] for i in ts.individuals_alive_at(step_ago) ]) # Create mesh and define function space mesh = fenics.RectangleMesh( p0=fenics.Point(0, 0), p1=fenics.Point(width, height), nx=fenics_nx, ny=fenics_ny, ) V = fenics.FunctionSpace(mesh, 'P', 1) # Define initial value # Note that since out simulation is 1D, but the analytic solution is 2D, # to convert from the simulations' density-per-unit-x-area # to fenic's density-per-unit-xy-area we need to multiply the simulation # by 'height', which corresponds to placing height/K mass at each point. u_n = project_locations(init_xy, V, K/height) # Define variational problem u = fenics.Function(V) v = fenics.TestFunction(V) def get_F(u, v, dt): dx = fenics.dx F = (u * v * dx + dt * (sigma**2 / 2) * fenics.dot(fenics.grad(u**2), fenics.grad(v)) * dx - (1 / theta) * dt * u * (1 - u) * v * dx - u_n * v * dx ) return F def observed(u, x_bins): """ Note this is in units of (average per unit xy-area). """ out = np.zeros(len(x_bins) - 1) for j in range(len(x_bins) - 1): out[j] = mean_value(u, x_bins[j], x_bins[j+1], V) return out # too much output!!! fenics.set_log_active(False) output = np.empty((len(x_bins) - 1, len(output_times))) # Time-stepping t = np.min(output_times) for j, next_t in enumerate(output_times): t_diff = next_t - t if t_diff > 0: num_dt = int(np.ceil(t_diff / fenics_dt)) dt = t_diff / num_dt F = get_F(u, v, dt=dt) for _ in range(num_dt): # Compute solution fenics.solve(F == 0, u) # Update previous solution u_n.assign(u) output[:, j] = observed(u_n, x_bins) t = next_t return output