Beispiel #1
0
 def test_determine_eta(self):
     g = simplex.StructuredTriangleGrid([1, 1])
     self.assertTrue(fvutils.determine_eta(g) == 1 / 3)
     g = structured.CartGrid([1, 1])
     self.assertTrue(fvutils.determine_eta(g) == 0)
Beispiel #2
0
def _mpfa_local(g,
                k,
                bnd,
                eta=None,
                inverter="numba",
                apertures=None,
                robin_weight=None):
    """
    Actual implementation of the MPFA O-method. To calculate MPFA on a grid
    directly, either call this method, or, to respect the privacy of this
    method, the main mpfa method with no memory constraints.

    Method properties and implementation details.
    The pressure is discretized as a linear function on sub-cells (see
    reference paper). In this implementation, the pressure is represented by
    its cell center value and the sub-cell gradients (this is in contrast to
    most papers, which use auxiliary pressures on the faces; the current
    formulation is equivalent, but somewhat easier to implement).
    The method will give continuous fluxes over the faces, and pressure
    continuity for certain points (controlled by the parameter eta). This can
    be expressed as a linear system on the form
        (i)    A * grad_p              = 0
        (ii)   Ar * grad_p + Cr * P_cc = 0
        (iii)  B * grad_p + C * p_cc   = 0
        (iv)   0            D * p_cc   = I
    Here, the first equation represents flux continuity, and involves only the
    pressure gradients (grad_p). The second equation gives the Robin conditions,
    relating flux to the pressure. The third equation gives pressure continuity
    over cell faces, thus B will contain distances between cell centers and the
    face continuity points, while C consists of +- 1 (depending on which side
    the cell is relative to the face normal vector). The fourth equation
    enforces the pressure to be unity in one cell at a time. Thus (i)-(iv) can
    be inverted to express the pressure gradients as in terms of the cell
    center variables, that is, we can compute the basis functions on the
    sub-cells. Because of the method construction (again see reference paper),
    the basis function of a cell c will be non-zero on all sub-cells sharing
    a vertex with c. Finally, the fluxes as functions of cell center values are
    computed by insertion into Darcy's law (which is essentially half of A from
    (i), that is, only consider contribution from one side of the face.
    Boundary values can be incorporated with appropriate modifications -
    Neumann conditions will have a non-zero right hand side for (i), while
    Dirichlet gives a right hand side for (iii).

    """
    if eta is None:
        eta = fvutils.determine_eta(g)

    # The method reduces to the more efficient TPFA in one dimension, so that
    # method may be called. In 0D, there is no internal discretization to be
    # done.
    if g.dim == 1:
        discr = tpfa.Tpfa()
        params = data.Parameters(g)
        params.set_bc("flow", bnd)
        params.set_aperture(apertures)
        params.set_tensor("flow", k)
        d = {"param": params}
        discr.discretize(g, d)
        return (
            d["flux"],
            d["bound_flux"],
            d["bound_pressure_cell"],
            d["bound_pressure_face"],
        )
    elif g.dim == 0:
        return sps.csr_matrix([0]), 0, 0, 0

    if robin_weight is None:
        if np.sum(bnd.is_rob) != 0:
            raise ValueError(
                "If applying Robin conditions you must supply an robin_weight")
        else:
            robin_weight = 1
    # The grid coordinates are always three-dimensional, even if the grid is
    # really 2D. This means that there is not a 1-1 relation between the number
    # of coordinates of a point / vector and the real dimension. This again
    # violates some assumptions tacitly made in the discretization (in
    # particular that the number of faces of a cell that meets in a vertex
    # equals the grid dimension, and that this can be used to construct an
    # index of local variables in the discretization). These issues should be
    # possible to overcome, but for the moment, we simply force 2D grids to be
    # proper 2D.

    if g.dim == 2:
        # Rotate the grid into the xy plane and delete third dimension. First
        # make a copy to avoid alterations to the input grid
        g = g.copy()
        cell_centers, face_normals, face_centers, R, _, nodes = cg.map_grid(g)
        g.cell_centers = cell_centers
        g.face_normals = face_normals
        g.face_centers = face_centers
        g.nodes = nodes

        # Rotate the permeability tensor and delete last dimension
        k = k.copy()
        k.perm = np.tensordot(R.T, np.tensordot(R, k.perm, (1, 0)), (0, 1))
        k.perm = np.delete(k.perm, (2), axis=0)
        k.perm = np.delete(k.perm, (2), axis=1)

    # Define subcell topology, that is, the local numbering of faces, subfaces,
    # sub-cells and nodes. This numbering is used throughout the
    # discretization.
    subcell_topology = fvutils.SubcellTopology(g)

    # Obtain normal_vector * k, pairings of cells and nodes (which together
    # uniquely define sub-cells, and thus index for gradients. See comment
    # below for the ordering of elements in the subcell gradient.
    nk_grad_all, cell_node_blocks, sub_cell_index = _tensor_vector_prod(
        g, k, subcell_topology, apertures)

    # Distance from cell centers to face centers, this will be the
    # contribution from gradient unknown to equations for pressure continuity
    pr_cont_grad_all = fvutils.compute_dist_face_cell(g, subcell_topology, eta)

    # Darcy's law
    darcy = -nk_grad_all[subcell_topology.unique_subfno]

    # Pair fluxes over subfaces, that is, enforce conservation
    nk_grad_all = subcell_topology.pair_over_subfaces(nk_grad_all)

    # Contribution from cell center potentials to local systems
    # For pressure continuity, +-1 (Depending on whether the cell is on the
    # positive or negative side of the face.
    # The .A suffix is necessary to get a numpy array, instead of a scipy
    # matrix.
    sgn = g.cell_faces[subcell_topology.fno, subcell_topology.cno].A
    pr_cont_cell_all = sps.coo_matrix(
        (sgn[0], (subcell_topology.subfno, subcell_topology.cno))).tocsr()
    # The cell centers give zero contribution to flux continuity
    nk_cell = sps.coo_matrix(
        (np.zeros(1), (np.zeros(1), np.zeros(1))),
        shape=(subcell_topology.num_subfno, subcell_topology.num_cno),
    ).tocsr()

    # For the Robin condition the distance from the cell centers to face centers
    # will be the contribution from the gradients. We integrate over the subface
    # and multiply by the area
    num_nodes = np.diff(g.face_nodes.indptr)
    sgn = g.cell_faces[subcell_topology.fno_unique,
                       subcell_topology.cno_unique].A
    scaled_sgn = (robin_weight * sgn[0] *
                  g.face_areas[subcell_topology.fno_unique] /
                  num_nodes[subcell_topology.fno_unique])
    # pair_over_subfaces flips the sign so we flip it back
    pr_trace_grad_all = sps.diags(scaled_sgn) * pr_cont_grad_all
    pr_trace_cell_all = sps.coo_matrix((
        robin_weight * g.face_areas[subcell_topology.fno] /
        num_nodes[subcell_topology.fno],
        (subcell_topology.subfno, subcell_topology.cno),
    )).tocsr()

    del sgn, scaled_sgn

    # Mapping from sub-faces to faces
    hf2f = sps.coo_matrix((
        np.ones(subcell_topology.unique_subfno.size),
        (subcell_topology.fno_unique, subcell_topology.subfno_unique),
    ))

    # Update signs
    sgn_unique = g.cell_faces[subcell_topology.fno_unique,
                              subcell_topology.cno_unique].A.ravel("F")

    # The boundary faces will have either a Dirichlet or Neumann condition, but
    # not both (Robin is not implemented).
    # Obtain mappings to exclude boundary faces.
    bound_exclusion = fvutils.ExcludeBoundaries(subcell_topology, bnd, g.dim)

    # No flux conditions for Dirichlet boundary faces
    nk_grad_n = bound_exclusion.exclude_robin_dirichlet(nk_grad_all)
    nk_cell = bound_exclusion.exclude_robin_dirichlet(nk_cell)

    # Robin condition is only applied to Robin boundary faces
    nk_grad_r = bound_exclusion.keep_robin(nk_grad_all)
    pr_trace_grad = bound_exclusion.keep_robin(pr_trace_grad_all)
    pr_trace_cell = bound_exclusion.keep_robin(pr_trace_cell_all)

    del nk_grad_all
    # No pressure condition for Neumann or Robin boundary faces
    pr_cont_grad = bound_exclusion.exclude_neumann_robin(pr_cont_grad_all)
    pr_cont_cell = bound_exclusion.exclude_neumann_robin(pr_cont_cell_all)

    # So far, the local numbering has been based on the numbering scheme
    # implemented in SubcellTopology (which treats one cell at a time). For
    # efficient inversion (below), it is desirable to get the system over to a
    # block-diagonal structure, with one block centered around each vertex.
    # Obtain the necessary mappings.

    rows2blk_diag, cols2blk_diag, size_of_blocks = _block_diagonal_structure(
        sub_cell_index, cell_node_blocks, subcell_topology.nno_unique,
        bound_exclusion)

    del cell_node_blocks, sub_cell_index

    # System of equations for the subcell gradient variables. On block diagonal
    # form.
    # NOTE: I think in the discretization for sub_cells a flow out of the cell is
    # negative. This is a contradiction to what is done for the boundary conditions
    # where we want to set dot(n, flux) where n is the normal pointing outwards.
    # thats why we need +nk_grad_r - pr_trace_grad -pr_trace_cell instead of = rhs
    # instead of how we would expect: -nk_grad_r + pr_trace_grad +pr_trace_cell= rhs.
    # This is also why we multiply with -1 in scaled_sgn in _create_bound_rhs
    grad_eqs = sps.vstack([nk_grad_n, nk_grad_r - pr_trace_grad, pr_cont_grad])

    num_nk_cell = nk_cell.shape[0]
    num_nk_rob = nk_grad_r.shape[0]
    num_pr_cont_grad = pr_cont_grad.shape[0]

    del nk_grad_n, nk_grad_r, pr_trace_grad

    grad = rows2blk_diag * grad_eqs * cols2blk_diag

    del grad_eqs
    igrad = (cols2blk_diag * fvutils.invert_diagonal_blocks(
        grad, size_of_blocks, method=inverter) * rows2blk_diag)

    del grad, cols2blk_diag, rows2blk_diag

    # Technical note: The elements in igrad are organized as follows:
    # The fields subcell_topology.cno and .nno will together identify Nd
    # placements in igrad that are associated with the same cell and the same
    # node, that is, they belong to the same subcell. These placements are used
    # to store the discrete gradient of that cell, with the first item
    # representing the x-component etc.
    # As an example, to find the gradient in the subcell of cell ci, associated
    # with node ni, first find the indexes of subcell_topology.cno and .nno
    # that contain ci and ni, respectively. The first of these indexes give the
    # row of the x-component of the gradient, the second the y-component etc.
    #
    # The columns of igrad corresponds to the ordering of the equations in
    # grad; as recovered in _block_diagonal_structure. In practice, the first
    # columns correspond to unit pressures assigned to faces (as used for
    # boundary conditions or to discretize discontinuities over internal faces,
    # say, to represent heterogeneous gravity), while the latter group
    # gives gradients induced by cell center pressures.
    #
    # Note tacit assumptions: 1) Each cell has exactly Nd faces meeting in a
    # vertex; or else, there would not be an exact match between the
    # number of equal (nno-cno) pairs and the number of components in the
    # gradient. This assumption is always okay in 2d, in 3d it rules out cells
    # shaped as pyramids, in which case mpfa is not defined without making
    # further specifications of the method.
    # 2) The number of components in the gradient is equal to the spatial
    # dimension of the grid, as defined in g.dim. Thus 2d grids embedded in 3d
    # will run into trouble, unless the grid is first projected down to its
    # natural plane. This can be fixed by a more general implementation, but
    # it would require quite deep changes to the code.

    # Flux discretization:
    # The negative in front of pr_trace_cell comes from the grad_egs
    flux = hf2f * darcy * igrad * (
        -sps.vstack([nk_cell, -pr_trace_cell, pr_cont_cell]))

    ####
    # Boundary conditions
    rhs_bound = _create_bound_rhs(
        bnd,
        bound_exclusion,
        subcell_topology,
        sgn_unique,
        g,
        num_nk_cell,
        num_nk_rob,
        num_pr_cont_grad,
    )
    # Discretization of boundary values
    bound_flux = hf2f * darcy * igrad * rhs_bound

    # Below here, fields necessary for reconstruction of boundary pressures

    # Diagonal matrix that divides by number of sub-faces per face
    half_face_per_face = sps.diags(1. / (hf2f * np.ones(hf2f.shape[1])))

    # Contribution to face pressure from sub-cell gradients, calculated as
    # gradient times distance. Then further map to faces, and divide by number
    # of contributions per face
    dp = (half_face_per_face * hf2f * pr_cont_grad_all * igrad *
          (-sps.vstack([nk_cell, pr_trace_cell, pr_cont_cell])))

    # Internal faces, and boundary faces with a Dirichle condition do not need
    # information on the gradient.
    # Implementation note: This can be expanded to pressure recovery also
    # on internal faces by including them here, and below.
    remove_not_neumann = sps.diags(bnd.is_neu.astype(np.int))
    dp = remove_not_neumann * dp

    # We also need pressure in the cell next to the boundary face.
    bound_faces = g.get_all_boundary_faces()
    # A trick to get the boundary face: We know that one element is -1 (e.g.
    # outside the domain). Add 1, sum cell indices (will only contain the
    # internal cell; the one outside is now zero), and then subtract 1 again.
    bound_cells = np.sum(g.cell_face_as_dense()[:, bound_faces] + 1,
                         axis=0) - 1
    cell_contrib = sps.coo_matrix(
        (np.ones_like(bound_faces), (bound_faces, bound_cells)),
        shape=(g.num_faces, g.num_cells),
    )
    cell_contrib = remove_not_neumann * cell_contrib

    bound_pressure_cell = dp + cell_contrib

    sgn_arr = np.zeros(g.num_faces)
    sgn_arr[bound_faces] = g.cell_faces[bound_faces].sum(axis=1).A.ravel()
    sgn_mat = sps.diags(sgn_arr)

    bound_pressure_face_neu = (sgn_mat * half_face_per_face * hf2f *
                               pr_cont_grad_all * igrad * rhs_bound)
    # For Dirichlet faces, simply recover the boundary condition
    bound_pressure_face_dir = sps.diags(bnd.is_dir.astype(np.int))

    bound_pressure_face = (bound_pressure_face_dir +
                           remove_not_neumann * bound_pressure_face_neu)

    return flux, bound_flux, bound_pressure_cell, bound_pressure_face
