Exemple #1
0
def set_condition(cond_pos, cond_val, max_dim=3):
    """Set the conditions for kriging.

    Parameters
    ----------
    cond_pos : :class:`list`
        the position tuple of the conditions (x, [y, z])
    cond_val : :class:`numpy.ndarray`
        the values of the conditions
    max_dim : :class:`int`, optional
        Cut of information above the given dimension. Default: 3

    Returns
    -------
    cond_pos : :class:`list`
        the error checked cond_pos
    cond_val : :class:`numpy.ndarray`
        the error checked cond_val
    """
    # convert the input for right shapes and dimension checks
    c_x, c_y, c_z = pos2xyz(cond_pos, dtype=np.double, max_dim=max_dim)
    cond_pos = xyz2pos(c_x, c_y, c_z)
    cond_val = np.array(cond_val, dtype=np.double).reshape(-1)
    if not all([len(cond_pos[i]) == len(cond_val) for i in range(max_dim)]):
        raise ValueError(
            "Please check your 'cond_pos' and 'cond_val' parameters. " +
            "The shapes do not match.")
    return cond_pos, cond_val
Exemple #2
0
    def _pre_pos(self, pos, mesh_type="unstructured", make_unstruct=False):
        """
        Preprocessing positions and mesh_type.

        Parameters
        ----------
        pos : :any:`iterable`
            the position tuple, containing main direction and transversal
            directions
        mesh_type : :class:`str`
            'structured' / 'unstructured'
        make_unstruct: :class:`bool`
            State if mesh_type should be made unstructured.

        Returns
        -------
        x : :class:`numpy.ndarray`
            first components of unrotated and isotropic position vectors
        y : :class:`numpy.ndarray` or None
            analog to x
        z : :class:`numpy.ndarray` or None
            analog to x
        pos : :class:`tuple` of :class:`numpy.ndarray`
            the normalized position tuple
        mesh_type_gen : :class:`str`
            'structured' / 'unstructured' for the generator
        mesh_type_changed : :class:`bool`
            State if the mesh_type was changed.
        axis_lens : :class:`tuple` or :any:`None`
            axis lengths of the structured mesh if mesh type was changed.
        """
        x, y, z = pos2xyz(pos, max_dim=self.model.dim)
        pos = xyz2pos(x, y, z)
        mesh_type_gen = mesh_type
        # format the positional arguments of the mesh
        check_mesh(self.model.dim, x, y, z, mesh_type)
        mesh_type_changed = False
        axis_lens = None
        if (self.model.do_rotation
                or make_unstruct) and mesh_type == "structured":
            mesh_type_changed = True
            mesh_type_gen = "unstructured"
            x, y, z, axis_lens = reshape_axis_from_struct_to_unstruct(
                self.model.dim, x, y, z)
        if self.model.do_rotation:
            x, y, z = unrotate_mesh(self.model.dim, self.model.angles, x, y, z)
        if not self.model.is_isotropic:
            y, z = make_isotropic(self.model.dim, self.model.anis, y, z)
        return x, y, z, pos, mesh_type_gen, mesh_type_changed, axis_lens
Exemple #3
0
    def set_condition(self, cond_pos, cond_val):
        """Set the conditions for kriging.

        Parameters
        ----------
        cond_pos : :class:`list`
            the position tuple of the conditions (x, [y, z])
        cond_val : :class:`numpy.ndarray`
            the values of the conditions
        """
        self._c_x, self._c_y, self._c_z = pos2xyz(
            cond_pos, dtype=np.double, max_dim=self.model.dim
        )
        self._cond_pos = xyz2pos(self._c_x, self._c_y, self._c_z)
        self._cond_val = np.array(cond_val, dtype=np.double).reshape(-1)
Exemple #4
0
 def _get_krige_vecs(self, pos, chunk_slice=(0, None), ext_drift=None):
     """Calculate the RHS of the kriging equation."""
     chunk_size = len(pos[0]) if chunk_slice[1] is None else chunk_slice[1]
     chunk_size -= chunk_slice[0]
     size = self.cond_no + int(self.unbiased) + self.drift_no
     res = np.empty((size, chunk_size), dtype=np.double)
     res[:self.cond_no, :] = self.model.vario_nugget(
         self._get_dists(self._krige_pos, pos, chunk_slice))
     if self.unbiased:
         res[self.cond_no, :] = 1
     # trend function need the anisotropic and rotated positions
     if not self.model.is_isotropic:
         x, y, z = pos2xyz(pos, max_dim=self.model.dim)
         y, z = make_anisotropic(self.model.dim, self.model.anis, y, z)
         if self.model.do_rotation:
             x, y, z = rotate_mesh(self.model.dim, self.model.angles, x, y,
                                   z)
         pos = xyz2pos(x, y, z, max_dim=self.model.dim)
     chunk_pos = list(pos[:self.model.dim])
     for i in range(self.model.dim):
         chunk_pos[i] = chunk_pos[i][slice(*chunk_slice)]
     for i, f in enumerate(self.drift_functions):
         res[-self.drift_no + i, :] = f(*chunk_pos)
     return res
