def grid_error(mappings, gb: pp.GridBucket, gb_ref: pp.GridBucket, variable,
               variable_dof):
    """ Compute grid errors for a given mapping

    The mapping is the one computed by gb_coarse_fine_cell_mapping()
    """
    # TODO: Fix this method. Something is wrong when passing a mapping to it.
    errors = {}

    for g, g_ref, mapping in mappings:
        # print(i, pair)
        # g = mappings[i][0]
        # g_ref = mappings[i][1]
        # mapping = mappings[i][2]

        assert g.num_cells < g_ref.num_cells

        data = gb.node_props(g)
        data_ref = gb_ref.node_props(g_ref)

        errors[data['node_number']] = {}  # Initialize this dict entry

        states = data[pp.STATE]
        states_ref = data_ref[pp.STATE]

        # TODO: Add some limitation to which keys you want to check,
        #  or how you should compute errors over certain types of keys
        state_keys = set(states.keys())
        state_ref_keys = set(states_ref.keys())
        check_keys = state_keys.intersection(state_ref_keys)

        if variable not in check_keys:
            logger.info(f"{variable} not present on grid number "
                        f"{gb.node_props(g, 'node_number')} of dim {g.dim}.")

        sol = states[variable].reshape((-1, variable_dof))
        mapped_sol = mapping.dot(sol).reshape((-1, 1))
        sol_ref = states_ref[variable]

        absolute_error = np.linalg.norm(mapped_sol - sol_ref)

        norm_ref = np.linalg.norm(sol_ref)
        if norm_ref < 1e-5:
            logger.warning(f"Relative error not reportable. "
                           f"Norm of reference solution is {norm_ref}. "
                           f"Reporting absolute error")
            relative_error = -1

        relative_error = absolute_error / norm_ref

        errors[data['node_number']] = {
            variable: {
                'absolute_error': absolute_error,
                'relative_error': relative_error
            }
        }

    return errors
Beispiel #2
0
def gb_coarse_fine_cell_mapping(
    gb: pp.GridBucket, gb_ref: pp.GridBucket, tol=1e-8
) -> None:
    """ Wrapper for coarse_fine_cell_mapping to construct mapping for grids in
    GridBucket.

    Adds a node_prop to each grid in gb. The key is 'coarse_fine_cell_mapping',
    and is the mapping generated by 'coarse_fine_cell_mapping(...)'.

    Note: No node prop is added to the reference grids in gb_ref.

    Parameters
    ----------
    gb : pp.GridBucket
        Coarse grid bucket
    gb_ref : pp.GridBucket
        Refined grid bucket
    tol : float, Optional
        Tolerance for point_in_poly* -methods
    """

    grids = gb.get_grids()
    grids_ref = gb_ref.get_grids()

    assert len(grids) == len(
        grids_ref
    ), "Weakly check that GridBuckets refer to same domains"
    assert np.allclose(
        np.append(*gb.bounding_box()), np.append(*gb_ref.bounding_box())
    ), "Weakly check that GridBuckets refer to same domains"

    # This method assumes a consistent node ordering between grids.
    # At least assign one.
    gb.assign_node_ordering(overwrite_existing=False)
    gb_ref.assign_node_ordering(overwrite_existing=False)

    # Add node prop on the coarse grid to map from coarse to fine cells.
    gb.add_node_props(keys="coarse_fine_cell_mapping")

    for i in np.arange(len(grids)):
        g, g_ref = grids[i], grids_ref[i]

        node_num = gb.node_props(g, "node_number")
        node_num_ref = gb_ref.node_props(g_ref, "node_number")
        assert node_num == node_num_ref, "Weakly check that grids refer to same domain."

        # Compute the mapping for this grid-pair,
        # and assign the result to the node of the coarse gb
        mapping = coarse_fine_cell_mapping(g, g_ref, point_in_poly_tol=tol)
        gb.set_node_prop(g, key="coarse_fine_cell_mapping", val=mapping)