Beispiel #3
0
def _mpfa_local(g, k, bnd, eta=None, inverter='numba', apertures=None):
    """
    Actual implementation of the MPFA O-method. To calculate MPFA on a grid
    directly, either call this method, or, to respect the privacy of this
    method, the main mpfa method with no memory constraints.

    Method properties and implementation details.
    The pressure is discretized as a linear function on sub-cells (see
    reference paper). In this implementation, the pressure is represented by
    its cell center value and the sub-cell gradients (this is in contrast to
    most papers, which use auxiliary pressures on the faces; the current
    formulation is equivalent, but somewhat easier to implement).
    The method will give continuous fluxes over the faces, and pressure
    continuity for certain points (controlled by the parameter eta). This can
    be expressed as a linear system on the form
        (i)   A * grad_p            = 0
        (ii)  B * grad_p + C * p_cc = 0
        (iii) 0            D * p_cc = I
    Here, the first equation represents flux continuity, and involves only the
    pressure gradients (grad_p). The second equation gives pressure continuity
    over cell faces, thus B will contain distances between cell centers and the
    face continuity points, while C consists of +- 1 (depending on which side
    the cell is relative to the face normal vector). The third equation
    enforces the pressure to be unity in one cell at a time. Thus (i)-(iii) can
    be inverted to express the pressure gradients as in terms of the cell
    center variables, that is, we can compute the basis functions on the
    sub-cells. Because of the method construction (again see reference paper),
    the basis function of a cell c will be non-zero on all sub-cells sharing
    a vertex with c. Finally, the fluxes as functions of cell center values are
    computed by insertion into Darcy's law (which is essentially half of A from
    (i), that is, only consider contribution from one side of the face.
    Boundary values can be incorporated with appropriate modifications -
    Neumann conditions will have a non-zero right hand side for (i), while
    Dirichlet gives a right hand side for (ii).

    """
    if eta is None:
        eta = fvutils.determine_eta(g)

    # The method reduces to the more efficient TPFA in one dimension, so that
    # method may be called. In 0D, there is no internal discretization to be
    # done.
    if g.dim == 1:
        discr = tpfa.Tpfa()
        params = data.Parameters(g)
        params.set_bc('flow', bnd)
        params.set_aperture(apertures)
        params.set_tensor('flow', k)
        d = {'param': params}
        discr.discretize(g, d)
        return d['flux'], d['bound_flux']
    elif g.dim == 0:
        return sps.csr_matrix([0]), 0

    # The grid coordinates are always three-dimensional, even if the grid is
    # really 2D. This means that there is not a 1-1 relation between the number
    # of coordinates of a point / vector and the real dimension. This again
    # violates some assumptions tacitly made in the discretization (in
    # particular that the number of faces of a cell that meets in a vertex
    # equals the grid dimension, and that this can be used to construct an
    # index of local variables in the discretization). These issues should be
    # possible to overcome, but for the moment, we simply force 2D grids to be
    # proper 2D.

    if g.dim == 2:
        # Rotate the grid into the xy plane and delete third dimension. First
        # make a copy to avoid alterations to the input grid
        g = g.copy()
        cell_centers, face_normals, face_centers, R, _, nodes = cg.map_grid(g)
        g.cell_centers = cell_centers
        g.face_normals = face_normals
        g.face_centers = face_centers
        g.nodes = nodes

        # Rotate the permeability tensor and delete last dimension
        k = k.copy()
        k.perm = np.tensordot(R.T, np.tensordot(R, k.perm, (1, 0)), (0, 1))
        k.perm = np.delete(k.perm, (2), axis=0)
        k.perm = np.delete(k.perm, (2), axis=1)

    # Define subcell topology, that is, the local numbering of faces, subfaces,
    # sub-cells and nodes. This numbering is used throughout the
    # discretization.
    subcell_topology = fvutils.SubcellTopology(g)

    # Obtain normal_vector * k, pairings of cells and nodes (which together
    # uniquely define sub-cells, and thus index for gradients.
    nk_grad, cell_node_blocks, \
        sub_cell_index = _tensor_vector_prod(g, k, subcell_topology, apertures)

    # Distance from cell centers to face centers, this will be the
    # contribution from gradient unknown to equations for pressure continuity
    pr_cont_grad = fvutils.compute_dist_face_cell(g, subcell_topology, eta)

    # Darcy's law
    darcy = -nk_grad[subcell_topology.unique_subfno]

    # Pair fluxes over subfaces, that is, enforce conservation
    nk_grad = subcell_topology.pair_over_subfaces(nk_grad)

    # Contribution from cell center potentials to local systems
    # For pressure continuity, +-1 (Depending on whether the cell is on the
    # positive or negative side of the face.
    # The .A suffix is necessary to get a numpy array, instead of a scipy
    # matrix.
    sgn = g.cell_faces[subcell_topology.fno, subcell_topology.cno].A
    pr_cont_cell = sps.coo_matrix(
        (sgn[0], (subcell_topology.subfno, subcell_topology.cno))).tocsr()
    # The cell centers give zero contribution to flux continuity
    nk_cell = sps.coo_matrix(
        (np.zeros(1), (np.zeros(1), np.zeros(1))),
        shape=(subcell_topology.num_subfno, subcell_topology.num_cno)).tocsr()
    del sgn

    # Mapping from sub-faces to faces
    hf2f = sps.coo_matrix(
        (np.ones(subcell_topology.unique_subfno.size),
         (subcell_topology.fno_unique, subcell_topology.subfno_unique)))

    # Update signs
    sgn_unique = g.cell_faces[subcell_topology.fno_unique,
                              subcell_topology.cno_unique].A.ravel('F')

    # The boundary faces will have either a Dirichlet or Neumann condition, but
    # not both (Robin is not implemented).
    # Obtain mappings to exclude boundary faces.
    bound_exclusion = fvutils.ExcludeBoundaries(subcell_topology, bnd, g.dim)

    # No flux conditions for Dirichlet boundary faces
    nk_grad = bound_exclusion.exclude_dirichlet(nk_grad)
    nk_cell = bound_exclusion.exclude_dirichlet(nk_cell)
    # No pressure condition for Neumann boundary faces
    pr_cont_grad = bound_exclusion.exclude_neumann(pr_cont_grad)
    pr_cont_cell = bound_exclusion.exclude_neumann(pr_cont_cell)

    # So far, the local numbering has been based on the numbering scheme
    # implemented in SubcellTopology (which treats one cell at a time). For
    # efficient inversion (below), it is desirable to get the system over to a
    # block-diagonal structure, with one block centered around each vertex.
    # Obtain the necessary mappings.
    rows2blk_diag, cols2blk_diag, size_of_blocks = _block_diagonal_structure(
        sub_cell_index, cell_node_blocks, subcell_topology.nno_unique,
        bound_exclusion)

    del cell_node_blocks, sub_cell_index

    # System of equations for the subcell gradient variables. On block diagonal
    # form.
    grad_eqs = sps.vstack([nk_grad, pr_cont_grad])

    num_nk_cell = nk_cell.shape[0]
    num_pr_cont_grad = pr_cont_grad.shape[0]
    del nk_grad, pr_cont_grad

    grad = rows2blk_diag * grad_eqs * cols2blk_diag

    del grad_eqs
    darcy_igrad = darcy * cols2blk_diag * fvutils.invert_diagonal_blocks(grad,
                                                                         size_of_blocks,
                                                                         method=inverter) \
        * rows2blk_diag

    del grad, cols2blk_diag, rows2blk_diag, darcy

    flux = hf2f * darcy_igrad * (-sps.vstack([nk_cell, pr_cont_cell]))

    del nk_cell, pr_cont_cell
    ####
    # Boundary conditions
    rhs_bound = _create_bound_rhs(bnd, bound_exclusion, subcell_topology,
                                  sgn_unique, g, num_nk_cell, num_pr_cont_grad)
    # Discretization of boundary values
    bound_flux = hf2f * darcy_igrad * rhs_bound

    return flux, bound_flux
Beispiel #4
0
def test_determine_eta():
    g = simplex.StructuredTriangleGrid([1, 1])
    assert fvutils.determine_eta(g) == 1 / 3
    g = structured.CartGrid([1, 1])
    assert fvutils.determine_eta(g) == 0