Exemple #1
0
    def project_u(self, g, u, data):
        """  Project the velocity computed with a dual vem solver to obtain a
        piecewise constant vector field, one triplet for each cell.

        Parameters
        ----------
        g : grid, or a subclass, with geometry fields computed.
        u : array (g.num_faces) Velocity at each face.

        Return
        ------
        P0u : ndarray (3, g.num_faces) Velocity at each cell.

        """
        # Allow short variable names in backend function
        # pylint: disable=invalid-name

        if g.dim == 0:
            return np.zeros(3).reshape((3, 1))

        # The velocity field already has permeability effects incorporated,
        # thus we assign a unit permeability to be passed to self.massHdiv
        k = tensor.SecondOrder(g.dim, kxx=np.ones(g.num_cells))
        param = data['param']
        a = param.get_aperture()

        faces, cells, sign = sps.find(g.cell_faces)
        index = np.argsort(cells)
        faces, sign = faces[index], sign[index]

        c_centers, f_normals, f_centers, R, dim, _ = cg.map_grid(g)

        # In the virtual cell approach the cell diameters should involve the
        # apertures, however to keep consistency with the hybrid-dimensional
        # approach and with the related hypotheses we avoid.
        diams = g.cell_diameters()

        P0u = np.zeros((3, g.num_cells))

        for c in np.arange(g.num_cells):
            loc = slice(g.cell_faces.indptr[c], g.cell_faces.indptr[c + 1])
            faces_loc = faces[loc]

            Pi_s = self.massHdiv(a[c] * k.perm[0:g.dim, 0:g.dim, c],
                                 c_centers[:, c], g.cell_volumes[c],
                                 f_centers[:, faces_loc], f_normals[:,
                                                                    faces_loc],
                                 sign[loc], diams[c])[1]

            # extract the velocity for the current cell
            P0u[dim, c] = np.dot(Pi_s, u[faces_loc]) / diams[c] * a[c]
            P0u[:, c] = np.dot(R.T, P0u[:, c])

        return P0u