def gb_coarse_fine_cell_mapping(
        gb: pp.GridBucket, gb_ref: pp.GridBucket, tol=1e-8
):
    """ Wrapper for coarse_fine_cell_mapping to construct mapping for grids in GridBucket.

    Parameters
    ----------
    gb : pp.GridBucket
        Coarse grid bucket
    gb_ref : pp.GridBucket
        Refined grid bucket
    tol : float, Optional
        Tolerance for point_in_poly* -methods

    Returns
    -------
    mapping : list of tuples with entries (pp.GridBucket, pp.GridBucket, sps.csc_matrix)
        The first entry is the coarse grid.
        The second entry is the refined grid.
        The third entry is the mapping from coarse to fine cells
    """

    grids = gb.get_grids()
    grids_ref = gb_ref.get_grids()

    assert len(grids) == len(grids_ref), "Weakly check that GridBuckets refer to same domains"
    assert np.array_equal(np.append(*gb.bounding_box()), np.append(*gb_ref.bounding_box())), \
        "Weakly check that GridBuckets refer to same domains"

    # This method assumes a consistent node ordering between grids. At least assign one.
    gb.assign_node_ordering(overwrite_existing=False)
    gb_ref.assign_node_ordering(overwrite_existing=False)

    n_grids = len(grids)
    # mappings = [None]*n_grids
    mappings = {'gb': gb, 'gb_ref': gb_ref}

    for i in np.arange(n_grids):
        g, g_ref = grids[i], grids_ref[i]
        node_num, node_num_ref = gb._nodes[g]['node_number'], gb_ref._nodes[g_ref]['node_number']

        assert node_num == node_num_ref, "Weakly check that grids refer to same domain."

        mapping = coarse_fine_cell_mapping(g, g_ref, tol=tol)

        mappings[(g, g_ref)] = {'node_number': node_num,
                                'data': gb.node_props(g),
                                'data_ref': gb_ref.node_props(g_ref)}

    return mappings
Beispiel #4
0
def _tag_injection_cell(
    gb: pp.GridBucket, g: pp.Grid, pts: np.ndarray, length_scale
) -> None:
    """ Helper method to tag find closest point on g to pts

    The tag is set locally to g and to node props on gb.
    length_scale is used to log the unscaled distance to
    the injection cell from pts.

    Parameters
    ----------
    gb : pp.GridBucket
    g : pp.Grid
    pts : np.ndarray, shape: (3,1)
    length_scale : float

    """
    assert pts.shape == (3, 1), "We only consider one point; array needs shape 3x1"
    tags = np.zeros(g.num_cells)
    ids, dsts = g.closest_cell(pts, return_distance=True)
    tags[ids] = 1
    g.tags["well_cells"] = tags
    d = gb.node_props(g)
    pp.set_state(d, {"well": tags})

    # Log information on the injection point
    logger.info(
        f"Closest cell found has (unscaled) distance: {dsts[0] * length_scale:4f}\n"
        f"ideal (scaled) point coordinate: {pts.T}\n"
        f"nearest (scaled) cell center coordinate: {g.cell_centers[:, ids].T}\n"
    )
Beispiel #5
0
def nd_sides_shearzone_injection_cell(
    params: FlowParameters, gb: pp.GridBucket, reset_frac_tags: bool = True,
) -> None:
    """ Tag the Nd cells surrounding a shear zone injection point

    Parameters
    ----------
    params : FlowParameters
        parameters that contain "source_scalar_borehole_shearzone"
        (with "shearzone", and "borehole") and "length_scale".
    gb : pp.GridBucket
        grid bucket
    reset_frac_tags : bool [Default: True]
        if set to False, keep injection tag in the shear zone.
    """
    # Shorthand
    shearzone = params.source_scalar_borehole_shearzone.get("shearzone")

    # First, tag the fracture cell, and get the tag
    shearzone_injection_cell(params, gb)
    fracture = gb.get_grids(lambda g: gb.node_props(g, "name") == shearzone)[0]
    tags = fracture.tags["well_cells"]
    # Second, map the cell to the Nd grid
    nd_grid: pp.Grid = gb.grids_of_dimension(gb.dim_max())[0]
    data_edge = gb.edge_props((fracture, nd_grid))
    mg: pp.MortarGrid = data_edge["mortar_grid"]

    slave_to_master_face = mg.mortar_to_master_int() * mg.slave_to_mortar_int()
    face_to_cell = nd_grid.cell_faces.T
    slave_to_master_cell = face_to_cell * slave_to_master_face
    nd_tags = np.abs(slave_to_master_cell) * tags

    # Set tags on the nd-grid
    nd_grid.tags["well_cells"] = nd_tags
    ndd = gb.node_props(nd_grid)
    pp.set_state(ndd, {"well": tags})

    if reset_frac_tags:
        # reset tags on the fracture
        zeros = np.zeros(fracture.num_cells)
        fracture.tags["well_cells"] = zeros
        d = gb.node_props(fracture)
        pp.set_state(d, {"well": zeros})
