Ejemplo n.º 1
0
def test_2d(solver, write_file=False):
    n = 200
    np.random.seed(123)
    x0 = np.random.rand(n, 2) - 0.5
    # y0 = np.ones(n)
    # y0 = x0[:, 0]
    # y0 = x0[:, 0]**2
    # y0 = np.cos(np.pi*x0.T[0])
    # y0 = np.cos(np.pi*x0.T[0]) * np.cos(np.pi*x0.T[1])
    y0 = np.cos(np.pi * np.sqrt(x0.T[0]**2 + x0.T[1]**2))

    import meshzoo

    points, cells = meshzoo.rectangle(-1.0, 1.0, -1.0, 1.0, 32, 32)

    # import pygmsh
    # geom = pygmsh.built_in.Geometry()
    # geom.add_circle([0.0, 0.0, 0.0], 1.0, 0.1)
    # points, cells, _, _, _ = pygmsh.generate_mesh(geom)
    # cells = cells['triangle']

    u = smoothfit.fit(x0, y0, points, cells, lmbda=1.0e-5, solver=solver)

    # ref = 4.411_214_155_799_310_5
    # val = assemble(u * u * dx)
    # assert abs(val - ref) < 1.0e-10 * ref

    if write_file:
        from dolfin import XDMFFile

        xdmf = XDMFFile("temp.xdmf")
        xdmf.write(u)
Ejemplo n.º 2
0
    class SolutionFile(SolutionFile_Base):
        # DOLFIN 2018.1.0.dev added (throughout the developement cycle) an optional append
        # attribute to XDMFFile.write_checkpoint, which should be set to its non-default value,
        # thus breaking backwards compatibility
        append_attribute = XDMFFile.write_checkpoint.__doc__.find(
            "append: bool") > -1

        def __init__(self, directory, filename):
            SolutionFile_Base.__init__(self, directory, filename)
            self._visualization_file = XDMFFile(self._full_filename + ".xdmf")
            self._visualization_file.parameters["flush_output"] = True
            self._restart_file = XDMFFile(self._full_filename +
                                          "_checkpoint.xdmf")
            self._restart_file.parameters["flush_output"] = True

        @staticmethod
        def remove_files(directory, filename):
            SolutionFile_Base.remove_files(directory, filename)
            #
            full_filename = os.path.join(str(directory), filename)
            if is_io_process() and os.path.exists(full_filename + ".xdmf"):
                os.remove(full_filename + ".xdmf")
                os.remove(full_filename + ".h5")
                os.remove(full_filename + "_checkpoint.xdmf")
                os.remove(full_filename + "_checkpoint.h5")

        def write(self, function, name, index):
            assert index in (self._last_index, self._last_index + 1)
            if index == self._last_index + 1:  # writing out solutions after time stepping
                self._update_function_container(function)
                time = float(index)
                self._visualization_file.write(self._function_container, time)
                bak_log_level = get_log_level()
                set_log_level(int(WARNING) + 1)  # disable xdmf logs)
                if self.append_attribute:
                    self._restart_file.write_checkpoint(
                        self._function_container, name, time, append=True)
                else:
                    self._restart_file.write_checkpoint(
                        self._function_container, name, time)
                set_log_level(bak_log_level)
                # Once solutions have been written to file, update last written index
                self._write_last_index(index)
            elif index == self._last_index:
                # corner case for problems with two (or more) unknowns which are written separately to file;
                # one unknown was written to file, while the other was not: since the problem might be coupled,
                # a recomputation of both is required, but there is no need to update storage
                pass
            else:
                raise ValueError("Invalid index")

        def read(self, function, name, index):
            if index <= self._last_index:
                time = float(index)
                self._restart_file.read_checkpoint(function, name, index)
                self._update_function_container(function)
                self._visualization_file.write(self._function_container, time)
            else:
                raise OSError
