예제 #1
0
def main(kf, description, multi_point, if_export=False):
    mesh_size = 0.045
    gb, domain = make_grid_bucket(mesh_size)
    # Assign parameters
    add_data(gb, domain, kf, mesh_size)

    # Choose discretization and define the solver
    if multi_point:
        solver = pp.MpfaMixedDim("flow")
    else:
        solver = pp.TpfaMixedDim("flow")

    # Discretize
    A, b = solver.matrix_rhs(gb)

    # Solve the linear system
    p = sps.linalg.spsolve(A, b)

    # Store the solution
    gb.add_node_props(["pressure"])
    solver.split(gb, "pressure", p)

    if if_export:
        save = pp.Exporter(gb, "fv", folder="fv_" + description)
        save.write_vtk(["pressure"])
예제 #2
0
    def test_uniform_flow_cart_2d_1d_simplex(self):
        # Unstructured simplex grid
        gb = setup_2d_1d(np.array([10, 10]), simplex_grid=True)

        # Python inverter is most efficient for small problems
        flux_discr = pp.TpfaMixedDim("flow")
        A, rhs = flux_discr.matrix_rhs(gb)
        p = np.linalg.solve(A.A, rhs)

        flux_discr.solver.split(gb, "pressure", p)

        self.assertTrue(check_pressures(gb))
예제 #3
0
    def test_two_cart_grids(self):
        """
        We set up the test case -----|---------
                                |    |        |
                                | g1 |    g2  |
                                |    |        |
                                -----|---------
        with a linear pressure increase from left to right
        """
        n = 2
        xmax = 3
        ymax = 1
        split = 2
        gb = self.generate_grids(n, xmax, ymax, split)
        tol = 1e-6
        for g, d in gb:
            d["param"] = pp.Parameters(g)
            left = g.face_centers[0] < tol
            right = g.face_centers[0] > xmax - tol
            dir_bc = left + right
            d["param"].set_bc("flow", pp.BoundaryCondition(g, dir_bc, "dir"))
            bc_val = np.zeros(g.num_faces)
            bc_val[left] = xmax
            bc_val[right] = 0
            d["param"].set_bc_val("flow", bc_val)

        flow_disc = pp.TpfaMixedDim()

        A, b = flow_disc.matrix_rhs(gb)

        x = sps.linalg.spsolve(A, b)

        flow_disc.split(gb, "pressure", x)

        # test pressure
        for g, d in gb:
            self.assertTrue(
                np.allclose(d["pressure"], xmax - g.cell_centers[0]))

        # test mortar solution
        for e, d_e in gb.edges():
            mg = d_e["mortar_grid"]
            g2, g1 = gb.nodes_of_edge(e)
            left_to_m = mg.left_to_mortar_avg()
            right_to_m = mg.right_to_mortar_avg()

            left_area = left_to_m * g1.face_areas
            right_area = right_to_m * g2.face_areas

            self.assertTrue(np.allclose(d_e["mortar_solution"] / left_area, 1))
            self.assertTrue(np.allclose(d_e["mortar_solution"] / right_area,
                                        1))
예제 #4
0
def solve_tpfa(gb, folder, return_only_matrix=False):

    # Choose and define the solvers and coupler
    solver_flow = pp.TpfaMixedDim("flow")
    A_flow, b_flow = solver_flow.matrix_rhs(gb)

    A = A_flow
    if return_only_matrix:
        return A, mortar_dof_size(A, gb, solver_flow)

    p = sps.linalg.spsolve(A, b_flow)
    solver_flow.split(gb, "pressure", p)

    save = Exporter(gb, "sol", folder=folder)
    save.write_vtk(["pressure"])
예제 #5
0
def solve_tpfa(gb, folder):

    # Choose and define the solvers and coupler
    logger.info('TPFA discretization')
    tic = time.time()
    solver_flow = pp.TpfaMixedDim("flow")
    A_flow, b_flow = solver_flow.matrix_rhs(gb)

    solver_source = pp.IntegralMixedDim("flow", [None])
    A_source, b_source = solver_source.matrix_rhs(gb)
    logger.info('Done. Elapsed time: ' + str(time.time() - tic))
    logger.info('Linear solver')
    tic = time.time()
    p = sps.linalg.spsolve(A_flow + A_source, b_flow + b_source)
    logger.info('Done. Elapsed time ' + str(time.time() - tic))
    solver_flow.split(gb, "pressure", p)
    pp.fvutils.compute_discharges(gb)

    export(gb, folder)
    sps_io.mmwrite(folder+"/matrix.mtx", A_flow)
