Exemple #1
0
    def universal_kriging(self, x, y, z, xDim, yDim):

        items = ("linear", "power", "gaussian", "spherical", "exponential")

        item, ok = QtGui.QInputDialog.getItem(self, "Kriging",
                                              "Select a Model", items, 0,
                                              False)

        if (ok):
            data = np.vstack((x, y))
            data = np.vstack((data, z)).T

            UK = UniversalKriging(data[:, 0],
                                  data[:, 1],
                                  data[:, 2],
                                  variogram_model=str(item),
                                  drift_terms=['regional_linear'])

            gridx = np.linspace(np.min(x), np.max(x), xDim)
            gridy = np.linspace(np.min(y), np.max(y), yDim)

            zVals, ss = UK.execute('grid', gridx, gridy)
            self.Z = zVals.data

            self._display_variogram_model(UK)
Exemple #2
0
    def _fit(self, X, y):
        """This method of the Kriging Class is used to fit Kriging interpolation model to
        the train data. This function shouldn't be called directly."""
        if self.type == "Ordinary":
            self.ok = OrdinaryKriging(X[:, 0],
                                      X[:, 1],
                                      y,
                                      variogram_model=self.variogram_model,
                                      enable_plotting=self.plotting,
                                      coordinates_type=self.coordinate_type,
                                      nlags=self.nlags)

        elif self.type == "Universal":
            self.uk = UniversalKriging(
                X[:, 0],
                X[:, 1],
                y,
                variogram_model=self.variogram_model,
                enable_plotting=self.plotting,
            )

        else:
            raise ValueError(
                "Choose either Universal or Ordinary - Given argument is neither"
            )

        return self
def kriging(df, field='Temperature'):
    mapping = LOCATION_MAPPING_AT

    interpolated_map = []
    grid_x = np.arange(MIN_LON, MAX_LON, (MAX_LON - MIN_LON) / SIZE_X)
    grid_y = np.arange(MIN_LAT, MAX_LAT, (MAX_LAT - MIN_LAT) / SIZE_Y)

    high = df[field].max()
    low = df[field].min()
    v_params = {
        'sill': high,
        'range': high - low,
        'nugget': low,
        'slope': high - low
    }

    old_month = 0

    groups = df.groupby('datetime')
    for idx in groups.indices:
        if idx.month > old_month:
            old_month = idx.month
            print('Kriging', idx)

        tmp_df = df.loc[df['datetime'] == idx]
        tmp_df = tmp_df.groupby('postal_code').mean()
        tmp_df = tmp_df.reset_index()

        points_x = [
            mapping['lon'].loc[mapping['zip'] == station].to_numpy().item()
            for station in tmp_df['postal_code'].to_list()
        ]
        points_y = [
            mapping['lat'].loc[mapping['zip'] == station].to_numpy().item()
            for station in tmp_df['postal_code'].to_list()
        ]
        real_values = tmp_df[field].to_numpy().squeeze()

        uk = UniversalKriging(points_x,
                              points_y,
                              real_values,
                              variogram_model='linear',
                              variogram_parameters=v_params)
        z, ss = uk.execute('grid', grid_x, grid_y)
        interpolated_map.append(z.transpose())

    interpolated_map = np.array(interpolated_map)
    return interpolated_map