Exemple #2
0
    def matrix_rhs(self, g, data):
        """
        Return the matrix and righ-hand side for a discretization of a second
        order elliptic equation using hybrid dual virtual element method.
        The name of data in the input dictionary (data) are:
        perm : tensor.SecondOrder
            Permeability defined cell-wise. If not given a identity permeability
            is assumed and a warning arised.
        source : array (self.g.num_cells)
            Scalar source term defined cell-wise. If not given a zero source
            term is assumed and a warning arised.
        bc : boundary conditions (optional)
        bc_val : dictionary (optional)
            Values of the boundary conditions. The dictionary has at most the
            following keys: 'dir' and 'neu', for Dirichlet and Neumann boundary
            conditions, respectively.

        Parameters
        ----------
        g : grid, or a subclass, with geometry fields computed.
        data: dictionary to store the data.

        Return
        ------
        matrix: sparse csr (g.num_faces+g_num_cells, g.num_faces+g_num_cells)
            Saddle point matrix obtained from the discretization.
        rhs: array (g.num_faces+g_num_cells)
            Right-hand side which contains the boundary conditions and the scalar
            source term.

        Examples
        --------
        b_faces_neu = ... # id of the Neumann faces
        b_faces_dir = ... # id of the Dirichlet faces
        bnd = bc.BoundaryCondition(g, np.hstack((b_faces_dir, b_faces_neu)),
                                ['dir']*b_faces_dir.size + ['neu']*b_faces_neu.size)
        bnd_val = {'dir': fun_dir(g.face_centers[:, b_faces_dir]),
                   'neu': fun_neu(f.face_centers[:, b_faces_neu])}

        data = {'perm': perm, 'source': f, 'bc': bnd, 'bc_val': bnd_val}

        H, rhs = hybrid.matrix_rhs(g, data)
        l = sps.linalg.spsolve(H, rhs)
        u, p = hybrid.compute_up(g, l, data)
        P0u = dual.project_u(g, perm, u)

        """
        # pylint: disable=invalid-name

        # If a 0-d grid is given then we return an identity matrix
        if g.dim == 0:
            return sps.identity(self.ndof(g), format="csr"), np.zeros(1)

        param = data['param']
        k = param.get_tensor(self)
        f = param.get_source(self)
        bc = param.get_bc(self)
        bc_val = param.get_bc_val(self)
        a = param.aperture

        faces, _, sgn = sps.find(g.cell_faces)

        # Map the domain to a reference geometry (i.e. equivalent to compute
        # surface coordinates in 1d and 2d)
        c_centers, f_normals, f_centers, _, _, _ = cg.map_grid(g)

        # Weight for the stabilization term
        diams = g.cell_diameters()
        weight = np.power(diams, 2 - g.dim)

        # Allocate the data to store matrix entries, that's the most efficient
        # way to create a sparse matrix.
        size = np.sum(np.square(g.cell_faces.indptr[1:] - \
                                g.cell_faces.indptr[:-1]))
        I = np.empty(size, dtype=np.int)
        J = np.empty(size, dtype=np.int)
        data = np.empty(size)
        rhs = np.zeros(g.num_faces)

        idx = 0
        massHdiv = dual.DualVEM().massHdiv

        for c in np.arange(g.num_cells):
            # For the current cell retrieve its faces
            loc = slice(g.cell_faces.indptr[c], g.cell_faces.indptr[c + 1])
            faces_loc = faces[loc]
            ndof = faces_loc.size

            # Retrieve permeability and normals assumed outward to the cell.
            sgn_loc = sgn[loc].reshape((-1, 1))
            normals = np.multiply(np.tile(sgn_loc.T, (g.dim, 1)),
                                  f_normals[:, faces_loc])

            # Compute the H_div-mass local matrix
            A = massHdiv(k.perm[0:g.dim, 0:g.dim, c], c_centers[:, c],
                         a[c] * g.cell_volumes[c], f_centers[:, faces_loc],
                         a[c] * normals, np.ones(ndof), diams[c], weight[c])[0]
            # Compute the Div local matrix
            B = -np.ones((ndof, 1))
            # Compute the hybrid local matrix
            C = np.eye(ndof, ndof)

            # Perform the static condensation to compute the hybrid local matrix
            invA = np.linalg.inv(A)
            S = 1 / np.dot(B.T, np.dot(invA, B))
            L = np.dot(np.dot(invA, np.dot(B, np.dot(S, B.T))), invA)
            L = np.dot(np.dot(C.T, L - invA), C)

            # Compute the local hybrid right using the static condensation
            rhs[faces_loc] += np.dot(C.T,
                                     np.dot(invA,
                                            np.dot(B, np.dot(S, f[c]))))[:, 0]

            # Save values for hybrid matrix
            cols = np.tile(faces_loc, (faces_loc.size, 1))
            loc_idx = slice(idx, idx + cols.size)
            I[loc_idx] = cols.T.ravel()
            J[loc_idx] = cols.ravel()
            data[loc_idx] = L.ravel()
            idx += cols.size

        # construct the global matrices
        H = sps.coo_matrix((data, (I, J))).tocsr()

        # Apply the boundary conditions
        if bc is not None:

            if np.any(bc.is_dir):
                norm = sps.linalg.norm(H, np.inf)
                is_dir = np.where(bc.is_dir)[0]

                H[is_dir, :] *= 0
                H[is_dir, is_dir] = norm
                rhs[is_dir] = norm * bc_val[is_dir]

            if np.any(bc.is_neu):
                faces, _, sgn = sps.find(g.cell_faces)
                sgn = sgn[np.unique(faces, return_index=True)[1]]

                is_neu = np.where(bc.is_neu)[0]
                rhs[is_neu] += sgn[is_neu] * bc_val[is_neu] * g.face_areas[
                    is_neu]

        return H, rhs
Exemple #3
0
    def compute_up(self, g, l, data):
        """
        Return the velocity and pressure computed from the hybrid variables.

        Parameters
        ----------
        g : grid, or a subclass, with geometry fields computed.
        l : array (g.num_faces) Hybrid solution of the system.
        data: dictionary to store the data. See self.matrix_rhs for a detaild
            description.

        Return
        ------
        u : array (g.num_faces) Velocity at each face.
        p : array (g.num_cells) Pressure at each cell.

        """
        # pylint: disable=invalid-name

        if g.dim == 0:
            return 0, l[0]

        param = data['param']
        k = param.get_tensor(self)
        f = param.get_source(self)
        a = param.aperture

        faces, _, sgn = sps.find(g.cell_faces)

        # Map the domain to a reference geometry (i.e. equivalent to compute
        # surface coordinates in 1d and 2d)
        c_centers, f_normals, f_centers, _, _, _ = cg.map_grid(g)

        # Weight for the stabilization term
        diams = g.cell_diameters()
        weight = np.power(diams, 2 - g.dim)

        # Allocation of the pressure and velocity vectors
        p = np.zeros(g.num_cells)
        u = np.zeros(g.num_faces)
        massHdiv = dual.DualVEM().massHdiv

        for c in np.arange(g.num_cells):
            # For the current cell retrieve its faces
            loc = slice(g.cell_faces.indptr[c], g.cell_faces.indptr[c + 1])
            faces_loc = faces[loc]
            ndof = faces_loc.size

            # Retrieve permeability and normals assumed outward to the cell.
            sgn_loc = sgn[loc].reshape((-1, 1))
            normals = np.multiply(np.tile(sgn_loc.T, (g.dim, 1)),
                                  f_normals[:, faces_loc])

            # Compute the H_div-mass local matrix
            A = massHdiv(k.perm[0:g.dim, 0:g.dim, c], c_centers[:, c],
                         a[c] * g.cell_volumes[c], f_centers[:, faces_loc],
                         a[c] * normals, np.ones(ndof), diams[c], weight[c])[0]
            # Compute the Div local matrix
            B = -np.ones((ndof, 1))
            # Compute the hybrid local matrix
            C = np.eye(ndof, ndof)

            # Perform the static condensation to compute the pressure and velocity
            S = 1 / np.dot(B.T, solve(A, B))
            l_loc = l[faces_loc].reshape((-1, 1))

            p[c] = np.dot(S, f[c] - np.dot(B.T, solve(A, np.dot(C, l_loc))))
            u[faces_loc] = -np.multiply(sgn_loc, solve(A, np.dot(B, p[c]) + \
                                                       np.dot(C, l_loc)))

        return u, p