Beispiel #6
0
    def parse(self, gb: pp.GridBucket):

        bc_val = self._bc.parse(gb)  # TODO Is this done anyhow already?
        keyword = self._bc.keyword
        g = self._g[0]
        data = gb.node_props(g)
        bc = data[pp.PARAMETERS][keyword]["bc"]
        is_dir = bc.is_dir
        is_not_dir = np.logical_not(is_dir)
        dir_bc_val = bc_val.copy()
        dir_bc_val[is_not_dir] = float("NaN")

        return dir_bc_val
Beispiel #7
0
    def parse(self, gb: pp.GridBucket) -> np.ndarray:
        """Convert the Ad expression into numerical values for the boundary conditions,
        in the form of an np.ndarray concatenated for all grids.

        Pameteres:
            gb (pp.GridBucket): Mixed-dimensional grid. The boundary condition will be
                taken from the data dictionaries with the relevant keyword.

        Returns:
            np.ndarray: Value of boundary conditions.

        """
        val = []
        for g in self._g:
            data = gb.node_props(g)
            val.append(data[pp.PARAMETERS][self.keyword]["bc_values"])

        return np.hstack([v for v in val])
Beispiel #8
0
def center_of_shearzone_injection_cell(
    params: FlowParameters, gb: pp.GridBucket
) -> None:
    """ Tag the center cell of the given shear zone with 1 (injection)

    Parameters
    ----------
    params : FlowParameters
    gb : pp.GridBucket
    """

    # Shorthand
    shearzone = params.source_scalar_borehole_shearzone.get("shearzone")

    # Get the grid to inject to
    frac: pp.Grid = gb.get_grids(lambda g: gb.node_props(g, "name") == shearzone)[0]
    centers: np.ndarray = frac.cell_centers
    pts = np.atleast_2d(np.mean(centers, axis=1)).T

    # Tag injection grid with 1 in the injection cell
    _tag_injection_cell(gb, frac, pts, params.length_scale)
Beispiel #9
0
def shearzone_injection_cell(params: FlowParameters, gb: pp.GridBucket) -> None:
    """ Tag the borehole - shearzone intersection cell with 1 (injection)

    Parameters
    ----------
    params : FlowParameters
    gb : pp.GridBucket
    """
    # Shorthand
    shearzone = params.source_scalar_borehole_shearzone.get("shearzone")

    # Get intersection point
    pts = shearzone_borehole_intersection(params)

    # Get the grid to inject to
    injection_grid = gb.get_grids(lambda g: gb.node_props(g, "name") == shearzone)[0]
    assert (
        injection_grid.dim == gb.dim_max() - 1
    ), "Injection grid should be a Nd-1 fracture"

    # Tag injection grid with 1 in the injection cell
    _tag_injection_cell(gb, injection_grid, pts, params.length_scale)