Exemple #4
0
def plot_the_last_measures():
    data = np.zeros((len(coordinates), 3))
    index = 0
    last_measure = get_values_from_DB.get_last_measure()
    for sensor_key in coordinates:
        data[index][0] = coordinates[sensor_key][0]
        data[index][1] = coordinates[sensor_key][1]
        data[index][2] = last_measure["measure"][sensor_key]
        index += 1
    gridx = np.arange(conf.x_min - conf.x_border, conf.x_max + conf.x_border,
                      conf.x_foot)
    gridy = np.arange(conf.y_min - conf.y_border, conf.y_max + conf.y_border,
                      conf.y_foot)
    input_values = np.zeros((len(gridx), len(gridy)))
    for i in range(len(gridx) - 1):
        for j in range(len(gridy) - 1):
            for sensor_key in coordinates:
                if gridx[i] <= coordinates[sensor_key][0] < gridx[i + 1]:
                    if gridy[j] <= coordinates[sensor_key][1] < gridy[j + 1]:
                        input_values[i][j] = last_measure["measure"][
                            sensor_key]
                        name = 'sensor number ' + str(sensor_key)
                        plt.scatter(i, j, label=name)
    print(data)
    UK = UniversalKriging(
        data[:, 0],
        data[:, 1],
        data[:, 2],
        variogram_model="gaussian",
    )

    z, ss = UK.execute("grid", gridx, gridy)
    print(z)
    # print(input_values)

    plt.imshow(z,
               cmap='gray',
               norm=matplotlib.colors.Normalize(vmin=0, vmax=conf.max_voltage),
               origin='lower')
    string = "heat map (white = Really dry -  black = really wet), made at time" + last_measure[
        'date'][0:19]
    plt.title(string)
    plt.legend()
    plt.show()
Exemple #5
0
def universal_kriging(grid, variogram_model):
    height = grid.shape[0]
    width = grid.shape[1]

    gridx = np.arange(0.0, float(width), 1.0)
    gridy = np.arange(0.0, float(height), 1.0)

    data_size = (~np.isnan(grid)).sum()

    data = np.zeros((data_size, 3))
    c = 0
    for i in range(0, height):
        for j in range(0, width):
            if (not (np.isnan(grid[i, j]))):
                data[c, :] = [i, j, grid[i, j]]
                c += 1

    OK = UniversalKriging(data[:, 1],
                          data[:, 0],
                          data[:, 2],
                          variogram_model=variogram_model)  # pykrige wants xyz
    kriged_grid, var_grid = OK.execute('grid', gridx, gridy)

    return (kriged_grid, var_grid)
Exemple #6
0
class Kriging(Base):
    """A class that is declared for performing Kriging interpolation.
    Kriging interpolation (usually) works on the principle of finding the 
    best unbiased predictor. Ordinary Kriging, for an example, involves finding out the
    best unbaised linear predictor. 

    Parameters
    ----------
    type : str, optional
    This parameter defines the type of Kriging under consideration. This 
    implementation uses PyKrige package  (https://github.com/bsmurphy/PyKrige).
    The user needs to choose between "Ordinary" and "Universal".

    plotting: boolean, optional
    This parameter plots the fit semivariogram. We use PyKrige's inbuilt plotter for the same.s
    
    variogram_model : str, optional
    Specifies which variogram model to use; may be one of the following:
    linear, power, gaussian, spherical, exponential, hole-effect.
    Default is linear variogram model. To utilize a custom variogram model,
    specify 'custom'; you must also provide variogram_parameters and
    variogram_function. Note that the hole-effect model is only technically
    correct for one-dimensional problems.

    require_variance : Boolean, optional
    This variable returns the uncertainity in the interpolated values using Kriging
    interpolation. If this is True, kindly call the attribute return_variance, of this class
    to retreive the computed variances. False is the default value.d
    
	nlags: int, optional
	Number of lags to be considered for semivariogram. As in PyKrige, we set default to be 6.
    """
    def __init__(self,
                 type="Ordinary",
                 plotting=False,
                 variogram_model='linear',
                 require_variance=False,
                 resolution="standard",
                 coordinate_type="Eucledian",
                 nlags=6):

        super().__init__(resolution, coordinate_type)
        self.variogram_model = variogram_model
        self.ok = None
        self.uk = None
        self.type = type
        self.plotting = plotting
        self.coordinate_type = None
        self.require_variance = require_variance
        self.variance = None

        if coordinate_type == "Eucledian":
            self.coordinate_type = 'euclidean'
        else:
            self.coordinate_type = 'geographic'

        self.nlags = nlags

    def _fit(self, X, y):
        """This method of the Kriging Class is used to fit Kriging interpolation model to
        the train data. This function shouldn't be called directly."""
        if self.type == "Ordinary":
            self.ok = OrdinaryKriging(X[:, 0],
                                      X[:, 1],
                                      y,
                                      variogram_model=self.variogram_model,
                                      enable_plotting=self.plotting,
                                      coordinates_type=self.coordinate_type,
                                      nlags=self.nlags)

        elif self.type == "Universal":
            self.uk = UniversalKriging(
                X[:, 0],
                X[:, 1],
                y,
                variogram_model=self.variogram_model,
                enable_plotting=self.plotting,
            )

        else:
            raise ValueError(
                "Choose either Universal or Ordinary - Given argument is neither"
            )

        return self

    def _predict_grid(self, x1lim, x2lim):
        """The function that is called to return the interpolated data in Kriging Interpolation
        in a grid. This method shouldn't be called directly"""
        lims = (*x1lim, *x2lim)
        x1min, x1max, x2min, x2max = lims
        x1 = np.linspace(x1min, x1max, self.resolution)
        x2 = np.linspace(x2min, x2max, self.resolution)

        if self.ok is not None:
            predictions, self.variance = self.ok.execute(style='grid',
                                                         xpoints=x1,
                                                         ypoints=x2)

        else:
            predictions, self.variance = self.uk.execute(style='grid',
                                                         xpoints=x1,
                                                         ypoints=x2)

        return predictions

    def _predict(self, X):
        """This function should be called to return the interpolated data in kriging
        in a pointwise manner. This method shouldn't be called directly."""
        if self.ok is not None:
            predictions, self.variance = self.ok.execute(style='points',
                                                         xpoints=X[:, 0],
                                                         ypoints=X[:, 1])

        else:
            predictions, self.variance = self.uk.execute(style='points',
                                                         xpoints=X[:, 0],
                                                         ypoints=X[:, 1])

        return predictions

    def return_variance(self):
        """This method of the Kriging class returns the variance at the interpolated
        points if the user chooses to use this option at the beginning of the interpolation"""
        if self.require_variance:
            return self.variance

        else:
            print(
                "Variance not asked for, while instantiating the object. Returning None"
            )
            return None
