Example #1
0
    def test_subcell_mapping_2d_simplex_1(self):
        p = np.array([[0, 1, 1, 0], [0, 0, 1, 1]])
        g = simplex.TriangleGrid(p)

        subcell_topology = fvutils.SubcellTopology(g)

        ccum = np.bincount(subcell_topology.cno,
                           weights=np.ones(subcell_topology.cno.size))
        self.assertTrue(np.all(ccum == 6))

        ncum = np.bincount(subcell_topology.nno,
                           weights=np.ones(subcell_topology.nno.size))
        self.assertTrue(ncum[0] == 2)
        self.assertTrue(ncum[1] == 4)
        self.assertTrue(ncum[2] == 2)
        self.assertTrue(ncum[3] == 4)

        fcum = np.bincount(subcell_topology.fno,
                           weights=np.ones(subcell_topology.fno.size))
        self.assertTrue(np.sum(fcum == 4) == 1)
        self.assertTrue(np.sum(fcum == 2) == 4)

        subfcum = np.bincount(subcell_topology.subfno,
                              weights=np.ones(subcell_topology.subfno.size))
        self.assertTrue(np.sum(subfcum == 2) == 2)
        self.assertTrue(np.sum(subfcum == 1) == 8)
Example #2
0
    def test_subcell_topology_2d_cart_1(self):
        x = np.ones(2, dtype=int)
        g = structured.CartGrid(x)

        subcell_topology = fvutils.SubcellTopology(g)

        self.assertTrue(np.all(subcell_topology.cno == 0))

        ncum = np.bincount(
            subcell_topology.nno, weights=np.ones(subcell_topology.nno.size)
        )
        self.assertTrue(np.all(ncum == 2))

        fcum = np.bincount(
            subcell_topology.fno, weights=np.ones(subcell_topology.fno.size)
        )
        self.assertTrue(np.all(fcum == 2))

        # There is only one cell, thus only unique subfno
        usubfno = np.unique(subcell_topology.subfno)
        self.assertTrue(usubfno.size == subcell_topology.subfno.size)

        self.assertTrue(
            np.all(np.in1d(subcell_topology.subfno, subcell_topology.subhfno))
        )