예제 #6
0
    def solve(self, gb, analytic_p):
        flow_disc = pp.TpfaMixedDim()
        source_disc = pp.IntegralMixedDim(coupling=[None])

        _, src = source_disc.matrix_rhs(gb)

        A, b = flow_disc.matrix_rhs(gb)
        x = sps.linalg.spsolve(A, b + src)

        flow_disc.split(gb, "pressure", x)
        # test pressure
        for g, d in gb:
            ap, _, _ = analytic_p(g.cell_centers)
            self.assertTrue(np.max(np.abs(d["pressure"] - ap)) < 5e-2)

        # test mortar solution
        for e, d_e in gb.edges():
            mg = d_e["mortar_grid"]
            g2, g1 = gb.nodes_of_edge(e)
            try:
                left_to_m = mg.left_to_mortar_avg()
                right_to_m = mg.right_to_mortar_avg()
            except AttributeError:
                continue
            d1 = gb.node_props(g1)
            d2 = gb.node_props(g2)

            _, analytic_flux, _ = analytic_p(g1.face_centers)
            # the aperture is assumed constant
            a1 = np.max(d1["param"].aperture)
            left_flux = a1 * np.sum(analytic_flux * g1.face_normals[:2], 0)
            left_flux = left_to_m * (d1["bound_flux"] * left_flux)
            # right flux is negative lambda
            a2 = np.max(d2["param"].aperture)
            right_flux = a2 * np.sum(analytic_flux * g2.face_normals[:2], 0)
            right_flux = -right_to_m * (d2["bound_flux"] * right_flux)

            self.assertTrue(
                np.max(np.abs(d_e["mortar_solution"] - left_flux)) < 5e-2)
            self.assertTrue(
                np.max(np.abs(d_e["mortar_solution"] - right_flux)) < 5e-2)
예제 #7
0
    def test_tpfa_fluxes_2d_1d_left_right_dir_neu(self):
        """
        Grid: 2 x 2 cells in matrix + 2 cells in the fracture from left to right.
        Dirichlet + inflow + no-flow, conductive fracture.
        Tests pressure solution and fluxes.
        """
        f = np.array([[0, 1], [.5, .5]])
        gb = pp.meshing.cart_grid([f], [2, 2], **{'physdims': [1, 1]})
        gb.compute_geometry()
        gb.assign_node_ordering()

        tol = 1e-3
        solver = pp.TpfaMixedDim(physics='flow')
        gb.add_node_props(['param'])
        a = 1e-2
        for g, d in gb:
            param = pp.Parameters(g)

            a_dim = np.power(a, gb.dim_max() - g.dim)
            aperture = np.ones(g.num_cells) * a_dim
            param.set_aperture(aperture)

            p = pp.SecondOrderTensor(
                3,
                np.ones(g.num_cells) * np.power(1e-3, g.dim < gb.dim_max()))
            param.set_tensor('flow', p)
            bound_faces = g.tags['domain_boundary_faces'].nonzero()[0]
            bound_face_centers = g.face_centers[:, bound_faces]

            right = bound_face_centers[0, :] > 1 - tol
            left = bound_face_centers[0, :] < tol

            labels = np.array(['neu'] * bound_faces.size)
            labels[right] = ['dir']

            bc_val = np.zeros(g.num_faces)
            bc_dir = bound_faces[right]
            bc_neu = bound_faces[left]
            bc_val[bc_dir] = g.face_centers[0, bc_dir]
            bc_val[bc_neu] = -g.face_areas[bc_neu] * a_dim

            param.set_bc('flow', pp.BoundaryCondition(g, bound_faces, labels))
            param.set_bc_val('flow', bc_val)

            d['param'] = param

        gb.add_edge_props('param')
        for e, d in gb.edges():
            g_h = gb.nodes_of_edge(e)[1]
            d['param'] = pp.Parameters(g_h)

        A, rhs = solver.matrix_rhs(gb)
        p = sps.linalg.spsolve(A, rhs)
        solver.split(gb, "pressure", p)
        pp.fvutils.compute_discharges(gb)

        p_known = np.array([
            1.7574919, 1.25249747, 1.7574919, 1.25249747, 1.25250298,
            1.80993337
        ])

        # Known discharges
        d_0, d_1 = fluxes_2d_1d_left_right_dir_neu()

        rtol = 1e-6
        atol = rtol

        for _, d in gb:
            if d['node_number'] == 0:
                assert np.allclose(d['discharge'], d_0, rtol, atol)
            if d['node_number'] == 1:
                assert np.allclose(d['discharge'], d_1, rtol, atol)

        assert np.allclose(p, p_known, rtol, atol)