Ejemplo n.º 3
0
class SolutionFileXDMF(SolutionFile_Base):
    # DOLFIN 2018.1.0.dev added (throughout the developement cycle) an optional append
    # attribute to XDMFFile.write_checkpoint, which should be set to its non-default value,
    # thus breaking backwards compatibility
    append_attribute = XDMFFile.write_checkpoint.__doc__.find("append: bool") > - 1
        
    def __init__(self, directory, filename):
        SolutionFile_Base.__init__(self, directory, filename)
        self._visualization_file = XDMFFile(self._full_filename + ".xdmf")
        self._visualization_file.parameters["flush_output"] = True
        self._restart_file = XDMFFile(self._full_filename + "_checkpoint.xdmf")
        self._restart_file.parameters["flush_output"] = True
            
    @staticmethod
    def remove_files(directory, filename):
        SolutionFile_Base.remove_files(directory, filename)
        #
        full_filename = os.path.join(str(directory), filename)
        def remove_files_task():
            if os.path.exists(full_filename + ".xdmf"):
                os.remove(full_filename + ".xdmf")
                os.remove(full_filename + ".h5")
                os.remove(full_filename + "_checkpoint.xdmf")
                os.remove(full_filename + "_checkpoint.h5")
        parallel_io(remove_files_task)
            
    def write(self, function, name, index):
        time = float(index)
        # Write visualization file (no append available, will overwrite)
        self._update_function_container(function)
        self._visualization_file.write(self._function_container, time)
        # Write restart file. It might be possible that the solution was written to file in a previous run
        # and the execution was interrupted before last written index was updated. In this corner case
        # there would be two functions corresponding to the same time, with two consecutive indices.
        # For now the inelegant way is to try to read: if that works, assume that we are in the corner case;
        # otherwise, we are in the standard case and we should write to file.
        try:
            self._restart_file.read_checkpoint(self._function_container, name, index)
        except RuntimeError:
            from dolfin.cpp.log import get_log_level, LogLevel, set_log_level
            self._update_function_container(function)
            bak_log_level = get_log_level()
            set_log_level(int(LogLevel.WARNING) + 1) # disable xdmf logs
            if self.append_attribute:
                self._restart_file.write_checkpoint(self._function_container, name, time, append=True)
            else:
                self._restart_file.write_checkpoint(self._function_container, name, time)
            set_log_level(bak_log_level)
            # Once solutions have been written to file, update last written index
        self._write_last_index(index)
            
    def read(self, function, name, index):
        if index <= self._last_index:
            time = float(index)
            self._restart_file.read_checkpoint(function, name, index)
            self._update_function_container(function)
            self._visualization_file.write(self._function_container, time) # because there is no append option available
        else:
            raise OSError
Ejemplo n.º 4
0
class XDMFWriter(object):
	def __init__(self, directory, file):
		self.outputFile = XDMFFile("{}/{}.xdmf".format(directory, file))
		self.outputFile.parameters["rewrite_function_mesh"] = False
		self.outputFile.parameters["functions_share_mesh"] = True

	def writeSingle(self, solution, time=0.0):
		self.outputFile.write(solution, time)

	def writeMultiple(self, solutionList, time=0.0):
		for solution in solutionList:
			self.outputFile.write(solution, time)

	def close(self):
		self.outputFile.close()
Ejemplo n.º 5
0
 def _write(self, filename, encoding=None):
     assert filename.endswith(".rtc.xml") or filename.endswith(".rtc.xdmf")
     # Create output folder
     try:
         os.makedirs(filename)
     except OSError:
         if not os.path.isdir(filename):
             raise
     # Write out MeshFunctions
     for (d, mesh_function_d) in enumerate(self):
         if filename.endswith(".rtc.xml"):
             File(filename + "/mesh_function_" + str(d) + ".xml") << mesh_function_d
         else:
             xdmf_file = XDMFFile(filename + "/mesh_function_" + str(d) + ".xdmf")
             if encoding is not None:
                 xdmf_file.write(mesh_function_d, encoding)
             else:
                 xdmf_file.write(mesh_function_d)