Beispiel #10
0
def propagate_fractures(gb: pp.GridBucket, faces: Dict[pp.Grid,
                                                       np.ndarray]) -> None:
    """
    gb - grid bucket with matrix and fracture grids.
    faces_h - list of list of faces to be split in the highest-dimensional
        grid. The length of the outer list equals the number of fractures.
        Each entry in the list is a list containing the higher-dimensional
        indices of the faces to be split for the extension of the corresponding
        fracture.
    Changes to grids done in-place.
    The call changes:
        Geometry and connectivity fields of the two grids involved.
        The face_cells mapping between them
        Their respective face tags.
    Also adds the following to node data dictionaries:
        new_cells and new_faces tags, for use in e.g. local discretization
        updates.
        partial_update, a boolean flag indicating that the grids have been
        updated.

    """

    dim_h: int = gb.dim_max()
    g_h: pp.Grid = gb.grids_of_dimension(dim_h)[0]

    n_old_faces_h: int = g_h.num_faces

    # First initialise certain tags to get rid of any existing tags from
    # previous calls
    d_h: Dict = gb.node_props(g_h)
    d_h["new_cells"] = np.empty(0, dtype=int)
    d_h["new_faces"] = np.empty(0, dtype=int)
    d_h["split_faces"] = np.empty(0, dtype=int)

    # Data structure for keeping track of faces in g_h to be split
    split_faces = np.empty(0, dtype=np.int)

    # By default, we will not update the higher-dimensional grid. This will be
    # changed in the below for loop if the grid gets faces split.
    # This variable can be used e.g. to check if a rediscretization is necessary on
    # the higher-dimensional grid
    d_h["partial_update"] = False

    # Initialize mapping between old and new faces for g_h. We will store the updates
    # from splitting related to each lower-dimensional grid, and then merge towards the
    # end; the split data may be handy for debugging
    face_map_h: List[sps.spmatrix] = [
        sps.dia_matrix((np.ones(g_h.num_faces), 0),
                       (g_h.num_faces, g_h.num_faces))
    ]

    # The propagation is divided into two main steps:
    # First, update the geomtry of the fracture grids, and, simultaneously, the higher
    # dimensional grid (the former will be updated once, the latter may undergo several
    # update steps, depending on how many fractures propagate).
    # Second, update the mortar grids. This is done after all fractures have been
    # propagated.

    for g_l in gb.grids_of_dimension(dim_h - 1):

        # The propagation of a fracture consists of the following major steps:
        #   1. Find which faces in g_h should be split for this g_l.
        #   2. Add nodes to g_l where the fracture will propagate.
        #   3. Update face-node and cell-face relation in g_l.
        #   4. Update face geometry of g_l.
        #   5. Update cell geometry of g_l.
        #   6. Split the faces in g_h to make room for the new fracture.
        #   7. Update geometry in g_l and g_h.
        #
        # IMPLEMENTATION NOTE: While point 7 replaces information from 4 and 5, the
        # provisional fields may still be needed in point 6.

        # Initialize data on new faces and cells
        d_l = gb.node_props(g_l)
        d_l["new_cells"] = np.empty(0, dtype=int)
        d_l["new_faces"] = np.empty(0, dtype=int)

        # Step 1:
        # Uniquify the faces to be split. Amongs others, this avoids trouble when
        # a faces is requested split twice, from two neighboring faces
        faces_h = np.unique(np.atleast_1d(np.array(faces[g_l])))
        split_faces = np.append(split_faces, faces_h)

        if faces_h.size == 0:
            # If there is no propagation for this fracture, we continue
            # No need to update discretization of this grid
            d_l["partial_update"] = False

            # Variable mappings are unit mappings
            d_l["face_index_map"] = sps.identity(g_l.num_faces)
            d_l["cell_index_map"] = sps.identity(g_l.num_cells)

            # Identity mapping of faces in this step
            face_map_h.append(sps.identity(g_h.num_faces))

            # Move on to the next fracture
            continue

        # Keep track of original information:
        n_old_faces_l = g_l.num_faces
        n_old_cells_l = g_l.num_cells
        n_old_nodes_l = g_l.num_nodes
        n_old_nodes_h = g_h.num_nodes

        # It is convenient to tag the nodes lying on the domain boundary. This
        # helps updating the face tags later:
        pp.utils.tags.add_node_tags_from_face_tags(gb, "domain_boundary")

        # Step 2:
        # Get the "involved nodes", i.e., the union between the new nodes in
        # the lower dimension and the boundary nodes where the fracture
        # propagates. The former are added to the nodes in g_l - specifically,
        # both node coordinates and global_point_ind of g_l are amended.
        unique_node_ind_l, unique_node_ind_h = _update_nodes_fracture_grid(
            g_h, g_l, faces_h)

        # Step 3:
        # Update the connectivity matrices (cell_faces and face_nodes) and tag
        # the lower-dimensional faces, including re-classification of (former)
        # tips to internal faces, where appropriate.
        n_new_faces, new_face_centers = _update_connectivity_fracture_grid(
            g_l,
            g_h,
            unique_node_ind_l,
            unique_node_ind_h,
            n_old_nodes_l,
            n_old_faces_l,
            n_old_cells_l,
            faces_h,
        )

        # Step 4: Update fracture grid face geometry
        # Note: This simply expands arrays with face geometry, but it does not
        # compute reasonable values for the geometry
        _append_face_geometry_fracture_grid(g_l, n_new_faces, new_face_centers)

        # Step 5: Update fracture grid cell geometry
        # Same for cells. Here the geometry quantities are copied from the
        # face values of g_h, thus values should be reasonable.
        new_cells: np.ndarray = _update_cells_fracture_grid(g_h, g_l, faces_h)

        # Step 6: Split g_h along faces_h
        _split_fracture_extension(gb,
                                  g_h,
                                  g_l,
                                  faces_h,
                                  unique_node_ind_h,
                                  new_cells,
                                  non_planar=True)

        # Store information on which faces and cells have just been added.
        # Note that we only keep track of the faces and cells from the last
        # propagation call!
        new_faces_l = np.arange(g_l.num_faces - n_new_faces, g_l.num_faces)
        new_faces_h = g_h.frac_pairs[1, np.isin(g_h.frac_pairs[0], faces_h)]

        # Sanity check on the grid; most likely something will have gone wrong
        # long before if there is a problem.
        assert np.all(new_faces_h >= n_old_faces_h)
        if not np.min(new_cells) >= n_old_cells_l:
            raise ValueError(
                "New cells are assumed to be appended to cell array")
        if not np.min(new_faces_l) >= n_old_faces_l:
            raise ValueError(
                "New faces are assumed to be appended to face array")

        # Update the geometry
        _update_geometry(g_h, g_l, new_cells, n_old_cells_l, n_old_faces_l)

        # Finally some bookkeeping that can become useful in a larger-scale simulation.

        # Mark both grids for a partial update
        d_h["partial_update"] = True
        d_l["partial_update"] = True

        # Append arrays of new faces (g_l, g_h) and cells (g_l)
        d_h["new_faces"] = np.append(d_h["new_faces"], new_faces_h)
        d_l["new_cells"] = np.append(d_l["new_cells"], new_cells)
        d_l["new_faces"] = np.append(d_l["new_faces"], new_faces_l)

        # Create mappings between the old and and faces and cells in g_l
        arr = np.arange(n_old_faces_l)
        face_map_l = sps.coo_matrix(
            (np.ones(n_old_faces_l, dtype=np.int), (arr, arr)),
            shape=(g_l.num_faces, n_old_faces_l),
        ).tocsr()
        arr = np.arange(n_old_cells_l)
        cell_map_l = sps.coo_matrix(
            (np.ones(n_old_cells_l, dtype=np.int), (arr, arr)),
            shape=(g_l.num_cells, n_old_cells_l),
        ).tocsr()

        # These can be stored directly - there should be no more changes for g_l
        d_l["face_index_map"] = face_map_l
        d_l["cell_index_map"] = cell_map_l

        # For g_h we construct the map of faces for the splitting of this g_l
        # and append it to the list of face_maps

        # The size of the next map should be compatible with the number of faces in
        # the previous map.
        nfh = face_map_h[-1].shape[0]
        arr = np.arange(nfh)
        face_map_h.append(
            sps.coo_matrix(
                (np.ones(nfh, dtype=np.int), (arr, arr)),
                shape=(g_h.num_faces, nfh),
            ).tocsr())

        # Append default tags for the new nodes. Both high and low-dimensional grid
        _append_node_tags(g_l, g_l.num_nodes - n_old_nodes_l)
        _append_node_tags(g_h, g_h.num_nodes - n_old_nodes_h)

    # The standard node tags are updated from the face tags, which are updated on the
    # fly in the above loop.
    node_tags = ["domain_boundary", "tip", "fracture"]
    for tag in node_tags:
        # The node tag is set to true if at least one neighboring face is tagged
        pp.utils.tags.add_node_tags_from_face_tags(gb, tag)
    # Done with all splitting.

    # Compose the mapping of faces for g_l
    fm = face_map_h[0]
    for m in face_map_h[1:]:
        fm = m * fm
    d_h["face_index_map"] = fm
    # Also make a cell-map, this is a 1-1 mapping in this case
    d_h["cell_index_map"] = sps.identity(g_h.num_cells)

    d_h["split_faces"] = np.array(split_faces, dtype=int)

    ##
    # Second main step of propagation: Update mortar grid.

    # When all faces have been split, we can update the mortar grids
    for e, d_e in gb.edges_of_node(g_h):
        _, g_l = e
        d_l = gb.node_props(g_l)
        _update_mortar_grid(g_h, g_l, d_e, d_l["new_cells"], d_h["new_faces"])

        # Mapping of cell indices on the mortar grid is composed by the corresponding
        # map for g_l.
        cell_map = sps.kron(sps.identity(2), d_l["cell_index_map"]).tocsr()
        d_e["cell_index_map"] = cell_map

        # Also update projection operators
        pp.contact_conditions.set_projections(gb, [e])