Example #3
0
    def _discretize_mech(self, g, data):
        """
        Discretization of poro-elasticity by the MPSA-W method.

        Implementation needs (in addition to those mentioned in mpsa function):
            1) Fields for non-zero boundary conditions. Should be simple.
            2) Split return value grad_p into forces and a divergence operator,
            so that we can compute Biot forces on a face.

        Parameters:
            g (core.grids.grid): grid to be discretized
            k (core.constit.second_order_tensor) permeability tensor
            bound_mech: Boundary condition object for mechancis
            bound_flow: Boundary condition object for flow.
            constit (porepy.bc.bc.BoundaryCondition) class for boundary values
            faces (np.ndarray) faces to be considered. Intended for partial
                discretization, may change in the future
            eta Location of pressure continuity point. Should be 1/3 for simplex
                grids, 0 otherwise. On boundary faces with Dirichlet conditions,
                eta=0 will be enforced.
            inverter (string) Block inverter to be used, either numba (default),
                cython or python. See fvutils.invert_diagonal_blocks for details.

        Returns:
            scipy.sparse.csr_matrix (shape num_faces * dim, num_cells * dim): stres
                discretization, in the form of mapping from cell displacement to
                face stresses.
            scipy.sparse.csr_matrix (shape num_faces * dim, num_faces * dim):
                discretization of boundary conditions. Interpreted as istresses
                induced by the boundary condition (both Dirichlet and Neumann). For
                Neumann, this will be the prescribed stress over the boundary face,
                and possibly stress on faces having nodes on the boundary. For
                Dirichlet, the values will be stresses induced by the prescribed
                displacement.  Incorporation as a right hand side in linear system
                by multiplication with divergence operator.
            scipy.sparse.csr_matrix (shape num_cells * dim, num_cells): Forces from
                the pressure gradient (I*p-term), represented as body forces.
                TODO: Should rather be represented as forces on faces.
            scipy.sparse.csr_matrix (shape num_cells, num_cells * dim): Trace of
                strain matrix, cell-wise.
            scipy.sparse.csr_matrix (shape num_cells x num_cells): Stabilization
                term.

        Example:
            # Set up a Cartesian grid
            g = structured.CartGrid([5, 5])
            c = tensor.FourthOrderTensor(g.dim, np.ones(g.num_cells))
            k = tensor.SecondOrderTensor(g.dim, np.ones(g.num_cells))

            # Dirirchlet boundary conditions for mechanics
            bound_faces = g.get_all_boundary_faces().ravel()
            bnd = bc.BoundaryCondition(g, bound_faces, ['dir'] * bound_faces.size)

            # Use no boundary conditions for flow, will default to homogeneous
            # Neumann.

            # Discretization
            stress, bound_stress, grad_p, div_d, stabilization = biot(g, c, bnd)
            flux, bound_flux = mpfa(g, k, None)

            # Source in the middle of the domain
            q_mech = np.zeros(g.num_cells * g.dim)

            # Divergence operator for the grid
            div_mech = fvutils.vector_divergence(g)
            div_flow = fvutils.scalar_divergence(g)
            a_mech = div_mech * stress
            a_flow = div_flow * flux

            a_biot = sps.bmat([[a_mech, grad_p], [div_d, a_flow +
                                                           stabilization]])

            # Zero boundary conditions by default.

            # Injection in the middle of the domain
            rhs = np.zeros(g.num_cells * (g.dim + 1))
            rhs[g.num_cells * g.dim + np.ceil(g.num_cells / 2)] = 1
            x = sps.linalg.spsolve(A, rhs)

            u_x = x[0:g.num_cells * g.dim: g.dim]
            u_y = x[1:g.num_cells * g.dim: g.dim]
            p = x[g.num_cells * gdim:]

        """
        param = data["param"]
        bound_mech = param.get_bc("mechanics")
        bound_flow = param.get_bc("flow")
        constit = param.get_tensor("mechanics")

        eta = data.get("eta", 0)
        inverter = data.get("inverter", None)

        # 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:
            g = g.copy()
            g.cell_centers = np.delete(g.cell_centers, (2), axis=0)
            g.face_centers = np.delete(g.face_centers, (2), axis=0)
            g.face_normals = np.delete(g.face_normals, (2), axis=0)
            g.nodes = np.delete(g.nodes, (2), axis=0)

            constit.c = np.delete(constit.c, (2, 5, 6, 7, 8), axis=0)
            constit.c = np.delete(constit.c, (2, 5, 6, 7, 8), axis=1)
        nd = g.dim

        # Define subcell topology
        subcell_topology = fvutils.SubcellTopology(g)
        # Obtain mappings to exclude boundary faces for mechanics
        bound_exclusion_mech = fvutils.ExcludeBoundaries(
            subcell_topology, bound_mech, nd)
        # ... and flow
        bound_exclusion_flow = fvutils.ExcludeBoundaries(
            subcell_topology, bound_flow, nd)

        num_subhfno = subcell_topology.subhfno.size

        num_nodes = np.diff(g.face_nodes.indptr)
        sgn = g.cell_faces[subcell_topology.fno, subcell_topology.cno].A

        # The pressure gradient term in the mechanics equation is discretized
        # as a force on the faces. The right hand side is thus formed of the
        # normal vectors.
        def build_rhs_normals_single_dimension(dim):
            val = (g.face_normals[dim, subcell_topology.fno] * sgn /
                   num_nodes[subcell_topology.fno])
            mat = sps.coo_matrix(
                (val.squeeze(),
                 (subcell_topology.subfno, subcell_topology.cno)),
                shape=(subcell_topology.num_subfno, subcell_topology.num_cno),
            )
            return mat

        rhs_normals = build_rhs_normals_single_dimension(0)
        for iter1 in range(1, nd):
            this_dim = build_rhs_normals_single_dimension(iter1)
            rhs_normals = sps.vstack([rhs_normals, this_dim])

        rhs_normals = bound_exclusion_mech.exclude_dirichlet_nd(rhs_normals)

        num_dir_subface = (bound_exclusion_mech.exclude_neu.shape[1] -
                           bound_exclusion_mech.exclude_neu.shape[0]) * nd
        # No right hand side for cell displacement equations.
        rhs_normals_displ_var = sps.coo_matrix((
            nd * subcell_topology.num_subfno - num_dir_subface,
            subcell_topology.num_cno,
        ))

        # Why minus?
        rhs_normals = -sps.vstack([rhs_normals, rhs_normals_displ_var])
        del rhs_normals_displ_var

        # Call core part of MPSA
        hook, igrad, rhs_cells, cell_node_blocks, hook_normal = mpsa.mpsa_elasticity(
            g, constit, subcell_topology, bound_exclusion_mech, eta, inverter)

        # Output should be on face-level (not sub-face)
        hf2f = fvutils.map_hf_2_f(subcell_topology.fno_unique,
                                  subcell_topology.subfno_unique, nd)

        # Stress discretization
        stress = hf2f * hook * igrad * rhs_cells

        # Right hand side for boundary discretization
        rhs_bound = mpsa.create_bound_rhs(bound_mech, bound_exclusion_mech,
                                          subcell_topology, g)
        # Discretization of boundary values
        bound_stress = hf2f * hook * igrad * rhs_bound

        # Face-wise gradient operator. Used for the term grad_p in Biot's
        # equations.
        rows = fvutils.expand_indices_nd(subcell_topology.cno, nd)
        cols = np.arange(num_subhfno * nd)
        vals = np.tile(sgn, (nd, 1)).ravel("F")
        div_gradp = sps.coo_matrix(
            (vals, (rows, cols)),
            shape=(subcell_topology.num_cno * nd, num_subhfno * nd),
        ).tocsr()

        #        del hook, rhs_bound
        del rows, cols, vals

        grad_p = div_gradp * hook_normal * igrad * rhs_normals
        # assert np.allclose(grad_p.sum(axis=0), np.zeros(g.num_cells))

        del hook_normal, div_gradp

        div = self._subcell_gradient_to_cell_scalar(g, cell_node_blocks)

        div_d = div * igrad * rhs_cells

        # The boundary discretization of the div_d term is represented directly
        # on the cells, instead of going via the faces.
        bound_div_d = div * igrad * rhs_bound
        del rhs_cells

        stabilization = div * igrad * rhs_normals

        data["stress"] = stress
        data["bound_stress"] = bound_stress
        data["grad_p"] = grad_p
        data["div_d"] = div_d
        data["stabilization"] = stabilization
        data["bound_div_d"] = bound_div_d
Example #4
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
Example #5
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