-
Notifications
You must be signed in to change notification settings - Fork 1
/
geostats_masked_sisim.py
4859 lines (4332 loc) · 181 KB
/
geostats_masked_sisim.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
"""
This file includes the reimplementations of GSLIB functionality in Python. While
this code will not be as well-tested and robust as the original GSLIB, it does
provide the opportunity to build 2D spatial modeling projects in Python without
the need to rely on compiled Fortran code from GSLIB. If you want to use the
GSLIB compiled code called from Python workflows use the functions available
with geostatspy.GSLIB.
This file includes the (1) GSLIB subroutines (converted to Python), followed by
the (2) functions: declus, gam, gamv, nscore, kb2d (more added all the time)
Note: some GSLIB subroutines are not included as they were replaced by available
NumPy and SciPy functionality or they were not required as we don't have to deal
with graphics and files in the same manner as GSLIB.
The original GSLIB code is from GSLIB: Geostatistical Library by Deutsch and
Journel, 1998. The reimplementation is by Michael Pyrcz, Associate Professor,
the University of Texas at Austin.
"""
"""
The sisim function was modified to handle the index mask (mask_idc). The mask is used to indicate
which pixels to simulate to make it more time-efficient. THe mask_idc argument is the indices of
pixels to perform the simulation at.
"""
import math # for trig functions etc.
from bisect import bisect # for maintaining array elements sorted
import numpy as np # for ndarrays
import numpy.linalg as linalg # for linear algebra
import scipy.spatial as sp # for fast nearest neighbor search
from numba import jit # for numerical speed up
from statsmodels.stats.weightstats import DescrStatsW
def backtr(df, vcol, vr, vrg, zmin, zmax, ltail, ltpar, utail, utpar):
"""Back transform an entire DataFrame column with a provided transformation table and tail extrapolation.
:param df: the source DataFrame
:param vcol: the column with the variable to transfrom
:param vr: the transformation table, 1D ndarray with the original values
:param vrg: the transformation table, 1D ndarray with the trasnformed variable
:param zmin: lower trimming limits
:param zmax: upper trimming limits
:param ltail: lower tail value
:param ltpar: lower tail extrapolation parameter
:param utail: upper tail value
:param utpar: upper tail extrapolation parameter
:return: TODO
"""
EPSLON = 1.0e-20
nd = len(df);
nt = len(vr) # number of data to transform and number of data in table
backtr = np.zeros(nd)
vrgs = df[vcol].values
# Value in the lower tail? 1=linear, 2=power, (3 and 4 are invalid):
for id in range(0, nd):
if vrgs[id] <= vrg[0]:
backtr[id] = vr[0]
cdflo = gcum(vrg[0])
cdfbt = gcum(vrgs[id])
if ltail == 1:
backtr[id] = powint(0.0, cdflo, zmin, vr[0], cdfbt, 1.0)
elif ltail == 2:
cpow = 1.0 / ltpar
backtr[id] = powint(0.0, cdflo, zmin, vr[0], cdfbt, cpow)
# Value in the upper tail? 1=linear, 2=power, 4=hyperbolic:
elif vrgs[id] >= vrg[nt - 1]:
backtr[id] = vr[nt - 1]
cdfhi = gcum(vrg[nt - 1])
cdfbt = gcum(vrgs[id])
if utail == 1:
backtr[id] = powint(cdfhi, 1.0, vr[nt - 1], zmax, cdfbt, 1.0)
elif utail == 2:
cpow = 1.0 / utpar
backtr[id] = powint(cdfhi, 1.0, vr[nt - 1], zmax, cdfbt, cpow)
elif utail == 4:
plambda = (vr[nt - 1] ** utpar) * (1.0 - gcum(vrg[nt - 1]))
backtr[id] = (plambda / (1.0 - gcum(vrgs))) ** (1.0 / utpar)
else:
# Value within the transformation table:
j = locate(vrg, 1, nt, vrgs[id])
j = max(min((nt - 2), j), 1)
backtr[id] = powint(vrg[j], vrg[j + 1], vr[j], vr[j + 1], vrgs[id], 1.0)
return backtr
def backtr_value(vrgs, vr, vrg, zmin, zmax, ltail, ltpar, utail, utpar):
"""Back transform a single value with a provided transformation table and tail extrapolation.
:param vrgs: value to transform
:param vr: the transformation table, 1D ndarray with the original values
:param vrg: the transformation table, 1D ndarray with the trasnformed variable
:param zmin: lower trimming limits
:param zmax: upper trimming limits
:param ltail: lower tail value
:param ltpar: lower tail extrapolation parameter
:param utail: upper tail value
:param utpar: upper tail extrapolation parameter
:return: TODO
"""
EPSLON = 1.0e-20
nt = len(vr) # number of data to transform
# Value in the lower tail? 1=linear, 2=power, (3 and 4 are invalid):
if vrgs <= vrg[0]:
backtr = vr[0]
cdflo = gcum(vrg[0])
cdfbt = gcum(vrgs)
if ltail == 1:
backtr = dpowint(0.0, cdflo, zmin, vr[0], cdfbt, 1.0)
elif ltail == 2:
cpow = 1.0 / ltpar
backtr = dpowint(0.0, cdflo, zmin, vr[0], cdfbt, cpow)
# Value in the upper tail? 1=linear, 2=power, 4=hyperbolic:
elif vrgs >= vrg[nt - 1]:
backtr = vr[nt - 1]
cdfhi = gcum(vrg[nt - 1])
cdfbt = gcum(vrgs)
if utail == 1:
backtr = dpowint(cdfhi, 1.0, vr[nt - 1], zmax, cdfbt, 1.0)
elif utail == 2:
cpow = 1.0 / utpar
backtr = dpowint(cdfhi, 1.0, vr[nt - 1], zmax, cdfbt, cpow)
elif utail == 4:
plambda = (vr[nt - 1] ** utpar) * (1.0 - gcum(vrg[nt - 1]))
backtr = (plambda / (1.0 - gcum(vrgs))) ** (1.0 / utpar)
else:
# Value within the transformation table:
j = dlocate(vrg, 1, nt, vrgs)
j = max(min((nt - 2), j), 1)
backtr = dpowint(vrg[j], vrg[j + 1], vr[j], vr[j + 1], vrgs, 1.0)
return backtr
def gcum(x):
"""Calculate the cumulative probability of the standard normal distribution.
:param x: the value from the standard normal distribution
:return: TODO
"""
z = x
if z < 0:
z = -z
t = 1. / (1. + 0.2316419 * z)
gcum = t * (0.31938153 + t * (-0.356563782 + t * (1.781477937 + t * (-1.821255978 + t * 1.330274429))))
e2 = 0.
# 6 standard deviations out gets treated as infinity:
if z <= 6.:
e2 = np.exp(-z * z / 2.) * 0.3989422803
gcum = 1.0 - e2 * gcum
if x >= 0:
return gcum
gcum = 1.0 - gcum
return gcum
def locate(xx, iis, iie, x):
"""Return value `j` such that `x` is between `xx[j]` and `xx[j+1]`, where
`xx` is an array of length `n`, and `x` is a given value. `xx` must be
monotonic, either increasing or decreasing (GSLIB version).
:param xx: array
:param iis: start point
:param iie: end point
:param x: given value
:return: TODO
"""
n = len(xx)
# Initialize lower and upper methods:
if iis <= 0:
iis = 0
if iie >= n:
iie = n - 1
jl = iis - 1
ju = iie
if xx[n - 1] <= x:
j = iie
return j
# If we are not done then compute a midpoint:
while (ju - jl) > 1:
jm = int((ju + jl) / 2)
# Replace the lower or upper limit with the midpoint:
if (xx[iie] > xx[iis]) == (x > xx[jm]):
jl = jm
else:
ju = jm
# Return with the array index:
j = jl
return j
def dlocate(xx, iis, iie, x):
"""Return value `j` such that `x` is between `xx[j]` and `xx[j+1]`, where
`xx` is an array of length `n`, and `x` is a given value. `xx` must be
monotonic, either increasing or decreasing (updated with Python bisect)
:param xx: array
:param iis: start point
:param iie: end point
:param x: given value
:return: TODO
"""
n = len(xx)
if iie <= iis:
iis = 0
iie = n - 1
array = xx[iis: iie - 1] # this is accounting for swith to 0,...,n-1 index
j = bisect(array, x)
return j
def powint(xlow, xhigh, ylow, yhigh, xval, power):
"""Power-based interpolator
:param xlow: x lower interval
:param xhigh: x upper interval
:param ylow: y lower interval
:param yhigh: y upper interval
:param xval: value on x
:param power: power for interpolation
:return: TODO
"""
EPSLON = 1.0e-20
if (xhigh - xlow) < EPSLON:
powint = (yhigh + ylow) / 2.0
else:
powint = ylow + (yhigh - ylow) * (((xval - xlow) / (xhigh - xlow)) ** power)
return powint
def dsortem(ib, ie, a, iperm, b=0, c=0, d=0, e=0, f=0, g=0, h=0):
"""Sort array in ascending order.
:param ib: start index
:param ie: end index
:param a: array
:param iperm: 0 no other array is permuted.
1 array b is permuted according to array a.
2 arrays b, c are permuted.
3 arrays b, c, d are permuted.
4 arrays b, c, d, e are permuted.
5 arrays b, c, d, e, f are permuted.
6 arrays b, c, d, e, f, g are permuted.
7 arrays b, c, d, e, f, g, h are permuted.
>7 no other array is permuted.
:param b: array to be permuted according to array a.
:param c: array to be permuted according to array a.
:param d: array to be permuted according to array a.
:param e: array to be permuted according to array a.
:param f: array to be permuted according to array a.
:param g: array to be permuted according to array a.
:param h: array to be permuted according to array a.
:return: a: the array, a portion of which has been sorted.
b, c, d, e, f, g, h: arrays permuted according to array a (see
iperm)
"""
a = a[ib:ie]
inds = a.argsort()
a = np.copy(a[inds]) # deepcopy forces pass to outside scope
if iperm == 1:
return a
b_slice = b[ib:ie]
b = b_slice[inds]
if iperm == 2:
return a, b
c_slice = c[ib:ie]
c = c_slice[inds]
if iperm == 3:
return a, b, c
d_slice = d[ib:ie]
d = d_slice[inds]
if iperm == 4:
return a, b, c, d
e_slice = e[ib:ie]
e = e_slice[inds]
if iperm == 5:
return a, b, c, d, e
f_slice = f[ib:ie]
f = f_slice[inds]
if iperm == 6:
return a, b, c, d, e, f
g_slice = g[ib:ie]
g = g_slice[inds]
if iperm == 7:
return a, b, c, d, e, f, g # TODO: changed from 'a, b, c, d, e, f, h'
h_slice = h[ib:ie]
h = h_slice[inds]
return a, b, c, d, e, f, g, h # TODO: changed from 'a, b, c, d, e, f, h'
def gauinv(p):
"""Compute the inverse of the standard normal cumulative distribution
function.
:param p: cumulative probability value
:return: TODO
"""
lim = 1.0e-10
p0 = -0.322_232_431_088
p1 = -1.0
p2 = -0.342_242_088_547
p3 = -0.020_423_121_024_5
p4 = -0.000_045_364_221_014_8
q0 = 0.099_348_462_606_0
q1 = 0.588_581_570_495
q2 = 0.531_103_462_366
q3 = 0.103_537_752_850
q4 = 0.003_856_070_063_4
# Check for an error situation
if p < lim:
xp = -1.0e10
return xp
if p > (1.0 - lim):
xp = 1.0e10
return xp
# Get k for an error situation
pp = p
if p > 0.5:
pp = 1 - pp
xp = 0.0
if p == 0.5:
return xp
# Approximate the function
y = np.sqrt(np.log(1.0 / (pp * pp)))
xp = float(
y
+ ((((y * p4 + p3) * y + p2) * y + p1) * y + p0)
/ ((((y * q4 + q3) * y + q2) * y + q1) * y + q0)
)
if float(p) == float(pp):
xp = -xp
return xp
def gcum(x):
"""Evaluate the standard normal cdf given a normal deviate `x`. `gcum` is
the area under a unit normal curve to the left of `x`. The results are
accurate only to about 5 decimal places.
:param x: TODO
:return: TODO
"""
z = x
if z < 0:
z = -z
t = 1.0 / (1.0 + 0.231_641_9 * z)
gcum_ = t * (
0.319_381_53
+ t
* (
-0.356_563_782
+ t * (1.781_477_937 + t * (-1.821_255_978 + t * 1.330_274_429))
)
)
e2 = 0.0
# Standard deviations out gets treated as infinity
if z <= 6:
e2 = np.exp(-z * z / 2.0) * 0.398_942_280_3
gcum_ = 1.0 - e2 * gcum_
if x >= 0.0:
return gcum_
gcum_ = 1.0 - gcum_
return gcum_
def dpowint(xlow, xhigh, ylow, yhigh, xval, pwr):
"""Power interpolate the value of `y` between (`xlow`, `ylow`) and
(`xhigh`, `yhigh`) for a value of `x` and a power `pwr`.
:param xlow: TODO
:param xhigh: TODO
:param ylow: TODO
:param yhigh: TODO
:param xval: TODO
:param pwr: power
:return: TODO
"""
EPSLON = 1.0e-20
if (xhigh - xlow) < EPSLON:
dpowint_ = (yhigh + ylow) / 2.0
else:
dpowint_ = ylow + (yhigh - ylow) * (
((xval - xlow) / (xhigh - xlow)) ** pwr
)
return dpowint_
# @jit(nopython=True) # all NumPy array operations included in this function for precompile with NumBa
def setup_rotmat2(c0, nst, it, cc, ang):
DTOR = 3.14159265 / 180.0;
EPSLON = 0.000000;
PI = 3.141593
# The first time around, re-initialize the cosine matrix for the
# variogram structures:
rotmat = np.zeros((4, nst))
maxcov = c0
for js in range(0, nst):
azmuth = (90.0 - ang[js]) * DTOR
rotmat[0, js] = math.cos(azmuth)
rotmat[1, js] = math.sin(azmuth)
rotmat[2, js] = -1 * math.sin(azmuth)
rotmat[3, js] = math.cos(azmuth)
if it[js] == 4:
maxcov = maxcov + 9999.9
else:
maxcov = maxcov + cc[js]
return rotmat, maxcov
@jit(nopython=True)
def setup_rotmat(c0, nst, it, cc, ang, pmx):
"""Setup rotation matrix.
:param c0: nugget constant (isotropic)
:param nst: number of nested structures (max. 4)
:param it: TODO
:param cc: multiplicative factor of each nested structure
:param ang: TODO
:param pmx: TODO
:return: TODO
"""
PI = 3.141_592_65
DTOR = PI / 180.0
# The first time around, re-initialize the cosine matrix for the variogram
# structures
rotmat = np.zeros((4, nst))
maxcov = c0
for js in range(0, nst):
azmuth = (90.0 - ang[js]) * DTOR
rotmat[0, js] = math.cos(azmuth)
rotmat[1, js] = math.sin(azmuth)
rotmat[2, js] = -1 * math.sin(azmuth)
rotmat[3, js] = math.cos(azmuth)
if it[js] == 4:
maxcov = maxcov + pmx
else:
maxcov = maxcov + cc[js]
return rotmat, maxcov
@jit(nopython=True)
def cova2(x1, y1, x2, y2, nst, c0, pmx, cc, aa, it, ang, anis, rotmat, maxcov):
"""Calculate the covariance associated with a variogram model specified by a
nugget effect and nested variogram structures.
:param x1: x coordinate of first point
:param y1: y coordinate of first point
:param x2: x coordinate of second point
:param y2: y coordinate of second point
:param nst: number of nested structures (maximum of 4)
:param c0: isotropic nugget constant (TODO: not used)
:param pmx: TODO
:param cc: multiplicative factor of each nested structure
:param aa: parameter `a` of each nested structure
:param it: TODO
:param ang: TODO: not used
:param anis: TODO
:param rotmat: rotation matrices
:param maxcov: TODO
:return: TODO
"""
EPSLON = 0.000001
# Check for very small distance
dx = x2 - x1
dy = y2 - y1
if (dx * dx + dy * dy) < EPSLON:
cova2_ = maxcov
return cova2_
# Non-zero distance, loop over all the structures
cova2_ = 0.0
for js in range(0, nst):
# Compute the appropriate structural distance
dx1 = dx * rotmat[0, js] + dy * rotmat[1, js]
dy1 = (dx * rotmat[2, js] + dy * rotmat[3, js]) / anis[js]
h = math.sqrt(max((dx1 * dx1 + dy1 * dy1), 0.0))
if it[js] == 1:
# Spherical model
hr = h / aa[js]
if hr < 1.0:
cova2_ = cova2_ + cc[js] * (1.0 - hr * (1.5 - 0.5 * hr * hr))
elif it[js] == 2:
# Exponential model
cova2_ = cova2_ + cc[js] * np.exp(-3.0 * h / aa[js])
elif it[js] == 3:
# Gaussian model
hh = -3.0 * (h * h) / (aa[js] * aa[js])
cova2_ = cova2_ + cc[js] * np.exp(hh)
elif it[js] == 4:
# Power model
cov1 = pmx - cc[js] * (h ** aa[js])
cova2_ = cova2_ + cov1
return cova2_
def sqdist(x1, y1, z1, x2, y2, z2, ind, rotmat):
# Compute component distance vectors and the squared distance:
dx = x1 - x2
dy = y1 - y2
dz = 0.0
sqdist = 0.0
for i in range(0, 2):
cont = rotmat[ind, i, 1] * dx + rotmat[ind, i, 2] * dy
sqdist = sqdist + cont * cont
return sqdist
def sqdist2(x1, y1, x2, y2, ist, rotmat, anis):
"""Calculate the 2D square distance based on geometric ani
:param x1: x coordinate of first point
:param y1: y coordinate of first point
:param x2: x coordinate of second point
:param y2: y coordinate of second point
:param ist: structure index
:param rotmat: 2d rotation matrix
:param anis: 2D anisotropy ratio
:return: TODO
"""
# Compute component distance vectors and the squared distance:
dx = x1 - x2
dy = y1 - y2
dx1 = (dx * rotmat[0, ist] + dy * rotmat[1, ist])
dy1 = (dx * rotmat[2, ist] + dy * rotmat[3, ist]) / anis[ist]
sqdist_ = (dx1 * dx1 + dy1 * dy1)
return sqdist_
def setrot(ang1, ang2, sang1, anis1, anis2, sanis1, nst, MAXROT):
"""GSLIB's SETROT subroutine (Deutsch and Journel, 1998) converted from the
original Fortran to Python by Michael Pyrcz, the University of Texas at
Austin (March, 2019).
Note this was simplified to 2D only.
"""
DEG2RAD = 3.141592654 / 180.0;
EPSLON = 1.e-20
rotmat = np.zeros((MAXROT + 1, 3, 3))
if ang1 >= 0.0 and ang1 < 270.0:
alpha = (90.0 - ang1) * DEG2RAD
else:
alpha = (450.0 - ang1) * DEG2RAD
# Get the required sines and cosines:
sina = math.sin(alpha)
cosa = math.cos(alpha)
# Construct the rotation matrix in the required memory:
afac1 = 1.0 / (max(anis1, EPSLON))
rotmat[0, 1, 1] = cosa
rotmat[0, 1, 2] = sina
rotmat[0, 2, 1] = afac1 * (-sina)
rotmat[0, 2, 2] = afac1 * (cosa)
# 2nd structure if present
if nst > 1:
if ang2 >= 0.0 and ang2 < 270.0:
alpha = (90.0 - ang2) * DEG2RAD
else:
alpha = (450.0 - ang2) * DEG2RAD
# Get the required sines and cosines:
sina = math.sin(alpha)
cosa = math.cos(alpha)
# Construct the rotation matrix in the required memory:
afac2 = 1.0 / (max(anis2, EPSLON))
rotmat[1, 1, 1] = cosa
rotmat[1, 1, 2] = sina
rotmat[1, 2, 1] = afac1 * (-sina)
rotmat[1, 2, 2] = afac1 * (cosa)
# search rotation
if sang1 >= 0.0 and sang1 < 270.0:
alpha = (90.0 - sang1) * DEG2RAD
else:
alpha = (450.0 - sang1) * DEG2RAD
# Get the required sines and cosines:
sina = math.sin(alpha)
cosa = math.cos(alpha)
# Construct the rotation matrix in the required memory:
afac1 = 1.0 / (max(sanis1, EPSLON))
rotmat[MAXROT, 1, 1] = cosa
rotmat[MAXROT, 1, 2] = sina
rotmat[MAXROT, 2, 1] = afac1 * (-sina)
rotmat[MAXROT, 2, 2] = afac1 * (cosa)
# Return to calling program:
return rotmat
def ksol_numpy(neq, a, r):
"""Find solution of a system of linear equations.
:param neq: number of equations
:param a: upper triangular left hand side matrix
:param r: right hand side matrix
:return: solution array, same dimension as `r`
"""
a = a[0: neq * neq] # trim the array
a = np.reshape(a, (neq, neq)) # reshape to 2D
ainv = linalg.inv(a) # invert matrix
r = r[0: neq] # trim the array
s = np.matmul(ainv, r) # matrix multiplication
return s
def ctable(MAXNOD, MAXCXY, MAXCTX, MAXCTY, MAXXYZ, xsiz, ysiz, isrot, nx, ny, nst, c0, cc, aa, it, ang, anis,
global_rotmat, radsqd):
"""GSLIB's CTABLE subroutine (Deutsch and Journel, 1998) converted from the
original Fortran to Python by Michael Pyrcz, the University of Texas at
Austin (March, 2019).
Note this was simplified to 2D only, WARNING: only spiral search setup works currently.
"""
# Declare constants
TINY = 1.0e-10
PMX = 9999.9
MAXROT = 2
# Size of the look-up table:
tmp = np.zeros(MAXXYZ)
MAXORD = MAXXYZ
if (nx * ny) < MAXCXY:
MAXORD = MAXCXY
order = np.zeros(MAXORD)
nctx = int(min(((MAXCTX - 1) / 2), (nx - 1)))
ncty = int(min(((MAXCTY - 1) / 2), (ny - 1)))
# print('CTable check')
# print('nctx ' + str(nctx) + ', ncty ' + str(ncty))
ixnode = np.zeros(MAXXYZ)
iynode = np.zeros(MAXXYZ)
covtab = np.zeros((MAXCTX, MAXCTY))
# Initialize the covariance subroutine and cbb at the same time:
rotmat, maxcov = setup_rotmat2(c0, nst, it, cc, ang)
cbb = cova2(0.0, 0.0, 0.0, 0.0, nst, c0, PMX, cc, aa, it, ang, anis, rotmat, maxcov)
# Now, set up the table and keep track of the node offsets that are
# within the search radius:
nlooku = -1 # adjusted for 0 origin
for i in range(-nctx, nctx + 1): # cover entire range
xx = i * xsiz
ic = nctx + i
for j in range(-ncty, ncty + 1): # cover entire range
yy = j * ysiz
jc = ncty + j
covtab[ic, jc] = cova2(0.0, 0.0, xx, yy, nst, c0, PMX, cc, aa, it, ang, anis, rotmat, maxcov)
# print('cov table offset'); print(xx,yy); print(covtab[ic,jc])
hsqd = sqdist(0.0, 0.0, 0.0, xx, yy, 0.0, MAXROT, global_rotmat)
if hsqd <= radsqd:
nlooku = nlooku + 1
# We want to search by closest variogram distance (and use the
# anisotropic Euclidean distance to break ties:
tmp[nlooku] = - (covtab[ic, jc] - TINY * hsqd)
order[nlooku] = (jc) * MAXCTX + ic
# print('populated presort'); print(tmp,order)
# Finished setting up the look-up table, now order the nodes such
# that the closest ones, according to variogram distance, are searched
# first. Note: the "loc" array is used because I didn't want to make
# special allowance for 2 byte integers in the sorting subroutine:
nlooku = nlooku + 1
# print('nlooku' + str(nlooku)); print('MAXCTX' + str(MAXCTX))
tmp, order = dsortem(0, nlooku, tmp, 2, b=order)
# print('populated postsort'); print(tmp,order)
for il in range(0, nlooku):
loc = int(order[il])
iy = int((loc - 0) / MAXCTX)
ix = loc - (iy - 0) * MAXCTX
iynode[il] = int(iy)
ixnode[il] = int(ix)
# print('populated ix, iy node list'); print(ixnode, iynode)
return covtab, tmp, order, ixnode, iynode, nlooku, nctx, ncty
def srchnd(ix, iy, nx, ny, xmn, ymn, xsiz, ysiz, sim, noct, nodmax, ixnode, iynode, nlooku, nctx, ncty, UNEST):
"""GSLIB's SRCHND subroutine (Deutsch and Journel, 1998) converted from the
original Fortran to Python by Michael Pyrcz, the University of Texas at
Austin (March, 2019).
Note this was simplified to 2D only.
"""
# Consider all the nearby nodes until enough have been found:
ncnode = 0;
icnode = np.zeros(nodmax, dtype=int);
icnode.fill(-1)
cnodev = np.zeros(nodmax);
cnodex = np.zeros(nodmax);
cnodey = np.zeros(nodmax);
# print('Node search at '); print(ix,iy)
# print('nlooku'); print(nlooku)
if noct > 0:
ninoct = np.zeros(8)
for il in range(0, nlooku):
if ncnode == nodmax: return ncnode, icnode, cnodev, cnodex, cnodey
i = ix + (int(ixnode[il]) - nctx)
j = iy + (int(iynode[il]) - ncty)
# print('i,j'); print(i,j)
if i < 0 or j < 0: continue
if i >= nx or j >= ny: continue
ind = i + (j) * nx
if sim[ind] > UNEST:
icnode[ncnode] = il
cnodex[ncnode] = xmn + (i) * xsiz # adjust for 0 origin
cnodey[ncnode] = ymn + (j) * ysiz
cnodev[ncnode] = sim[ind]
# print('srchnd found at index - ' +str(ind) + ' at x and y ' + str(cnodex[ncnode]) + ',' + str(cnodey[ncnode]))
# print(' ix = ' + str(i) + ' and iy = ' + str(j))
# print(' value = ' + str(sim[ind]))
ncnode = ncnode + 1 # moved to account for origin 0
return ncnode, icnode, cnodev, cnodex, cnodey
def beyond(ivtype, nccut, ccut, ccdf, ncut, cut, cdf, zmin, zmax, ltail, ltpar, middle, mpar, utail, utpar, zval,
cdfval):
"""GSLIB's BEYOND subroutine (Deutsch and Journel, 1998) converted from the
original Fortran to Python by Michael Pyrcz, the University of Texas at
Austin (March, 2019).
Note this was simplified to 2D only.
"""
EPSLON = 1.0e-20;
UNEST = -1.0
# Check for both "zval" and "cdfval" defined or undefined:
ierr = 1;
if zval > UNEST and cdfva > UNEST:
return -1
if zval <= UNEST and cdfval <= UNEST:
return - 1
# Handle the case of a categorical variable:
if ivtype == 0:
cum = 0
for i in range(0, nccut):
cum = cum + ccdf[i]
if cdfval <= cum:
zval = ccut[i]
return zval
return zval
# Figure out what part of distribution: ipart = 0 - lower tail
# ipart = 1 - middle
# ipart = 2 - upper tail
ierr = 0
ipart = 1
if zva > UNEST:
if zval <= ccut[0]:
ipart = 0
if zval >= ccut[nccut - 1]:
ipart = 2
else:
if cdfval <= ccdf[0]:
ipart = 0
if cdfval >= ccdf[nccut - 1]:
ipart = 2
# ARE WE IN THE LOWER TAIL?
if ipart == 0:
if ltail == 1:
# Straight Linear Interpolation:
powr = 1.0
if zval > UNEST:
cdfval = powint(zmin, ccut[0], 0.0, ccdf[0], zval, powr)
else:
zval = powint(0.0, ccdf[0], zmin, ccut[0], cdfval, powr)
elif ltail == 2:
# Power Model interpolation to lower limit "zmin"?
if zval > UNEST:
cdfval = powint(zmin, ccut[0], 0.0, ccdf[0], zval, ltpar)
else:
powr = 1.0 / ltpar
zval = powint(0.0, ccdf[0], zmin, ccut[0], cdfval, powr)
# Linear interpolation between the rescaled global cdf?
elif ltail == 3:
if zval > UNEST:
# Computing the cdf value. Locate the point and the class bound:
idat = locate(cut, 1, ncut, zval)
iupp = locate(cut, ncut, 1, ncut, ccut[0])
# Straight linear interpolation if no data; otherwise, linear:
if idat <= -1 or idat >= ncut - 1 or iupp <= -1 or iupp >= ncut - 1: # modfity for 0 index
cdfval = powint(zmin, cut[0], 0.0, cdf[0], zval, 1.)
else:
temp = powint(cut[idat], cut[idat + 1], cdf[idat], cdf[idat + 1], zval, 1.)
cdfval = temp * ccdf[0] / cdf[iupp]
else:
# Computing Z value: Are there any data out in the tail?
iupp = locate(cut, ncut, 1, ncut, ccut[0])
# Straight linear interpolation if no data; otherwise, local linear
# interpolation:
if iupp <= 0 or iupp >= ncut:
zval = powint(0.0, cdf[0], zmin, cut[0], cdfval, 1.)
else:
temp = cdfval * cdf[iupp] / ccdf[1]
idat = locate(cdf, ncut, 1, ncut, temp)
if idat <= -1 or idat >= ncut - 1: # adjusted for 0 origin
zval = powint(0.0, cdf[0], zmin, cut[0], cdfval, 1.)
else:
zval = powint(cdf[idat], cdf[idat + 1], cut[dat], cut[idat + 1], temp, 1.)
else:
# Error situation - unacceptable option:
ierr = 2
return -1
# FINISHED THE LOWER TAIL, ARE WE IN THE MIDDLE?
if ipart == 1:
# Establish the lower and upper limits:
if zval > UNEST:
cclow = locate(ccut, 1, nccut, zval)
else:
cclow = locate(ccdf, 1, nccut, cdfval)
cchigh = cclow + 1
if middle == 1:
# Straight Linear Interpolation:
powr = 1.0
if zval > UNEST:
cdfval = powint(ccut[cclow], ccut[cchigh], ccdf[cclow], ccdf[cchigh], zval, powr)
else:
zval = powint(ccdf[cclow], ccdf[cchigh], ccut[cclow], ccut[cchigh], cdfval, powr)
# Power interpolation between class bounds?
elif middle == 2:
if zval > UNEST:
cdfval = powint(ccut[cclow], ccut[cchigh], ccdf[cclow], ccdf[cchigh], zval, mpar)
else:
powr = 1.0 / mpar
zval = powint(ccdf[cclow], ccdf[cchigh], ccut[cclow], ccut[cchigh], cdfval, powr)
# Linear interpolation between the rescaled global cdf?
elif middle == 3:
ilow = locate(cut, ncut, 1, ncut, ccut[cclow])
iupp = locate(cut, ncut, 1, ncut, ccut[cchigh])
if cut[ilow] < ccut[cclow]:
ilow = ilow + 1
if cut[iupp] > ccut[cchigh]:
iupp = iupp - 1
if zval > UNEST:
idat = locate(cut, 1, ncut, zval)
# Straight linear interpolation if no data; otherwise, local linear
# interpolation:
if idat <= -1 or idat >= ncut - 1 or ilow <= -1 or ilow >= ncut - 1 or iupp <= -1 or iupp >= ncut - 1 or iupp <= ilow:
cdfval = powint(ccut[cclow], ccut[cchigh], ccdf[cclow], ccdf[cchigh], zval, 1.)
else:
temp = powint(cut[idat], cut[idat + 1], cdf[idat], cdf[idat + 1], zval, 1.)
cdfval = powint(cdf[ilow], cdf[iupp], ccdf[cclow], ccdf[cchigh], temp, 1.)
else:
# Straight linear interpolation if no data; otherwise, local linear
# interpolation:
if ilow <= -1 or ilow >= ncut - 1 or iup <= -1 or iupp >= ncut - 1 or iupp < ilow:
zval = powint(ccdf[cclow], ccdf[cchigh], ccut[cclow], ccut[cchigh], cdfval, 1.)
else:
temp = powint(ccdf[cclow], ccdf[cchigh], cdf[ilow], cdf[iupp], cdfval, 1.)
idat = locate(cdf, 1, ncut, temp)
if cut[idat] < ccut[cclow]:
idat = idat + 1
if idat <= -1 or idat >= ncut - 1 or cut[idat + 1] > ccut[cchigh]:
zval = powint(ccdf[cclow], ccdf[cchigh], ccut[cclow], ccut[cchigh], cdfval, 1.)
else:
zval = powint(cdf[idat], cdf[idat + 1], cut[idat], cut[idat + 1], temp, 1.)
zval = powint(cdf[idat], cdf[idat + 1], cut[idat], cut[idat + 1], temp, 1.)
else:
# Error situation - unacceptable option:
ierr = 2
return -1
# FINISHED THE MIDDLE, ARE WE IN THE UPPER TAIL?
if ipart == 2:
if utail == 1:
powr = 1.0
if zval > UNEST:
cdfval = powint(ccut(nccut), zmax, ccdf(nccut), 1.0, zval, powr)
else:
zval = powint(ccdf(nccut), 1.0, ccut(nccut), zmax, cdfval, powr)
elif utail == 2:
# Power interpolation to upper limit "utpar"?
if zval > UNEST:
cdfval = powint(ccut(nccut), zmax, ccdf(nccut), 1.0, zval, utpar)
else:
powr = 1.0 / utpar
zval = powint(ccdf(nccut), 1.0, ccut(nccut), zmax, cdfval, powr)
# Linear interpolation between the rescaled global cdf?
elif utail == 3:
if zval > UNEST:
# Approximately Locate the point and the class bound:
idat = locate(cut, 1, ncut, zval, idat)
ilow = locate(cut, 1, ncut, ccut(nccut), ilow)
if cut[idat] < zval:
idat = idat + 1
if cut[ilow] < ccut[nccut - 1]:
ilow = ilow + 1
# Straight linear interpolation if no data; otherwise, local linear
# interpolation:
if idat < -1 or idat >= ncut - 1 or ilow <= -1 or ilow >= ncut - 1:
cdfval = powint(ccut(nccut), zmax, ccdf(nccut), 1.0, zval, 1.)
else:
temp = powint(cut(idat), cut(idat + 1), cdf(idat), cdf(idat + 1), zval, 1.)
cdfval = powint(cdf(ilow), 1.0, ccdf(nccut), 1.0, temp, 1.)
else:
# Computing Z value: Are there any data out in the tail?
ilow = locate(cut, ncut, 1, ncut, ccut(nccut), ilow)
if cut[ilow] < ccut[nccut - 1]:
ilow = ilow + 1
# Straight linear interpolation if no data; otherwise, local linear
# interpolation:
if ilow <= -1 or ilow >= ncut - 1:
zval = powint(ccdf(nccut), 1.0, ccut(nccut), zmax, cdfval, 1.)
else:
temp = powint(ccdf(nccut), 1.0, cdf(ilow), 1.0, cdfval, 1.)
idat = locate(cdf, ncut, 1, ncut, temp)
if cut[idat] < ccut[nccut - 1]:
idat = idat + 1
if idat >= ncut - 1:
zval = powint(ccdf[nccut - 1], 1.0, ccut[nccut - 1], zmax, cdfval, 1.)
else:
zval = powint(cdf[idat], cdf[idat + 1], cut[idat], cut[idat + 1], temp, 1.)
# Fit a Hyperbolic Distribution?
elif utail == 4:
# Figure out "lambda" and required info:
lambd = math.pow(ccut[nccut], utpar) * (1.0 - ccdf[nccut - 1])
if zval > UNEST:
cdfval = 1.0 - (lambd / (math.pow(zval, utpar)))
else:
zval = (lambd / math.pow((1.0 - cdfval), (1.0 / utpar)))
else:
# Error situation - unacceptable option:
ierr = 2
return -1
if zval < zmin:
zval = zmin
if zval > zmax:
zval = zmax
# All finished - return:
return zval
def krige(ix, iy, nx, ny, xx, yy, lktype, x, y, vr, sec, colocorr, lvm, close, covtab, nctx, ncty, icnode, ixnode,
iynode, cnodev, cnodex, cnodey, nst, c0, PMX, cc, aa, it, ang, anis, rotmat, maxcov, MAXCTX, MAXCTY, MAXKR1,
MAXKR2):
"""GSLIB's KRIGE subroutine (Deutsch and Journel, 1998) converted from the
original Fortran to Python by Michael Pyrcz, the University of Texas at
Austin (March, 2019).
Note this was simplified to 2D only.
"""
EPSLON = 1.0e-20
cur_index = ix + (iy) * nx
# print('krige at grid '); print(ix,iy)
# print('krige at node '); print(xx,yy)
# print('grid index = '); print(cur_index)
# print('Check ixnode '); print(ixnode); print(iynode)
nclose = len(close)
ncnode = (icnode >= 0).sum()
# print('In kriging, maxcov = ' + str(maxcov))
# print('kriging')
# print('nclose ' + str(nclose) + ', ncnode ' + str(ncnode))
# print('MAXKR1'); print(MAXKR1)
vra = np.zeros(MAXKR1);
vrea = np.zeros(MAXKR1)
r = np.zeros(MAXKR1);
rr = np.zeros(MAXKR1);
s = np.zeros(MAXKR1);
a = np.zeros(MAXKR2)
cbb = cova2(0, 0, 0, 0, nst, c0, 9999.9, cc, aa, it, ang, anis, rotmat, maxcov)
# print(r.shape)
# Local mean
if lktype == 2:
gmean = lvm[cur_index]
else:
gmean = 0.0
# Size of the kriging system:
first = False
na = nclose + ncnode
# print('lktype' + str(lktype))
if lktype == 0: neq = na
if lktype == 1:
# print('ordinary kriging')
neq = na + 1
if lktype == 2: neq = na
if lktype == 3: neq = na + 2
if lktype == 4: neq = na + 1
# print('prior matrix build neq'); print(neq)
# print('na'); print(na)