def save_results(problem, solver, num_dofs, mesh_size, time_step, functional, error): 'Save results to file.' # Print summary if MPI.process_number() == 0 : print '' print 'Problem |', problem print 'Solver |', solver print 'Unknowns |', num_dofs print 'Mesh size |', mesh_size print 'Time step |', time_step print 'Functional |', functional print 'Error |', error # Print DOLFIN summary set_log_active(True) list_timings() # Append to file, let each dx, dt have its own log file results_dir = problem.options['results_dir'] dx = problem.options['refinement_level'] dt = problem.options['dt_division'] name = '%s_%s_results_dx%d_dt%d.log' % (str(problem), str(solver), dx, dt) filename = os.path.join(results_dir, name) # create the dir for results if needed if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) with open(filename, 'a') as f: f.write('%s, %s, %s, %d, %.15g, %.15g, %.15g, %s\n' % (time.asctime(), problem, solver, num_dofs, mesh_size, time_step, functional, str(error)))
def save_results(problem, solver, num_dofs, mesh_size, time_step, functional, error): 'Save results to file.' # Print summary if MPI.process_number() == 0: print '' print 'Problem |', problem print 'Solver |', solver print 'Unknowns |', num_dofs print 'Mesh size |', mesh_size print 'Time step |', time_step print 'Functional |', functional print 'Error |', error # Print DOLFIN summary set_log_active(True) list_timings() # Append to file, let each dx, dt have its own log file results_dir = problem.options['results_dir'] dx = problem.options['refinement_level'] dt = problem.options['dt_division'] name = '%s_%s_results_dx%d_dt%d.log' % (str(problem), str(solver), dx, dt) filename = os.path.join(results_dir, name) # create the dir for results if needed if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) with open(filename, 'a') as f: f.write('%s, %s, %s, %d, %.15g, %.15g, %.15g, %s\n' % (time.asctime(), problem, solver, num_dofs, mesh_size, time_step, functional, str(error)))
def test_numba_assembly(): mesh = UnitSquareMesh(MPI.comm_world, 13, 13) V = FunctionSpace(mesh, ("Lagrange", 1)) a = cpp.fem.Form([V._cpp_object, V._cpp_object]) a.set_tabulate_cell(0, tabulate_tensor_A.address) L = cpp.fem.Form([V._cpp_object]) L.set_tabulate_cell(0, tabulate_tensor_b.address) A = dolfin.fem.assemble(a) b = dolfin.fem.assemble(L) Anorm = A.norm(PETSc.NormType.FROBENIUS) bnorm = b.norm(PETSc.NormType.N2) assert (np.isclose(Anorm, 56.124860801609124)) assert (np.isclose(bnorm, 0.0739710713711999)) list_timings([TimingType.wall])
def test_numba_assembly(): mesh = UnitSquareMesh(MPI.comm_world, 13, 13) Q = FunctionSpace(mesh, "Lagrange", 1) u = TrialFunction(Q) v = TestFunction(Q) a = cpp.fem.Form([Q._cpp_object, Q._cpp_object]) L = cpp.fem.Form([Q._cpp_object]) sig = types.void(types.CPointer(typeof(ScalarType())), types.CPointer(types.CPointer(typeof(ScalarType()))), types.CPointer(types.double), types.intc) fnA = cfunc(sig, cache=True)(tabulate_tensor_A) a.set_cell_tabulate(0, fnA.address) fnb = cfunc(sig, cache=True)(tabulate_tensor_b) L.set_cell_tabulate(0, fnb.address) if (False): ufc_form = ffc_jit(dot(grad(u), grad(v)) * dx) ufc_form = cpp.fem.make_ufc_form(ufc_form[0]) a = cpp.fem.Form(ufc_form, [Q._cpp_object, Q._cpp_object]) ufc_form = ffc_jit(v * dx) ufc_form = cpp.fem.make_ufc_form(ufc_form[0]) L = cpp.fem.Form(ufc_form, [Q._cpp_object]) assembler = cpp.fem.Assembler([[a]], [L], []) A = PETScMatrix() b = PETScVector() assembler.assemble(A, cpp.fem.Assembler.BlockType.monolithic) assembler.assemble(b, cpp.fem.Assembler.BlockType.monolithic) Anorm = A.norm(cpp.la.Norm.frobenius) bnorm = b.norm(cpp.la.Norm.l2) print(Anorm, bnorm) assert (np.isclose(Anorm, 56.124860801609124)) assert (np.isclose(bnorm, 0.0739710713711999)) list_timings([TimingType.wall])
def test_numba_assembly(): mesh = UnitSquareMesh(MPI.comm_world, 13, 13) V = FunctionSpace(mesh, ("Lagrange", 1)) a = cpp.fem.Form([V._cpp_object, V._cpp_object]) a.set_tabulate_cell(-1, tabulate_tensor_A.address) a.set_tabulate_cell(12, tabulate_tensor_A.address) a.set_tabulate_cell(2, tabulate_tensor_A.address) L = cpp.fem.Form([V._cpp_object]) L.set_tabulate_cell(-1, tabulate_tensor_b.address) A = dolfin.fem.assemble_matrix(a) A.assemble() b = dolfin.fem.assemble_vector(L) b.ghostUpdate(addv=PETSc.InsertMode.ADD, mode=PETSc.ScatterMode.REVERSE) Anorm = A.norm(PETSc.NormType.FROBENIUS) bnorm = b.norm(PETSc.NormType.N2) assert (np.isclose(Anorm, 56.124860801609124)) assert (np.isclose(bnorm, 0.0739710713711999)) list_timings([TimingType.wall])
def test_cffi_assembly(): mesh = UnitSquareMesh(MPI.comm_world, 13, 13) V = FunctionSpace(mesh, ("Lagrange", 1)) if MPI.rank(mesh.mpi_comm()) == 0: from cffi import FFI ffibuilder = FFI() ffibuilder.set_source( "_cffi_kernelA", r""" #include <math.h> #include <stdalign.h> void tabulate_tensor_poissonA(double* restrict A, const double* w, const double* restrict coordinate_dofs, int cell_orientation) { // Precomputed values of basis functions and precomputations // FE* dimensions: [entities][points][dofs] // PI* dimensions: [entities][dofs][dofs] or [entities][dofs] // PM* dimensions: [entities][dofs][dofs] alignas(32) static const double FE3_C0_D01_Q1[1][1][2] = { { { -1.0, 1.0 } } }; // Unstructured piecewise computations const double J_c0 = coordinate_dofs[0] * FE3_C0_D01_Q1[0][0][0] + coordinate_dofs[2] * FE3_C0_D01_Q1[0][0][1]; const double J_c3 = coordinate_dofs[1] * FE3_C0_D01_Q1[0][0][0] + coordinate_dofs[5] * FE3_C0_D01_Q1[0][0][1]; const double J_c1 = coordinate_dofs[0] * FE3_C0_D01_Q1[0][0][0] + coordinate_dofs[4] * FE3_C0_D01_Q1[0][0][1]; const double J_c2 = coordinate_dofs[1] * FE3_C0_D01_Q1[0][0][0] + coordinate_dofs[3] * FE3_C0_D01_Q1[0][0][1]; alignas(32) double sp[20]; sp[0] = J_c0 * J_c3; sp[1] = J_c1 * J_c2; sp[2] = sp[0] + -1 * sp[1]; sp[3] = J_c0 / sp[2]; sp[4] = -1 * J_c1 / sp[2]; sp[5] = sp[3] * sp[3]; sp[6] = sp[3] * sp[4]; sp[7] = sp[4] * sp[4]; sp[8] = J_c3 / sp[2]; sp[9] = -1 * J_c2 / sp[2]; sp[10] = sp[9] * sp[9]; sp[11] = sp[8] * sp[9]; sp[12] = sp[8] * sp[8]; sp[13] = sp[5] + sp[10]; sp[14] = sp[6] + sp[11]; sp[15] = sp[12] + sp[7]; sp[16] = fabs(sp[2]); sp[17] = sp[13] * sp[16]; sp[18] = sp[14] * sp[16]; sp[19] = sp[15] * sp[16]; // UFLACS block mode: preintegrated A[0] = 0.5 * sp[19] + 0.5 * sp[18] + 0.5 * sp[18] + 0.5 * sp[17]; A[1] = -0.5 * sp[19] + -0.5 * sp[18]; A[2] = -0.5 * sp[18] + -0.5 * sp[17]; A[3] = -0.5 * sp[19] + -0.5 * sp[18]; A[4] = 0.5 * sp[19]; A[5] = 0.5 * sp[18]; A[6] = -0.5 * sp[18] + -0.5 * sp[17]; A[7] = 0.5 * sp[18]; A[8] = 0.5 * sp[17]; } void tabulate_tensor_poissonL(double* restrict A, const double* w, const double* restrict coordinate_dofs, int cell_orientation) { // Precomputed values of basis functions and precomputations // FE* dimensions: [entities][points][dofs] // PI* dimensions: [entities][dofs][dofs] or [entities][dofs] // PM* dimensions: [entities][dofs][dofs] alignas(32) static const double FE4_C0_D01_Q1[1][1][2] = { { { -1.0, 1.0 } } }; // Unstructured piecewise computations const double J_c0 = coordinate_dofs[0] * FE4_C0_D01_Q1[0][0][0] + coordinate_dofs[2] * FE4_C0_D01_Q1[0][0][1]; const double J_c3 = coordinate_dofs[1] * FE4_C0_D01_Q1[0][0][0] + coordinate_dofs[5] * FE4_C0_D01_Q1[0][0][1]; const double J_c1 = coordinate_dofs[0] * FE4_C0_D01_Q1[0][0][0] + coordinate_dofs[4] * FE4_C0_D01_Q1[0][0][1]; const double J_c2 = coordinate_dofs[1] * FE4_C0_D01_Q1[0][0][0] + coordinate_dofs[3] * FE4_C0_D01_Q1[0][0][1]; alignas(32) double sp[4]; sp[0] = J_c0 * J_c3; sp[1] = J_c1 * J_c2; sp[2] = sp[0] + -1 * sp[1]; sp[3] = fabs(sp[2]); // UFLACS block mode: preintegrated A[0] = 0.1666666666666667 * sp[3]; A[1] = 0.1666666666666667 * sp[3]; A[2] = 0.1666666666666667 * sp[3]; } """) ffibuilder.cdef(""" void tabulate_tensor_poissonA(double* restrict A, const double* w, const double* restrict coordinate_dofs, int cell_orientation); void tabulate_tensor_poissonL(double* restrict A, const double* w, const double* restrict coordinate_dofs, int cell_orientation); """) ffibuilder.compile(verbose=True) MPI.barrier(mesh.mpi_comm()) from _cffi_kernelA import ffi, lib a = cpp.fem.Form([V._cpp_object, V._cpp_object]) ptrA = ffi.cast("intptr_t", ffi.addressof(lib, "tabulate_tensor_poissonA")) a.set_tabulate_cell(0, ptrA) L = cpp.fem.Form([V._cpp_object]) ptrL = ffi.cast("intptr_t", ffi.addressof(lib, "tabulate_tensor_poissonL")) L.set_tabulate_cell(0, ptrL) A = dolfin.fem.assemble(a) b = dolfin.fem.assemble(L) Anorm = A.norm(PETSc.NormType.FROBENIUS) bnorm = b.norm(PETSc.NormType.N2) assert (np.isclose(Anorm, 56.124860801609124)) assert (np.isclose(bnorm, 0.0739710713711999)) list_timings([TimingType.wall])
update(**vars()) t += dt tstep += 1 stop = save_solution(**vars()) if tstep % info_intv == 0 or stop: info_green("Time = {0:f}, timestep = {1:d}".format(t, tstep)) split_computing_time = timer.stop() split_num_tsteps = tstep - tstep_0 timer.start() tstep_0 = tstep total_computing_time += split_computing_time total_num_tsteps += split_num_tsteps info_cyan("Computing time for previous {0:d}" " timesteps: {1:f} seconds" " ({2:f} seconds/timestep)".format( split_num_tsteps, split_computing_time, split_computing_time / split_num_tsteps)) df.list_timings(df.TimingClear.clear, [df.TimingType.wall]) if total_num_tsteps > 0: info_cyan("Total computing time for all {0:d}" " timesteps: {1:f} seconds" " ({2:f} seconds/timestep)".format( total_num_tsteps, total_computing_time, total_computing_time / total_num_tsteps)) end_hook(**vars())
from dolfin import list_timings, TimingType, TimingClear comm = mpi4py.MPI.COMM_WORLD rank = comm.Get_rank() size = comm.Get_size() if rank == 0: lab = '\\ell={}, E={}, \\sigma_D = {}'.format( parameters['material']['ell'], parameters['material']['E'], parameters['material']['sigma_D0']) tc = (parameters['material']['sigma_D0']/parameters['material']['E'])**(.5) # tc = sqrt(2.)/2. ell = parameters['material']['ell'] fig1, ax1 =pp.plot_energy(parameters, data, tc) fig1.savefig(os.path.join(experiment, "energy.pdf"), bbox_inches='tight') (fig2, ax1, ax2) =pp.plot_spectrum(parameters, data, tc) plt.legend(loc='lower left') fig2.savefig(os.path.join(experiment, "spectrum.pdf"), bbox_inches='tight') list_timings(TimingClear.keep, [TimingType.wall, TimingType.system]) dump_timings_to_xml(os.path.join(experiment, "timings_avg_min_max.xml"), TimingClear.clear)
est = np.array(est, dtype='float') gs = gridspec.GridSpec(3, 2, width_ratios=[7, 1]) plt.subplot(gs[0]) plt.plot(dofs, est[:, 0], 'o-', label='est') plt.loglog() plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.subplot(gs[2]) plt.plot(dofs, est[:, 1], 'o-', label='est') plt.loglog() plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.subplot(gs[4]) plt.plot(dofs, est[:, 2], 'o-', label='est') plt.loglog() plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.) plt.tight_layout() mkdir_p(prefix) plt.savefig(prefix+'/convergence.pdf') if os.environ.get("DOLFIN_NOPLOT", "0") == "0": dolfin.info('Blocking matplotlib figure on rank 0. Close to continue...') plt.show() if os.environ.get("DOLFIN_NOPLOT", "0") == "0": dolfin.interactive() dolfin.list_timings(dolfin.TimingClear_keep, [dolfin.TimingType_wall])
pde_projection.solve_problem(psibar_h.cpp_object(), phi.cpp_object(), lambda_h.cpp_object(), 'mumps', 'default') del time gamma_assigner.assign(gamma0, phi) # Solve Stokes time = Timer("ZZZ Stokes assemble") ssc.assemble_global_system(True) del time time = Timer("ZZZ Stokes solve") for bc in bcs: ssc.apply_boundary(bc) ssc.solve_problem(Uhbar.cpp_object(), Uh.cpp_object(), "mumps", "default") del time velocity_assigner.assign(u_vec, Uh.sub(0)) output_data_step(append=True) # Output particles and composition field if float(t) > next_snap_shot_time: points_list = list(Point(*pp) for pp in ptcls.positions()) particles_values = ptcls.get_property(property_idx) XDMFFile(os.path.join(particles_directory, "step%.4d.xdmf" % (j+1))) \ .write(points_list, particles_values) XDMFFile("composition.xdmf").write_checkpoint(phi, "composition", float(t), append=True) next_snap_shot_time += time_snap_shot_interval list_timings(TimingClear.clear, [TimingType.wall])
update(**vars()) t += dt tstep += 1 stop = save_solution(**vars()) if tstep % info_intv == 0 or stop: info_green("Time = {0:f}, timestep = {1:d}".format(t, tstep)) split_computing_time = df.toc() split_num_tsteps = tstep-tstep_0 df.tic() tstep_0 = tstep total_computing_time += split_computing_time total_num_tsteps += split_num_tsteps info_cyan("Computing time for previous {0:d}" " timesteps: {1:f} seconds" " ({2:f} seconds/timestep)".format( split_num_tsteps, split_computing_time, split_computing_time/split_num_tsteps)) df.list_timings(df.TimingClear_clear, [df.TimingType_wall]) if total_num_tsteps > 0: info_cyan("Total computing time for all {0:d}" " timesteps: {1:f} seconds" " ({2:f} seconds/timestep)".format( total_num_tsteps, total_computing_time, total_computing_time/total_num_tsteps)) end_hook(**vars())
np.array([1, 2], dtype=np.uintp), theta_p, step) if step == 2: theta_L.assign(theta_next) # Probably can be combined into one file? xdmf_u.write(Uh.sub(0), t) xdmf_p.write(Uh.sub(1), t) del t1 timer.stop() # Compute errors u_exact.t = t p_exact.t = t u_error = sqrt(assemble(dot(Uh.sub(0) - u_exact, Uh.sub(0) - u_exact) * dx)) p_error = sqrt(assemble(dot(Uh.sub(1) - p_exact, Uh.sub(1) - p_exact) * dx)) udiv = sqrt(assemble(div(Uh.sub(0)) * div(Uh.sub(0)) * dx)) momentum = assemble((dot(Uh.sub(0), ex) + dot(Uh.sub(0), ey)) * dx) if comm.Get_rank() == 0: print("Velocity error " + str(u_error)) print("Pressure error " + str(p_error)) print("Momentum " + str(momentum)) print("Divergence " + str(udiv)) print("Elapsed time " + str(timer.elapsed()[0])) list_timings(TimingClear.keep, [TimingType.wall])