예제 #8
0
    def test_tpfa_fluxes_2d_1d_cross_with_elimination(self):
        f1 = np.array([[0, 1], [.5, .5]])
        f2 = np.array([[.5, .5], [0, 1]])

        gb = pp.meshing.cart_grid([f1, f2], [2, 2], **{'physdims': [1, 1]})
        gb.compute_geometry()
        gb.assign_node_ordering()

        # Enforce node orderning because of Python 3.5 and 2.7.
        # Don't do it in general.
        cell_centers_1 = np.array([[7.50000000e-01, 2.500000000e-01],
                                   [5.00000000e-01, 5.00000000e-01],
                                   [-5.55111512e-17, 5.55111512e-17]])
        cell_centers_2 = np.array([[5.00000000e-01, 5.00000000e-01],
                                   [7.50000000e-01, 2.500000000e-01],
                                   [-5.55111512e-17, 5.55111512e-17]])

        for g, d in gb:
            if g.dim == 1:
                if np.allclose(g.cell_centers, cell_centers_1):
                    d['node_number'] = 1
                elif np.allclose(g.cell_centers, cell_centers_2):
                    d['node_number'] = 2
                else:
                    raise ValueError('Grid not found')

        tol = 1e-3
        solver = pp.TpfaMixedDim('flow')
        gb.add_node_props(['param'])
        a = 1e-2
        for g, d in gb:
            param = pp.Parameters(g)

            a_dim = np.power(a, gb.dim_max() - g.dim)
            aperture = np.ones(g.num_cells) * a_dim
            param.set_aperture(aperture)

            kxx = np.ones(g.num_cells) * np.power(1e3, g.dim < gb.dim_max())
            p = pp.SecondOrderTensor(3, kxx, kyy=kxx, kzz=kxx)
            param.set_tensor('flow', p)

            bound_faces = g.tags['domain_boundary_faces'].nonzero()[0]
            if bound_faces.size != 0:
                bound_face_centers = g.face_centers[:, bound_faces]

                right = bound_face_centers[0, :] > 1 - tol
                left = bound_face_centers[0, :] < tol

                labels = np.array(['neu'] * bound_faces.size)
                labels[right] = ['dir']

                bc_val = np.zeros(g.num_faces)
                bc_dir = bound_faces[right]
                bc_neu = bound_faces[left]
                bc_val[bc_dir] = g.face_centers[0, bc_dir]
                bc_val[bc_neu] = -g.face_areas[bc_neu] * a_dim

                param.set_bc('flow',
                             pp.BoundaryCondition(g, bound_faces, labels))
                param.set_bc_val('flow', bc_val)
            else:
                param.set_bc("flow",
                             pp.BoundaryCondition(g, np.empty(0), np.empty(0)))
            d['param'] = param

        gb.add_edge_props('param')
        for e, d in gb.edges():
            g_h = gb.nodes_of_edge(e)[1]
            d['param'] = pp.Parameters(g_h)

        A, rhs = solver.matrix_rhs(gb)
        p = sps.linalg.spsolve(A, rhs)

        p = sps.linalg.spsolve(A, rhs)
        p_cond, p_red, _, _ = condensation.solve_static_condensation(A,
                                                                     rhs,
                                                                     gb,
                                                                     dim=0)

        solver.split(gb, "p_cond", p_cond)
        solver.split(gb, "pressure", p)

        # Make a copy of the grid bucket without the 0d grid
        dim_to_remove = 0
        gb_r, elimination_data = gb.duplicate_without_dimension(dim_to_remove)
        # Compute the flux discretization on the new edges
        condensation.compute_elimination_fluxes(gb, gb_r, elimination_data)
        # Compute the discharges from the flux discretizations and computed
        # pressures
        solver.split(gb_r, "pressure", p_red)
        pp.fvutils.compute_discharges(gb)
        pp.fvutils.compute_discharges(gb_r)

        # Known discharges
        d_0, d_1, d_2 = fluxes_2d_1d_cross_with_elimination()

        # Check node fluxes, ...
        rtol = 1e-6
        atol = rtol
        for g, d in gb:
            if d['node_number'] == 0:
                assert np.allclose(d['discharge'], d_0, rtol, atol)
            if d['node_number'] == 1:
                assert np.allclose(d['discharge'], d_1, rtol, atol)
            if d['node_number'] == 2:
                assert np.allclose(d['discharge'], d_2, rtol, atol)
        for g, d in gb_r:

            if d['node_number'] == 0:
                assert np.allclose(d['discharge'], d_0, rtol, atol)
            if d['node_number'] == 1:
                assert np.allclose(d['discharge'], d_1, rtol, atol)
            if d['node_number'] == 2:
                assert np.allclose(d['discharge'], d_2, rtol, atol)

        # ... edge fluxes ...
        d_01, d_10, d_02, d_20, d_13, d_23 \
            = coupling_fluxes_2d_1d_cross_no_el()

        for e, data in gb.edges():
            g1, g2 = gb.nodes_of_edge(e)
            pa = data['param']
            node_numbers = [gb.node_props(g, 'node_number') for g in [g2, g1]]
            if pa is not None:

                if node_numbers == (0, 1):
                    assert np.allclose(data['discharge'], d_01, rtol, atol) or \
                        np.allclose(data['discharge'], d_10, rtol, atol)
                if node_numbers == (0, 2):
                    assert np.allclose(data['discharge'], d_02, rtol, atol) or \
                        np.allclose(data['discharge'], d_20, rtol, atol)
                if node_numbers == (1, 3):
                    assert np.allclose(data['discharge'], d_13, rtol, atol)
                if node_numbers == (2, 3):
                    assert np.allclose(data['discharge'], d_23, rtol, atol)

        d_11, d_21, d_22 = coupling_fluxes_2d_1d_cross_with_el()
        for e, data in gb_r.edges():
            g1, g2 = gb_r.nodes_of_edge(e)
            pa = data['param']
            node_numbers = [
                gb_r.node_props(g, 'node_number') for g in [g2, g1]
            ]
            if pa is not None:

                if node_numbers == (0, 1):
                    assert np.allclose(data['discharge'], d_01, rtol, atol) or \
                        np.allclose(data['discharge'], d_10, rtol, atol)
                if node_numbers == (0, 2):
                    assert np.allclose(data['discharge'], d_02, rtol, atol) or \
                        np.allclose(data['discharge'], d_20, rtol, atol)
                if node_numbers == (1, 1):
                    assert np.allclose(data['discharge'], d_11, rtol, atol)
                if node_numbers == (2, 1):
                    assert np.allclose(data['discharge'], d_21, rtol, atol)
                if node_numbers == (2, 2):
                    assert np.allclose(data['discharge'], d_22, rtol, atol)
        # ... and pressures
        tol = 1e-10
        assert ((np.amax(np.absolute(p - p_cond))) < tol)
        assert (np.sum(
            pp.error.error_L2(g, d['pressure'], d['p_cond'])
            for g, d in gb) < tol)