Exemple #7
0
    def uk(self,
           sill,
           vmodel='spherical',
           anisotropy=1.0,
           smoothie=0,
           plane='sn',
           plot=False):
        """
        Performs Universal Kriging (UK) interpolation with defined anisotropy 
        to the instance's data using the specified model for its semivariogram.
        The sill for the semivariogram needs to be defined. The range used is
        equal to the sill times the anisotropy defined.
        
        Args:
                sill <float>        : Sill value for semivariogram in UK
        
        Kwargs: vmodel <str>        : Semivariogram model (default: 'spherical')
                anisotropy <float>  : anisotropy parameter: if >1.0, it brings points closer in the
                                      longitudinal (s) direction, if <1.0 it brings points closer 
                                      in the transverse (n) direction
                smoothie <int>      : smoothing degree (Gaussian window)
                plane <str>         : chooses plane for interpolation; 'xy' for Cartesian, 'sn' for flow-oriented
                plot <boolean>      : decides to plot or not the resulting UK values
        """
        gc.enable()
        print "Calculating: Universal Kriging [UK]"

        uk = deepcopy(self.z)  #avoid overwrite

        #calculate UK with anisotropy defined
        if plane == 'sn':
            UK = UniversalKriging(
                self.s[self.isdata],
                self.n[self.isdata],
                uk[self.isdata],
                anisotropy_scaling=anisotropy,
                anisotropy_angle=0.0,
                nlags=self.cols,
                variogram_model=vmodel,
                variogram_parameters=[sill, sill * anisotropy, 0.0],
                drift_terms=['functional'],
                functional_drift=[self.uk_funct],
                verbose=True,
                enable_plotting=True)
            uk[self.nodata], sigmas = UK.execute('points', self.s[self.nodata],
                                                 self.n[self.nodata])
        elif plane == 'xy':
            x = self.x.flatten()
            y = self.y.flatten()
            UK = UniversalKriging(
                x[self.isdata],
                y[self.isdata],
                uk[self.isdata],
                anisotropy_scaling=anisotropy,
                anisotropy_angle=0.0,
                nlags=self.cols,
                variogram_model=vmodel,
                variogram_parameters=[sill, sill * anisotropy, 0.0],
                drift_terms=['regional_linear'],
                functional_drift=[self.uk_funct],
                verbose=False,
                enable_plotting=False)
            uk[self.nodata], sigmas = UK.execute('points', x[self.nodata],
                                                 y[self.nodata])
        else:
            print "Error: Plane for interpolation not correctly specified. No interpolation performed."
            return

        #grid (matrix) notation
        uk = common.to_grid(uk, self.rows, self.cols)
        #add pre-defined banks
        uk = self.__add_banks(uk)
        #smoothen
        for i in range(self.rows):
            uk[i, :] = common.smooth(uk[i, :], smoothie)
        print "Finished [UK]."
        self.z_interpol = uk
        del uk
        #plot
        if plot:
            self.plot(fignum='UK')