Beispiel #11
0
def set_projections(
        gb: pp.GridBucket,
        edges: Optional[List[Tuple[pp.Grid, pp.Grid]]] = None) -> None:
    """Define a local coordinate system, and projection matrices, for all
    grids of co-dimension 1.

    The function adds one item to the data dictionary of all GridBucket edges
    that neighbors a co-dimension 1 grid, defined as:
        key: tangential_normal_projection, value: pp.TangentialNormalProjection
            provides projection to the surface of the lower-dimensional grid

    Note that grids of co-dimension 2 and higher are ignored in this construction,
    as we do not plan to do contact mechanics on these objects.

    It is assumed that the surface is planar.

    """
    if edges is None:
        edges = [e for e, _ in gb.edges()]

    # Information on the vector normal to the surface is not available directly
    # from the surface grid (it could be constructed from the surface geometry,
    # which spans the tangential plane). We instead get the normal vector from
    # the adjacent higher dimensional grid.
    # We therefore access the grids via the edges of the mixed-dimensional grid.
    for e in edges:
        d_m = gb.edge_props(e)

        mg = d_m["mortar_grid"]
        # Only consider edges where the lower-dimensional neighbor is of co-dimension 1
        if not mg.dim == (gb.dim_max() - 1):
            continue

        # Neigboring grids
        g_l, g_h = gb.nodes_of_edge(e)

        # Find faces of the higher dimensional grid that coincide with the mortar
        # grid. Go via the primary to mortar projection
        # Convert matrix to csr, then the relevant face indices are found from
        # the (column) indices
        faces_on_surface = mg.primary_to_mortar_int().tocsr().indices

        # Find out whether the boundary faces have outwards pointing normal vectors
        # Negative sign implies that the normal vector points inwards.
        sgn, _ = g_h.signs_and_cells_of_boundary_faces(faces_on_surface)

        # Unit normal vector
        unit_normal = g_h.face_normals[:g_h.dim] / g_h.face_areas
        # Ensure all normal vectors on the relevant surface points outwards
        unit_normal[:, faces_on_surface] *= sgn

        # Now we need to pick out *one*  normal vector of the higher dimensional grid

        # which coincides with this mortar grid, so we kill off all entries for the
        # "other" side:
        unit_normal[:, mg._ind_face_on_other_side] = 0

        # Project to the mortar and then to the fracture
        outwards_unit_vector_mortar = mg.primary_to_mortar_int().dot(
            unit_normal.T).T
        normal_lower = mg.mortar_to_secondary_int().dot(
            outwards_unit_vector_mortar.T).T

        # NOTE: The normal vector is based on the first cell in the mortar grid,
        # and will be pointing from that cell towards the other side of the
        # mortar grid. This defines the positive direction in the normal direction.
        # Although a simpler implementation seems to be possible, going via the
        # first element in faces_on_surface, there is no guarantee that this will
        # give us a face on the positive (or negative) side, hence the more general
        # approach is preferred.
        #
        # NOTE: The basis for the tangential direction is determined by the
        # construction internally in TangentialNormalProjection.
        projection = pp.TangentialNormalProjection(normal_lower)

        d_l = gb.node_props(g_l)
        # Store the projection operator in the lower-dimensional data
        d_l["tangential_normal_projection"] = projection