Exemple #5
0
    def __call__(
        self, pos, seed=np.nan, point_volumes=0.0, mesh_type="unstructured"
    ):
        """Generate the spatial random field.

        The field is saved as `self.field` and is also returned.

        Parameters
        ----------
        pos : :class:`list`
            the position tuple, containing main direction and transversal
            directions
        seed : :class:`int`, optional
            seed for RNG for reseting. Default: keep seed from generator
        point_volumes : :class:`float` or :class:`numpy.ndarray`
            If your evaluation points for the field are coming from a mesh,
            they are probably representing a certain element volume.
            This volume can be passed by `point_volumes` to apply the
            given variance upscaling. If `point_volumes` is ``0`` nothing
            is changed. Default: ``0``
        mesh_type : :class:`str`
            'structured' / 'unstructured'

        Returns
        -------
        field : :class:`numpy.ndarray`
            the SRF
        """
        # internal conversation
        x, y, z = pos2xyz(pos, max_dim=self.model.dim)
        self.pos = xyz2pos(x, y, z)
        self.mesh_type = mesh_type
        # update the model/seed in the generator if any changes were made
        self.generator.update(self.model, seed)
        # format the positional arguments of the mesh
        check_mesh(self.model.dim, x, y, z, mesh_type)
        mesh_type_changed = False
        if self.model.do_rotation:
            if mesh_type == "structured":
                mesh_type_changed = True
                mesh_type_old = mesh_type
                mesh_type = "unstructured"
                x, y, z, axis_lens = reshape_axis_from_struct_to_unstruct(
                    self.model.dim, x, y, z
                )
            x, y, z = unrotate_mesh(self.model.dim, self.model.angles, x, y, z)
        y, z = make_isotropic(self.model.dim, self.model.anis, y, z)

        # generate the field
        self.raw_field = self.generator.__call__(x, y, z, mesh_type)

        # reshape field if we got an unstructured mesh
        if mesh_type_changed:
            mesh_type = mesh_type_old
            self.raw_field = reshape_field_from_unstruct_to_struct(
                self.model.dim, self.raw_field, axis_lens
            )

        # apply given conditions to the field
        if self.condition:
            (
                cond_field,
                krige_field,
                err_field,
                krigevar,
                info,
            ) = self.cond_func(self)
            # store everything in the class
            self.field = cond_field
            self.krige_field = krige_field
            self.err_field = err_field
            self.krige_var = krigevar
            if "mean" in info:  # ordinary krging estimates mean
                self.mean = info["mean"]
        else:
            self.field = self.raw_field + self.mean

        # upscaled variance
        if not np.isscalar(point_volumes) or not np.isclose(point_volumes, 0):
            scaled_var = self.upscaling_func(self.model, point_volumes)
            self.field -= self.mean
            self.field *= np.sqrt(scaled_var / self.model.sill)
            self.field += self.mean

        return self.field
