def test_functional3D(): """Test integration of function interpolated in non-matching meshes""" f = Quadratic3D() # Interpolate quadratic function on course mesh mesh0 = UnitCubeMesh(8, 8, 8) V0 = FunctionSpace(mesh0, "Lagrange", 2) u0 = interpolate_nonmatching_mesh(f, V0) # Interpolate FE function on finer mesh mesh1 = UnitCubeMesh(21, 21, 21) V1 = FunctionSpace(mesh1, "Lagrange", 2) u1 = interpolate_nonmatching_mesh(u0, V1) assert round(assemble(u0*dx) - assemble(u1*dx), 10) == 0 mesh1 = UnitCubeMesh(20, 20, 20) V1 = FunctionSpace(mesh1, "Lagrange", 2) u1 = interpolate_nonmatching_mesh(u0, V1) assert round(assemble(u0*dx) - assemble(u1*dx), 10) == 0 f = Expression(("x[0]*x[0] + x[1]*x[1]", "x[0]*x[0] + x[1]*x[1] + 1", "x[0]*x[0] + x[1]*x[1] + 2")) V0 = FunctionSpace(mesh0, "Nedelec 1st kind H(curl)", 2) u0 = interpolate(f, V0) # Interpolate FE function on finer mesh V1 = FunctionSpace(mesh1, "Nedelec 1st kind H(curl)", 2) u1 = interpolate_nonmatching_mesh_any(u0, V1) assert round(assemble(dot(u0, u0)*dx) - assemble(dot(u1, u1)*dx), 2) == 0
def main(): mesh = df.Mesh() h5f = df.HDF5File(mesh.mpi_comm(), "simple_duct.h5", "r") h5f.read(mesh, "mesh", False) V = df.VectorFunctionSpace(mesh, "CG", 1) P = df.FunctionSpace(mesh, "CG", 1) u_expr = df.Expression(("0.", "0.", expr_str(100)), degree=1) u = ft.interpolate_nonmatching_mesh(u_expr, V) u_avg = df.assemble(u.sub(2) * df.dx) / 40. u.vector()[:] /= u_avg xdmff = df.XDMFFile(mesh.mpi_comm(), "simple_duct_u0.xdmf") xdmff.parameters["rewrite_function_mesh"] = False xdmff.parameters["flush_output"] = True xdmff.write(u, float(0.)) p_expr = df.Expression("0.", degree=1) p = ft.interpolate_nonmatching_mesh(p_expr, P) xdmfp = df.XDMFFile(mesh.mpi_comm(), "simple_duct_p0.xdmf") xdmfp.parameters["rewrite_function_mesh"] = False xdmfp.parameters["flush_output"] = True xdmfp.write(p, float(0.)) df.plot(u.sub(2), interactive=True)
def test_functional3D(): """Test integration of function interpolated in non-matching meshes""" f = Quadratic3D(degree=2) # Interpolate quadratic function on course mesh mesh0 = UnitCubeMesh(8, 8, 8) V0 = FunctionSpace(mesh0, "Lagrange", 2) u0 = interpolate_nonmatching_mesh(f, V0) # Interpolate FE function on finer mesh mesh1 = UnitCubeMesh(21, 21, 21) V1 = FunctionSpace(mesh1, "Lagrange", 2) u1 = interpolate_nonmatching_mesh(u0, V1) assert round(assemble(u0 * dx) - assemble(u1 * dx), 10) == 0 mesh1 = UnitCubeMesh(20, 20, 20) V1 = FunctionSpace(mesh1, "Lagrange", 2) u1 = interpolate_nonmatching_mesh(u0, V1) assert round(assemble(u0 * dx) - assemble(u1 * dx), 10) == 0 f = Expression(("x[0]*x[0] + x[1]*x[1]", "x[0]*x[0] + x[1]*x[1] + 1", "x[0]*x[0] + x[1]*x[1] + 2"), degree=2) V0 = FunctionSpace(mesh0, "Nedelec 1st kind H(curl)", 2) u0 = interpolate(f, V0) # Interpolate FE function on finer mesh V1 = FunctionSpace(mesh1, "Nedelec 1st kind H(curl)", 2) u1 = interpolate_nonmatching_mesh_any(u0, V1) assert round(assemble(dot(u0, u0) * dx) - assemble(dot(u1, u1) * dx), 2) == 0
def main(): args = get_settings() interp = itp.Interpolation(args.mesh_file_in, args.u_file_in, p_filename_in=args.p_file_in) interp.update(args.step) u_1 = interp.u p_1 = interp.p mesh_2 = import_mesh(args.other_mesh_in) S_2 = df.FunctionSpace(mesh_2, "CG", 1) u_ = dict() for key, val in u_1.iteritems(): u_[key] = ft.interpolate_nonmatching_mesh(val, S_2) u__ = df.as_vector([u_[key] for key in u_.keys()]) u = AssignedVectorFunction(u__) u() p = ft.interpolate_nonmatching_mesh(p_1, S_2) xdmff_u = df.XDMFFile(mesh_2.mpi_comm(), args.initfile_out + "_u.xdmf") xdmff_u.parameters["rewrite_function_mesh"] = False xdmff_u.parameters["flush_output"] = True xdmff_u.write(u, 0.) xdmff_p = df.XDMFFile(mesh_2.mpi_comm(), args.initfile_out + "_p.xdmf") xdmff_p.parameters["rewrite_function_mesh"] = False xdmff_p.parameters["flush_output"] = True xdmff_p.write(p, 0.)
def translate_value(self, value, function_space=None): # for both internal and boundary values _degree = self.settings['fe_degree'] if function_space: W = function_space else: W = self.function_space if isinstance(value, (tuple, list, np.ndarray)): # json dump tuple into list if len(value) == self.dimension and isinstance( value[0], (numbers.Number)): if isinstance(value, list): value = tuple(value) values_0 = Constant(value) elif len(value) == self.dimension and isinstance(value[0], (str)): if isinstance(value, list): value = Constant(tuple(value)) values_0 = interpolate(Expression(value, degree=_degree), W) elif self.transient_settings['transient'] and len( value) > self.dimension: values_0 = value[self.current_step] else: print( ' {} is supplied, but only tuple of number and string expr of dim = len(v) are supported' .format(type(value))) elif isinstance(value, (numbers.Number)): values_0 = Constant(value) elif isinstance(value, (Constant, Function)): values_0 = value # leave it as it is, since they can be used in equation elif isinstance(value, (Expression, )): # FIXME can not interpolate an expression, not necessary? values_0 = value # interpolate(value, W) elif callable(value) and self.transient_settings[ 'transient']: # Function is also callable values_0 = value(self.get_current_time()) elif isinstance(value, (str, )): # file or string expression if os.path.exists(value): # also possible continue from existent solution, or interpolate from diff mesh density values_0 = Function(W) File(value) >> values_0 #project(velocity, self.vector_space) # FIXME: diff element degree is not tested import fenicstools values_0 = fenicstools.interpolate_nonmatching_mesh( values_0, W) else: # C++ expressing string values_0 = interpolate(Expression(value, degree=_degree), W) elif value == None: raise TypeError('None type is supplied as value to be translated') else: print( 'Warning: {} is supplied, not tuple, number, Constant,file name, Expression' .format(type(value))) values_0 = value return values_0
def test_functional2D(): """Test integration of function interpolated in non-matching meshes""" f = Quadratic2D(degree=2) # Interpolate quadratic function on course mesh mesh0 = UnitSquareMesh(8, 8) V0 = FunctionSpace(mesh0, "Lagrange", 2) u0 = interpolate_nonmatching_mesh(f, V0) # Interpolate FE function on finer mesh mesh1 = UnitSquareMesh(31, 31) V1 = FunctionSpace(mesh1, "Lagrange", 2) u1 = interpolate_nonmatching_mesh(u0, V1) assert round(assemble(u0*dx) - assemble(u1*dx), 10) == 0 mesh1 = UnitSquareMesh(30, 30) V1 = FunctionSpace(mesh1, "Lagrange", 2) u1 = interpolate_nonmatching_mesh(u0, V1) assert round(assemble(u0*dx) - assemble(u1*dx), 10) == 0 f = Expression(("x[0]*x[0] + x[1]*x[1]", "x[0]*x[0] + x[1]*x[1] + 1"), degree=2) V0 = FunctionSpace(mesh0, "Nedelec 1st kind H(curl)", 2) u0 = interpolate(f, V0) # Interpolate FE function on finer mesh V1 = FunctionSpace(mesh1, "Nedelec 1st kind H(curl)", 2) u1 = interpolate_nonmatching_mesh_any(u0, V1) assert round(assemble(dot(u0, u0)*dx) - assemble(dot(u1, u1)*dx), 4) == 0 # Test with another expression f = Expression(("2*(x[0]*x[0] + x[1]*x[1])", "2*(x[0]*x[0] + x[1]*x[1] + 1)"), degree=2) u0 = interpolate_nonmatching_mesh_any(f, V0) u1 = interpolate_nonmatching_mesh_any(u0, V1) assert round(assemble(dot(u0, u0)*dx) - assemble(dot(u1, u1)*dx), 4) == 0
def get_whole_function(V, mesh,u1,u2,domains): u2 = interpolate_nonmatching_mesh ( u2 , V) V_dofmap = V.dofmap() chi1 = Function(V) chi2 = Function(V) gamma_dofs = [] for cell in cells(mesh): # set the characteristic functions if domains[cell] == 1: chi1.vector()[V_dofmap.cell_dofs(cell.index())] = 1 gamma_dofs.extend(V_dofmap.cell_dofs(cell.index())) else: chi2.vector()[V_dofmap.cell_dofs(cell.index())]=1 gamma_dofs = list(set(gamma_dofs)) u2.vector()[gamma_dofs] = 0 u_0 = project(chi1*u1, V) u_0 += project(chi2*u2, V) return u_0
from dolfin import * from fenicstools import interpolate_nonmatching_mesh # Test for nonmatching mesh and FunctionSpace mesh = UnitCubeMesh(16, 16, 16) mesh2 = UnitCubeMesh(32, 32, 32) V = FunctionSpace(mesh, 'CG', 1) V2 = FunctionSpace(mesh2, 'CG', 1) # Just create some random data to be used for probing x0 = interpolate(Expression('x[0]'), V) u = interpolate_nonmatching_mesh(x0, V2) VV = VectorFunctionSpace(mesh, 'CG', 1) VV2 = VectorFunctionSpace(mesh2, 'CG', 1) v0 = interpolate(Expression(('x[0]', '2*x[1]', '3*x[2]')), VV) v = interpolate_nonmatching_mesh(v0, VV2) plot(u) plot(v) interactive()
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()
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 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("--hist", action="store_true", help="Histogram") parser.add_argument("--num_points", type=int, default=10000, help="Number of points") 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") # Loading geometry g_ab = [] gab = [] K_ab = [] xyz_a = [] var_names = ["t", "s"] index_names = ["tt", "st", "ss"] index_numbers = [0, 1, 4] indices = zip(index_names, index_numbers) dim_names = ["x", "y", "z"] for ts in tss: 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]) K_ab_loc = dict([(idx, ts.function("K_{}".format(idx))) for idx in index_names]) xyz_a_loc = dict([(xi + "" + idx, ts.function("{}{}".format(xi, idx))) for xi, idx in product(dim_names, var_names)]) for idx, ij in indices: 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]) ts.set_val(K_ab_loc[idx], ts.K_ab[:, ij]) # for ij, (idx, xi) in enumerate(product(var_names, dim_names)): # ts.set_val(xyz_a_loc[xi + "" + idx], ts.xyz_a[:, ij]) for (d, xi), (i, idx) in product(enumerate(dim_names), enumerate(var_names)): ts.set_val(xyz_a_loc[xi + "" + idx], ts.xyz_a[i][:, d]) g_ab_loc["ts"] = g_ab_loc["st"] gab_loc["ts"] = gab_loc["st"] K_ab_loc["ts"] = K_ab_loc["st"] g_ab.append(g_ab_loc) gab.append(gab_loc) K_ab.append(K_ab_loc) xyz_a.append(xyz_a_loc) v_ = [] for g_ab_loc, gab_loc, K_ab_loc, xyz_a_loc, ts in zip( g_ab, gab, K_ab, xyz_a, tss): g_ab_ = to_vector(g_ab_loc) gab_ = to_vector(gab_loc) K_ab_ = to_vector(K_ab_loc) xyz_a_ = to_vector(xyz_a_loc) Ka_b_ = dict() Ka_b_loc = dict() for i in var_names: for j in var_names: Ka_b_[i + j] = sum( [gab_[i + k] * K_ab_[k + j] for k in var_names]) Ka_b_loc[i + j] = ts.function("K{}_{}".format(i, j)) Ka_b_loc[i + j].vector()[:] = Ka_b_[i + j] kappa1 = ts.function("kappa1") kappa2 = ts.function("kappa2") v1 = dict([(i, ts.function("v1{}".format(i))) for i in var_names]) v2 = dict([(i, ts.function("v2{}".format(i))) for i in var_names]) kappa1_ = kappa1.vector().get_local() kappa2_ = kappa2.vector().get_local() v1_ = dict([(i, vi.vector().get_local()) for i, vi in v1.items()]) v2_ = dict([(i, vi.vector().get_local()) for i, vi in v2.items()]) for idof in range(len(kappa1_)): M = np.array([[Ka_b_["tt"][idof], Ka_b_["ts"][idof]], [Ka_b_["st"][idof], Ka_b_["ss"][idof]]]) kappas, vs = eig_sorted(M) assert (abs(kappas[0]) >= abs(kappas[1])) kappa1_[idof] = kappas[0] kappa2_[idof] = kappas[1] for ind, i in enumerate(var_names): v1_[i][idof] = vs[ind, 0] v2_[i][idof] = vs[ind, 1] kappa1.vector()[:] = kappa1_ kappa2.vector()[:] = kappa2_ for i in var_names: v1[i].vector()[:] = v1_[i] v2[i].vector()[:] = v2_[i] v_.append(v1_) v1_out = NdFunction([v1["t"], v1["s"]], name="v1") v1_out() dump_xdmf(v1_out) v2_out = NdFunction([v2["t"], v2["s"]], name="v2") v2_out() dump_xdmf(v2_out) kappa = NdFunction([kappa1, kappa2], name="kappa") kappa() dump_xdmf(kappa, folder=ts.geometry_folder) tau1_vec = [ ts.function("tau1_{}".format(dim_names[i])) for i in range(3) ] tau2_vec = [ ts.function("tau2_{}".format(dim_names[i])) for i in range(3) ] tau1_norm_ = np.sqrt( sum([ g_ab_[i + j] * v1_[i] * v1_[j] for i, j in product(var_names, var_names) ])) tau2_norm_ = np.sqrt( sum([ g_ab_[i + j] * v2_[i] * v2_[j] for i, j in product(var_names, var_names) ])) for d, xi in enumerate(dim_names): tau1_vec[d].vector()[:] = sum( [xyz_a_[xi + j] * v1_[j] for j in var_names]) / tau1_norm_ tau2_vec[d].vector()[:] = sum( [xyz_a_[xi + j] * v2_[j] for j in var_names]) / tau2_norm_ tau1 = NdFunction(tau1_vec, name="tau1") tau2 = NdFunction(tau2_vec, name="tau2") tau1() tau2() dump_xdmf(tau1, folder=ts.geometry_folder) dump_xdmf(tau2, folder=ts.geometry_folder) sqrt_g = df.Function(ref_spaces["psi"], name="sqrt_g") costheta = df.Function(ref_spaces["psi"], name="costheta") for its, ts in enumerate(tss): if args.time is not None: step, time = get_step_and_info(ts, args.time) ts.update(f_in[its]["psi"], "psi", step) psi = f_in[its]["psi"] dpsi_a = dict() dpsi_a_ = dict() for ind, i in enumerate(var_names): dpsi_a[i] = df.project(psi.dx(ind), ts.function_space) dpsi_a_[i] = dpsi_a[i].vector().get_local() gab_ = to_vector(gab[its]) g_ab_ = to_vector(g_ab[its]) dpsi_norm_ = np.sqrt( sum([ gab_[i + j] * dpsi_a_[i] * dpsi_a_[j] for i, j in product(var_names, var_names) ])) v1a_ = v_[its] v1_norm_ = np.sqrt( sum([ g_ab_[i + j] * v1a_[i] * v1a_[j] for i, j in product(var_names, var_names) ])) v1_dot_dpsi_ = sum([v1a_[i] * dpsi_a_[i] for i in var_names]) costheta_loc = ts.function("costheta") costheta_loc.vector()[:] = abs(v1_dot_dpsi_ / (v1_norm_ * dpsi_norm_ + 1e-8)) sqrt_g_loc = ts.function("sqrt_g") sqrt_g_loc.vector()[:] = np.sqrt(g_ab_["tt"] * g_ab_["ss"] - g_ab_["ts"] * g_ab_["st"]) dump_xdmf(costheta_loc, folder=ts.geometry_folder) costheta_intp = interpolate_nonmatching_mesh(costheta_loc, ref_spaces["psi"]) costheta.vector()[:] += costheta_intp.vector().get_local() / Ntss sqrt_g_intp = interpolate_nonmatching_mesh(sqrt_g_loc, ref_spaces["psi"]) sqrt_g.vector()[:] += sqrt_g_intp.vector().get_local() / Ntss dump_xdmf(costheta) p_cell = np.zeros((ref_spaces["psi"].mesh().num_cells())) x_cell = np.zeros((ref_spaces["psi"].mesh().num_cells(), 6)) for i, ic in enumerate(df.cells(ref_spaces["psi"].mesh())): x_cell[i, :] = np.array(ic.get_coordinate_dofs()) p_cell[i] = sqrt_g(ic.midpoint()) * ic.volume() p_cell /= p_cell.sum() x_pts = pick_random_points(p_cell, x_cell, args.num_points) if args.show: plt.figure() fig = df.plot(costheta) plt.scatter(x_pts[:, 0], x_pts[:, 1], s=0.2, color='k') plt.colorbar(fig) plt.title("cos(theta)") plt.show() if args.hist: probes = MyProbes(x_pts) probes(costheta) ct = probes.array()[0] theta = np.arccos(ct) plt.figure() plt.hist(theta, bins=100, density=True) plt.xlabel("theta") plt.ylabel("P(theta)") plt.show()
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") 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") # Loading geometry rad_t = [] rad_s = [] g = [] g_inv = [] 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"]] for ij in range(3): ts.set_val(g_loc[ij], ts.g[:, ij]) # Could compute the following locally instead of loading ts.set_val(g_inv_loc[ij], ts.g_inv[:, ij]) g.append(g_loc) g_inv.append(g_inv_loc) costheta = df.Function(ref_spaces["psi"], name="costheta") # Number of nodes: arrsiz = int(len(costheta.vector().get_local())) # Array to hold costheta^2 values for all runs: costhetas = np.zeros([arrsiz,Ntss]) # Number of random samples to perform per simulation nsamples=1000 # Array for randomly sampled costheta^2 values: costhetasamp=np.zeros([nsamples,Ntss]) #xmin= for its, ts in enumerate(tss): if args.time is not None: step, time = get_step_and_info(ts, args.time) 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]] 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 = df.Function(ts.function_space) costheta_loc.vector()[:] = abs(gp_t/(gp_norm+1e-8))**2 costheta_intp = interpolate_nonmatching_mesh(costheta_loc, ref_spaces["psi"]) costheta.vector()[:] += costheta_intp.vector().get_local()/Ntss costhetas[:, its] = costheta_intp.vector().get_local() # print(costheta(df.Point(0,0))) t_coords = df.interpolate(df.Expression("x[0]", degree=2), ts.function_space) s_coords = df.interpolate(df.Expression("x[1]", degree=2), ts.function_space) t_min = min(t_coords.vector()) t_max = max(t_coords.vector()) s_min = min(s_coords.vector()) s_max = max(s_coords.vector()) for k in range(0,nsamples-1): Pt = t_min+(t_max-t_min)*random.random() Ps = s_min+(s_max-s_min)*random.random() P = df.Point(Pt,Ps) costhetasamp[k,its] = costheta_loc(P) dump_xdmf(costheta) if args.show: #fig = df.plot(costheta) #plt.colorbar(fig) rc('text', usetex=True) plt.hist(costhetas,bins=20,density=True,stacked=True) #plt.hist(costhetasamp,bins=10,density=True,stacked=True) ax = plt.gca() #ax.set_aspect(0.7) ax.set_xlabel('$\\cos^2(\\theta)$') ax.set_ylabel('Relative frequency') plt.show()
def value_shape(self): return (2,) def mixinglayermesh(L=3, H=12, Nx=40, Ny=40): mesh = RectangleMesh(-L, 0, L, H, Nx, Ny) x = mesh.coordinates() x[:, 0] = sign(x[:, 0]) * (1. - cos(pi * x[:, 0] / L / 2.)) * L return mesh # Set up problem with mesh and function spaces mesh = mixinglayermesh(Nx=40, Ny=40) V = FunctionSpace(mesh, 'CG', 1) FM = MixedFunctionSpace([V, V]) # fmean, variance fm = TrialFunction(FM) fm_v = TestFunction(FM) f0 = interpolate_nonmatching_mesh(Finit(), FM) fm_ = f0.copy(True) x = Vector(f0.vector()) # Dirichlet boundary condition on inlet bc = DirichletBC(FM, f0, "on_boundary && x[1] < 10 * DOLFIN_EPS") # Normalized velocity U0 = Constant((0., 10.)) # Normalized mixing frequency (Need this to be zero at x[1] = 0 to be consistent with eq-solution. If flamelet solution is used as Dirichlet on inlet it can be nonzero.) #itau = Constant(10.) itau_e = Expression("1. * (1. - exp(-5. * x[1] * x[1] * x[1]))") itau = interpolate(itau_e, V) # Variational form for first two integer moments of mixture fraction
sk=0.05) params = dict(meshParams=meshParams, chemistryParams=chemistryParams) chemistry = InhibitorChemistry() meshGenerator = GemmaMeshGenerator() model0 = NotchGrowth(meshGenerator, chemistry, params=params) simulator0 = Simulator(model0, outputDir=sys.path[0]) simulator0.run(float(sys.argv[1]), int(sys.argv[2])) # Cut and wait cutMeshParams = dict(mesh=model0.mesh, width=0.8, notches=[], fileName='cutMesh.xml') params = dict(meshParams=cutMeshParams, chemistryParams=chemistryParams) meshGenerator = SliceMeshGenerator() model1 = NotchGrowth(meshGenerator, chemistry, params=params) simulator1 = Simulator(model1, outputDir=sys.path[0]) model1.ci.project(interpolate_nonmatching_mesh(model0.ci, model1.C)) model1.co.project(interpolate_nonmatching_mesh(model0.co, model1.C)) simulator1.run(float(sys.argv[1]), int(sys.argv[3])) # Establish new notches model1.notches0 = [Point(0, 0.4, 0), Point(0, -0.4, 0)] model1.stateField.notches = [Point(0, 0.4, 0), Point(0, -0.4, 0)] simulator1.run(float(sys.argv[1]), int(sys.argv[4]))
def get_forward_solution(self, rho, save_results): #Fe.set_log_level(30) # CRITICAL = 50, // errors that may lead to data corruption and suchlike # ERROR = 40, // things that go boom # WARNINg = 30, // things that may go boom later # INFO = 20, // information of general interest # PROGRESS = 16, // what's happening (broadly) # TRACE = 13, // what's happening (in detail) # DBG = 10 // sundry #self.w = Function(self.W) #Isso ajuda a convergir durante a otimizacao por causa do erro(1e-7) if self.mesh_adapt is not None: self.mesh_full = self.mesh self.mesh = self.mesh_adapt self.subdominios() self.functionsp() rho = interpolate_nonmatching_mesh(rho, self.A) BondConditions = self.boundaries_cond() (u, p) = split(self.w) (v, q) = TestFunctions(self.W) epsilon = sym(grad(u)) '''# Navier-Stokes Nao linear F = (self.alpha(rho) * inner(u, v) * dx \ + self.mu*inner(grad(u), grad(v)) * dx \ - div(v)*p* dx \ - inner(div(u), q) * dx) \ + inner(epsilon*u,v) * dx #Fe.solve(F == 0, self.w, BondConditions) Jacob = derivative(F, self.w) problem = NonlinearVariationalProblem(F, self.w, BondConditions, Jacob) solver = NonlinearVariationalSolver(problem) prm = solver.parameters prm['newton_solver']['absolute_tolerance'] = 1E-7 prm['newton_solver']['relative_tolerance'] = 1E-9 prm['newton_solver']['maximum_iterations'] = 2000 prm['newton_solver']['relaxation_parameter'] = 1.0 print("Resolvendo valor de mu {}".format(float(self.mu))) print("Resolvendo valor de kmax {}".format(float(self.alphabar))) solver.solve() ''' (u, p) = TrialFunctions(self.W) F = self.alpha(rho) * inner(u, v) * dx \ + self.mu*inner(grad(u)+grad(u).T, grad(v)) * dx \ + inner(grad(p), v) * dx \ + inner(div(u), q) * dx problem = LinearVariationalProblem(lhs(F), rhs(F), self.w, BondConditions) solver = LinearVariationalSolver(problem) prm = solver.parameters solver.solve() (u, p) = self.w.split() u.rename("velocidade", "conforme_tempo") p.rename("pressao", "conforme_tempo") if save_results: self.veloc_file << u self.press_file << p if self.mesh_adapt is not None: w_adapt = self.w.copy(deepcopy=True) self.mesh = self.mesh_full self.subdominios() self.functionsp() self.w = interpolate_nonmatching_mesh(w_adapt, self.W) return self.w
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") 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") # Loading geometry rad_t = [] rad_s = [] g = [] g_inv = [] 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"]] for ij in range(3): ts.set_val(g_loc[ij], ts.g[:, ij]) # Could compute the following locally instead of loading ts.set_val(g_inv_loc[ij], ts.g_inv[:, ij]) g.append(g_loc) g_inv.append(g_inv_loc) costheta = df.Function(ref_spaces["psi"], name="costheta") arrsiz = int(len(costheta.vector().get_local())) print("Function vector size: ", arrsiz) costhetas = np.zeros([arrsiz, Ntss]) nsamples = 1000 costhetasamp = np.zeros([nsamples, Ntss]) for its, ts in enumerate(tss): if args.time is not None: step, time = get_step_and_info(ts, args.time) 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]] 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 = df.Function(ts.function_space) # For theta (hat x, gradpsi): #costheta_loc.vector()[:] = abs(gp_t/(gp_norm+1e-8))**2 #costheta_loc.vector()[:] = abs(gp_t/(gp_norm+1e-8)) # Plot cos(theta): #costheta_loc.vector()[:] = gp_t/(gp_norm+1e-8) # Plot theta = acos(cos(theta)): costheta_loc.vector()[:] = np.arccos(gp_t / (gp_norm + 1e-8)) # For theta (hat r, gradpsi): #costheta_loc.vector()[:] = abs((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 costhetas[:, its] = costheta_intp.vector().get_local() #print(costheta(df.Point(0,0))) t_coords = df.interpolate(df.Expression("x[0]", degree=2), ts.function_space) s_coords = df.interpolate(df.Expression("x[1]", degree=2), ts.function_space) t_min = min(t_coords.vector()) t_max = max(t_coords.vector()) s_min = min(s_coords.vector()) s_max = max(s_coords.vector()) for k in range(0, nsamples - 1): Pt = t_min + (t_max - t_min) * random.random() Ps = s_min + (s_max - s_min) * random.random() P = df.Point(Pt, Ps) try: costhetasamp[k, its] = costheta_loc(P) except: print("Error occurred at (t,s) = ", Pt, ",", Ps) print("Geometric parameters: ") print("t_min = ", t_min) print("t_max = ", t_max) print("s_min = ", s_min) print("s_max = ", s_max) dump_xdmf(costheta) if args.show: #fig = df.plot(costheta) #plt.colorbar(fig) rc('text', usetex=True) fig = plt.figure(figsize=(1.75, 2.5)) #plt.hist(costhetas,bins=10,density=True,stacked=True) # Stacked version: # Create color palette manually: #pal = [] #for k in range(0,Ntss): # pal.append('#e34a33') #print("Color palette: ", pal) #plt.hist(costhetas,bins=100,density=True,stacked=True,color=pal,rasterized=True) #plt.hist(costhetasamp,bins=10,density=True,stacked=True) # Unstacked version: costhetas_coll = np.reshape(costhetas, [arrsiz * Ntss, 1]) print(costhetas_coll) plt.hist(costhetas_coll, bins=100, density=True, color='#e34a33', rasterized=True) ax = plt.gca() #ax.set_aspect(0.7) ax.set_xlabel('$\\theta$', fontsize=10) #ax.set_xlabel('$\\theta$') ax.set_ylabel('Relative frequency', fontsize=10) #plt.xticks(np.arange(0,3.2,np.pi)) #plt.yticks(np.arange(0,2.1,1)) plt.yticks([], []) ax.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2)) ax.xaxis.set_minor_locator(plt.MultipleLocator(np.pi / 12)) ax.xaxis.set_major_formatter(plt.FuncFormatter(multiple_formatter())) ax.set_ylim([0, 3]) x1 = np.linspace(0, np.pi, num=200) x2 = np.linspace(0, np.pi, num=200) #f = (2/np.pi)*(1-(2/np.pi)*abs(x1-np.pi/2)) fz = (1 / np.pi) * x2 / x2 #plt.plot(x1,f,lw=2) #plt.plot(x2,fz,lw=2) L = 2 * np.pi * 20 * np.sqrt(2) lam = 2 * np.pi * np.sqrt(2) k = 0 xs = [] ys = [] while k * lam / L <= 1: xk = np.arccos(k * lam / L) yk = np.arcsin(k * lam / L) xs.append(xk) ys.append(yk) k += 1 #plt.vlines(xs,0,0.3) #plt.vlines(ys,0.3,0.6) plt.savefig('hist_cyl_h20.pdf', format="pdf", bbox_inches='tight', pad_inches=0) plt.show()
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") # Loading geometry rad_t = [] rad_s = [] g = [] g_inv = [] 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"]] for ij in range(3): ts.set_val(g_loc[ij], ts.g[:, ij]) # Could compute the following locally instead of loading ts.set_val(g_inv_loc[ij], ts.g_inv[:, ij]) g.append(g_loc) g_inv.append(g_inv_loc) costheta = df.Function(ref_spaces["psi"], name="costheta") for its, ts in enumerate(tss): if args.time is not None: step, time = get_step_and_info(ts, args.time) 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]] 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 = df.Function(ts.function_space) costheta_loc.vector()[:] = abs( (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: fig = df.plot(costheta) plt.colorbar(fig) 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()