Esempio n. 1
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())
    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)

    # Solving loop
    xdmf_file = XDMFFile(mesh.mpi_comm(), "output/elastodynamics.xdmf")

    if record:
        pvd  = File("paraview/{}.pvd".format(file_name))
        pvd << (u0, t)


    # =========== TIME TO PML =========== #
    #n = 100
    #u_s_0 = parametrized_initial_u_and_times(u0, Lx, Ly, n)
    #time_array_x = p.zeros(n)
    #time_array_y = p.zeros(n)

    # =================== EXPERIMEnT InFO ==================== #
    txt_file =  open(r"surface_2layers_animations_and_info/{}_info.txt".format(file_name),"w+") 
    if experiment != "12":
      info = ["t_end: {} [s]\n".format(t_end),"\n",
              "lambda_0: {}\n".format(l_0),"\n",
              "lambda_1: {}\n".format(l_1),"\n",
num_cells = 0
for i in range(MC.multimesh.num_parts()):
    num_cells += MC.multimesh.part(i).num_cells()

from dolfin import plot, File

perturbation = numpy.array([0, 1])
dJ = MC.eval_dJ(c1)
dJp = numpy.dot(dJ, perturbation)
J = MC.J

epsilon = [0.8 * 0.5**(i) for i in range(6)]
res_0 = []
res_1 = []
outputs = [
    File("output/taylor%d.pvd" % i) for i in range(MC.multimesh.num_parts())
]
for i in range(MC.multimesh.num_parts()):
    outputs[i] << MC.T.part(i)
for eps in epsilon:
    J_eps = MC.eval_J(c1 + eps * perturbation)
    res_0.append(numpy.abs(J_eps - J))
    res_1.append(numpy.abs(J_eps - J - eps * dJp))
    for i in range(MC.multimesh.num_parts()):
        outputs[i] << MC.T.part(i)

print("#Cells", num_cells)
print(' '.join('{:1.5e}'.format(k) for k in epsilon))
print(' '.join('{:1.5e}'.format(k) for k in res_0))
print(' '.join('{:1.5e}'.format(k) for k in res_1))
print(' '.join('{:1.5e}'.format(k) for k in convergence_rates(res_0, epsilon)))
Esempio n. 4
0
def fluent2xml(ifilename, ofilename):
    """Converting from ANSYS Fluent format (.msh) to FEniCS xml format
    The fluent mesh (the .msh file) is basically stored as a list of vertices, and then a 
    list of faces for each zone of the mesh, the interior and the boundaries."""

    # Use regular expressions to identify sections and tokens found in a fluent file
    re_dimline = re.compile(r"\(2\s(\d)\)")
    re_comment = re.compile(r"\(0\s.*")
    re_zone_init = re.compile(r"\(10\s\(0\s(\w+)\s(\w+)\s(\d+)\s(\d+)\)\)")
    re_zone = re.compile(r"\(10\s\((\w+)\s(\w+)\s(\w+)\s(\d+)\s(\d)\)(\(|)")
    re_face_init = re.compile(r"\(13(\s*)\(0\s+(\w+)\s+(\w+)\s+(0|0 0)\)\)")
    re_face = re.compile(
        r"\(13(\s*)\((\w+)\s+(\w+)\s+(\w+)\s+(\w+)\s+(\w+)\)(\s*)(\(|)")
    re_periodic = re.compile(r"\(18.*\((\w+)\s+(\w+)\s+(\w+)\s+(\w+)\).*\(")
    re_pfaces = re.compile(r"((^\s)|)(\w+)(\s*)(\w+)")
    re_cells_init = re.compile(
        r"\(12(\s*)\(0(\s+)(\w+)(\s+)(\w+)(\s+)(0|0 0)\)\)")
    re_cells = re.compile(r"\(12.*\((\w+)\s+(\w+)\s+(\w+)\s+(\d+)\s+(\d+)\)\)")
    re_cells2 = re.compile(
        r"\(12(\s*)\((\w+)\s+(\w+)\s+(\w+)\s+(\w+)\s+(\w+)\)(\s*)(\(|)")
    re_zones = re.compile(
        r"\((45|39)\s+\((\d+)\s+(\S+)\s+(\S+).*\)\((.*|[0-9]+[\.]*[0-9]*)\)\)")
    re_parthesis = re.compile(r"(^\s*\)(\s*)|^\s*\)\)(\s*)|^\s*\(\s*)")

    # Declare som maps that will be built when reading in the lists of vertices and faces:
    cell_map = {}  # Maps cell id with vertices
    boundary_cells = {
    }  # List of cells attached to a boundary facet. Key is zone id
    zones = {}  # zone information (not really used yet)

    def read_periodic(ifile, periodic_dx):
        """Scan past periodic section. Periodicity is computed by FEniCS."""
        while 1:
            line = ifile.readline()
            a = re.search(re_pfaces, line)
            if a:
                continue
            break

    def read_zone_vertices(dim, Nmin, Nmax, ifile, editor):
        """Scan ifile for vertices and add to mesh_editor."""
        # First line could be either just "(" or a regular vertex.
        # Check for initial paranthesis. If paranthesis then read a new line, else reset
        pos = ifile.tell()
        line = ifile.readline()
        if not re.search(re_parthesis, line):
            ifile.seek(pos)  # reset
        # read Nmax-Nmin vertices
        for i in range(Nmin, Nmax + 1):
            line = ifile.readline()
            vertex = [eval(x) for x in line.split()]
            if dim == 2:
                editor.add_vertex(i - Nmin, vertex[0], vertex[1])
            else:
                editor.add_vertex(i - Nmin, vertex[0], vertex[1], vertex[2])

    def read_faces(zone_id, Nmin, Nmax, bc_type, face, ifile):
        """Read all faces and create cell_map + boundary maps."""
        pos = ifile.tell()  # current position
        line = ifile.readline()
        if not re.search(
                re_parthesis, line
        ):  # check for initial paranthesis. If paranthesis then read a new line, else reset
            ifile.seek(pos)

        # read Nmax-Nmin faces
        for i in range(Nmin, Nmax + 1):
            line = ifile.readline()
            ln = line.split()
            if face == 0:
                nd = int(ln[0], 16)  # Number of vertices
                nds = [int(x, 16) for x in ln[1:(nd + 1)]]
                cells = [int(x, 16) for x in ln[(nd + 1):]]
            else:
                nd = face
                nds = [int(x, 16) for x in ln[:nd]]
                cells = [int(x, 16) for x in ln[nd:]]

            if min(cells) == 0:  # A boundary zone
                if zone_id in boundary_cells:
                    boundary_cells[zone_id][max(cells)] = array(nds)
                else:
                    boundary_cells[zone_id] = {max(cells): array(nds)}

            for c in cells:
                if c > 0:
                    if not c in cell_map:
                        cell_map[c] = copy(nds)
                    else:
                        cell_map[c] = list(Set(cell_map[c] + nds))

    def scan_fluent_mesh(ifile, mesh, editor):
        """Scan fluent mesh and generate maps."""
        dim = 0
        one = 0
        while 1:
            line = ifile.readline()
            if len(line) == 0:
                print 'Finished reading file\n'
                break

            if dim == 0:  # Dimension usually comes first
                a = re.search(re_dimline, line)
                if a:
                    print 'Reading dimensions\n'
                    dim = int(a.group(1))
                    editor.open(mesh, dim, dim)
                    continue

            if one == 0:  # The total number of vertices
                a = re.search(re_zone_init, line)
                if a:
                    print 'Reading zone info\n'
                    one, num_vertices, dummy1, dummy2 = int(a.group(1)), \
                        int(a.group(2), 16), int(a.group(3), 16), int(a.group(4))
                    editor.init_vertices(num_vertices)
                    continue

            a = re.search(re_zone, line)  # Vertices
            if a:
                zone_id, first_id, last_id = int(a.group(1), 16), \
                    int(a.group(2), 16), int(a.group(3), 16)
                print 'Reading ', last_id - first_id + 1, ' vertices in zone ', zone_id + 1, '\n'
                read_zone_vertices(dim, first_id, last_id, ifile, editor)
                continue

            a = re.search(re_zones, line)  # Zone info
            if a:
                print 'Reading zone info ', line
                dummy, zone_id, zone_type, zone_name, radius =  \
                        int(a.group(1)), int(a.group(2)),  a.group(3), \
                        a.group(4), a.group(5)
                zones[zone_id] = [zone_type, zone_name, radius]
                continue

            a = re.search(re_cells_init,
                          line)  # Get total number of cells/elements
            if a:
                print 'Reading cell info ', line
                first_id, tot_num_cells = int(a.group(3),
                                              16), int(a.group(5), 16)
                editor.init_cells(tot_num_cells)
                continue

            a = re.search(re_cells, line)  # Get the cell info.
            if a:
                zone_id, first_id, last_id, bc_type, element_type = \
                    int(a.group(1)), int(a.group(2), 16), int(a.group(3), 16), \
                    int(a.group(4), 16), int(a.group(5), 16)
                print 'Found ', last_id - first_id + 1, ' cells in zone ', zone_id, '\n'
                if last_id == 0:
                    raise TypeError("Zero elements!")
                continue

            a = re.search(re_cells2, line)  # Get the cell info.
            if a:
                raise TypeError(
                    "Wrong cell type. Can only handle one single cell type")

            a = re.search(re_face_init, line)
            if a:
                print 'Reading total number of faces\n', line
                continue

            a = re.search(re_face, line)
            if a:
                print 'Reading faces ', line
                zone_id, first_id, last_id, bc_type, face_type = \
                    int(a.group(2), 16), int(a.group(3), 16), int(a.group(4), 16), \
                    int(a.group(5), 16), int(a.group(6), 16)
                read_faces(zone_id, first_id, last_id, bc_type, face_type,
                           ifile)
                continue

            a = re.search(re_periodic, line)
            if a:
                print 'Scanning past periodic connectivity\n', line
                read_periodic(ifile, periodic_dx)
                continue

            if any([re.search(st, line) for st in (re_parthesis, re_comment)]) or \
                                                                not line.strip():
                continue

            # Should not make it here
            raise IOError('Something went wrong reading fluent mesh.')

    def write_fenics_file(ofile, mesh, editor):

        dim = mesh.geometry().dim()
        for i in range(1, len(cell_map) + 1):
            if dim == 2:
                editor.add_cell(i - 1, cell_map[i][0] - 1, cell_map[i][1] - 1,
                                cell_map[i][2] - 1)
            else:
                editor.add_cell(i - 1, cell_map[i][0] - 1, cell_map[i][1] - 1,
                                cell_map[i][2] - 1, cell_map[i][3] - 1)

        mesh.order()
        # Set MeshValueCollections from info in  boundary_cell
        #mvc = mesh.domains().markers(dim-1)
        md = mesh.domains()
        for zone, cells in boundary_cells.iteritems():
            for cell, nds in cells.iteritems():
                dolfin_cell = Cell(mesh, cell - 1)
                vertices_of_cell = dolfin_cell.entities(0)
                vertices_of_face = nds - 1
                for jj, ff in enumerate(facets(dolfin_cell)):
                    facet_vertices = ff.entities(0)
                    if all(map(lambda x: x in vertices_of_face,
                               facet_vertices)):
                        local_index = jj
                        break
                #mvc.set_value(cell-1, local_index, zone)
                md.set_marker((ff.index(), zone), dim - 1)

        ofile << mesh
        from dolfin import plot
        plot(mesh, interactive=True)
        print 'Finished writing FEniCS mesh\n'

    ifile = open(ifilename, "r")
    ofile = File(ofilename)
    mesh = Mesh()
    editor = MeshEditor()
    scan_fluent_mesh(ifile, mesh, editor)
    write_fenics_file(ofile, mesh, editor)
    ifile.close()
Esempio n. 5
0
        facet_f = MeshFunction('size_t', fine_mesh, 1, 0)
        facet_style_map = {0: 'very thin, black'}

        mesh_f = MeshFunction('size_t', fine_mesh, 2, 0)
        try:
            for child, parent in fine_mesh.parent_entity_map[
                    mesh.id()][2].items():
                mesh_f[child] = graph_colors[parent]
        except AttributeError:
            for child, parent in enumerate(fine_mesh.data().array(
                    'parent_cell', 2)):
                mesh_f[child] = graph_colors[parent]

        # TODO: put tikz here
        File('%s.pvd' % name) << mesh_f

        code = tikzify_2d_mesh(facet_f, facet_style_map, mesh_f,
                               cell_style_map)

        with open('%s.tex' % name, 'w') as out:
            out.write(code)

    # ---
    from dolfin import *

    mesh = UnitIntervalMesh(10)
    x = mesh.coordinates()
    for cell in cells(mesh):
        assert abs(simplex_area(x[cell.entities(0)]) - cell.volume()) < 1E-15
Esempio n. 6
0
def create_mesh():
    N = 20
    x0, y0, z0 = -1.5, -1.5, -0.25
    x1, y1, z1 = 1.5, 1.5, 0.25

    # mesh = UnitCubeMesh.create(N, N, N//2, CellType.Type.hexahedron)
    mesh = BoxMesh(Point(x0, y0, z0), Point(x1, y1, z1), N, N, N//2)
    # mesh = UnitCubeMesh(N, N, N)

    # mesh size is smaller near x=y=0
    # mesh.coordinates()[:, :2] = mesh.coordinates()[:, :2]**2
    # mesh size is smaller near z=0 and mapped to a [-1;0] domain along z
    # mesh.coordinates()[:, 2] = -mesh.coordinates()[:, 2]**2
    # left =  CompiledSubDomain("near(x[0], side) && on_boundary", side = 0.0)
    # right = CompiledSubDomain("near(x[0], side) && on_boundary", side = 1.0)
    class Top(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[2], z1) and on_boundary

    class Bottom(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[2], z0) and on_boundary

    class Left(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[0], x0) and on_boundary

    class Right(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[0], x1) and on_boundary

    class Front(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[1], y0) and on_boundary

    class Back(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[1], y1) and on_boundary

    class Symmetry_x(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[0], 0) and on_boundary

    class Symmetry_y(SubDomain):
        def inside(self, x, on_boundary):
            return near(x[1], 0) and on_boundary



    # exterior facets MeshFunction
    boundaries = MeshFunction("size_t", mesh, mesh.topology().dim()-1)
    boundaries.set_all(0)
    Top().mark(boundaries, 1)
    Bottom().mark(boundaries, 2)
    Left().mark(boundaries, 3)
    Right().mark(boundaries, 4)
    Front().mark(boundaries, 5)
    Back().mark(boundaries, 6)
    # Symmetry_x().mark(boundaries, 2)
    # Symmetry_y().mark(boundaries, 3)


    subdomains = MeshFunction("size_t", mesh, mesh.topology().dim())
    subdomains.set_all(0)
    File("hyperelastic_cube.xml") << mesh
    File("hyperelastic_cube_physical_region.xml") << subdomains
    File("hyperelastic_cube_facet_region.xml") << boundaries

    return (mesh, subdomains, boundaries)
Esempio n. 7
0
    # Output
    parser.add_argument('-output', type=str, help='Optional output', default='')
    # Save marking gunctions for checking
    save_parser = parser.add_mutually_exclusive_group(required=False)
    save_parser.add_argument('--save', dest='save', action='store_true')
    save_parser.add_argument('--no-save', dest='save', action='store_false')

    parser.set_defaults(save=True)
    # Remove Xml and stuff
    parser.add_argument('--cleanup', type=str, nargs='+',
                        help='extensions to delete', default=())
    args = parser.parse_args()

    # Protecting self
    assert not(set(('geo', '.geo')) & set(args.cleanup))
    

    if not args.output:
        args.output = '.'.join([os.path.splitext(args.input)[0], 'h5'])
    mesh = convert(args.input, args.output)

    if args.save:
        h5 = HDF5File(mpi_comm_world(), args.output, 'r')

        surfaces = MeshFunction('size_t', mesh, mesh.topology().dim()-1, 0)
        h5.read(surfaces, 'facet')

        File('results/%s_surf.pvd' % os.path.splitext(args.input)[0]) << surfaces

    cleanup(exts=args.cleanup)
    for cell in cells(mesh):
        mp = cell.midpoint()
        if mp.x() > 4.8e-3 and mp.x() < 10.2e-3:
            if abs(mp.y() - 10.0e-3) < 0.2e-3:
                refine_cells[cell] = True
            elif abs(mp.y() - 5.0e-3) < 0.2e-3:
                refine_cells[cell] = True
                
        if mp.y() > 4.8e-3 and mp.y() < 10.2e-3:
            if abs(mp.x() - 10.0e-3) < 0.2E-3:
                refine_cells[cell] = True
            elif abs(mp.x() - 5.0e-3) < 0.2e-3:
                refine_cells[cell] = True
                
    mesh = refine(mesh, refine_cells)
    File('mesh_refine.pvd') << mesh

def left_boundary(x, on_boundary):
    return on_boundary and near(x[0], 0.0)
def right_boundary(x, on_boundary):
    return on_boundary and near(x[0], 15.0e-3)
def bottom_boundary(x, on_boundary):
    return on_boundary and near(x[1], 0.0)
def top_boundary(x, on_boundary):
    return on_boundary and near(x[1], 15.0e-3) 

################################### FE part ###################################   
    
P1 = FiniteElement('P', 'triangle', 2)
element = MixedElement([P1, P1, P1])
ME = FunctionSpace(mesh, element)
Esempio n. 9
0
rcParams['text.usetex']=True
rcParams['font.size'] = 12
rcParams['font.family'] = 'serif'

Us = zeros((50,n))
betas = zeros((50,n))

fig,axs = subplots(2,1,sharex=True)
fig.set_size_inches(8,4)

bed_indices = model.mesh.coordinates()[:,2]==0
surface_indices = model.mesh.coordinates()[:,2]==1
prof_indices = model.mesh.coordinates()[:,1]==0.25

for ii in range(50):
    File('./results/run_'+str(ii)+'/U_opt.xml') >> U_opt
    File('./results/run_'+str(ii)+'/beta2_opt.xml') >> b_opt

    betas[ii] = b_opt.compute_vertex_values()
    us = U_opt.compute_vertex_values()
    Us[ii] = sqrt(us[:n]**2 + us[n:2*n]**2 + us[2*n:]**2)
betas = betas[:,bed_indices*prof_indices]
Us = Us[:,surface_indices*prof_indices]

profile = linspace(0,1,21)
axs[0].errorbar(profile,mean(Us,axis=0),yerr=std(Us,axis=0),fmt='k-', \
                linewidth=2.0)
axs[0].set_ylabel('Velocity')
axs[1].errorbar(profile,mean(betas,axis=0),yerr=std(betas,axis=0),fmt='k-', \
                linewidth=2.0)
axs[1].set_ylabel('\\beta^2')
Esempio n. 10
0
    h5_file = convert(args.input)

    # VTK visualize tags
    if args.save_pvd or args.mesh_size:
        h5 = HDF5File(mpi_comm_world(), h5_file, 'r')
        mesh = Mesh()
        h5.read(mesh, 'mesh', False)

        info('Mesh has %d cells' % mesh.num_cells())
        info('Mesh has %d vertices' % mesh.num_vertices())
        info('Box size %s' %
             (mesh.coordinates().max(axis=0) - mesh.coordinates().min(axis=0)))

        hmin, hmax = mesh.hmin(), mesh.hmax()
        info('Mesh has sizes %g %g' % (hmin, hmax))

        root = os.path.splitext(args.input)[0]
        tdim = mesh.topology().dim()

        data_sets = ('curves', 'surfaces', 'volumes')
        dims = (1, tdim - 1, tdim)
        for ds, dim in zip(data_sets, dims):
            if h5.has_dataset(ds):
                f = MeshFunction('size_t', mesh, dim, 0)
                h5.read(f, ds)

                if args.save_pvd:
                    File('%s_%s.pvd' % (root, ds)) << f

    cleanup(exts=args.cleanup)
Esempio n. 11
0
    def output_data(self):
        if "step" in self.inspection_params:
            modulo_base = self.inspection_params["step"]

            if self.solver_step % modulo_base == 0:
                if self.verbose > 0:
                    printiv(self.solver_step)
                    printiv(self.Qs)
                    printiv(self.probes_values)
                    printiv(self.drag)
                    printiv(self.lift)
                    printiv(self.recirc_area)

        if "dump" in self.inspection_params:
            modulo_base = self.inspection_params["dump"]

            #Sauvegarde du drag dans le csv a la fin de chaque episode
            self.episode_drags = np.append(self.episode_drags, [self.history_parameters["drag"].get()[-1]])
            self.episode_areas = np.append(self.episode_areas, [self.history_parameters["recirc_area"].get()[-1]])
            self.episode_lifts = np.append(self.episode_lifts, [self.history_parameters["lift"].get()[-1]])

            if(self.last_episode_number != self.episode_number and "single_run" in self.inspection_params and self.inspection_params["single_run"] == False):
                self.last_episode_number = self.episode_number
                avg_drag = np.average(self.episode_drags[len(self.episode_drags)//2:])
                avg_area = np.average(self.episode_areas[len(self.episode_areas)//2:])
                avg_lift = np.average(self.episode_lifts[len(self.episode_lifts)//2:])
                name = "output.csv"
                if(not os.path.exists("saved_models")):
                    os.mkdir("saved_models")
                if(not os.path.exists("saved_models/"+name)):
                    with open("saved_models/"+name, "w") as csv_file:
                        spam_writer=csv.writer(csv_file, delimiter=";", lineterminator="\n")
                        spam_writer.writerow(["Episode", "AvgDrag", "AvgLift", "AvgRecircArea"])
                        spam_writer.writerow([self.last_episode_number, avg_drag, avg_lift, avg_area])
                else:
                    with open("saved_models/"+name, "a") as csv_file:
                        spam_writer=csv.writer(csv_file, delimiter=";", lineterminator="\n")
                        spam_writer.writerow([self.last_episode_number, avg_drag, avg_lift, avg_area])
                self.episode_drags = np.array([])
                self.episode_areas = np.array([])
                self.episode_lifts = np.array([])

                if(os.path.exists("saved_models/output.csv")):
                    if(not os.path.exists("best_model")):
                        shutil.copytree("saved_models", "best_model")

                    else :
                        with open("saved_models/output.csv", 'r') as csvfile:
                            data = csv.reader(csvfile, delimiter = ';')
                            for row in data:
                                lastrow = row
                            last_iter = lastrow[1]

                        with open("best_model/output.csv", 'r') as csvfile:
                            data = csv.reader(csvfile, delimiter = ';')
                            for row in data:
                                lastrow = row
                            best_iter = lastrow[1]

                        if float(best_iter) < float(last_iter):
                            print("best_model updated")
                            if(os.path.exists("best_model")):
                                shutil.rmtree("best_model")
                            shutil.copytree("saved_models", "best_model")

            if self.solver_step % modulo_base == 0:

                if not self.initialized_output:
                    self.u_out = File('results/u_out.pvd')
                    self.p_out = File('results/p_out.pvd')
                    self.initialized_output = True

                if(not self.area_probe is None):
                    self.area_probe.dump(self.area_probe)
                self.u_out << self.flow.u_
                self.p_out << self.flow.p_
Esempio n. 12
0
        if d == MPI.min(mesh.mpi_comm(), d):
            v = regions[int(i)]
        else:
            v = 0

        v = MPI.max(mesh.mpi_comm(), v)
        mesh = create_submesh(mesh, regions, v)

    return mesh


if __name__ == '__main__':
    import mshr
    from dolfin import *
    set_log_level(100)
    domain = mshr.Sphere(Point(-1.0,0.0,0.0), 1.2)+mshr.Sphere(Point(1.0,0.0,0.0), 1.2)
    mesh = mshr.generate_mesh(domain, 30)
    p = np.array([1.0,1.0,0.0])

    n = np.array([0,1,0])

    slicemesh = create_slice(mesh, p, n, closest_region=False, crinkle_clip=True)

    plot(slicemesh)
    interactive()

    from dolfin import File

    File("basemesh.pvd") << mesh
    File("slice_mesh.xdmf") << slicemesh
    if comm.rank == 0:
        if not os.path.exists(outdir):
            os.makedirs(outdir)
        with open(output_table, "w") as write_file:
            write_file.write(
                "%-12s %-15s %-20s %-10s %-20s %-20s \n" %
                ("Time step", "Number of cells", "Number of particles",
                 "L2 error", "Global mass error", "Wall clock time"))

    for (nx, dt, pres, store_step) in zip(nx_list, dt_list, pres_list,
                                          storestep_list):
        if comm.Get_rank() == 0:
            print("Starting computation with grid resolution " + str(nx))

        output_field = File(outdir + 'psi_h' + '_nx' + str(nx) + '.pvd')

        # Compute num steps till completion
        num_steps = np.rint(Tend / float(dt))

        # Generate mesh
        mesh = RectangleMesh.create(
            [Point(xmin, ymin), Point(xmax, ymax)], [nx, nx],
            CellType.Type.triangle)

        # Velocity and initial condition
        V = VectorFunctionSpace(mesh, 'CG', 1)
        uh = Function(V)
        uh.assign(Expression((ux, vy), degree=1))

        psi0_expression = SineHump(center=[0.5, 0.5],
Esempio n. 14
0
c2 = numpy.array([-0.4, -0.15])
c3 = numpy.array([0.2, -0.4])
cable_positions = numpy.array([c1[0], c1[1], c2[0], c2[1], c3[0], c3[1]])
compute_angles(cable_positions)

scales = numpy.array([1, 1, 1])
sources = numpy.array([2, 0.5, 0.5])

from MultiCable import *
from IpoptMultiCableSolver import *

MC = MultiCable(scales, cable_positions, lmb_metal, lmb_insulation, lmb_air,
                sources)
from dolfin import plot, File
outputs = [
    File("output/isosceles%d.pvd" % i) for i in range(MC.multimesh.num_parts())
]
MC.eval_J(cable_positions)
for i in range(MC.multimesh.num_parts()):
    outputs[i] << MC.T.part(i)

opt = MultiCableOptimization(3, scales, MC.eval_J, MC.eval_dJ)
opt.nlp.int_option('max_iter', 35)
opt.nlp.num_option('tol', 1e-6)

opt_sol = opt.solve(cable_positions)
for i in range(MC.multimesh.num_parts() - 1):
    print("%.3e, %.3e" % (opt_sol[2 * i], opt_sol[2 * i + 1]))
compute_angles(opt_sol)
MC.eval_J(opt_sol)
Esempio n. 15
0
        'max_fun': 20,
        'objective_function': 'linear',
        'animate': False,
        'bounds': None,
        'control_variable': None,
        'regularization_type': 'Tikhonov'
    }
}

F = SteadySolver(model, config)
F.solve()

model.eps_reg = 1e-5
config['adjoint']['control_variable'] = [model.beta2]
config['adjoint']['bounds'] = [(0.0, 5000.0)]
File('results/beta2_obs.xml') << model.beta2
File('results/beta2_obs.pvd') << model.beta2

A = AdjointSolver(model, config)
u_o = model.u.vector().get_local()
v_o = model.v.vector().get_local()
U_e = 10.0

for i in range(50):
    model.beta2.vector()[:] = 1000.
    u_error = U_e * random.randn(len(u_o))
    v_error = U_e * random.randn(len(v_o))
    model.u_o.vector().set_local(u_o + u_error)
    model.v_o.vector().set_local(v_o + v_error)
    model.u_o.vector().apply('insert')
    model.v_o.vector().apply('insert')
Esempio n. 16
0
    # Remove layer
    tt = Timer('cleanup')
    ncells_x, ncells_y = args.m, args.n
    surfaces, volumes = deactivate_cells(surfaces, volumes, ncells_x, ncells_y)

    info('Removing boundary took %g s' % tt.stop())

    # Write 
    tt = Timer('write')
    # Completely new
    if not args.in_place:
        h5_file = ''.join(['_'.join([root, 'noBdry']), ext])

        h5 = HDF5File(get_comm_world(), h5_file, 'w')
        # FIXME: replacing
        h5.write(mesh, 'mesh')
        h5.write(surfaces, 'surfaces')
        h5.write(volumes, 'volumes')
        h5.close()
    else:
        import h5py
        
        assert False
            
    info('Writing new entity functions took %g s' % tt.stop())

    # Optional visualization
    if args.save_pvd:
        File('%s_nobdry_volumes.pvd' % root) << volumes
        File('%s_nobdry_surfaces.pvd' % root)  << surfaces
Esempio n. 17
0
    def report_results(self,
                       num_of_iterations,
                       mode_num,
                       supress_results=False):
        freqs, vecs = self.initial_solution(mode_number=mode_num)

        A, A1, A2, AO = self.calculate_volumes()

        r = freqs[0]
        r1 = freqs[1]
        r2 = freqs[2]
        print("Target Frequency:", sqrt(r))
        print("Initial Left Domain Frequency:", sqrt(r1))
        print("Initial Right Domain Frequency:", sqrt(r2))

        rx = vecs[0]
        rx1 = vecs[1]
        rx2 = vecs[2]

        self.build_transfer_matrices()

        u = Function(self.V)
        u.vector()[:] = self.adjustment * rx
        LL, HH, SS = self.big_error_norms(u, self.insides)

        L2, H1, _, u1, u2, r1, r2 = self.schwarz_algorithm(
            num_of_iterations, mode_num)

        print('Initial L2 Error:', np.sqrt(L2[0] / LL), 'Initial H1 Error:',
              np.sqrt(H1[0] / HH))

        for i in range(1, len(L2)):
            print('Iteration', i, 'L2 Error:', np.sqrt(L2[i] / LL),
                  'H1 Error:', np.sqrt(H1[i] / HH))

        if (supress_results == False):
            file = File('paraview.pvd')
            file << u
            file << u1
            file << u2

            uu1 = Function(self.V1)
            uu1.vector()[:] = rx1
            fig, ax = plt.subplots()
            c = plot(uu1)
            fig.colorbar(c)
            plt.savefig('initial_left.png')
            plt.cla()
            plt.clf()
            plt.close()

            uu2 = Function(self.V2)
            uu2.vector()[:] = rx2
            fig, ax = plt.subplots()
            c = plot(uu2)
            fig.colorbar(c)
            plt.savefig('initial_right.png')
            plt.cla()
            plt.clf()
            plt.close()

            fig, ax = plt.subplots()
            ax.plot(L2 / (LL * AO), label='L2 Error Norm (relative)')
            ax.plot(H1 / (HH * AO), label='H1 Error Norm (relative)')
            plt.grid(b=True, ls='-.')
            ax.legend(loc='upper right')
            ax.set_ylabel('Relative Error Norms per Volume', fontsize=18)
            ax.set_xlabel('Iteration Steps', fontsize=18)
            plt.savefig('error_norms.png')
            plt.cla()
            plt.clf()
            plt.close()

            fig, ax = plt.subplots()
            c = plot(u1)
            fig.colorbar(c)
            ax.set_title('Mode of Vibration on Left Domain')
            plt.savefig('final_left.png')
            plt.cla()
            plt.clf()
            plt.close()

            fig, ax = plt.subplots()
            c = plot(u2)
            fig.colorbar(c)
            ax.set_title('Mode of Vibration on Right Domain')
            plt.savefig('final_right.png')
            plt.cla()
            plt.clf()
            plt.close()

            fig, ax = plt.subplots()
            b = plot(u1)
            c = plot(u2)
            fig.colorbar(c)
            ax.set_title('Juxtaposition of Left and Right Domains')
            plt.savefig('composition.png')
            plt.cla()
            plt.clf()
            plt.close()

            fig, ax = plt.subplots()
            ax.plot(np.sqrt(abs((r1))), label='Left Domain Frequency')
            ax.plot((np.sqrt(abs(r2))), label='Right Domain Frequency')
            plt.grid(b=True)
            ax.axhline(y=np.sqrt(r), label='Target Frequency', color='r')
            ax.legend(loc='lower right')
            ax.set_ylabel(r'Natural Frequency $\omega _n$')
            ax.set_xlabel('Iteration Steps')
            plt.savefig('eigenvalues.png')
            plt.close()

            fig, ax = plt.subplots()
            d = plot(u)
            fig.colorbar(d)
            ax.set_title('Reference Mode of Vibration')
            plt.savefig('target.png')
            plt.close()

        return L2 / (LL * AO), H1 / (H1 * AO), L2, H1
Esempio n. 18
0
    u = df.Function(df.FunctionSpace(mesh, 'CG', 1))
    op = Average(u, line_mesh, sq)


    from scipy.spatial import Delaunay
    from dolfin import File
        
    surface = render_avg_surface(op)

    nodes = np.row_stack(surface)
    tri = Delaunay(nodes)

    cells = np.fromiter(tri.simplices.flatten(), dtype='uintp').reshape(tri.simplices.shape)
    
    bounded_volume = make_mesh(nodes, cells, tdim=2, gdim=3)
    File('foo.pvd') << bounded_volume
    
    # for points in surface
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
        
    for plane in surface:
        ax.plot3D(plane[:, 0], plane[:, 1], plane[:, 2], marker='o', linestyle='none')
        
    sq_integrate = lambda f, shape=sq, n=n, x0=x0: shape_integrate(f, shape, x0, n)

    # Sanity
    one = lambda x, y, z: 1
    assert is_close(sq_integrate(one), 1)
Esempio n. 19
0
    print(f"({x0}, {y0}, {z0}), ({x1}, {y1}, {z1})")
    return Box(Point(x0, y0, z0), Point(x1, y1, z1))


T = 32.0  # final time
num_steps = 160  # number of time steps
dt = T / num_steps  # time step size
alpha = 0.3  # parameter alpha
beta = 0.0625  # parameter beta
theta = 0.125  # parameter theta

set_log_active(True)
set_log_level(4)

msh_file = File('heat/slab_mesh.pvd')
sol_file = File('heat/slab_solution.pvd')

# Create mesh and define function space
# mesh = BoxMesh(Point(0., 0., 0.), Point(1., 0.1, 0.04), 60, 10, 5)
strap = createStrap(thickness=10)

meshing_domain = CSGCGALDomain3D(strap)
meshing_domain.remove_degenerate_facets(1e-12)
print(f"Meshing domain created")

gen = CSGCGALMeshGenerator3D()
# gen.parameters["facet_angle"] = 25.0
# gen.parameters["facet_size"] = 0.05
# gen.parameters["edge_size"] = 0.05
    def output_data(self):
        '''
        Extend arrays of episode drag,lift and recirculation
        If episode just ended, record avgs into saved_models/output.csv and empty episode lists
        Update best_model if improved
        Generate vtu files for area, u and p
        '''

        # Extend drag, lift and area histories
        self.episode_drags = np.append(self.episode_drags, [self.history_parameters["drag"].get()[-1]])
        self.episode_areas = np.append(self.episode_areas, [self.history_parameters["recirc_area"].get()[-1]])
        self.episode_lifts = np.append(self.episode_lifts, [self.history_parameters["lift"].get()[-1]])

        # If new episode (not single run), record avg qtys for last ep
        if(self.last_episode_number != self.episode_number and "single_run" in self.inspection_params and self.inspection_params["single_run"] == False):
            self.last_episode_number = self.episode_number  # Update last_episode_number, as now we will record the avgs for the last episode
            # Find avgs for the 2nd half of each ep
            avg_drag = np.average(self.episode_drags[len(self.episode_drags)//2:])
            avg_area = np.average(self.episode_areas[len(self.episode_areas)//2:])
            avg_lift = np.average(self.episode_lifts[len(self.episode_lifts)//2:])

            name = "output.csv"
            if(not os.path.exists("saved_models")):
                os.mkdir("saved_models")
            if(not os.path.exists("saved_models/"+name)):
                with open("saved_models/"+name, "w") as csv_file:
                    spam_writer=csv.writer(csv_file, delimiter=";", lineterminator="\n")
                    spam_writer.writerow(["Episode", "AvgDrag", "AvgLift", "AvgRecircArea"])
                    spam_writer.writerow([self.last_episode_number, avg_drag, avg_lift, avg_area])
            else:
                with open("saved_models/"+name, "a") as csv_file:
                    spam_writer=csv.writer(csv_file, delimiter=";", lineterminator="\n")
                    spam_writer.writerow([self.last_episode_number, avg_drag, avg_lift, avg_area])

            # Also write in Cylinder2DFlowControlWithRL folder (useful to have data of all episodes together in parallel runs)
            if(not os.path.exists("../episode_averages")):
                os.mkdir("../episode_averages")
            if(not os.path.exists("../episode_averages/"+name)):
                with open("../episode_averages/"+name, "w") as csv_file:
                    spam_writer=csv.writer(csv_file, delimiter=";", lineterminator="\n")
                    spam_writer.writerow(["Episode", "AvgDrag", "AvgLift", "AvgRecircArea"])
                    spam_writer.writerow([self.last_episode_number, avg_drag, avg_lift, avg_area])
            else:
                with open("../episode_averages/"+name, "a") as csv_file:
                    spam_writer=csv.writer(csv_file, delimiter=";", lineterminator="\n")
                    spam_writer.writerow([self.last_episode_number, avg_drag, avg_lift, avg_area])

            # Empty the episode lists for the new episode
            self.episode_drags = np.array([])
            self.episode_areas = np.array([])
            self.episode_lifts = np.array([])

            if(os.path.exists("saved_models/output.csv")):
                if(not os.path.exists("best_model")):
                    shutil.copytree("saved_models", "best_model")

                else :
                    with open("saved_models/output.csv", 'r') as csvfile:
                        data = csv.reader(csvfile, delimiter = ';')
                        for row in data:
                            lastrow = row
                        last_iter_drag = lastrow[1]  # get avg drag of last episode

                    with open("best_model/output.csv", 'r') as csvfile:
                        data = csv.reader(csvfile, delimiter = ';')
                        for row in data:
                            lastrow = row
                        best_iter_drag = lastrow[1]  # get avg drag of best episode in best_model/

                    # If last episode model is better than current best model, we replace the best model
                    if float(best_iter_drag) < float(last_iter_drag):
                        print("best_model updated")
                        if(os.path.exists("best_model")):
                            shutil.rmtree("best_model")
                        shutil.copytree("saved_models", "best_model")

        if "dump_vtu" in self.inspection_params and self.inspection_params["dump_vtu"] < 10000 and self.solver_step % self.inspection_params["dump_vtu"] == 0:

            if not self.initialized_vtu:  # Initialize results .pvd output if not done already
                self.u_out = File('results/u_out.pvd')
                self.p_out = File('results/p_out.pvd')
                self.initialized_vtu = True

            # Generate vtu files for area, drag and lift
            if(not self.area_probe is None):
                self.area_probe.dump(self.area_probe)
            self.u_out << self.flow.u_
            self.p_out << self.flow.p_
Esempio n. 21
0
# --------------------------------------------------------------------

if __name__ == '__main__':
    from dolfin import RectangleMesh, Point, File

    dx, dy = 0.5, 0.5

    meshes = []
    for j in range(3):
        for i in range(3):
            x0, y0 = dx * i, dy * j
            x1, y1 = x0 + dx, y0 + dy

            meshes.append(RectangleMesh(Point(x0, y0), Point(x1, y1), 4, 4))
    union = union_mesh(meshes)

    y = union.coordinates()
    for mesh in meshes:

        found = False
        for m_id, m_map in union.leafs:
            found = m_id == mesh.id()
            if found: break
        assert found

        x = mesh.coordinates()

        print m_id, np.linalg.norm(x - y[m_map])
    File('fff.pvd') << union
Esempio n. 22
0
                            deform=False,
                            generate_pbcs=True)

Q = model.Q
U_obs = project(dolfin.as_vector([Function(Q), Function(Q)]))
b_obs = Function(Q)
U_opt = project(as_vector([Function(Q), Function(Q), Function(Q)]))
b_opt = Function(Q)

rcParams['text.usetex'] = True
rcParams['font.size'] = 12
rcParams['font.family'] = 'serif'

for L in [10000]:

    File('./results/U_obs.xml') >> U_obs
    File('./results/U_opt.xml') >> U_opt
    File('./results/beta2_obs.xml') >> b_obs
    File('./results/beta2_opt.xml') >> b_opt

    U_b = zeros(100)
    U_p = zeros(100)
    b_b = zeros(100)
    b_p = zeros(100)
    profile = linspace(0, 1, 100)

    for ii, x in enumerate(profile):
        uu, vv = U_obs(x, 0.25, 0.99999)
        U_b[ii] = sqrt(uu**2 + vv**2)
        uu, vv, ww = U_opt(x, 0.25, 0.99999)
        U_p[ii] = sqrt(uu**2 + vv**2)
Esempio n. 23
0
    V = FunctionSpace(mesh, 'CG', 3)
    x = interpolate(Expression('x[0]', degree=1), V)
    y = interpolate(Expression('x[1]', degree=1), V)

    basis = []
    for i in range(deg):
        for j in range(deg):
            basis.append(Eval((x**i) * (y**j)))

    ip = lambda u, v: u.vector().inner(v.vector())
    #ip = lambda u, v: assemble(inner(u, v)*dx)
    #ip = lambda u, v: assemble(inner(u, v)*dx + inner(grad(u), grad(v))*dx)

    # NOTE: skipping 1 bacause Eval of it is not a Function
    energy, pod_basis = pod(basis[1:], ip=ip)

    out = File('pod_test.pvd')
    for i, f in enumerate(pod_basis):
        f.rename('f', '0')
        out << (f, float(i))

    with XDMFFile(mesh.mpi_comm(), 'pod_test.xdmf') as out:
        for i, f in enumerate(pod_basis):
            f.rename('f', '0')
            out.write(f, float(i))

    for fi in pod_basis:
        for fj in pod_basis:
            print ip(fi, fj)
        print
Esempio n. 24
0
                    MeshValueCollection, Constant, DirichletBC,
                    plot, TestFunctions, TrialFunctions,
                    inner, grad, dx, div, solve,
                    VectorFunctionSpace, BoundaryMesh, project,
                    Expression, dof_to_vertex_map,
                    vertex_to_dof_map, Vertex, Identity, tr,
                    Measure, TrialFunction, TestFunction, sym, ALE,
                    MeshEntity, SpatialCoordinate, as_vector, assemble,
                    set_log_level, LogLevel)
set_log_level(LogLevel.ERROR)
from IPython import embed
import numpy
from pdb import set_trace
from matplotlib.pyplot import show

sm_def = File("output/sm_deform.pvd")
class StokesSolver():
    def __init__(self, mesh, mf, bc_dict, move_dict):
        """
        Inititalize Stokes solver with a mesh, its corresponding facet function,
        a dictionary describing boundary conditions and 
        a dictionary describing which boundaries are fixed in the shape optimization setting
        """
        self.mesh = mesh
        self.backup = mesh.coordinates().copy()
        self.mf = mf
        V2 = VectorElement("CG", mesh.ufl_cell(), 2)
        S1 = FiniteElement("CG", mesh.ufl_cell(), 1)
        TH = V2 * S1
        self.VQ = FunctionSpace(self.mesh, TH)
        self.w = Function(self.VQ)
Esempio n. 25
0
            child2parent[fc] = pc
            fc += 1
        center += 1

    tdim = mesh.topology().dim()
    fine_mesh = make_mesh(np.row_stack([x, xnew]), fine_cells, tdim, mesh.geometry().dim())

    fine_mesh.set_parent(mesh)
    mesh.set_child(fine_mesh)

    fine_mesh.parent_entity_map = {mesh.id(): {0: dict(enumerate(range(mesh.num_vertices()))),
                                               tdim: dict(enumerate(child2parent))}}
       
    return fine_mesh

# --------------------------------------------------------------------

if __name__ == '__main__':
    from dolfin import UnitSquareMesh, File, MeshFunction
    
    mesh = UnitSquareMesh(2, 2)

    fine_mesh = cross_grid_refine(mesh)
    assert fine_mesh.has_parent()

    mesh_f = MeshFunction('size_t', fine_mesh, 2, 0)
    for child, parent in list(fine_mesh.parent_entity_map[mesh.id()][2].items()):
        mesh_f[child] = parent
    
    File('foo.pvd') << mesh_f
Esempio n. 26
0
           { 
             'alpha'              : None,
             'beta'               : None,
             'max_fun'            : None,
             'objective_function' : 'logarithmic',
             'animate'            : False
           }}

model = Model()
model.set_geometry(Surface(), Bed())

mesh      = MeshFactory.get_circle()
flat_mesh = MeshFactory.get_circle()
model.set_mesh(mesh, flat_mesh=flat_mesh, deform=True)

model.mesh.coordinates()[:,2] = model.mesh.coordinates()[:,2]/1000.0
model.set_parameters(IceParameters())
model.initialize_variables()

F = SteadySolver(model,config)
F.solve()

T = TransientSolver(model,config)
T.solve()

File('./results/u.xml') << model.u
File('./results/v.xml') << model.v
File('./results/w.xml') << model.w
File('./results/S.xml') << model.S
File('./results/T.xml') << model.T
Esempio n. 27
0
    assert convert(msh_file, h5_file, args.save_mvc)

    if args.save_pvd:
        h5 = HDF5File(mpi_comm_world(), h5_file, 'r')
        mesh = Mesh()
        h5.read(mesh, 'mesh', False)

        surfaces = MeshFunction('size_t', mesh, mesh.topology().dim()-1, 0)
        volumes = MeshFunction('size_t', mesh, mesh.topology().dim(), 0)

        if not args.save_mvc:
            h5.read(surfaces, 'surfaces')
            h5.read(volumes, 'volumes')
        # The data is mesh value collections
        else:
            from tiling_cpp import fill_mf_from_mvc

            surfaces_mvc = MeshValueCollection('size_t', mesh, mesh.topology().dim()-1)
            h5.read(surfaces_mvc, 'surfaces')
            fill_mf_from_mvc(surfaces_mvc, surfaces)

            volumes_mvc = MeshValueCollection('size_t', mesh, mesh.topology().dim())
            h5.read(volumes_mvc, 'volumes')
            fill_mf_from_mvc(volumes_mvc, volumes)

        File('results/%s_surf.pvd' % root) << surfaces
        File('results/%s_vols.pvd' % root) << volumes    

    cleanup(exts=args.cleanup)
Esempio n. 28
0
        data = load_data(tile, h5, args.cell_tags, cell_dim, data)

    t = Timer('tile')
    mesh, mesh_data = TileMesh(tile, shape, mesh_data=data)
    info('\nTiling took %g s; nvertices %d, ncells %d' % (t.stop(),
                                                          mesh.num_vertices(),
                                                          mesh.num_cells()))

    # Saving
    t = Timer('save')
    h5_file = '%s_%d_%d.h5' % (root, shape[0], shape[1])
        
    out = HDF5File(mesh.mpi_comm(), h5_file, 'w')
    out.write(mesh, 'mesh')
    
    tt = Timer('data')
    # To mesh functions
    if mesh_data:
        mfs = mf_from_data(mesh, mesh_data)

        for dim, name in (zip((facet_dim, cell_dim), (args.facet_tags, args.cell_tags))):
            if name:
                out.write(mfs[dim], name)
            
                if args.save_pvd:
                    File('%s_%d_%d_%s.pvd' % (root, shape[0], shape[1], name)) << mfs[dim]
                
    info('\t\tGetting data as MeshFoo took %g s' % tt.stop())
    
    info('\tSaving took %g' % t.stop())
Esempio n. 29
0
def main(module_name, ncases, params, petsc_params):
    '''
    Run the test case in module with ncases. Optionally store results
    in savedir. For some modules there are multiple (which) choices of 
    preconditioners.
    '''

    # Unpack
    for k, v in params.items():
        exec(k + '=v', locals())

    RED = '\033[1;37;31m%s\033[0m'
    print RED % ('\tRunning %s' % module_name)

    module = __import__(module_name)  # no importlib in python2.7

    # Setup the MMS case
    u_true, rhs_data = module.setup_mms(eps)

    # Setup the convergence monitor
    if log:
        params = [('solver', solver), ('precond', str(precond)),
                  ('eps', str(eps))]

        path = '_'.join([module_name] + ['%s=%s' % pv for pv in params])
        path = os.path.join(save_dir if save_dir else '.', path)
        path = '.'.join([path, 'txt'])
    else:
        path = ''

    memory, residuals = [], []
    monitor = module.setup_error_monitor(u_true, memory, path=path)

    # Sometimes it is usedful to transform the solution before computing
    # the error. e.g. consider subdomains
    if hasattr(module, 'setup_transform'):
        # NOTE: transform take two args for case and the current computed
        # solution
        transform = module.setup_transform
    else:
        transform = lambda i, x: x

    print '=' * 79
    print '\t\t\tProblem eps = %g' % eps
    print '=' * 79
    for i in ncases:
        a, L, W = module.setup_problem(i, rhs_data, eps=eps)

        # Assemble blocks
        t = Timer('assembly')
        t.start()
        AA, bb = map(ii_assemble, (a, L))
        print '\tAssembled blocks in %g s' % t.stop()

        wh = ii_Function(W)

        if solver == 'direct':
            # Turn into a (monolithic) PETScMatrix/Vector
            t = Timer('conversion')
            t.start()
            AAm, bbm = map(ii_convert, (AA, bb))
            print '\tConversion to PETScMatrix/Vector took %g s' % t.stop()

            t = Timer('solve')
            t.start()
            LUSolver('umfpack').solve(AAm, wh.vector(), bbm)
            print '\tSolver took %g s' % t.stop()

            niters = 1
        else:
            # Here we define a Krylov solver using PETSc
            BB = module.setup_preconditioner(W, precond, eps=eps)
            ## AA and BB as block_mat
            ksp = PETSc.KSP().create()

            # Default is minres
            if '-ksp_type' not in petsc_params:
                petsc_params['-ksp_type'] = 'minres'

            opts = PETSc.Options()
            for key, value in petsc_params.iteritems():
                opts.setValue(key, None if value == 'none' else value)

            ksp.setOperators(ii_PETScOperator(AA))

            ksp.setNormType(PETSc.KSP.NormType.NORM_PRECONDITIONED)
            # ksp.setTolerances(rtol=1E-6, atol=None, divtol=None, max_it=300)
            ksp.setConvergenceHistory()
            # We attach the wrapped preconditioner defined by the module
            ksp.setPC(ii_PETScPreconditioner(BB, ksp))

            ksp.setFromOptions()

            print ksp.getTolerances()

            # Want the iterations to start from random
            wh.block_vec().randomize()
            # Solve, note the past object must be PETSc.Vec
            t = Timer('solve')
            t.start()
            ksp.solve(as_petsc_nest(bb), wh.petsc_vec())
            print '\tSolver took %g s' % t.stop()

            niters = ksp.getIterationNumber()

            residuals.append(ksp.getConvergenceHistory())

        # Let's check the final size of the residual
        r_norm = (bb - AA * wh.block_vec()).norm()

        # Convergence?
        monitor.send((transform(i, wh), niters, r_norm))

    # Only send the final
    if save_dir:
        path = os.path.join(save_dir, module_name)
        for i, wh_i in enumerate(wh):
            # Renaming to make it easier to save state in Visit/Pareview
            wh_i.rename('u', str(i))

            File('%s_%d.pvd' % (path, i)) << wh_i

    # Plot relative residual norm
    if plot:
        plt.figure()
        [
            plt.semilogy(res / res[0], label=str(i))
            for i, res in enumerate(residuals, 1)
        ]
        plt.legend(loc='best')
        plt.show()
Esempio n. 30
0
            f.write(options)  # Options and alpha go as comments
            f.write('# %s\n' % alpha_str)

        print RED % (header % str(alpha))

        wh, mms_data = analyze(module, (args.case0, args.ncases), alpha, args.norm, logfile)

        if args.plot:
            out = './plots/wh_%s_%s' % (problem, alpha_str)
            out = '_'.join([out, '%dsub.pvd'])
            out = os.path.join(savedir, out)

            eout = './plots/w_%s_%s' % (problem, alpha_str)
            eout = '_'.join([eout, '%dsub.pvd'])
            eout = os.path.join(savedir, eout)

            mesh = wh[0].function_space().mesh()
            facet_f = MeshFunction('size_t', mesh, mesh.topology().dim()-1, 0)
            CompiledSubDomain('near(x[0], 0)').mark(facet_f, 1)
            CompiledSubDomain('near(x[1], 0)').mark(facet_f, 2)
            CompiledSubDomain('near(x[0], 1)').mark(facet_f, 3)
            CompiledSubDomain('near(x[1], 1)').mark(facet_f, 4)

            ds_ = Measure('ds', domain=mesh, subdomain_data=facet_f)
            n = FacetNormal(mesh)
            for i, (whi, whi_true) in enumerate(zip(wh, mms_data.solution)):
                whi.rename('f', '0')
                #whi.vector().zero()
                
                File(out % i) << whi