Exemple #6
0
    def __call__(self, pos, mesh_type="unstructured"):
        """
        Generate the ordinary kriging field.

        The field is saved as `self.field` and is also returned.

        Parameters
        ----------
        pos : :class:`list`
            the position tuple, containing main direction and transversal
            directions (x, [y, z])
        mesh_type : :class:`str`
            'structured' / 'unstructured'

        Returns
        -------
        field : :class:`numpy.ndarray`
            the kriged field
        krige_var : :class:`numpy.ndarray`
            the kriging error variance
        """
        # internal conversation
        x, y, z = pos2xyz(pos, dtype=np.double, max_dim=self.model.dim)
        c_x, c_y, c_z = pos2xyz(self.cond_pos,
                                dtype=np.double,
                                max_dim=self.model.dim)
        self.pos = xyz2pos(x, y, z)
        self.mesh_type = mesh_type
        # format the positional arguments of the mesh
        check_mesh(self.model.dim, x, y, z, mesh_type)
        mesh_type_changed = False
        if mesh_type == "structured":
            mesh_type_changed = True
            mesh_type_old = mesh_type
            mesh_type = "unstructured"
            x, y, z, axis_lens = reshape_axis_from_struct_to_unstruct(
                self.model.dim, x, y, z)
        if self.model.do_rotation:
            x, y, z = unrotate_mesh(self.model.dim, self.model.angles, x, y, z)
            c_x, c_y, c_z = unrotate_mesh(self.model.dim, self.model.angles,
                                          c_x, c_y, c_z)
        y, z = make_isotropic(self.model.dim, self.model.anis, y, z)
        c_y, c_z = make_isotropic(self.model.dim, self.model.anis, c_y, c_z)

        # set condtions
        cond = np.concatenate((self.cond_val, [0]))
        krig_mat = inv(self._get_krig_mat((c_x, c_y, c_z), (c_x, c_y, c_z)))
        krig_vecs = self._get_vario_mat((c_x, c_y, c_z), (x, y, z), add=True)
        # generate the kriged field
        field, krige_var = krigesum(krig_mat, krig_vecs, cond)
        # calculate the estimated mean (kriging field at infinity)
        mean_est = np.concatenate((np.full_like(self.cond_val,
                                                self.model.sill), [1]))
        self.mean = np.einsum("i,ij,j", cond, krig_mat, mean_est)

        # reshape field if we got an unstructured mesh
        if mesh_type_changed:
            mesh_type = mesh_type_old
            field = reshape_field_from_unstruct_to_struct(
                self.model.dim, field, axis_lens)
            krige_var = reshape_field_from_unstruct_to_struct(
                self.model.dim, krige_var, axis_lens)
        # save the field
        self.krige_var = krige_var
        self.field = field
        return self.field, self.krige_var
Exemple #7
0
    def __call__(self, pos, mesh_type="unstructured"):
        """
        Generate the simple kriging field.

        The field is saved as `self.field` and is also returned.

        Parameters
        ----------
        pos : :class:`list`
            the position tuple, containing main direction and transversal
            directions (x, [y, z])
        mesh_type : :class:`str`
            'structured' / 'unstructured'

        Returns
        -------
        field : :class:`numpy.ndarray`
            the kriged field
        krige_var : :class:`numpy.ndarray`
            the kriging error variance
        """
        # internal conversation
        x, y, z = pos2xyz(pos, dtype=np.double, max_dim=self.model.dim)
        c_x, c_y, c_z = pos2xyz(self.cond_pos,
                                dtype=np.double,
                                max_dim=self.model.dim)
        self.pos = xyz2pos(x, y, z)
        self.mesh_type = mesh_type
        # format the positional arguments of the mesh
        check_mesh(self.model.dim, x, y, z, mesh_type)
        mesh_type_changed = False
        if mesh_type == "structured":
            mesh_type_changed = True
            mesh_type_old = mesh_type
            mesh_type = "unstructured"
            x, y, z, axis_lens = reshape_axis_from_struct_to_unstruct(
                self.model.dim, x, y, z)
        if self.model.do_rotation:
            x, y, z = unrotate_mesh(self.model.dim, self.model.angles, x, y, z)
            c_x, c_y, c_z = unrotate_mesh(self.model.dim, self.model.angles,
                                          c_x, c_y, c_z)
        y, z = make_isotropic(self.model.dim, self.model.anis, y, z)
        c_y, c_z = make_isotropic(self.model.dim, self.model.anis, c_y, c_z)

        # set condtions to zero mean
        cond = self.cond_val - self.mean
        krig_mat = inv(self._get_cov_mat((c_x, c_y, c_z), (c_x, c_y, c_z)))
        krig_vecs = self._get_cov_mat((c_x, c_y, c_z), (x, y, z))
        # generate the kriged field
        field, krige_var = krigesum(krig_mat, krig_vecs, cond)

        # reshape field if we got an unstructured mesh
        if mesh_type_changed:
            mesh_type = mesh_type_old
            field = reshape_field_from_unstruct_to_struct(
                self.model.dim, field, axis_lens)
            krige_var = reshape_field_from_unstruct_to_struct(
                self.model.dim, krige_var, axis_lens)
        # calculate the kriging error
        self.krige_var = self.model.sill - krige_var
        # add the given mean
        self.field = field + self.mean
        return self.field, self.krige_var