예제 #9
0
    def atest_upwind_2d_1d_cross_with_elimination(self):
        """
        Simplest possible elimination scenario, one 0d-grid removed. Check on upwind
        matrix, rhs, solution and time step estimate. Full solution included
        (as comments) for comparison purposes if test breaks.
        """
        f1 = np.array([[0, 1], [.5, .5]])
        f2 = np.array([[.5, .5], [0, 1]])
        domain = {"xmin": 0, "ymin": 0, "xmax": 1, "ymax": 1}
        mesh_size = 0.4
        mesh_kwargs = {}
        mesh_kwargs["mesh_size"] = {
            "mode": "constant",
            "value": mesh_size,
            "bound_value": mesh_size,
        }
        gb = pp.meshing.cart_grid([f1, f2], [2, 2], **{"physdims": [1, 1]})
        # gb = pp.meshing.simplex_grid( [f1, f2],domain,**mesh_kwargs)
        gb.compute_geometry()
        gb.assign_node_ordering()

        # Enforce node orderning because of Python 3.5 and 2.7.
        # Don't do it in general.
        cell_centers_1 = np.array([
            [7.50000000e-01, 2.500000000e-01],
            [5.00000000e-01, 5.00000000e-01],
            [-5.55111512e-17, 5.55111512e-17],
        ])
        cell_centers_2 = np.array([
            [5.00000000e-01, 5.00000000e-01],
            [7.50000000e-01, 2.500000000e-01],
            [-5.55111512e-17, 5.55111512e-17],
        ])

        for g, d in gb:
            if g.dim == 1:
                if np.allclose(g.cell_centers, cell_centers_1):
                    d["node_number"] = 1
                elif np.allclose(g.cell_centers, cell_centers_2):
                    d["node_number"] = 2
                else:
                    raise ValueError("Grid not found")

        tol = 1e-3
        solver = pp.TpfaMixedDim()
        gb.add_node_props(["param"])
        a = 1e-2
        for g, d in gb:
            param = pp.Parameters(g)

            a_dim = np.power(a, gb.dim_max() - g.dim)
            aperture = np.ones(g.num_cells) * a_dim
            param.set_aperture(aperture)

            kxx = np.ones(g.num_cells) * np.power(1e3, g.dim < gb.dim_max())
            p = pp.SecondOrderTensor(3, kxx, kyy=kxx, kzz=kxx)
            param.set_tensor("flow", p)

            bound_faces = g.tags["domain_boundary_faces"].nonzero()[0]
            if bound_faces.size != 0:
                bound_face_centers = g.face_centers[:, bound_faces]

                right = bound_face_centers[0, :] > 1 - tol
                left = bound_face_centers[0, :] < tol

                labels = np.array(["neu"] * bound_faces.size)
                labels[right] = ["dir"]

                bc_val = np.zeros(g.num_faces)
                bc_dir = bound_faces[right]
                bc_neu = bound_faces[left]
                bc_val[bc_dir] = g.face_centers[0, bc_dir]
                bc_val[bc_neu] = -g.face_areas[bc_neu] * a_dim

                param.set_bc("flow",
                             pp.BoundaryCondition(g, bound_faces, labels))
                param.set_bc_val("flow", bc_val)
                # Transport
                bottom = bound_face_centers[1, :] < tol
                top = bound_face_centers[1, :] > 1 - tol

                labels = np.array(["neu"] * bound_faces.size)
                labels[np.logical_or(np.logical_or(left, right),
                                     np.logical_or(top, bottom))] = ["dir"]

                bc_val = np.zeros(g.num_faces)

                param.set_bc("transport",
                             pp.BoundaryCondition(g, bound_faces, labels))
                param.set_bc_val("transport", bc_val)
            else:
                param.set_bc("transport",
                             pp.BoundaryCondition(g, np.empty(0), np.empty(0)))
                param.set_bc("flow",
                             pp.BoundaryCondition(g, np.empty(0), np.empty(0)))
            # Transport:
            source = g.cell_volumes * a_dim
            param.set_source("transport", source)

            d["param"] = param

        gb.add_edge_props("param")
        for e, d in gb.edges():
            g_h = gb.nodes_of_edge(e)[1]
            d["param"] = pp.Parameters(g_h)

        A, rhs = solver.matrix_rhs(gb)
        # p = sps.linalg.spsolve(A,rhs)
        _, p_red, _, _ = condensation.solve_static_condensation(A,
                                                                rhs,
                                                                gb,
                                                                dim=0)
        dim_to_remove = 0
        gb_r, elimination_data = gb.duplicate_without_dimension(dim_to_remove)
        condensation.compute_elimination_fluxes(gb, gb_r, elimination_data)

        solver.split(gb_r, "pressure", p_red)

        # pp.fvutils.compute_discharges(gb)
        pp.fvutils.compute_discharges(gb_r)

        # ------Transport------#
        advection_discr = upwind.Upwind(physics="transport")
        advection_coupling_conditions = upwind.UpwindCoupling(advection_discr)
        advection_coupler = coupler.Coupler(advection_discr,
                                            advection_coupling_conditions)
        U_r, rhs_u_r = advection_coupler.matrix_rhs(gb_r)
        _, rhs_src_r = pp.IntegralMixedDim(
            physics="transport").matrix_rhs(gb_r)
        rhs_u_r = rhs_u_r + rhs_src_r
        deltaT = np.amin(
            gb_r.apply_function(advection_discr.cfl,
                                advection_coupling_conditions.cfl).data)

        theta_r = sps.linalg.spsolve(U_r, rhs_u_r)

        U_known, rhs_known, theta_known, deltaT_known = known_for_elimination()
        tol = 1e-7
        self.assertTrue(np.isclose(deltaT, deltaT_known, tol, tol))
        self.assertTrue((np.amax(np.absolute(U_r - U_known))) < tol)
        self.assertTrue((np.amax(np.absolute(rhs_u_r - rhs_known))) < tol)
        self.assertTrue((np.amax(np.absolute(theta_r - theta_known))) < tol)