Beispiel #12
0
def grid_error(
    gb: pp.GridBucket,
    gb_ref: pp.GridBucket,
    variable: List[str],
    variable_dof: List[int],
) -> dict:
    """ Compute grid errors a grid bucket and refined reference grid bucket

    Assumes that the coarse grid bucket has a node property
    'coarse_fine_cell_mapping' assigned on each grid, which
    maps from coarse to fine cells according to the method
    'coarse_fine_cell_mapping(...)'.

    Parameters
    ----------
    gb, gb_ref : pp.GridBucket
        Coarse and fine grid buckets, respectively
    variable : List[str]
        which variables to compute error over
    variable_dof : List[int]
        Degrees of freedom for each variable in the list 'variable'.

    Returns
    -------
    errors : dict
        Dictionary with top level keys as node_number,
        within which for each variable, the error is
        reported.
    """

    if not isinstance(variable, list):
        variable = [variable]
    if not isinstance(variable_dof, list):
        variable_dof = [variable_dof]
    assert len(variable) == len(variable_dof), (
        "Each variable must have associated "
        "with it a number of degrees of freedom.")
    n_variables = len(variable)

    errors = {}

    grids = gb.get_grids()
    grids_ref = gb_ref.get_grids()
    n_grids = len(grids)

    for i in np.arange(n_grids):
        g, g_ref = grids[i], grids_ref[i]
        mapping = gb.node_props(g, "coarse_fine_cell_mapping")

        # Get states
        data = gb.node_props(g)
        data_ref = gb_ref.node_props(g_ref)
        states = data[pp.STATE]
        states_ref = data_ref[pp.STATE]

        node_number = data["node_number"]

        # Initialize errors
        errors[node_number] = {}

        for var_idx in range(0, n_variables):
            var = variable[var_idx]
            var_dof = variable_dof[var_idx]

            # Check if the variable exists on both
            # the grid and reference grid
            state_keys = set(states.keys())
            state_ref_keys = set(states_ref.keys())
            check_keys = state_keys.intersection(state_ref_keys)
            if var not in check_keys:
                logger.info(f"{var} not present on grid number "
                            f"{node_number} of dim {g.dim}.")
                continue

            # Compute errors relative to the reference grid
            # TODO: Should the solution be divided by
            #  g.cell_volumes or similar?
            # TODO: If scaling is used, consider that
            #  - or use the export-ready variables,
            #   'u_exp', 'p_exp', etc.
            sol = (states[var].reshape((var_dof, -1),
                                       order="F").T)  # (num_cells x var_dof)
            mapped_sol: np.ndarray = mapping.dot(
                sol)  # (num_cells x variable_dof)
            sol_ref = (states_ref[var].reshape(
                (var_dof, -1), order="F").T)  # (num_cells x var_dof)

            # axis=0 gives component-wise norm.
            absolute_error = np.linalg.norm(mapped_sol - sol_ref, axis=0)
            norm_ref = np.linalg.norm(sol_ref, axis=0)

            if np.any(norm_ref < 1e-10):
                logger.info(f"Relative error not reportable. "
                            f"Norm of reference solution is {norm_ref}. "
                            f"Reporting absolute error")
                error = absolute_error
                is_relative = False
            else:
                error = absolute_error / norm_ref
                is_relative = True

            errors[node_number][var] = {
                "error": error,
                "is_relative": is_relative,
            }

    return errors
