forked from GatorGlaciology/GStatSim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgstatsim.py
1395 lines (1172 loc) · 56.4 KB
/
gstatsim.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding: utf-8
### geostatistical tools
import numpy as np
import numpy.linalg as linalg
import pandas as pd
import sklearn as sklearn
from sklearn.neighbors import KDTree
import math
from scipy.spatial import distance_matrix
from scipy.interpolate import Rbf
from tqdm import tqdm
import random
from sklearn.metrics import pairwise_distances
############################
# Grid data
############################
class Gridding:
def prediction_grid(xmin, xmax, ymin, ymax, res):
"""
Make prediction grid
Parameters
----------
xmin : float, int
minimum x extent
xmax : float, int
maximum x extent
ymin : float, int
minimum y extent
ymax : float, int
maximum y extent
res : float, int
grid cell resolution
Returns
-------
prediction_grid_xy : numpy.ndarray
x,y array of coordinates
"""
cols = np.rint((xmax - xmin + res)/res)
rows = np.rint((ymax - ymin + res)/res)
x = np.linspace(xmin, xmin+(cols*res), num=int(cols), endpoint=False)
y = np.linspace(ymin, ymin+(rows*res), num=int(rows), endpoint=False)
xx, yy = np.meshgrid(x,y)
yy = np.flip(yy)
x = np.reshape(xx, (int(rows)*int(cols), 1))
y = np.reshape(yy, (int(rows)*int(cols), 1))
prediction_grid_xy = np.concatenate((x,y), axis = 1)
return prediction_grid_xy
def make_grid(xmin, xmax, ymin, ymax, res):
"""
Generate coordinates for output of gridded data
Parameters
----------
xmin : float, int
minimum x extent
xmax : float, int
maximum x extent
ymin : float, int
minimum y extent
ymax : float, int
maximum y extent
res : float, int
grid cell resolution
Returns
-------
prediction_grid_xy : numpy.ndarray
x,y array of coordinates
rows : int
number of rows
cols : int
number of columns
"""
cols = np.rint((xmax - xmin)/res)
rows = np.rint((ymax - ymin)/res)
rows = rows.astype(int)
cols = cols.astype(int)
x = np.arange(xmin,xmax,res); y = np.arange(ymin,ymax,res)
xx, yy = np.meshgrid(x,y)
x = np.reshape(xx, (int(rows)*int(cols), 1))
y = np.reshape(yy, (int(rows)*int(cols), 1))
prediction_grid_xy = np.concatenate((x,y), axis = 1)
return prediction_grid_xy, cols, rows
def grid_data(df, xx, yy, zz, res):
"""
Grid conditioning data
Parameters
----------
df : pandas DataFrame
dataframe of conditioning data and coordinates
xx : string
column name for x coordinates of input data frame
yy : string
column name for y coordinates of input data frame
zz : string
column for z values (or data variable) of input data frame
res : float, int
grid cell resolution
Returns
-------
df_grid : pandas DataFrame
dataframe of gridded data
grid_matrix : numpy.ndarray
matrix of gridded data
rows : int
number of rows in grid_matrix
cols : int
number of columns in grid_matrix
"""
df = df.rename(columns = {xx: "X", yy: "Y", zz: "Z"})
xmin = df['X'].min()
xmax = df['X'].max()
ymin = df['Y'].min()
ymax = df['Y'].max()
# make array of grid coordinates
grid_coord, cols, rows = Gridding.make_grid(xmin, xmax, ymin, ymax, res)
df = df[['X','Y','Z']]
np_data = df.to_numpy()
np_resize = np.copy(np_data)
origin = np.array([xmin,ymin])
resolution = np.array([res,res])
# shift and re-scale the data by subtracting origin and dividing by resolution
np_resize[:,:2] = np.rint((np_resize[:,:2]-origin)/resolution)
grid_sum = np.zeros((rows,cols))
grid_count = np.copy(grid_sum)
for i in range(np_data.shape[0]):
xindex = np.int32(np_resize[i,1])
yindex = np.int32(np_resize[i,0])
if ((xindex >= rows) | (yindex >= cols)):
continue
grid_sum[xindex,yindex] = np_data[i,2] + grid_sum[xindex,yindex]
grid_count[xindex,yindex] = 1 + grid_count[xindex,yindex]
np.seterr(invalid='ignore')
grid_matrix = np.divide(grid_sum, grid_count)
grid_array = np.reshape(grid_matrix,[rows*cols])
grid_sum = np.reshape(grid_sum,[rows*cols])
grid_count = np.reshape(grid_count,[rows*cols])
# make dataframe
grid_total = np.array([grid_coord[:,0], grid_coord[:,1],
grid_sum, grid_count, grid_array])
df_grid = pd.DataFrame(grid_total.T,
columns = ['X', 'Y', 'Sum', 'Count', 'Z'])
grid_matrix = np.flipud(grid_matrix)
return df_grid, grid_matrix, rows, cols
###################################
# RBF trend estimation
###################################
def rbf_trend(grid_matrix, smooth_factor, res):
"""
Estimate trend using radial basis functions
Parameters
----------
grid_matrix : numpy.ndarray
matrix of gridded conditioning data
smooth_factor : float
Parameter controlling smoothness of trend. Values greater than
zero increase the smoothness of the approximation.
res : float
grid cell resolution
Returns
-------
trend_rbf : numpy.ndarray
RBF trend estimate
"""
sigma = np.rint(smooth_factor/res)
ny, nx = grid_matrix.shape
rbfi = Rbf(np.where(~np.isnan(grid_matrix))[1],
np.where(~np.isnan(grid_matrix))[0],
grid_matrix[~np.isnan(grid_matrix)],smooth = sigma)
# evaluate RBF
yi = np.arange(nx)
xi = np.arange(ny)
xi,yi = np.meshgrid(xi, yi)
trend_rbf = rbfi(xi, yi)
return trend_rbf
####################################
# Nearest neighbor octant search
####################################
class NearestNeighbor:
def center(arrayx, arrayy, centerx, centery):
"""
Shift data points so that grid cell of interest is at the origin
Parameters
----------
arrayx : numpy.ndarray
x coordinates of data
arrayy : numpy.ndarray
y coordinates of data
centerx : float
x coordinate of grid cell of interest
centery : float
y coordinate of grid cell of interest
Returns
-------
centered_array : numpy.ndarray
array of coordinates that are shifted with respect to grid cell of interest
"""
centerx = arrayx - centerx
centery = arrayy - centery
centered_array = np.array([centerx, centery])
return centered_array
def distance_calculator(centered_array):
"""
Compute distances between coordinates and the origin
Parameters
----------
centered_array : numpy.ndarray
array of coordinates
Returns
-------
dist : numpy.ndarray
array of distances between coordinates and origin
"""
dist = np.linalg.norm(centered_array, axis=0)
return dist
def angle_calculator(centered_array):
"""
Compute angles between coordinates and the origin
Parameters
----------
centered_array : numpy.ndarray
array of coordinates
Returns
-------
angles : numpy.ndarray
array of angles between coordinates and origin
"""
angles = np.arctan2(centered_array[0], centered_array[1])
return angles
def nearest_neighbor_search(radius, num_points, loc, data2):
"""
Nearest neighbor octant search
Parameters
----------
radius : int, float
search radius
num_points : int
number of points to search for
loc : numpy.ndarray
coordinates for grid cell of interest
data2 : pandas DataFrame
data
Returns
-------
near : numpy.ndarray
nearest neighbors
"""
locx = loc[0]
locy = loc[1]
data = data2.copy()
centered_array = NearestNeighbor.center(data['X'].values, data['Y'].values,
locx, locy)
data["dist"] = NearestNeighbor.distance_calculator(centered_array)
data["angles"] = NearestNeighbor.angle_calculator(centered_array)
data = data[data.dist < radius]
data = data.sort_values('dist', ascending = True)
bins = [-math.pi, -3*math.pi/4, -math.pi/2, -math.pi/4, 0,
math.pi/4, math.pi/2, 3*math.pi/4, math.pi]
data["Oct"] = pd.cut(data.angles, bins = bins, labels = list(range(8)))
oct_count = num_points // 8
smallest = np.ones(shape=(num_points, 3)) * np.nan
for i in range(8):
octant = data[data.Oct == i].iloc[:oct_count][['X','Y','Z']].values
for j, row in enumerate(octant):
smallest[i*oct_count+j,:] = row
near = smallest[~np.isnan(smallest)].reshape(-1,3)
return near
def nearest_neighbor_search_cluster(radius, num_points, loc, data2):
"""
Nearest neighbor octant search when doing sgs with clusters
Parameters
----------
radius : int, float
search radius
num_points : int
number of points to search for
loc : numpy.ndarray
coordinates for grid cell of interest
data2 : pandas DataFrame
data
Returns
-------
near : numpy.ndarray
nearest neighbors
cluster_number : int
nearest neighbor cluster number
"""
locx = loc[0]
locy = loc[1]
data = data2.copy()
centered_array = NearestNeighbor.center(data['X'].values, data['Y'].values,
locx, locy)
data["dist"] = NearestNeighbor.distance_calculator(centered_array)
data["angles"] = NearestNeighbor.angle_calculator(centered_array)
data = data[data.dist < radius]
data = data.sort_values('dist', ascending = True)
data = data.reset_index()
cluster_number = data.K[0]
bins = [-math.pi, -3*math.pi/4, -math.pi/2, -math.pi/4, 0,
math.pi/4, math.pi/2, 3*math.pi/4, math.pi]
data["Oct"] = pd.cut(data.angles, bins = bins, labels = list(range(8)))
oct_count = num_points // 8
smallest = np.ones(shape=(num_points, 3)) * np.nan
for i in range(8):
octant = data[data.Oct == i].iloc[:oct_count][['X','Y','Z']].values
for j, row in enumerate(octant):
smallest[i*oct_count+j,:] = row
near = smallest[~np.isnan(smallest)].reshape(-1,3)
return near, cluster_number
def nearest_neighbor_secondary(loc, data2):
"""
Find the neareset neighbor secondary data point to grid cell of interest
Parameters
----------
loc : numpy.ndarray
coordinates for grid cell of interest
data2 : pandas DataFrame
secondary data
Returns
-------
nearest_second : float
nearest neighbor value to secondary data
"""
locx = loc[0]
locy = loc[1]
data = data2.copy()
centered_array = NearestNeighbor.center(data['X'].values, data['Y'].values,
locx, locy)
data["dist"] = NearestNeighbor.distance_calculator(centered_array)
data = data.sort_values('dist', ascending = True)
data = data.reset_index()
nearest_second = data.iloc[0][['X','Y','Z']].values
return nearest_second
def find_colocated(df1, xx1, yy1, zz1, df2, xx2, yy2, zz2):
"""
Find colocated data between primary and secondary variables
Parameters
----------
df1 : pandas DataFrame
data frame of primary conditioning data
xx1 : string
column name for x coordinates of input data frame for primary data
yy1 : string
column name for y coordinates of input data frame for primary data
zz1 : string
column for z values (or data variable) of input data frame for primary data
df2 : pandas DataFrame
data frame of secondary data
xx2 : string
column name for x coordinates of input data frame for secondary data
yy2 : string
column name for y coordinates of input data frame for secondary data
zz2 : string
column for z values (or data variable) of input data frame for secondary data
Returns
-------
df_colocated : pandas DataFrame
data frame of colocated values
"""
df1 = df1.rename(columns = {xx1: "X", yy1: "Y", zz1: "Z"})
df2 = df2.rename(columns = {xx2: "X", yy2: "Y", zz2: "Z"})
secondary_variable_xy = df2[['X','Y']].values
secondary_variable_tree = KDTree(secondary_variable_xy)
primary_variable_xy = df1[['X','Y']].values
nearest_indices = np.zeros(len(primary_variable_xy))
# query search tree
for i in range(0,len(primary_variable_xy)):
nearest_indices[i] = secondary_variable_tree.query(primary_variable_xy[i:i+1,:],
k=1,return_distance=False)
nearest_indices = np.transpose(nearest_indices)
secondary_data = df2['Z']
colocated_secondary_data = secondary_data[nearest_indices]
df_colocated = pd.DataFrame(np.array(colocated_secondary_data).T, columns = ['colocated'])
df_colocated.reset_index(drop=True, inplace=True)
return df_colocated
###############################
# adaptive partioning
###############################
def adaptive_partitioning(df_data, xmin, xmax, ymin, ymax, i, max_points, min_length, max_iter=None):
"""
Rercursively split clusters until they are all below max_points, but don't go smaller than min_length
Parameters
----------
df_data : pandas DataFrame
DataFrame with X, Y, and K (cluster id) columns
xmin : float
min x value of this partion
xmax : float
max x value of this partion
ymin : float
min y value of this partion
ymax : float
max y value of this partion
i : int
keeps track of total calls to this function
max_points : int
all clusters will be "quartered" until points below this
min_length : float
minimum side length of sqaures, preference over max_points
max_iter : int
maximum iterations if worried about unending recursion
Returns
-------
df_data : pandas DataFrame
updated DataFrame with new cluster assigned
i : int
number of iterations
"""
# optional 'safety' if there is concern about runaway recursion
if max_iter is not None:
if i >= max_iter:
return df_data, i
dx = xmax - xmin
dy = ymax - ymin
# >= and <= greedy so we don't miss any points
xleft = (df_data.X >= xmin) & (df_data.X <= xmin+dx/2)
xright = (df_data.X <= xmax) & (df_data.X >= xmin+dx/2)
ybottom = (df_data.Y >= ymin) & (df_data.Y <= ymin+dy/2)
ytop = (df_data.Y <= ymax) & (df_data.Y >= ymin+dy/2)
# index the current cell into 4 quarters
q1 = df_data.loc[xleft & ybottom]
q2 = df_data.loc[xleft & ytop]
q3 = df_data.loc[xright & ytop]
q4 = df_data.loc[xright & ybottom]
# for each quarter, qaurter if too many points, else assign K and return
for q in [q1, q2, q3, q4]:
if (q.shape[0] > max_points) & (dx/2 > min_length):
i = i+1
df_data, i = adaptive_partitioning(df_data, q.X.min(),
q.X.max(), q.Y.min(), q.Y.max(), i,
max_points, min_length, max_iter)
else:
qcount = df_data.K.max()
# ensure zero indexing
if np.isnan(qcount) == True:
qcount = 0
else:
qcount += 1
df_data.loc[q.index, 'K'] = qcount
return df_data, i
#########################
# Rotation Matrix
#########################
def make_rotation_matrix(azimuth, major_range, minor_range):
"""
Make rotation matrix for accommodating anisotropy
Parameters
----------
azimuth : int, float
angle (in degrees from horizontal) of axis of orientation
major_range : int, float
range parameter of variogram in major direction, or azimuth
minor_range : int, float
range parameter of variogram in minor direction, or orthogonal to azimuth
Returns
-------
rotation_matrix : numpy.ndarray
2x2 rotation matrix used to perform coordinate transformations
"""
theta = (azimuth / 180.0) * np.pi
rotation_matrix = np.dot(
np.array([[np.cos(theta), -np.sin(theta)],
[np.sin(theta), np.cos(theta)],]),
np.array([[1 / major_range, 0], [0, 1 / minor_range]]))
return rotation_matrix
###########################
# Covariance functions
###########################
class Covariance:
def covar(effective_lag, sill, nug, vtype):
"""
Compute covariance
Parameters
----------
effective_lag : int, float
lag distance that is normalized to a range of 1
sill : int, float
sill of variogram
nug : int, float
nugget of variogram
vtype : string
type of variogram model (Exponential, Gaussian, or Spherical)
Raises
------
AtrributeError : if vtype is not 'Exponential', 'Gaussian', or 'Spherical'
Returns
-------
c : numpy.ndarray
covariance
"""
if vtype.lower() == 'exponential':
c = (sill - nug)*np.exp(-3 * effective_lag)
elif vtype.lower() == 'gaussian':
c = (sill - nug)*np.exp(-3 * np.square(effective_lag))
elif vtype.lower() == 'spherical':
c = sill - nug - 1.5 * effective_lag + 0.5 * np.power(effective_lag, 3)
c[effective_lag > 1] = sill - 1
else:
raise AttributeError(f"vtype must be 'Exponential', 'Gaussian', or 'Spherical'")
return c
def make_covariance_matrix(coord, vario, rotation_matrix):
"""
Make covariance matrix showing covariances between each pair of input coordinates
Parameters
----------
coord : numpy.ndarray
coordinates of data points
vario : list
list of variogram parameters [azimuth, nugget, major_range, minor_range, sill, vtype]
azimuth, nugget, major_range, minor_range, and sill can be int or float type
vtype is a string that can be either 'Exponential', 'Spherical', or 'Gaussian'
rotation_matrix : numpy.ndarray
rotation matrix used to perform coordinate transformations
Returns
-------
covariance_matrix : numpy.ndarray
nxn matrix of covariance between n points
"""
nug = vario[1]
sill = vario[4]
vtype = vario[5]
mat = np.matmul(coord, rotation_matrix)
effective_lag = pairwise_distances(mat,mat)
covariance_matrix = Covariance.covar(effective_lag, sill, nug, vtype)
return covariance_matrix
def make_covariance_array(coord1, coord2, vario, rotation_matrix):
"""
Make covariance array showing covariances between each data points and grid cell of interest
Parameters
----------
coord1 : numpy.ndarray
coordinates of n data points
coord2 : numpy.ndarray
coordinates of grid cell of interest (i.e. grid cell being simulated) that is repeated n times
vario : list
list of variogram parameters [azimuth, nugget, major_range, minor_range, sill, vtype]
azimuth, nugget, major_range, minor_range, and sill can be int or float type
vtype is a string that can be either 'Exponential', 'Spherical', or 'Gaussian'
rotation_matrix - rotation matrix used to perform coordinate transformations
Returns
-------
covariance_array : numpy.ndarray
nx1 array of covariance between n points and grid cell of interest
"""
nug = vario[1]
sill = vario[4]
vtype = vario[5]
mat1 = np.matmul(coord1, rotation_matrix)
mat2 = np.matmul(coord2.reshape(-1,2), rotation_matrix)
effective_lag = np.sqrt(np.square(mat1 - mat2).sum(axis=1))
covariance_array = Covariance.covar(effective_lag, sill, nug, vtype)
return covariance_array
######################################
# Simple Kriging Function
######################################
class Interpolation:
def skrige(prediction_grid, df, xx, yy, zz, num_points, vario, radius, quiet=False):
"""
Simple kriging interpolation
Parameters
----------
prediction_grid : numpy.ndarray
x,y coordinate numpy array of prediction grid, or grid cells that will be estimated
df : pandas DataFrame
data frame of conditioning data
xx : string
column name for x coordinates of input data frame
yy : string
column name for y coordinates of input data frame
zz : string
column for z values (or data variable) of input data frame
num_points : int
the number of conditioning points to search for
vario : list
list of variogram parameters [azimuth, nugget, major_range, minor_range, sill, vtype]
azimuth, nugget, major_range, minor_range, and sill can be int or float type
vtype is a string that can be either 'Exponential', 'Spherical', or 'Gaussian'
radius : int, float
search radius
quiet : bool
If False, a progress bar will be printed to the console.
Default is False
Returns
-------
est_sk : numpy.ndarray
simple kriging estimate for each coordinate in prediction_grid
var_sk : numpy.ndarray
simple kriging variance
"""
# unpack variogram parameters
azimuth = vario[0]
major_range = vario[2]
minor_range = vario[3]
rotation_matrix = make_rotation_matrix(azimuth, major_range, minor_range)
df = df.rename(columns = {xx: "X", yy: "Y", zz: "Z"})
mean_1 = df['Z'].mean()
var_1 = vario[4]
est_sk = np.zeros(shape=len(prediction_grid))
var_sk = np.zeros(shape=len(prediction_grid))
# build the iterator
if not quiet:
_iterator = enumerate(tqdm(prediction_grid, position=0, leave=True))
else:
_iterator = enumerate(prediction_grid)
# for each coordinate in the prediction grid
for z, predxy in _iterator:
test_idx = np.sum(prediction_grid[z]==df[['X', 'Y']].values,axis = 1)
if np.sum(test_idx==2)==0:
# gather nearest points within radius
nearest = NearestNeighbor.nearest_neighbor_search(radius, num_points,
prediction_grid[z], df[['X','Y','Z']])
norm_data_val = nearest[:,-1]
xy_val = nearest[:, :-1]
new_num_pts = len(nearest)
# covariance between data
covariance_matrix = Covariance.make_covariance_matrix(xy_val,
vario, rotation_matrix)
# covariance between data and unknown
covariance_array = Covariance.make_covariance_array(xy_val,
np.tile(prediction_grid[z], new_num_pts),
vario, rotation_matrix)
k_weights, res, rank, s = np.linalg.lstsq(covariance_matrix,
covariance_array, rcond = None)
est_sk[z] = mean_1 + (np.sum(k_weights*(norm_data_val[:] - mean_1)))
var_sk[z] = var_1 - np.sum(k_weights*covariance_array)
var_sk[var_sk < 0] = 0
else:
est_sk[z] = df['Z'].values[np.where(test_idx==2)[0][0]]
var_sk[z] = 0
return est_sk, var_sk
def okrige(prediction_grid, df, xx, yy, zz, num_points, vario, radius, quiet=False):
"""
Ordinary kriging interpolation
Parameters
----------
prediction_grid : numpy.ndarray
x,y coordinate numpy array of prediction grid, or grid cells that will be estimated
df : pandas DataFrame
data frame of conditioning data
xx : string
column name for x coordinates of input data frame
yy : string
column name for y coordinates of input data frame
zz : string
column for z values (or data variable) of input data frame
num_points : int
the number of conditioning points to search for
vario : list
list of variogram parameters [azimuth, nugget, major_range, minor_range, sill, vtype]
azimuth, nugget, major_range, minor_range, and sill can be int or float type
vtype is a string that can be either 'Exponential', 'Spherical', or 'Gaussian'
radius : int, float
search radius
quiet : bool
If False, a progress bar will be printed to the console.
Default is False
Returns
-------
est_ok : numpy.ndarray
ordinary kriging estimate for each coordinate in prediction_grid
var_ok : numpy.ndarray
ordinary kriging variance
"""
# unpack variogram parameters
azimuth = vario[0]
major_range = vario[2]
minor_range = vario[3]
rotation_matrix = make_rotation_matrix(azimuth, major_range, minor_range)
df = df.rename(columns = {xx: "X", yy: "Y", zz: "Z"})
var_1 = vario[4]
est_ok = np.zeros(shape=len(prediction_grid))
var_ok = np.zeros(shape=len(prediction_grid))
# build the iterator
if not quiet:
_iterator = enumerate(tqdm(prediction_grid, position=0, leave=True))
else:
_iterator = enumerate(prediction_grid)
for z, predxy in _iterator:
test_idx = np.sum(prediction_grid[z]==df[['X', 'Y']].values,axis = 1)
if np.sum(test_idx==2)==0:
# find nearest data points
nearest = NearestNeighbor.nearest_neighbor_search(radius, num_points,
prediction_grid[z], df[['X','Y','Z']])
norm_data_val = nearest[:,-1]
local_mean = np.mean(norm_data_val)
xy_val = nearest[:,:-1]
new_num_pts = len(nearest)
# covariance between data
covariance_matrix = np.zeros(shape=((new_num_pts+1, new_num_pts+1)))
covariance_matrix[0:new_num_pts,0:new_num_pts] = Covariance.make_covariance_matrix(xy_val,
vario, rotation_matrix)
covariance_matrix[new_num_pts,0:new_num_pts] = 1
covariance_matrix[0:new_num_pts,new_num_pts] = 1
# covariance between data and unknown
covariance_array = np.zeros(shape=(new_num_pts+1))
k_weights = np.zeros(shape=(new_num_pts+1))
covariance_array[0:new_num_pts] = Covariance.make_covariance_array(xy_val,
np.tile(prediction_grid[z], new_num_pts),
vario, rotation_matrix)
covariance_array[new_num_pts] = 1
covariance_matrix.reshape(((new_num_pts+1)), ((new_num_pts+1)))
k_weights, res, rank, s = np.linalg.lstsq(covariance_matrix,
covariance_array, rcond = None)
est_ok[z] = local_mean + np.sum(k_weights[0:new_num_pts]*(norm_data_val[:] - local_mean))
var_ok[z] = var_1 - np.sum(k_weights[0:new_num_pts]*covariance_array[0:new_num_pts])
var_ok[var_ok < 0] = 0
else:
est_ok[z] = df['Z'].values[np.where(test_idx==2)[0][0]]
var_ok[z] = 0
return est_ok, var_ok
def skrige_sgs(prediction_grid, df, xx, yy, zz, num_points, vario, radius, quiet=False):
"""
Sequential Gaussian simulation using simple kriging
Parameters
----------
prediction_grid : numpy.ndarray
x,y coordinate numpy array of prediction grid, or grid cells that will be estimated
df : pandas DataFrame
data frame of conditioning data
xx : string
column name for x coordinates of input data frame
yy : string
column name for y coordinates of input data frame
zz : string
column for z values (or data variable) of input data frame
num_points : int
the number of conditioning points to search for
vario : list
list of variogram parameters [azimuth, nugget, major_range, minor_range, sill, vtype]
azimuth, nugget, major_range, minor_range, and sill can be int or float type
vtype is a string that can be either 'Exponential', 'Spherical', or 'Gaussian'
radius : int, float
search radius
quiet : bool
If False, a progress bar will be printed to the console.
Default is False
Returns
-------
sgs : numpy.ndarray
simulated value for each coordinate in prediction_grid
"""
# unpack variogram parameters
azimuth = vario[0]
major_range = vario[2]
minor_range = vario[3]
rotation_matrix = make_rotation_matrix(azimuth, major_range, minor_range)
df = df.rename(columns = {xx: 'X', yy: 'Y', zz: 'Z'})
xyindex = np.arange(len(prediction_grid))
random.shuffle(xyindex)
mean_1 = df['Z'].mean()
var_1 = vario[4]
sgs = np.zeros(shape=len(prediction_grid))
# build the iterator
if not quiet:
_iterator = enumerate(tqdm(prediction_grid, position=0, leave=True))
else:
_iterator = enumerate(prediction_grid)
for idx, predxy in _iterator:
z = xyindex[idx]
test_idx = np.sum(prediction_grid[z]==df[['X', 'Y']].values, axis=1)
if np.sum(test_idx==2)==0:
# get nearest neighbors
nearest = NearestNeighbor.nearest_neighbor_search(radius, num_points,
prediction_grid[z], df[['X','Y','Z']])
norm_data_val = nearest[:,-1]
xy_val = nearest[:,:-1]
new_num_pts = len(nearest)
# covariance between data
covariance_matrix = Covariance.make_covariance_matrix(xy_val, vario, rotation_matrix)
# covariance between data and unknown
covariance_array = Covariance.make_covariance_array(xy_val,
np.tile(prediction_grid[z], new_num_pts),
vario, rotation_matrix)
k_weights, res, rank, s = np.linalg.lstsq(covariance_matrix,
covariance_array, rcond = None)
# get estimates
est = mean_1 + np.sum(k_weights*(norm_data_val - mean_1))
var = var_1 - np.sum(k_weights*covariance_array)
var = np.absolute(var)
sgs[z] = np.random.normal(est,math.sqrt(var),1)
else:
sgs[z] = df['Z'].values[np.where(test_idx==2)[0][0]]
coords = prediction_grid[z:z+1,:]
df = pd.concat([df,pd.DataFrame({'X': [coords[0,0]], 'Y': [coords[0,1]],
'Z': [sgs[z]]})], sort=False)
return sgs
def okrige_sgs(prediction_grid, df, xx, yy, zz, num_points, vario, radius, quiet=False):
"""
Sequential Gaussian simulation using ordinary kriging
Parameters
----------
prediction_grid : numpy.ndarray
x,y coordinate numpy array of prediction grid, or grid cells that will be estimated
df : pandas DataFrame
data frame of conditioning data
xx : string
column name for x coordinates of input data frame
yy : string
column name for y coordinates of input data frame
zz : string
column for z values (or data variable) of input data frame
num_points : int
the number of conditioning points to search for
vario : list
list of variogram parameters [azimuth, nugget, major_range, minor_range, sill, vtype]
azimuth, nugget, major_range, minor_range, and sill can be int or float type
vtype is a string that can be either 'Exponential', 'Spherical', or 'Gaussian'
radius : int, float
search radius
quiet : bool
If False, a progress bar will be printed to the console.
Default is False
Returns
-------
sgs : numpy.ndarray
simulated value for each coordinate in prediction_grid
"""
# unpack variogram parameters
azimuth = vario[0]
major_range = vario[2]
minor_range = vario[3]
rotation_matrix = make_rotation_matrix(azimuth, major_range, minor_range)
df = df.rename(columns = {xx: "X", yy: "Y", zz: "Z"})
xyindex = np.arange(len(prediction_grid))
random.shuffle(xyindex)
var_1 = vario[4]
sgs = np.zeros(shape=len(prediction_grid))
# build the iterator
if not quiet:
_iterator = enumerate(tqdm(prediction_grid, position=0, leave=True))
else:
_iterator = enumerate(prediction_grid)
for idx, predxy in _iterator:
z = xyindex[idx]