Exemple #8
0
def grid_kriging(static_grid,
                 personal_grid,
                 kriging_type='ordinary',
                 variogram_model='linear',
                 plot_filename=None,
                 vmin=0,
                 vmax=8):
    '''
    perform kriging on PM values
    static_grid, personal_grid are spatial only (dimension n x m) pm values
    kriging type can be ordinary or universal
    variogram model can be linear, gaussian, exponential, spherical
    if plot filename specified plot heatmaps
    returns 
    '''
    grid_dim = static_grid.shape
    # get position of non zero values, will be our x/y coords
    # note y coords must be reversed
    y_coords, x_coords = static_grid.nonzero()
    pm_values = static_grid[(y_coords, x_coords)]

    # create grid of all values
    personal_grid_mask = personal_grid.copy()
    personal_grid_mask[static_grid.nonzero()] = 0
    all_grid = static_grid + personal_grid_mask

    # grid objects to interpolate on
    xgrid = np.arange(grid_dim[1]).astype(np.float64)
    ygrid = np.arange(grid_dim[0]).astype(np.float64)

    # kriging
    if kriging_type == 'ordinary':
        krige = OrdinaryKriging(x_coords,
                                grid_dim[0] - 1 - y_coords,
                                pm_values,
                                variogram_model=variogram_model)
    elif kriging_type == 'universal':
        krige = UniversalKriging(x_coords,
                                 grid_dim[0] - 1 - y_coords,
                                 pm_values,
                                 variogram_model=variogram_model,
                                 drift_terms=['regional_linear'])
    z, ss = krige.execute('grid', xgrid, ygrid)
    z_flip = np.flip(
        z,
        axis=0)  # y coordinate must be flipped to compare to np array indexing

    # losses as dictionary
    errors = {}
    predicted = z_flip[all_grid.nonzero()]
    true = all_grid[all_grid.nonzero()]
    errors['rmse'] = rmse(predicted, true)
    errors['mae'] = mae(predicted, true)
    errors['mape'] = mape(predicted, true)

    if plot_filename is not None:
        plot_kriging_heatmaps(all_grid,
                              static_grid,
                              z_flip,
                              plot_filename=plot_filename,
                              vmin=vmin,
                              vmax=vmax)

    return z_flip, errors