Exemple #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
Exemple #5
0
    def matrix(self, g, data, bc_weight=False):
        """
        Return the matrix for a discretization of a second order elliptic equation
        using dual virtual element method. See self.matrix_rhs for a detaild
        description.

        Additional parameter:
        --------------------
        bc_weight: to compute the infinity norm of the matrix and use it as a
            weight to impose the boundary conditions. Default True.

        Additional return:
        weight: if bc_weight is True return the weight computed.

        """
        # Allow short variable names in backend function
        # pylint: disable=invalid-name

        # If a 0-d grid is given then we return an identity matrix
        if g.dim == 0:
            M = sps.dia_matrix(([1, 0], 0), (self.ndof(g), self.ndof(g)))
            if bc_weight:
                return M, 1
            return M

        # Retrieve the permeability, boundary conditions, and aperture
        # The aperture is needed in the hybrid-dimensional case, otherwise is
        # assumed unitary
        param = data['param']
        k = param.get_tensor(self)
        bc = param.get_bc(self)
        a = param.get_aperture()

        faces, cells, sign = sps.find(g.cell_faces)
        index = np.argsort(cells)
        faces, sign = faces[index], sign[index]

        # Map the domain to a reference geometry (i.e. equivalent to compute
        # surface coordinates in 1d and 2d)
        c_centers, f_normals, f_centers, R, dim, _ = cg.map_grid(g)

        if not data.get('is_tangential', False):
            # Rotate the permeability tensor and delete last dimension
            if g.dim < 3:
                k = k.copy()
                k.rotate(R)
                remove_dim = np.where(np.logical_not(dim))[0]
                k.perm = np.delete(k.perm, (remove_dim), axis=0)
                k.perm = np.delete(k.perm, (remove_dim), axis=1)

        # In the virtual cell approach the cell diameters should involve the
        # apertures, however to keep consistency with the hybrid-dimensional
        # approach and with the related hypotheses we avoid.
        diams = g.cell_diameters()
        # Weight for the stabilization term
        weight = np.power(diams, 2 - g.dim)

        # Allocate the data to store matrix entries, that's the most efficient
        # way to create a sparse matrix.
        size = np.sum(np.square(g.cell_faces.indptr[1:]-\
                                g.cell_faces.indptr[:-1]))
        I = np.empty(size, dtype=np.int)
        J = np.empty(size, dtype=np.int)
        dataIJ = np.empty(size)
        idx = 0

        for c in np.arange(g.num_cells):
            # For the current cell retrieve its faces
            loc = slice(g.cell_faces.indptr[c], g.cell_faces.indptr[c + 1])
            faces_loc = faces[loc]

            # Compute the H_div-mass local matrix
            A = self.massHdiv(a[c] * k.perm[0:g.dim, 0:g.dim, c],
                              c_centers[:, c], g.cell_volumes[c],
                              f_centers[:, faces_loc], f_normals[:, faces_loc],
                              sign[loc], diams[c], weight[c])[0]

            # Save values for Hdiv-mass local matrix in the global structure
            cols = np.tile(faces_loc, (faces_loc.size, 1))
            loc_idx = slice(idx, idx + cols.size)
            I[loc_idx] = cols.T.ravel()
            J[loc_idx] = cols.ravel()
            dataIJ[loc_idx] = A.ravel()
            idx += cols.size

        # Construct the global matrices
        mass = sps.coo_matrix((dataIJ, (I, J)))
        div = -g.cell_faces.T
        M = sps.bmat([[mass, div.T], [div, None]], format='csr')

        norm = sps.linalg.norm(mass, np.inf) if bc_weight else 1

        # assign the Neumann boundary conditions
        if bc and np.any(bc.is_neu):
            is_neu = np.hstack((bc.is_neu, np.zeros(g.num_cells,
                                                    dtype=np.bool)))
            M[is_neu, :] *= 0
            M[is_neu, is_neu] = norm

        if bc_weight:
            return M, norm
        return M
Exemple #6
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