Ejemplo n.º 6
0
 def _update_xdmf_file(self, field_name, saveformat, data, timestep, t):
     "Update xdmf file with new data."
     assert isinstance(data, Function)
     assert saveformat == "xdmf"
     fullname, metadata = self._get_datafile_name(field_name, saveformat,
                                                  timestep)
     key = (field_name, saveformat)
     datafile = self._datafile_cache.get(key)
     if datafile is None:
         datafile = XDMFFile(mpi_comm_world(), fullname)
         datafile.parameters["rewrite_function_mesh"] = False
         datafile.parameters["flush_output"] = True
         self._datafile_cache[key] = datafile
     try:
         datafile.write(data, float(t))
     except:
         datafile << (data, float(t))
     return metadata
Ejemplo n.º 7
0
                t1 = Timer("[P] Solve projection")
                pde_projection.solve_problem(psibar_h, psi_h, "mumps",
                                             "default")
                del t1
            else:
                t1 = Timer("[P] Solve projection")
                lstsq_psi.project(psi_h)
                del t1

            t1 = Timer("[P] Update and store")
            # Update old solution
            assign(psi0_h, psi_h)

            # Store field
            if step % store_step == 0 or step == 1:
                output_field.write(psi_h, t)

            # Avoid getting accused of cheating, compute
            # L2 error and mass error at half rotation
            if int(np.floor(2 * step - num_steps)) == 0:
                psi0_expression.t = step * float(dt)
                l2_error_half = sqrt(
                    assemble(
                        dot(psi_h - psi0_expression, psi_h - psi0_expression) *
                        dx))
                area_half = assemble(psi_h * dx)
            del t1
        timer.stop()

        # Compute error (we should accurately recover initial condition)
        psi0_expression.t = step * float(dt)
# Set-up Stokes Solve
forms_stokes = FormsStokes(mesh, mixedL, mixedG, alpha,
                           ds=ds).forms_multiphase(rho, ustar, dt, rho * nu, f)
ssc = StokesStaticCondensation(mesh, forms_stokes['A_S'], forms_stokes['G_S'],
                               forms_stokes['B_S'], forms_stokes['Q_S'],
                               forms_stokes['S_S'])

# Loop and output
step = 0
t = 0.

# Store tstep 0
assign(rho, rho0)
xdmf_rho.write_checkpoint(rho, "rho", t)
xdmf_u.write(Uh.sub(0), t)
xdmf_p.write(Uh.sub(1), t)
p.dump2file(mesh, fname_list, property_list, 'wb')
comm.barrier()

# Save some data in txt files
nc = mesh.num_entities_global(2)
npt = p.number_of_particles()

with open(meta_data, "w") as write_file:
    write_file.write("%-12s %-12s %-15s %-20s %-15s %-15s \n" %
                     ("Time step", "Number of steps", "Number of cells",
                      "Number of particles", "Projection", "Solver"))
    write_file.write("%-12.5g %-15d %-15d %-20d %-15s %-15s \n" %
                     (float(dt), num_steps, nc, npt, projection_type, solver))
# Initialize advection class, use RK3 scheme
ap = advect_rk3(p, V, uh, 'closed')
# Init projection
lstsq_psi = l2projection(p, W, 1)

# Do projection to get initial field
lstsq_psi.project(psi_h.cpp_object(), lb, ub)
AD = AddDelete(p, 10, 20, [psi_h], [1], [lb, ub])

step = 0
t = 0.
area_0 = assemble(psi_h * dx)
timer = Timer()
timer.start()