def initFrameValues(frame,
                    type="random",
                    options={
                        'sample_size': 0.02,
                        'sill': 0.05,
                        'range_per': 5.0,
                        'nugget': 0
                    },
                    ked_secondary=None):
    valFrame = []
    if (type == "random"):
        for obs in frame:
            valFrame.append([obs[0], obs[1], random.random()])
        return valFrame

    if (type == "kriging"):
        x, y, z = zip(*frame)
        #Randomly sample from the input frame a set number of seeds to use
        #For kriging.
        # Set as a percentage
        sampleSize = int(options['sample_size'] *
                         len(x))  #int(options[0] * len(x))

        #Create our kriging matrix:
        kMat = random.sample(frame, k=sampleSize)
        sam_x, sam_y, sam_z = zip(*kMat)
        x = [float(i) for i in x]
        y = [float(i) for i in y]
        z = [float(i) for i in z]

        #Calculate the range as a percentage of the maximum distance in the matrix based on the input dimensions
        max_dist = math.sqrt((max(x) - min(x))**2 + (max(y) - min(y))**2)
        options['range'] = max_dist * options['range_per']
        #Krig:
        ok_krig = OrdinaryKriging(sam_x,
                                  sam_y,
                                  sam_z,
                                  variogram_model="spherical",
                                  variogram_parameters={
                                      'sill': options['sill'],
                                      'range': options['range'],
                                      'nugget': options['nugget']
                                  },
                                  verbose=False,
                                  enable_plotting=False)
        #Get results:
        z, ss = ok_krig.execute('points', x, y)
        return (zip(x, y, z))

    if (type == "ked"):
        if (ked_secondary == None):
            print(
                "You must specify a secondary frame to base the drift off of for Kriging with External Drift."
            )
        x, y, z = zip(*frame)
        #Randomly sample from the input frame a set number of seeds to use
        #For kriging.
        # Set as a percentage
        sampleSize = int(options['sample_size'] *
                         len(x))  #int(options[0] * len(x))

        #Create our kriging matrix:
        kMat = random.sample(frame, k=sampleSize)
        sam_x, sam_y, sam_z = zip(*kMat)
        x = [float(i) for i in x]
        y = [float(i) for i in y]
        z = [float(i) for i in z]

        #Create the drift matrix:
        dri_x, dri_y, dri_z = zip(*ked_secondary)
        ked_x = [float(i) for i in dri_x]
        ked_y = [float(i) for i in dri_y]
        ked_z = [float(i) for i in dri_z]
        ked_dta = np.array([ked_x, ked_y, ked_z])

        ked_pd = pd.DataFrame(ked_dta, columns=['x', 'y', 'z'])
        print(ked_pd)
        ked_pivot = ked_pd.pivot_table(values='z', index='x', columns='y')
        print(ked_pivot)
        #Calculate the range as a percentage of the maximum distance in the matrix based on the input dimensions
        max_dist = math.sqrt((max(x) - min(x))**2 + (max(y) - min(y))**2)
        options['range'] = max_dist * options['range_per']

        ked_krig = UniversalKriging(sam_x,
                                    sam_y,
                                    sam_z,
                                    drift_terms='external_Z',
                                    variogram_model="spherical",
                                    point_drift=ked_mat,
                                    variogram_parameters={
                                        'sill': options['sill'],
                                        'range': options['range'],
                                        'nugget': options['nugget']
                                    },
                                    verbose=False,
                                    enable_plotting=False)
        #Get results:
        z, ss = ked_krig.execute('points', x, y)
        return (zip(x, y, z))

    return False