Beispiel #13
0
    def to_ad(
        self,
        gb: pp.GridBucket,
        state: Optional[np.ndarray] = None,
        active_variables: Optional[list] = None,
    ):
        """Evaluate the residual and Jacobian matrix for a given state.

        Parameters:
            gb (pp.GridBucket): GridBucket used to represent the problem. Will be used
                to parse the operators that combine to form this Equation..
            state (np.ndarray, optional): State vector for which the residual and its
                derivatives should be formed. If not provided, the state will be pulled from
                the previous iterate (if this exists), or alternatively from the state
                at the previous time step.

        Returns:
            An Ad-array representation of the residual and Jacbobian.

        """
        # Parsing in two stages: First make an Ad-representation of the variable state
        # (this must be done jointly for all variables of the Equation to get all
        # derivatives represented). Then parse the equation by traversing its
        # tree-representation, and parse and combine individual operators.

        # Initialize variables
        prev_vals = np.zeros(self._dof_manager.num_dofs())

        populate_state = state is None
        if populate_state:
            state = np.zeros(self._dof_manager.num_dofs())

        assert state is not None
        for (g, var) in self._dof_manager.block_dof:
            ind = self._dof_manager.dof_ind(g, var)
            if isinstance(g, tuple):
                prev_vals[ind] = gb.edge_props(g, pp.STATE)[var]
            else:
                prev_vals[ind] = gb.node_props(g, pp.STATE)[var]

            if populate_state:
                if isinstance(g, tuple):
                    try:
                        state[ind] = gb.edge_props(g, pp.STATE)[pp.ITERATE][var]
                    except KeyError:
                        prev_vals[ind] = gb.edge_props(g, pp.STATE)[var]
                else:
                    try:
                        state[ind] = gb.node_props(g, pp.STATE)[pp.ITERATE][var]
                    except KeyError:
                        state[ind] = gb.node_props(g, pp.STATE)[var]

        # Initialize Ad variables with the current iterates
        if active_variables is None:
            ad_vars = initAdArrays([state[ind] for ind in self._variable_dofs])
            self._ad = {var_id: ad for (var_id, ad) in zip(self._variable_ids, ad_vars)}
        else:
            active_variable_ids = [v.id for v in active_variables]

            ad_variable_ids = list(
                set(self._variable_ids).intersection(active_variable_ids)
            )
            assert all([i in self._variable_ids for i in active_variable_ids])
            ad_variable_local_ids = [
                self._variable_ids.index(i) for i in active_variable_ids
            ]
            ad_variable_dofs = [self._variable_dofs[i] for i in ad_variable_local_ids]
            ad_vars = initAdArrays([state[ind] for ind in ad_variable_dofs])
            self._ad = {var_id: ad for (var_id, ad) in zip(ad_variable_ids, ad_vars)}

        # Also make mappings from the previous iteration.
        if active_variables is None:
            prev_iter_vals_list = [state[ind] for ind in self._prev_iter_dofs]
            self._prev_iter_vals = {
                var_id: val
                for (var_id, val) in zip(self._prev_iter_ids, prev_iter_vals_list)
            }
        else:
            # FIXME: This needs explanations
            prev_iter_vals_list = [state[ind] for ind in self._prev_iter_dofs]
            non_ad_variable_ids = list(set(self._variable_ids) - set(ad_variable_ids))
            non_ad_variable_local_ids = [
                self._variable_ids.index(i) for i in non_ad_variable_ids
            ]
            non_ad_variable_dofs = [
                self._variable_dofs[i] for i in non_ad_variable_local_ids
            ]
            non_ad_vals_list = [state[ind] for ind in non_ad_variable_dofs]
            self._prev_iter_vals = {
                var_id: val
                for (var_id, val) in zip(
                    self._prev_iter_ids + non_ad_variable_ids,
                    prev_iter_vals_list + non_ad_vals_list,
                )
            }

        # Also make mappings from the previous time step.
        prev_vals_list = [prev_vals[ind] for ind in self._prev_time_dofs]
        self._prev_vals = {
            var_id: val for (var_id, val) in zip(self._prev_time_ids, prev_vals_list)
        }

        # Parse operators. This is left to a separate function to facilitate the
        # necessary recursion for complex operators.
        eq = self._parse_operator(self._operator, gb)

        return eq