def normalise_eigen(self, v, beta, mode='none'): if mode == 'none': return elif mode == 'one': coef = beta.vector().norm('l2') elif mode == 'max': coef = max(abs(beta.vector()[:])) coeff_glob = np.array(0.0, 'd') comm.Allreduce(coef, coeff_glob, op=mpi4py.MPI.MAX) log(LogLevel.DEBUG, 'Normalising eigenvector mode={}'.format(mode)) real = np.all(np.isfinite(v.vector()[:])) log(LogLevel.DEBUG, '{}: v vector real {}'.format(rank, real)) real = np.all(np.isfinite(beta.vector()[:])) log(LogLevel.DEBUG, '{}: beta vector real {}'.format(rank, real)) log(LogLevel.DEBUG, '{}: coeff {}'.format(rank, coef)) log(LogLevel.DEBUG, '{}: coeff_glob {}'.format(rank, coeff_glob)) vval = v.vector()[:] / coeff_glob bval = beta.vector()[:] / coeff_glob v.vector().set_local(vval) beta.vector().set_local(bval) v.vector().vec().ghostUpdate() beta.vector().vec().ghostUpdate() return coeff_glob
def test_reduced_mesh_load_collapsed_matrix(mesh, load_tempdir): log(PROGRESS, "*** Collapsed case, matrix, online computation ***") (V, U) = CollapsedFunctionSpaces(mesh) reduced_mesh = ReducedMesh((V, U)) reduced_mesh.load(load_tempdir, "test_reduced_mesh_collapsed_matrix") _test_reduced_mesh_collapsed_matrix(V, U, reduced_mesh)
def update_lower_bound(self): """ Update lower bound. """ alpha = self.state["alpha"] self.lb = alpha.copy(deepcopy=True).vector() log(LogLevel.DEBUG, 'DEBUG: Updated irreversibility')
def _test_reduced_mesh_elliptic_function(V, reduced_mesh): reduced_V = reduced_mesh.get_reduced_function_spaces() dofs = [d[0] for d in reduced_mesh.get_dofs_list()] # convert from 1-tuple to int reduced_dofs = [d[0] for d in reduced_mesh.get_reduced_dofs_list()] # convert from 1-tuple to int mesh_dim = V.mesh().geometry().dim() assert mesh_dim in (1, 2) if mesh_dim is 1: e = Expression("1+x[0]", element=V.ufl_element()) else: e = Expression("(1+x[0])*(1+x[1])", element=V.ufl_element()) f = project(e, V) f_N = project(e, reduced_V[0]) f_dofs = evaluate_sparse_function_at_dofs(f, dofs, V, dofs) f_reduced_dofs = evaluate_sparse_function_at_dofs(f, dofs, reduced_V[0], reduced_dofs) f_N_reduced_dofs = evaluate_sparse_function_at_dofs(f_N, reduced_dofs, reduced_V[0], reduced_dofs) log(PROGRESS, "f at dofs:\n" + str(nonzero_values(f_dofs))) log(PROGRESS, "f at reduced dofs:\n" + str(nonzero_values(f_reduced_dofs))) log(PROGRESS, "f_N at reduced dofs:\n" + str(nonzero_values(f_N_reduced_dofs))) log(PROGRESS, "Error:\n" + str(nonzero_values(f_dofs) - nonzero_values(f_reduced_dofs))) log(PROGRESS, "Error:\n" + str(f_reduced_dofs.vector().get_local() - f_N_reduced_dofs.vector().get_local())) assert isclose(nonzero_values(f_dofs), nonzero_values(f_reduced_dofs)).all() assert isclose(f_reduced_dofs.vector().get_local(), f_N_reduced_dofs.vector().get_local()).all()
def test_reduced_mesh_load_collapsed_vector(mesh, load_tempdir): log(PROGRESS, "*** Collapsed case, vector, online computation ***") (V, _) = CollapsedFunctionSpaces(mesh) reduced_mesh = ReducedMesh((V, )) reduced_mesh.load(load_tempdir, "test_reduced_mesh_collapsed_vector") _test_reduced_mesh_collapsed_vector(V, reduced_mesh)
def test_separated_parametrized_forms_vector_6(): a6 = inner(expr7 * grad(u), grad(v)) * dx + inner( grad(u) * expr6, v) * dx + expr5 * inner(u, v) * dx a6_sep = SeparatedParametrizedForm(a6) log(PROGRESS, "*** ### FORM 6 ### ***") log( PROGRESS, "We change the coefficients to be non-parametrized. No (parametrized) coefficients are extracted this time" ) a6_sep.separate() log( PROGRESS, "\tLen coefficients:\n" + "\t\t" + str(len(a6_sep.coefficients)) + "\n") assert 0 == len(a6_sep.coefficients) log( PROGRESS, "\tLen unchanged forms:\n" + "\t\t" + str(len(a6_sep._form_unchanged)) + "\n") assert 3 == len(a6_sep._form_unchanged) log( PROGRESS, "\tUnchanged forms:\n" + "\t\t" + str(a6_sep._form_unchanged[0].integrals()[0].integrand()) + "\n" + "\t\t" + str(a6_sep._form_unchanged[1].integrals()[0].integrand()) + "\n" + "\t\t" + str(a6_sep._form_unchanged[2].integrals()[0].integrand()) + "\n") assert "sum_{i_{72}} sum_{i_{71}} ({ A | A_{i_{66}, i_{67}} = sum_{i_{68}} f_11[i_{66}, i_{68}] * (grad(v_1))[i_{68}, i_{67}] })[i_{71}, i_{72}] * (grad(v_0))[i_{71}, i_{72}] " == str( a6_sep._form_unchanged[0].integrals()[0].integrand()) assert "sum_{i_{73}} ({ A | A_{i_{69}} = sum_{i_{70}} f_10[i_{70}] * (grad(v_1))[i_{69}, i_{70}] })[i_{73}] * v_0[i_{73}] " == str( a6_sep._form_unchanged[1].integrals()[0].integrand()) assert "f_9 * (sum_{i_{74}} v_0[i_{74}] * v_1[i_{74}] )" == str( a6_sep._form_unchanged[2].integrals()[0].integrand())
def test_separated_parametrized_forms_vector_18(): a18 = inner(grad(expr14[0]), u) * v[0] * dx + expr14[0].dx(0) * inner( u, v) * dx a18_sep = SeparatedParametrizedForm(a18) log(PROGRESS, "*** ### FORM 18 ### ***") log( PROGRESS, "This form is similar to form 14, but each term is multiplied by the gradient/partial derivative of a component of a Function which is not solution of a parametrized problem. This results in no parametrized coefficients" ) a18_sep.separate() log( PROGRESS, "\tLen coefficients:\n" + "\t\t" + str(len(a18_sep.coefficients)) + "\n") assert 0 == len(a18_sep.coefficients) log( PROGRESS, "\tLen unchanged forms:\n" + "\t\t" + str(len(a18_sep._form_unchanged)) + "\n") assert 2 == len(a18_sep._form_unchanged) log( PROGRESS, "\tUnchanged forms:\n" + "\t\t" + str(a18_sep._form_unchanged[0].integrals()[0].integrand()) + "\n" + "\t\t" + str(a18_sep._form_unchanged[1].integrals()[0].integrand()) + "\n") assert "v_0[0] * (sum_{i_{177}} (grad(f_30))[0, i_{177}] * v_1[i_{177}] )" == str( a18_sep._form_unchanged[0].integrals()[0].integrand()) assert "(grad(f_30))[0, 0] * (sum_{i_{178}} v_0[i_{178}] * v_1[i_{178}] )" == str( a18_sep._form_unchanged[1].integrals()[0].integrand())
def test_separated_parametrized_forms_vector_13(): a13 = inner(expr15 * grad(u), grad(v)) * dx + inner( grad(u) * expr14, v) * dx + expr13 * inner(u, v) * dx a13_sep = SeparatedParametrizedForm(a13) log(PROGRESS, "*** ### FORM 13 ### ***") log( PROGRESS, "This form is similar to form 11, but each term is multiplied by a Function, which is not the solution of a parametrized problem. This results in no parametrized coefficients" ) a13_sep.separate() log( PROGRESS, "\tLen coefficients:\n" + "\t\t" + str(len(a13_sep.coefficients)) + "\n") assert 0 == len(a13_sep.coefficients) log( PROGRESS, "\tLen unchanged forms:\n" + "\t\t" + str(len(a13_sep._form_unchanged)) + "\n") assert 3 == len(a13_sep._form_unchanged) log( PROGRESS, "\tUnchanged forms:\n" + "\t\t" + str(a13_sep._form_unchanged[0].integrals()[0].integrand()) + "\n" + "\t\t" + str(a13_sep._form_unchanged[1].integrals()[0].integrand()) + "\n" + "\t\t" + str(a13_sep._form_unchanged[2].integrals()[0].integrand()) + "\n") assert "sum_{i_{151}} sum_{i_{150}} ({ A | A_{i_{145}, i_{146}} = sum_{i_{147}} f_33[i_{145}, i_{147}] * (grad(v_1))[i_{147}, i_{146}] })[i_{150}, i_{151}] * (grad(v_0))[i_{150}, i_{151}] " == str( a13_sep._form_unchanged[0].integrals()[0].integrand()) assert "sum_{i_{152}} ({ A | A_{i_{148}} = sum_{i_{149}} f_30[i_{149}] * (grad(v_1))[i_{148}, i_{149}] })[i_{152}] * v_0[i_{152}] " == str( a13_sep._form_unchanged[1].integrals()[0].integrand()) assert "f_27 * (sum_{i_{153}} v_0[i_{153}] * v_1[i_{153}] )" == str( a13_sep._form_unchanged[2].integrals()[0].integrand())
def test_separated_parametrized_forms_vector_17(): a17 = inner(grad(expr14) * grad(u), grad(v)) * dx + inner( grad(u) * grad(expr13), v) * dx + expr13.dx(0) * inner(u, v) * dx a17_sep = SeparatedParametrizedForm(a17) log(PROGRESS, "*** ### FORM 17 ### ***") log( PROGRESS, "This form is similar to form 13, but each term is multiplied by a the gradient/partial derivative of Function, which is not the solution of a parametrized problem. This results in no parametrized coefficients" ) a17_sep.separate() log( PROGRESS, "\tLen coefficients:\n" + "\t\t" + str(len(a17_sep.coefficients)) + "\n") assert 0 == len(a17_sep.coefficients) log( PROGRESS, "\tLen unchanged forms:\n" + "\t\t" + str(len(a17_sep._form_unchanged)) + "\n") assert 3 == len(a17_sep._form_unchanged) log( PROGRESS, "\tUnchanged forms:\n" + "\t\t" + str(a17_sep._form_unchanged[0].integrals()[0].integrand()) + "\n" + "\t\t" + str(a17_sep._form_unchanged[1].integrals()[0].integrand()) + "\n" + "\t\t" + str(a17_sep._form_unchanged[2].integrals()[0].integrand()) + "\n") assert "sum_{i_{174}} sum_{i_{173}} ({ A | A_{i_{168}, i_{169}} = sum_{i_{170}} (grad(v_1))[i_{170}, i_{169}] * (grad(f_30))[i_{168}, i_{170}] })[i_{173}, i_{174}] * (grad(v_0))[i_{173}, i_{174}] " == str( a17_sep._form_unchanged[0].integrals()[0].integrand()) assert "sum_{i_{175}} ({ A | A_{i_{171}} = sum_{i_{172}} (grad(v_1))[i_{171}, i_{172}] * (grad(f_27))[i_{172}] })[i_{175}] * v_0[i_{175}] " == str( a17_sep._form_unchanged[1].integrals()[0].integrand()) assert "(grad(f_27))[0] * (sum_{i_{176}} v_0[i_{176}] * v_1[i_{176}] )" == str( a17_sep._form_unchanged[2].integrals()[0].integrand())
def test_reduced_mesh_load_mixed_vector(mesh, load_tempdir): log(PROGRESS, "*** Mixed case, vector, online computation ***") V = MixedFunctionSpace(mesh) reduced_mesh = ReducedMesh((V, )) reduced_mesh.load(load_tempdir, "test_reduced_mesh_mixed_vector") _test_reduced_mesh_mixed_vector(V, reduced_mesh)
def test_reduced_mesh_load_elliptic_matrix(mesh, load_tempdir): log(PROGRESS, "*** Elliptic case, matrix, online computation ***") V = EllipticFunctionSpace(mesh) reduced_mesh = ReducedMesh((V, V)) reduced_mesh.load(load_tempdir, "test_reduced_mesh_elliptic_matrix") _test_reduced_mesh_elliptic_matrix(V, reduced_mesh)
def test_reduced_mesh_load_elliptic_vector(mesh, load_tempdir): log(PROGRESS, "*** Elliptic case, vector, online computation ***") V = EllipticFunctionSpace(mesh) reduced_mesh = ReducedMesh((V, )) reduced_mesh.load(load_tempdir, "test_reduced_mesh_elliptic_vector") _test_reduced_mesh_elliptic_vector(V, reduced_mesh)
def solve(self): log(LogLevel.INFO, '________________________ EQUILIBRIUM _________________________') log(LogLevel.INFO, 'Solving elasticity') problem = self.problem u = problem.state["u"].vector() self.solver.solve(problem, u) return (self.solver.snes().getIterationNumber(), self.solver.snes().getConvergedReason())
def plotstep(): if rank == 0: fig = plt.figure(dpi=80, facecolor='w', edgecolor='k') plt.subplot(1, 1, 1) plt.set_cmap('binary') dolfin.plot( project(stability.inactivemarker4, L2), alpha = 1., vmin=0., vmax=1.) plt.title('intersec deriv, ub') plt.savefig(os.path.join(outdir, "inactivesets-{:.3f}-{:d}.pdf".format(load, iteration))) plt.set_cmap('hot') fig = plt.figure(dpi=80, facecolor='w', edgecolor='k') for i,mode in enumerate(pert): plt.subplot(2, _nmodes+1, i+2) plt.axis('off') plot(mode[1], cmap = cm.ocean) plt.title('mode {} $h^*$={:.3f}\n $\\lambda_{}$={:.3e} \n $\\Delta E$={:.3e}' .format(i, h_opts[i], i, stability.eigs[i], en_vars[i]), fontsize= 15) # plt.title('mode {}' # .format(i), fontsize= 15) plt.subplot(2, _nmodes+1, _nmodes+2+1+i) plt.axis('off') _pert_beta = mode[1] _pert_v = mode[0] if hbounds[i][0] == hbounds[i][1] == 0: plt.plot(hbounds[i][0], 0) else: hs = np.linspace(hbounds[i][0], hbounds[i][1], 100) z = np.polyfit(np.linspace(hbounds[i][0], hbounds[i][1], len(en_perts[i])), en_perts[i], parameters['stability']['order']) p = np.poly1d(z) plt.plot(hs, p(hs), c='k') plt.plot(np.linspace(hbounds[i][0], hbounds[i][1], len(en_perts[i])), en_perts[i], marker='o', markersize=10, c='k') plt.plot(hs, stability.eigs[i]*hs**2, c='r', lw=.3) plt.axvline(h_opts[i], lw = .3, c='k') plt.axvline(0, lw=2, c='k') # plt.title('{}'.format(i)) plt.tight_layout(h_pad=1.5, pad=1.5) # plt.legend() plt.savefig(os.path.join(outdir, "modes-{:.3f}-{}.pdf".format(load, iteration))) plt.close(fig) plt.clf() log(LogLevel.INFO, 'plotted modes') plt.figure() plt.plot(mineigs, marker = 'o') plt.axhline(0.) plt.savefig(os.path.join(outdir, "mineigs-{:.3f}.pdf".format(load)))
def test_reduced_mesh_save_elliptic_vector(mesh, save_tempdir): log(PROGRESS, "*** Elliptic case, vector, offline computation ***") V = EllipticFunctionSpace(mesh) reduced_mesh = ReducedMesh((V, )) dofs = [(1, ), (11, ), (48, ), (41, )] for pair in dofs: log(PROGRESS, "Adding " + str(pair)) reduced_mesh.append(pair) reduced_mesh.save(save_tempdir, "test_reduced_mesh_elliptic_vector") _test_reduced_mesh_elliptic_vector(V, reduced_mesh)
def outputData(): np.save(os.path.join(outdir, 'bifurcation_loads'), bifurcation_loads, allow_pickle=True, fix_imports=True) with files['output'] as file: file.write(alpha, load) file.write(u, load) with files['postproc'] as file: file.write_checkpoint(alpha, "alpha-{}".format(step), step, append = True) file.write_checkpoint(u, "u-{}".format(step), step, append = True) log(LogLevel.INFO, 'Written postprocessing step {}'.format(step)) time_data_pd.to_json(os.path.join(outdir, "time_data.json"))
def test_reduced_mesh_save_elliptic_matrix(mesh, save_tempdir): log(PROGRESS, "*** Elliptic case, matrix, offline computation ***") V = EllipticFunctionSpace(mesh) reduced_mesh = ReducedMesh((V, V)) dofs = [(1, 2), (11, 12), (48, 12), (41, 41)] for pair in dofs: log(PROGRESS, "Adding " + str(pair)) reduced_mesh.append(pair) reduced_mesh.save(save_tempdir, "test_reduced_mesh_elliptic_matrix") _test_reduced_mesh_elliptic_matrix(V, reduced_mesh)
def test_reduced_mesh_save_collapsed_vector(mesh, save_tempdir): log(PROGRESS, "*** Collapsed case, vector, offline computation ***") (V, _) = CollapsedFunctionSpaces(mesh) reduced_mesh = ReducedMesh((V, )) dofs = [(2, ), (48, ), (40, ), (11, )] for pair in dofs: log(PROGRESS, "Adding " + str(pair)) reduced_mesh.append(pair) reduced_mesh.save(save_tempdir, "test_reduced_mesh_collapsed_vector") _test_reduced_mesh_collapsed_vector(V, reduced_mesh)
def test_reduced_mesh_save_collapsed_matrix(mesh, save_tempdir): log(PROGRESS, "*** Collapsed case, matrix, offline computation ***") (V, U) = CollapsedFunctionSpaces(mesh) reduced_mesh = ReducedMesh((V, U)) dofs = [(2, 1), (48, 33), (40, 12), (31, 39)] for pair in dofs: log(PROGRESS, "Adding " + str(pair)) reduced_mesh.append(pair) reduced_mesh.save(save_tempdir, "test_reduced_mesh_collapsed_matrix") _test_reduced_mesh_collapsed_matrix(V, U, reduced_mesh)
def test_reduced_mesh_save_mixed_vector(mesh, save_tempdir): log(PROGRESS, "*** Mixed case, vector, offline computation ***") V = MixedFunctionSpace(mesh) reduced_mesh = ReducedMesh((V, )) dofs = [(2, ), (33, ), (48, ), (42, )] for pair in dofs: log(PROGRESS, "Adding " + str(pair)) reduced_mesh.append(pair) reduced_mesh.save(save_tempdir, "test_reduced_mesh_mixed_vector") _test_reduced_mesh_mixed_vector(V, reduced_mesh)
def test_reduced_mesh_save_mixed_matrix(mesh, save_tempdir): log(PROGRESS, "*** Mixed case, matrix, offline computation ***") V = MixedFunctionSpace(mesh) reduced_mesh = ReducedMesh((V, V)) dofs = [(1, 2), (31, 33), (48, 12), (42, 42)] for pair in dofs: log(PROGRESS, "Adding " + str(pair)) reduced_mesh.append(pair) reduced_mesh.save(save_tempdir, "test_reduced_mesh_mixed_matrix") _test_reduced_mesh_mixed_matrix(V, reduced_mesh)
def solve(self, alpha_old): """ Solves second order problem returning stability flag and number of negative eigenvalues. """ self.alpha_old = alpha_old self.assigner.assign(self.z, [self.u, self.alpha]) if self.is_elastic(): log(LogLevel.INFO, 'Current state: elastic') else: log(LogLevel.INFO, 'Current state: inelastic') inactive_dofs = self.getInactiveSet() index_set = self.getFreeDofsIS(inactive_dofs) print(f'inactive_dofs {inactive_dofs}') print(f'free_dofs {index_set}') self.inertia_setup() negev = self.get_inertia(self._Hessian, restricted_dofs_is=index_set) eigen = EigenSolver(self.H, self.z, restricted_dofs_is=index_set, slepc_options=self.parameters['eigen'], initial_guess=self.getInitialGuess()) nconv, it = eigen.solve( min(self.parameters['stability']['maxmodes'], negev + 1)) eigs = eigen.get_eigenvalues(nconv) self.sanityCheck(negev, eigs) _stabilityData = self.postprocEigs(eigs, eigen) self.compileData(_stabilityData, eigs) self.i += 1 self.stable = eigs[0, 0].real > float( self.parameters['eigen']['eig_rtol']) # based on eigenvalue if self.is_elastic(): self.stable = True return (self.stable, int(negev))
def __init__(self, problem, parameters={}, lb=None): super(DamageSolverSNES, self).__init__() self.problem = problem self.energy = problem.energy self.state = problem.state self.alpha = problem.state['alpha'] self.alpha_dvec = as_backend_type(self.alpha.vector()) self.alpha_pvec = self.alpha_dvec.vec() self.bcs = problem.bcs self.parameters = parameters comm = self.alpha.function_space().mesh().mpi_comm() self.comm = comm V = self.alpha.function_space() self.V = V self.Ealpha = derivative( self.energy, self.alpha, dolfin.TestFunction(self.alpha.ufl_function_space())) self.dm = self.alpha.function_space().dofmap() solver = PETScSNESSolver() snes = solver.snes() if lb == None: lb = interpolate(Constant(0.), V) ub = interpolate(Constant(1.), V) prefix = "damage_" snes.setOptionsPrefix(prefix) for option, value in self.parameters["snes"].items(): PETScOptions.set(prefix + option, value) log(LogLevel.DEBUG, "DEBUG: Set: {} = {}".format(prefix + option, value)) snes.setFromOptions() (J, F, bcs_alpha) = (problem.J, problem.F, problem.bcs) self.ass = SystemAssembler(J, F, bcs_alpha) self.b = self.init_residual() snes.setFunction(self.residual, self.b.vec()) self.A = self.init_jacobian() snes.setJacobian(self.jacobian, self.A.mat()) snes.ksp.setOperators(self.A.mat()) snes.setVariableBounds(self.problem.lb.vec(), self.problem.ub.vec()) # # snes.solve(None, Function(V).vector().vec()) self.solver = snes
def test_shared_entities_detection(mesh, submesh, tempdir): dim_to_text = { submesh.topology().dim(): "cells", submesh.topology().dim() - 1: "facets", 0: "vertices" } for dim in [submesh.topology().dim(), submesh.topology().dim() - 1, 0]: shared_entities = submesh.topology().shared_entities(dim) log(PROGRESS, "Submesh shared indices for " + str(dim_to_text[dim])) log(PROGRESS, str(shared_entities)) filename = "test_shared_entities_detection__dim_" + str( dim) + "__size_" + str(MPI.size( submesh.mpi_comm())) + "_rank_" + str( MPI.rank(submesh.mpi_comm())) + ".pkl" dict_save(shared_entities, tempdir, filename) dict_assert_equal(shared_entities, data_dir, filename)
def test_mesh_to_submesh_global_vertex_indices(mesh, submesh, tempdir): log(PROGRESS, "Mesh to submesh global vertex indices:") for (mesh_local_index, submesh_local_index ) in submesh.mesh_to_submesh_vertex_local_indices.items(): mesh_global_index = mesh.topology().global_indices(0)[mesh_local_index] submesh_global_index = submesh.topology().global_indices( 0)[submesh_local_index] log(PROGRESS, "\t" + str(mesh_global_index) + " -> " + str(submesh_global_index)) assert_mesh_plotter(mesh, submesh, "V", tempdir, "test_mesh_to_submesh_global_vertex_indices") filename = "test_mesh_to_submesh_global_vertex_indices" + "_size_" + str( MPI.size(submesh.mpi_comm())) + "_rank_" + str( MPI.rank(submesh.mpi_comm())) + ".pkl" dict_save(submesh.mesh_to_submesh_vertex_local_indices, tempdir, filename) dict_assert_equal(submesh.mesh_to_submesh_vertex_local_indices, data_dir, filename)
def test_submesh_to_mesh_global_vertex_indices(mesh, submesh, tempdir): log(PROGRESS, "Submesh to mesh global vertex indices:") for (submesh_local_index, mesh_local_index) in enumerate( submesh.submesh_to_mesh_vertex_local_indices): submesh_global_index = submesh.topology().global_indices( 0)[submesh_local_index] mesh_global_index = mesh.topology().global_indices(0)[mesh_local_index] log(PROGRESS, "\t" + str(submesh_global_index) + " -> " + str(mesh_global_index)) assert_mesh_plotter(mesh, submesh, "V", tempdir, "test_submesh_to_mesh_global_vertex_indices") filename = "test_submesh_to_mesh_global_vertex_indices" + "_size_" + str( MPI.size(submesh.mpi_comm())) + "_rank_" + str( MPI.rank(submesh.mpi_comm())) + ".pkl" array_save(submesh.submesh_to_mesh_vertex_local_indices, tempdir, filename) array_assert_equal(submesh.submesh_to_mesh_vertex_local_indices, data_dir, filename)
def solve(self): """ Solve the damage problem for the current state. """ log(LogLevel.INFO, "Solving damage") try: self.solver.solve() return (self.solver.solver.getIterationNumber(), self.solver.solver.getConvergedReason()) except: log(LogLevel.WARNING, "WARNING: Damage solver failed, what's next?") raise RuntimeError("Damage solvers did not converge")
def __init__(self, energy, state, bcs, parameters={}): super(ElasticitySolver, self).__init__() solver_name = 'elasticity' self.problem = ElasticityProblem(energy, state, bcs) # Set the solver self.solver = PETScSNESSolver() snes = self.solver.snes() prefix = "elasticity_" snes.setOptionsPrefix(prefix) print(parameters) for parameter, value in parameters.items(): log(LogLevel.DEBUG, "DEBUG: Set: {} = {}".format(prefix + parameter, value)) PETScOptions.set(prefix + parameter, value) snes.setFromOptions()
def test_separated_parametrized_forms_vector_14(): a14 = expr14[0]*inner(u, v)*dx a14_sep = SeparatedParametrizedForm(a14) log(PROGRESS, "*** ### FORM 14 ### ***") log(PROGRESS, "This form is similar to form 12, but each term is multiplied by a component of a Function which is not solution of a parametrized problem. This results in no parametrized coefficients") a14_sep.separate() log(PROGRESS, "\tLen coefficients:\n" + "\t\t" + str(len(a14_sep.coefficients)) + "\n" ) assert 0 == len(a14_sep.coefficients) log(PROGRESS, "\tLen unchanged forms:\n" + "\t\t" + str(len(a14_sep._form_unchanged)) + "\n" ) assert 1 == len(a14_sep._form_unchanged) log(PROGRESS, "\tUnchanged forms:\n" + "\t\t" + str(a14_sep._form_unchanged[0].integrals()[0].integrand()) + "\n" ) assert "f_30[0] * (sum_{i_{154}} v_0[i_{154}] * v_1[i_{154}] )" == str(a14_sep._form_unchanged[0].integrals()[0].integrand())
def get_auxiliary_reduced_function_space(self, auxiliary_problem, component, index=None): assert isinstance(component, tuple) assert len(component) > 0 index = self._get_dict_index(index) auxiliary_V = _sub_from_tuple(auxiliary_problem.V, component) key = (auxiliary_problem, component, index) if key not in self._auxiliary_reduced_function_space: auxiliary_reduced_V = wrapping.convert_functionspace_to_submesh(auxiliary_V, self.reduced_mesh[index], self._get_auxiliary_reduced_function_space_type(auxiliary_V)) self._auxiliary_reduced_function_space[key] = auxiliary_reduced_V if not self._load_auxiliary_reduced_function_space(key): # Get the map between DOFs on auxiliary_V and auxiliary_reduced_V (auxiliary_dofs_to_reduced_dofs, _) = wrapping.map_functionspaces_between_mesh_and_submesh(auxiliary_V, self.mesh, auxiliary_reduced_V, self.reduced_mesh[index]) log(DEBUG, "Auxiliary DOFs to reduced DOFs is " + str(auxiliary_dofs_to_reduced_dofs)) self._auxiliary_dofs_to_reduced_dofs[key] = auxiliary_dofs_to_reduced_dofs # Save to file self._save_auxiliary_reduced_function_space(key) else: assert key in self._auxiliary_dofs_to_reduced_dofs return self._auxiliary_reduced_function_space[key]
def jit_generate(cpp_code, module_name, signature, parameters): log(LogLevel.TRACE, "Calling dijitso just-in-time (JIT) compiler for pybind11 code.") # Split code on reserved word "SIGNATURE" which will be replaced # by the module signature # This must occur only once in the code split_cpp_code = re.split('SIGNATURE', cpp_code) if len(split_cpp_code) < 2: raise RuntimeError("Cannot find keyword: SIGNATURE in pybind11 C++ code.") elif len(split_cpp_code) > 2: raise RuntimeError("Found multiple instances of keyword: SIGNATURE in pybind11 C++ code.") code_c = split_cpp_code[0] + signature + split_cpp_code[1] code_h = "" depends = [] return code_h, code_c, depends
def jit_generate(class_data, module_name, signature, parameters): """TODO: document""" template_code = """ // Based on https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define DLL_EXPORT __attribute__ ((dllexport)) #else #define DLL_EXPORT __declspec(dllexport) #endif #else #define DLL_EXPORT __attribute__ ((visibility ("default"))) #endif #include <dolfin/function/Expression.h> #include <dolfin/math/basic.h> #include <Eigen/Dense> {math_header} namespace dolfin {{ class {classname} : public Expression {{ public: {members} {classname}() {{ {constructor} }} void eval(Eigen::Ref<Eigen::VectorXd> values, Eigen::Ref<const Eigen::VectorXd> x) const override {{ {statement} }} void set_property(std::string name, double _value) override {{ {set_props} throw std::runtime_error("No such property"); }} double get_property(std::string name) const override {{ {get_props} throw std::runtime_error("No such property"); return 0.0; }} void set_generic_function(std::string name, std::shared_ptr<dolfin::GenericFunction> _value) override {{ {set_generic_function} throw std::runtime_error("No such property"); }} std::shared_ptr<dolfin::GenericFunction> get_generic_function(std::string name) const override {{ {get_generic_function} throw std::runtime_error("No such property"); }} }}; }} extern "C" DLL_EXPORT dolfin::Expression * create_{classname}() {{ return new dolfin::{classname}; }} """ _get_props = """ if (name == "{key_name}") return {name};""" _set_props = """ if (name == "{key_name}") {{ {name} = _value; return; }}""" log(LogLevel.TRACE, "Calling dijitso just-in-time (JIT) compiler for Expression.") statements = class_data["statements"] statement = "" if isinstance(statements, str): statement += " values[0] = " + statements + ";\n" else: for i, val in enumerate(statements): statement += " values[" + str(i) + "] = " + val + ";\n" constructor = "" members = "" set_props = "" get_props = "" set_generic_function = "" get_generic_function = "" # Add code for setting and getting property values properties = class_data["properties"] for k in properties: value = properties[k] if isinstance(value, (float, int)): members += "double " + k + ";\n" set_props += _set_props.format(key_name=k, name=k) get_props += _get_props.format(key_name=k, name=k) elif hasattr(value, "_cpp_object"): members += "std::shared_ptr<dolfin::GenericFunction> generic_function_{key};\n".format(key=k) set_generic_function += _set_props.format(key_name=k, name="generic_function_" + k) get_generic_function += _get_props.format(key_name=k, name="generic_function_" + k) value_size = value._cpp_object.value_size() if value_size == 1: _setup_statement = """ double {key}; generic_function_{key}->eval(Eigen::Map<Eigen::Matrix<double, 1, 1>>(&{key}), x);\n""".format(key=k) else: _setup_statement = """ double {key}[{value_size}]; generic_function_{key}->eval(Eigen::Map<Eigen::Matrix<double, {value_size}, 1>>({key}), x);\n""".format(key=k, value_size=value_size) statement = _setup_statement + statement # Set the value_shape for dim in class_data['value_shape']: constructor += "_value_shape.push_back(" + str(dim) + ");" classname = signature code_c = template_code.format(statement=statement, classname=classname, members=members, constructor=constructor, set_props=set_props, get_props=get_props, get_generic_function=get_generic_function, set_generic_function=set_generic_function, math_header=_math_header) code_h = "" depends = [] return code_h, code_c, depends
def jit_generate(class_data, module_name, signature, parameters): template_code = """ // Based on https://gcc.gnu.org/wiki/Visibility #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define DLL_EXPORT __attribute__ ((dllexport)) #else #define DLL_EXPORT __declspec(dllexport) #endif #else #define DLL_EXPORT __attribute__ ((visibility ("default"))) #endif #include <dolfin/common/Array.h> #include <dolfin/math/basic.h> #include <dolfin/mesh/SubDomain.h> #include <Eigen/Dense> {math_header} namespace dolfin {{ class {classname} : public SubDomain {{ public: {members} {classname}() {{ {constructor} }} // Return true for points inside the sub domain bool inside(const Eigen::Ref<const Eigen::VectorXd> x, bool on_boundary) const final {{ return {inside}; }} void set_property(std::string name, double value) {{ {set_props} }} double get_property(std::string name) const {{ {get_props} return 0.0; }} }}; }} extern "C" DLL_EXPORT dolfin::SubDomain * create_{classname}() {{ return new dolfin::{classname}; }} """ _set_prop = """ if (name == "{name}") {name} = value;\n""" _get_prop = """ if (name == "{name}") return {name};\n""" log(LogLevel.TRACE, "Calling dijitso just-in-time (JIT) compiler for SubDomain.") inside_code = class_data['statements'][0] members = "" get_props = "" set_props = "" for k in class_data['properties']: members += " double " + k + ";\n" get_props += _get_prop.format(name=k) set_props += _set_prop.format(name=k) classname = signature code_c = template_code.format(inside=inside_code, classname=classname, math_header=_math_header, members=members, constructor="", get_props=get_props, set_props=set_props) code_h = "" depends = [] return code_h, code_c, depends