Exemple #10
0
def KrigeCV(P, lags, date, metric, output):
    #create dictionary for gridsearch to use in parameter tuning
    param_dict = {
        "method": ["ordinary", "universal"],
        "variogram_model":
        ["exponential", "gaussian", "linear", "power", "spherical"],
        "nlags":
        lags,
        "weight": [True, False]
    }
    estimator = GridSearchCV(Krige(), param_dict, verbose=False,
                             cv=2)  ###This cv=2 could be adjusted
    X = (P[:, 0:2])  #select x variables
    y = P[:, 2]  #select y variable
    estimator.fit(X=X, y=y)
    if hasattr(estimator, 'best_score_'):
        print('best_score R² = {:.3f}'.format(estimator.best_score_))
        print('Optimal Lags: {}'.format(estimator.best_params_['nlags']))
        print('best_params = ', estimator.best_params_)

    #define grid
    dist = .15
    gridx = np.arange(math.floor(min(P[:, 0])), math.ceil(max(P[:, 0])), dist)
    gridy = np.arange(math.floor(min(P[:, 1])), math.ceil(max(P[:, 1])), dist)
    ##to be used for shapefile output
    #gridxShape = np.arange(math.floor(min(P[:,0])) - (.5*dist), math.ceil(max(P[:,0])) + (.5*dist), dist)
    #gridyShape = np.arange(math.floor(min(P[:,1])) - (.5*dist), math.ceil(max(P[:,1])) + (.5*dist), dist)

    if estimator.best_params_[
            'method'] == 'universal':  #for all universal kriging
        UK = UniversalKriging(
            P[:, 0],
            P[:, 1],
            P[:, 2],
            variogram_model=estimator.best_params_['variogram_model'],
            nlags=estimator.best_params_['nlags'],
            weight=estimator.best_params_['weight'],
            verbose=False,
            enable_plotting=True
        )  #perform kriging with params chosen by gridsearch
        z, ss = UK.execute('grid', gridx, gridy)
        if output == 'ASCII':
            filename = str(date) + '_' + str(
                metric) + '.asc'  #Create unique filename
            kt.write_asc_grid(gridx, gridy, z,
                              filename=filename)  #write out as ASCII file
        elif output == 'Shapefile':
            geo_df = OutputShape(z, gridxShape, gridyShape)
            filename = str(date) + '_' + str(metric) + '.shp'
            geo_df.to_file(filename)
        else:
            print("output parameter must be 'ASCII' or 'Shapefile'. ")
    elif estimator.best_params_[
            'method'] == 'ordinary':  #for all ordinary kriging
        OK = OrdinaryKriging(
            P[:, 0],
            P[:, 1],
            P[:, 2],
            variogram_model=estimator.best_params_['variogram_model'],
            nlags=estimator.best_params_['nlags'],
            weight=estimator.best_params_['weight'],
            verbose=False,
            enable_plotting=True
        )  #perform kriging with params chosen by gridsearch
        z, ss = OK.execute('grid', gridx, gridy)
        if output == 'ASCII':
            filename = str(date) + '_' + str(
                metric) + '.asc'  #Create unique filename
            kt.write_asc_grid(gridx, gridy, z,
                              filename=filename)  #write out as ASCII file
        elif output == 'Shapefile':
            geo_df = OutputShape(z, gridxShape, gridyShape)
            filename = str(date) + '_' + str(metric) + '.shp'
            geo_df.to_file(filename)
        else:
            print("output parameter must be 'ASCII' or 'Shapefile'. ")
    else:
        print('Kriging method not recognized as Universal or Ordinary')
    sub = [
    ]  #create and fill list, to save Rsquared and other outputs/parameters
    sub.extend((date, metric, estimator.best_score_, estimator.best_params_))
    return sub
Exemple #11
0
                 [4.7, 3.8, 1.74]])

nx = 3
ny = 3
gridx = np.arange(0.0, 5.5, 1 / nx)
gridy = np.arange(0.0, 5.5, 1 / ny)

# Create the ordinary kriging object. Required inputs are the X-coordinates of
# the data points, the Y-coordinates of the data points, and the Z-values of the
# data points. Variogram is handled as in the ordinary kriging case.
# drift_terms is a list of the drift terms to include; currently supported terms
# are 'regional_linear', 'point_log', and 'external_Z'. Refer to
# UniversalKriging.__doc__ for more information.
UK = UniversalKriging(data[:, 0],
                      data[:, 1],
                      data[:, 2],
                      variogram_model='linear',
                      drift_terms=['regional_linear'])

OK = OrdinaryKriging(data[:, 0],
                     data[:, 1],
                     data[:, 2],
                     variogram_model='linear',
                     verbose=False,
                     enable_plotting=False)