outfile.write(psi_h, t)
while step < num_steps:
    step += 1
    t += float(dt)

    if comm.Get_rank() == 0:
        print("Step " + str(step))

    AD.do_sweep()
    ap.do_step(float(dt))
    AD.do_sweep_failsafe(4)

    lstsq_psi.project(psi_h.cpp_object(), lb, ub)

    if step % store_step == 0:
        outfile.write(psi_h, t)
        b = assemble(L)
        bc.apply(A, b)
        

        # Compute solution
        solver.solve(S.vector(), b)
        (u, U) = S.split(True)

        # Update previous time step
        update(u, u0, v0, a0, beta, gamma, dt)
        update(U, U0, V0, A0, beta, gamma, dt)

        #  time_array_x, time_array_y = time_to_pml_border(u_s_0, u0, time_array_x,time_array_y, t, Lx, Ly, n)
        # Save solution to XDMF file format
        
        xdmf_file.write(u, t)
        if record and rec_counter % 2 == 0:

            pvd << (u0,t)
        rec_counter += 1

        #s = p.linspace(0,Lx+2*Ly, n)
        #file_time = open('filename_time_to_pml.obj', 'w') 
        #pickle.dump([s,time_array_x,time_array_y], file_time)



  #plt.plot(s, time_array_x)
  #plt.plot(s, time_array_y)
  #plt.show()
  # Close file
Ejemplo n.º 11
0
    t += delta_t  # Update current time

    # Solve variational problem for time step
    solve(F == 0,
          u,
          solver_parameters={
              "newton_solver": {
                  "relative_tolerance": 1e-6
              },
              "newton_solver": {
                  "maximum_iterations": 60
              }
          })
    print('solver done')

    # Save solution to files for visualization and postprocessing(HDF5)
    _u_A, _u_B, _u_C, _u_T = u_n.split()

    _u_D = _u_C * 3

    if Writting_xdmf:
        xdmffile_A.write(_u_A, t)
        xdmffile_B.write(_u_B, t)
        xdmffile_C.write(_u_C, t)
        xdmffile_D.write(_u_D, t)
        xdmffile_T.write(_u_T, t)

    u_n.assign(u)

# _______________END_______________ #
Ejemplo n.º 12
0
    if MPI.size(MPI.comm_world) == 1:
        xdmu = XDMFFile("biot_" + discretization + "_u.xdmf")
        xdmp = XDMFFile("biot_" + discretization + "_p.xdmf")

        print("Discretization:", discretization)
        while t < T:
            t += dt
            print("\tsolving at time", t)
            AA = block_assemble(lhs)
            FF = block_assemble(rhs)
            bcs.apply(AA)
            bcs.apply(FF)
            block_solve(AA, w.block_vector(), FF, "mumps")
            block_assign(w0, w)
            xdmu.write(w[0], t)
            xdmp.write(w[1], t)

            u_con.assign(w[0])
            p_con.assign(w[1])
            mass = assemble(mass_con)
            print("\taverage mass residual: ", np.average(np.abs(mass[:])))

        if discretization == "DG":
            assert np.isclose(w[0].vector().norm("l2"), 0.019389822)
            assert np.isclose(w[1].vector().norm("l2"), 11778.77487)
        elif discretization == "EG":
            assert np.isclose(w[0].vector().norm("l2"), 0.019391447)
            # The assert on the norm of w[1] is missing because its value is not consistent across
            # runs on different machines. The field itself looks very similar to the DG one, though.
            # TODO Investigate further what the issue is (conditioning?).
Ejemplo n.º 13
0
ssc = StokesStaticCondensation(mesh, forms_stokes['A_S'], forms_stokes['G_S'],
                               forms_stokes['B_S'], forms_stokes['Q_S'],
                               forms_stokes['S_S'])

# Set pressure in upper left corner to zero
bc1 = DirichletBC(mixedG.sub(1), Constant(0), Corner(xmin, ymax), "pointwise")
bcs = [bc1]

lstsq_u = l2projection(p, W_2, 2)

# Loop and output
step = 0
t = 0.

# Store at step 0
xdmf_rho.write(rho0, t)
xdmf_u.write(Uh.sub(0), t)
xdmf_p.write(Uh.sub(1), t)

p.dump2file(mesh, fname_list, property_list, 'wb')