zordinary, ss = OK.execute('grid', gridx, gridy)
# Creates the kriged grid and the variance grid. Allows for kriging on a rectangular
# grid of points, on a masked rectangular grid of points, or with arbitrary points.
# (See UniversalKriging.__doc__ for more information.)
z, ss = UK.execute('grid', gridx, gridy)
def krige_2d(NTag,
             mh1,
             mh2,
             pdf,
             n_indices=None,
             show=False,
             uk_kwargs=None,
             pairagraph=False):
    """
    Runs universal kriging on the mh1 mh2 pdf data generated earlier

    Returns matrix of predictions and matrix of variances at each point.

    Parameters::
    - NTag: 2 or 4, which data to use
    - mh1, mh2, pdf: data to use for the fit, 1d arrays
    - n_indices: integer, for a sampling of 10 points, say n_indices = 10
    - show: boolean, whether to display plot of predictions
    - uk_kwargs: dict, kwargs for pykrige
    - pairagraph: bool, did we use pairagraph data?
    """

    if n_indices is not None:
        print("sampling", n_indices, "indices")
        indices = np.random.randint(0, len(mh1), n_indices)
        sampled_mh1 = mh1[indices]
        sampled_mh2 = mh2[indices]
        sampled_pdf = pdf[indices]
    else:
        sampled_mh1 = mh1
        sampled_mh2 = mh2
        sampled_pdf = pdf

    if NTag == 4:
        print('removing SR')
        in_SR = binning.binInSR(sampled_mh1, sampled_mh2)
        filtered_mh1 = sampled_mh1[np.logical_not(in_SR)]
        filtered_mh2 = sampled_mh2[np.logical_not(in_SR)]
        filtered_pdf = sampled_pdf[np.logical_not(in_SR)]
    else:
        filtered_mh1 = sampled_mh1
        filtered_mh2 = sampled_mh2
        filtered_pdf = sampled_pdf

    ###########################################################################
    # Create the kriging object. Required inputs are the X-coordinates of
    # the data points, the Y-coordinates of the data points, and the Z-values
    # of the data points. If no variogram model is specified, defaults to a
    # linear variogram model. If no variogram model parameters are specified,
    # then the code automatically calculates the parameters by fitting the
    # variogram model to the binned experimental semivariogram. The verbose
    # kwarg controls code talk-back, and the enable_plotting kwarg controls
    # the display of the semivariogram.
    """
    Variables to play with:

    x, y, z: inputs, don't mess with those

    variogram_model = linear, power, gaussian, spherical, exponential, hole-effect

    variogram_parameters = 
            # linear
               {'slope': slope, 'nugget': nugget}
            # power
               {'scale': scale, 'exponent': exponent, 'nugget': nugget}
            # gaussian, spherical, exponential and hole-effect:
               {'sill': s, 'range': r, 'nugget': n}
               # OR
               {'psill': p, 'range': r, 'nugget': n}
    nlags = integer, default 6
    weight = bool, default False
    drift_terms : list of strings, optional
        List of drift terms to include in universal kriging. Supported drift
        terms are currently 'regional_linear', 'point_log', 'external_Z',
        'specified', and 'functional'.
    exact_values : bool, default True
    """
    UK = UniversalKriging(filtered_mh1,
                          filtered_mh2,
                          filtered_pdf,
                          verbose=True,
                          enable_plotting=False,
                          **uk_kwargs)

    ###########################################################################
    # Creates the kriged grid and the variance grid. Allows for kriging on a
    # rectangular grid of points, on a masked rectangular grid of points, or
    # with arbitrary points. (See UniversalKriging.__doc__ for more info)

    # inputs on which to evaluete the kriged model
    # can be any values really, e.g. these
    #gridx = np.arange(np.min(original_x), np.max(original_x)+1, x_grid_res)
    #gridy = np.arange(np.min(original_y), np.max(original_y)+1, y_grid_res)
    # or evaluate on the original points

    mh1_bins = np.linspace(min(mh1), max(mh1), 200)  # list(sorted(set(x)))
    mh2_bins = np.linspace(min(mh2), max(mh2), 200)  # list(sorted(set(y)))

    #print(len(mh1))
    #print(len(mh1_bins))

    # evaluate
    pdf_pred_grid, variance_grid = UK.execute("grid", mh1_bins, mh2_bins)

    ###########################################################################
    # might as well plot while we're at it
    plot_predictions(mh1_bins,
                     mh2_bins,
                     pdf_pred_grid,
                     NTag,
                     show=show,
                     uk_kwargs=uk_kwargs,
                     pairagraph=pairagraph)
    plot_variance(mh1_bins,
                  mh2_bins,
                  variance_grid,
                  NTag,
                  show=show,
                  uk_kwargs=uk_kwargs,
                  pairagraph=pairagraph)

    ###########################################################################
    # save z preds and variance so we can play with them later
    deal_with_files.save_kriging(NTag,
                                 uk_kwargs,
                                 pdf_pred_grid,
                                 variance_grid,
                                 dim=2,
                                 pairagraph=pairagraph)

    return pdf_pred_grid, variance_grid