dump_list = [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]
with open(pressure_table, "wb") as PT:
    pickle.dump(dump_list, PT)

timer = Timer("[P] Total time consumed")
timer.start()

while step < num_steps:
    step += 1
    t += float(dt)
Ejemplo n.º 14
0
def forward(mu_expression,
            lmbda_expression,
            rho,
            Lx=10,
            Ly=10,
            t_end=1,
            omega_p=5,
            amplitude=5000,
            center=0,
            target=False):
    Lpml = Lx / 10
    #c_p = cp(mu.vector(), lmbda.vector(), rho)
    max_velocity = 200  #c_p.max()

    stable_hx = stable_dx(max_velocity, omega_p)
    nx = int(Lx / stable_hx) + 1
    #nx = max(nx, 60)
    ny = int(Ly * nx / Lx) + 1
    mesh = mesh_generator(Lx, Ly, Lpml, nx, ny)
    used_hx = Lx / nx
    dt = stable_dt(used_hx, max_velocity)
    cfl_ct = cfl_constant(max_velocity, dt, used_hx)
    print(used_hx, stable_hx)
    print(cfl_ct)
    #time.sleep(10)
    PE = FunctionSpace(mesh, "DG", 0)
    mu = interpolate(mu_expression, PE)
    lmbda = interpolate(lmbda_expression, PE)

    m = 2
    R = 10e-8
    t = 0.0
    gamma = 0.50
    beta = 0.25

    ff = MeshFunction("size_t", mesh, mesh.geometry().dim() - 1)
    Dirichlet(Lx, Ly, Lpml).mark(ff, 1)

    # Create function spaces
    VE = VectorElement("CG", mesh.ufl_cell(), 1, dim=2)
    TE = TensorElement("DG", mesh.ufl_cell(), 0, shape=(2, 2), symmetry=True)

    W = FunctionSpace(mesh, MixedElement([VE, TE]))
    F = FunctionSpace(mesh, "CG", 2)
    V = W.sub(0).collapse()
    M = W.sub(1).collapse()

    alpha_0 = Alpha_0(m, stable_hx, R, Lpml)
    alpha_1 = Alpha_1(alpha_0, Lx, Lpml, degree=2)
    alpha_2 = Alpha_2(alpha_0, Ly, Lpml, degree=2)

    beta_0 = Beta_0(m, max_velocity, R, Lpml)
    beta_1 = Beta_1(beta_0, Lx, Lpml, degree=2)
    beta_2 = Beta_2(beta_0, Ly, Lpml, degree=2)

    alpha_1 = interpolate(alpha_1, F)
    alpha_2 = interpolate(alpha_2, F)
    beta_1 = interpolate(beta_1, F)
    beta_2 = interpolate(beta_2, F)

    a_ = alpha_1 * alpha_2
    b_ = alpha_1 * beta_2 + alpha_2 * beta_1
    c_ = beta_1 * beta_2

    Lambda_e = as_tensor([[alpha_2, 0], [0, alpha_1]])
    Lambda_p = as_tensor([[beta_2, 0], [0, beta_1]])

    a_ = alpha_1 * alpha_2
    b_ = alpha_1 * beta_2 + alpha_2 * beta_1
    c_ = beta_1 * beta_2

    Lambda_e = as_tensor([[alpha_2, 0], [0, alpha_1]])
    Lambda_p = as_tensor([[beta_2, 0], [0, beta_1]])

    # Set up boundary condition
    bc = DirichletBC(W.sub(0), Constant(("0.0", "0.0")), ff, 1)

    # Create measure for the source term
    dx = Measure("dx", domain=mesh)
    ds = Measure("ds", domain=mesh, subdomain_data=ff)

    # Set up initial values
    u0 = Function(V)
    u0.set_allow_extrapolation(True)
    v0 = Function(V)
    a0 = Function(V)
    U0 = Function(M)
    V0 = Function(M)
    A0 = Function(M)

    # Test and trial functions
    (u, S) = TrialFunctions(W)
    (w, T) = TestFunctions(W)

    g = ModifiedRickerPulse(0, omega_p, amplitude, center)

    F = rho * inner(a_ * N_ddot(u, u0, a0, v0, dt, beta) \
        + b_ * N_dot(u, u0, v0, a0, dt, beta, gamma) + c_ * u, w) * dx \
        + inner(N_dot(S, U0, V0, A0, dt, beta, gamma).T * Lambda_e + S.T * Lambda_p, grad(w)) * dx \
        - inner(g, w) * ds \
        + inner(compliance(a_ * N_ddot(S, U0, A0, V0, dt, beta) + b_ * N_dot(S, U0, V0, A0, dt, beta, gamma) + c_ * S, u, mu, lmbda), T) * dx \
        - 0.5 * inner(grad(u) * Lambda_p + Lambda_p * grad(u).T + grad(N_dot(u, u0, v0, a0, dt, beta, gamma)) * Lambda_e \
        + Lambda_e * grad(N_dot(u, u0, v0, a0, dt, beta, gamma)).T, T) * dx \

    a, L = lhs(F), rhs(F)

    # Assemble rhs (once)
    A = assemble(a)

    # Create GMRES Krylov solver
    solver = KrylovSolver(A, "gmres")

    # Create solution function
    S = Function(W)

    if target:
        xdmffile_u = XDMFFile("inversion_temporal_file/target/u.xdmf")
        pvd = File("inversion_temporal_file/target/u.pvd")
        xdmffile_u.write(u0, t)
        timeseries_u = TimeSeries(
            "inversion_temporal_file/target/u_timeseries")
    else:
        xdmffile_u = XDMFFile("inversion_temporal_file/obs/u.xdmf")
        xdmffile_u.write(u0, t)
        timeseries_u = TimeSeries("inversion_temporal_file/obs/u_timeseries")

    rec_counter = 0

    while t < t_end - 0.5 * dt:
        t += float(dt)

        if rec_counter % 10 == 0:
            print(
                '\n\rtime: {:.3f} (Progress: {:.2f}%)'.format(
                    t, 100 * t / t_end), )

        g.t = t

        # Assemble rhs and apply boundary condition
        b = assemble(L)
        bc.apply(A, b)

        # Compute solution
        solver.solve(S.vector(), b)
        (u, U) = S.split(True)

        # Update previous time step
        update(u, u0, v0, a0, beta, gamma, dt)
        update(U, U0, V0, A0, beta, gamma, dt)

        xdmffile_u.write(u, t)
        pvd << (u, t)
        timeseries_u.store(u.vector(), t)

        energy = inner(u, u) * dx
        E = assemble(energy)
        print("E = ", E)
        print(u.vector().max())
Ejemplo n.º 15
0
    # Needed for particle advection
    assign(Udiv, Uh.sub(0))

    # Needed for constrained map
    assign(ubar0_a, Uhbar.sub(0))
    assign(u0_a, ustar)
    assign(duh00, duh0)
    assign(duh0, project(Uh.sub(0) - ustar, W_2))

    p.increment(Udiv.cpp_object(), ustar.cpp_object(),
                np.array([1, 2], dtype=np.uintp), theta_p, step)

    if step == 2:
        theta_L.assign(theta_next)

    xdmf_u.write(Uh.sub(0), t)
    xdmf_p.write(Uh.sub(1), t)

    # Compute vorticity
    curl_func.assign(project(curl(Uh.sub(0)), W_2))
    xdmf_curl.write(curl_func, t)

timer.stop()

# Compute errors
ex = as_vector((1.0, 0.0, 0.0))
ey = as_vector((0.0, 1.0, 0.0))
ez = as_vector((0.0, 0.0, 1.0))

momentum = assemble(
    (dot(Uh.sub(0), ex) + dot(Uh.sub(0), ey) + dot(Uh.sub(0), ez)) * dx)