Exemple #13
0
    ]
)

gridx = np.arange(0.0, 5.5, 0.5)
gridy = np.arange(0.0, 5.5, 0.5)

###############################################################################
# Create the universal kriging object. Required inputs are the X-coordinates of
# the data points, the Y-coordinates of the data points, and the Z-values of the
# data points. Variogram is handled as in the ordinary kriging case.
# drift_terms is a list of the drift terms to include; currently supported terms
# are 'regional_linear', 'point_log', and 'external_Z'. Refer to
# UniversalKriging.__doc__ for more information.

UK = UniversalKriging(
    data[:, 0],
    data[:, 1],
    data[:, 2],
    variogram_model="linear",
    drift_terms=["regional_linear"],
)

###############################################################################
# Creates the kriged grid and the variance grid. Allows for kriging on a rectangular
# grid of points, on a masked rectangular grid of points, or with arbitrary points.
# (See UniversalKriging.__doc__ for more information.)

z, ss = UK.execute("grid", gridx, gridy)
plt.imshow(z)
plt.show()
Exemple #14
0
maxdist = trg[1, 0] - trg[0, 0]
result_near = ip_near(vals.ravel(), maxdist=maxdist)

# 5.2.3 Kriging ===============================
df_meg_nodes_np = np.array(df_meg_nodes)
gridx = np.arange(0.0, 5.5, 0.5)
gridy = np.arange(0.0, 5.5, 0.5)

# Ordninary Kriging
ok = ipol.OrdinaryKriging(src, trg)
gridplot(ok(vals.ravel()), "Ordinary Kriging")

# Universal Kriging
UK = UniversalKriging(df_meg_nodes_np[:, 0],
                      df_meg_nodes_np[:, 4],
                      df_meg_nodes_np[:, 1],
                      variogram_model='linear',
                      drift_terms=['regional_linear'])
z, ss = UK.execute('grid', xtrg, ytrg)

# Variogram KDE Sample Points
from skgstat import Variogram

data = np.array(df_meg_nodes_np[:, [5, 6, 7]])
coordinates = np.array(data[:, [0, 1]])
values = np.array(data[:, 2])

V_exp = Variogram(coordinates, values, model="exponential")
V_exp.plot()

V_gaussian = Variogram(coordinates, values, model="gaussian")
#ncells = ( xur - xll)/dxy
gridx = np.arange(xll, xll + (ncells * dxy), dxy)
gridy = np.arange(yll, yll + (ncells * dxy), dxy)
#%%
fbound = r'D:\TreasureValley\notebooks\data\gis\TV_bound_2010.shp'
with fiona.open(fbound, 'r') as shp:
    geoms = [feature['geometry'] for feature in shp]
#%%-----------------
# Get drift function for dtw scores
var = 4  # DTW nscores
# Krige to get similar transforms as pykrige
UK = UniversalKriging(data[:, 0],
                      data[:, 1],
                      data[:, var],
                      variogram_model='exponential',
                      weight=True,
                      nlags=20,
                      lagdist=1000,
                      anisotropy_angle=10,
                      anisotropy_scaling=1.6)

UKgrid = UniversalKriging(gridx, gridy, gridy)

XADJ,YADJ = \
    _adjust_for_anisotropy(np.vstack((data[:, 0],data[:, 1])).T,
                          [UK.XCENTER, UK.YCENTER],
                          [UK.anisotropy_scaling],
                          [UK.anisotropy_angle]).T
gridx_adj, gridy_adj = \
    _adjust_for_anisotropy(np.vstack((gridx,gridy)).T,
                           [UKgrid.XCENTER,UKgrid.YCENTER],
Exemple #16
0
 def get_kriger(vel)->UniversalKriging:
     return UniversalKriging(x, y, vel,
                             verbose=False,
                             enable_plotting=False,
                             **self.ukrige_args
                             )