-
Notifications
You must be signed in to change notification settings - Fork 55
/
test_variogram.py
1670 lines (1267 loc) · 52.2 KB
/
test_variogram.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
import unittest
import os
import pickle
import warnings
import numpy as np
import pandas as pd
from numpy.testing import assert_array_almost_equal
from scipy.spatial.distance import pdist
try:
import plotly.graph_objects as go
PLOTLY_FOUND = True
except ImportError:
print('No plotly installed. Skip plot tests')
PLOTLY_FOUND = False
try:
import gstools
print(f'Found PyKrige: {gstools.__version__}')
GSTOOLS_AVAILABLE = True
except ImportError:
GSTOOLS_AVAILABLE = False # pragma: no cover
from skgstat import Variogram, DirectionalVariogram
from skgstat import OrdinaryKriging
from skgstat import estimators
from skgstat import plotting
from skgstat.models import variogram, spherical, gaussian, exponential, cubic, stable, matern
class TestSpatiallyCorrelatedData(unittest.TestCase):
def setUp(self):
# Generate some random but spatially correlated data
# with a range of ~20
np.random.seed(42)
c = np.random.sample((50, 2)) * 60
np.random.seed(42)
v = np.random.normal(10, 4, 50)
V = Variogram(c, v).describe()
V["effective_range"] = 20
OK = OrdinaryKriging(V, coordinates=c, values=v)
self.c = np.random.sample((500, 2)) * 60
self.v = OK.transform(self.c)
self.c = self.c[~np.isnan(self.v),:]
self.v = self.v[~np.isnan(self.v)]
def test_dense_maxlag_inf(self):
Vdense = Variogram(self.c, self.v)
Vsparse = Variogram(self.c, self.v, maxlag=10000000)
for x, y in zip(Vdense.parameters, Vsparse.parameters):
self.assertAlmostEqual(x, y, places=3)
def test_sparse_maxlag_50(self):
V = Variogram(self.c, self.v, maxlag=50)
for x, y in zip(V.parameters, [20.264, 6.478, 0]):
self.assertAlmostEqual(x, y, places=3)
def test_sparse_maxlag_30(self):
V = Variogram(self.c, self.v, maxlag=30)
for x, y in zip(V.parameters, [17.128, 6.068, 0]):
self.assertAlmostEqual(x, y, places=3)
class TestVariogramInstantiation(unittest.TestCase):
def setUp(self):
# set up default values, whenever c and v are not important
np.random.seed(42)
self.c = np.random.gamma(10, 4, (30, 2))
np.random.seed(42)
self.v = np.random.normal(10, 4, 30)
def test_standard_settings(self):
V = Variogram(self.c, self.v)
for x, y in zip(V.parameters, [7.122, 13.966, 0]):
self.assertAlmostEqual(x, y, places=3)
def test_sparse_standard_settings(self):
V = Variogram(self.c, self.v, maxlag=10000)
for x, y in zip(V.parameters, [7.122, 13.966, 0]):
self.assertAlmostEqual(x, y, places=3)
def test_input_dimensionality(self):
c1d = np.random.normal(0, 1, 100)
c3d = np.random.normal(0, 1, size=(100, 3))
v = np.random.normal(10, 4, 100)
# test 1D coords
V = Variogram(c1d, v)
self.assertTrue(V.dim == 1)
# test 3D coords
V2 = Variogram(c3d, v)
self.assertTrue(V2.dim == 3)
def test_pass_median_maxlag_on_instantiation(self):
np.random.seed(1312)
c = np.random.gamma(5, 1, (50, 2))
np.random.seed(1312)
v = np.random.weibull(5, 50)
V = Variogram(c, v, maxlag='median', n_lags=4)
bins = [0.88, 1.77, 2.65, 3.53]
for b, e in zip(bins, V.bins):
self.assertAlmostEqual(b, e, places=2)
def test_pass_mean_maxlag_on_instantiation(self):
V = Variogram(self.c, self.v, maxlag='mean', n_lags=4)
bins = [4.23, 8.46, 12.69, 16.91]
for b, e in zip(bins, V.bins):
self.assertAlmostEqual(b, e, places=2)
def test_unknown_binning_func(self):
with self.assertRaises(ValueError) as e:
Variogram(self.c, self.v, bin_func='notafunc')
self.assertEqual(
"'notafunc' is not a valid estimator for `bins`",
str(e.exception)
)
def test_invalid_binning_func(self):
with self.assertRaises(AttributeError) as e:
V = Variogram(self.c, self.v)
V.set_bin_func(42)
self.assertTrue('of type string' in str(e.exception))
def test_unknown_model(self):
with self.assertRaises(ValueError) as e:
Variogram(self.c, self.v, model='unknown')
self.assertEqual(
'The theoretical Variogram function unknown is not understood, please provide the function',
str(e.exception)
)
def test_unsupported_n_lags(self):
with self.assertRaises(ValueError) as e:
Variogram(self.c, self.v, n_lags=15.7)
self.assertEqual(
'n_lags has to be a positive integer',
str(e.exception)
)
def test_value_warning(self):
with self.assertWarns(Warning) as w:
Variogram(self.c, [42] * 30, fit_method='lm')
self.assertEqual(
'All input values are the same.',
str(w.warning)
)
def test_value_error_on_set_trf(self):
"""Test the Attribute error when switching to TRF on single value input"""
# catch the same input value warning
with warnings.catch_warnings():
warnings.simplefilter('ignore')
with self.assertRaises(AttributeError) as e:
v = Variogram(self.c, [42] * 30, fit_method='lm')
v.fit_method = 'trf'
self.assertTrue("'trf' is bounded and therefore" in str(e.exception))
def test_value_error_trf(self):
"""Test the Attribute error on TRF instantiation on single value input"""
# catch the same input value warning
with warnings.catch_warnings():
warnings.simplefilter('ignore')
with self.assertRaises(AttributeError) as e:
v = Variogram(self.c, [42] * 30, fit_method='trf')
self.assertTrue("'trf' is bounded and therefore" in str(e.exception))
def test_pairwise_diffs(self):
"""
Test that the cross-variogram changes do not mess with the standard
implementation of Variogram.
"""
# build the variogram
V = Variogram(self.c, self.v)
# build the actual triangular distance matrix array
diff = pdist(np.column_stack((self.v, np.zeros(len(self.v)))), metric='euclidean')
assert_array_almost_equal(V.pairwise_diffs, diff, decimal=2)
def test_pairwise_diffs_preprocessing(self):
"""
Remove the diffs and then request the diffs again to check preprocessing
trigger on missing pairwise residual diffs.
"""
V = Variogram(self.c, self.v)
# build the diffs
diff = pdist(np.column_stack((self.v, np.zeros(len(self.v)))), metric='euclidean')
# remove the diffs
V._diff = None
# check preprocessing
assert_array_almost_equal(V.pairwise_diffs, diff, decimal=2)
class TestVariogramArguments(unittest.TestCase):
def setUp(self):
# set up default values, whenever c and v are not important
np.random.seed(42)
self.c = np.random.gamma(10, 4, (30, 2))
np.random.seed(42)
self.v = np.random.normal(10, 4, 30)
def test_binning_method_setting(self):
V = Variogram(self.c, self.v, n_lags=4)
# lags
even = [10.58, 21.15, 31.73, 42.3]
uniform = [10.25, 16.21, 22.71, 42.3]
# test even
assert_array_almost_equal(even, V.bins, decimal=2)
# set to uniform
V.set_bin_func('uniform')
assert_array_almost_equal(uniform, V.bins, decimal=2)
# restore even
V.bin_func = 'even'
assert_array_almost_equal(even, V.bins, decimal=2)
def test_binning_method_scott(self):
V = Variogram(self.c, self.v, bin_func='scott')
# scott should yield 11 bins here
self.assertTrue(V.n_lags == 11)
assert_array_almost_equal(
V.bins,
np.array([4.9, 8.6, 12.4, 16.1, 19.9, 23.6, 27.3, 31.1, 34.8, 38.6, 42.3]),
decimal=1
)
def test_binning_method_stable(self):
V = Variogram(self.c, self.v, bin_func='stable_entropy')
assert_array_almost_equal(
V.bins,
np.array([4.3, 8.4, 12.8, 17.1, 21.4, 25.2, 29.9, 33.2, 38.5, 42.8]),
decimal=0
)
def test_binning_method_stable_maxiter(self):
# increase maxiter - the result should stay the same
V = Variogram(self.c, self.v, bin_func='stable_entropy', binning_maxiter=20000)
assert_array_almost_equal(
V.bins,
np.array([4.3, 8.4, 12.8, 17.1, 21.4, 25.2, 29.9, 33.2, 38.5, 42.8]),
decimal=0
)
def test_binning_method_stable_fix_bins(self):
# use 50 bins over the sqrt method - this should change the bins
V = Variogram(
self.c,
self.v,
bin_func='stable_entropy',
binning_entropy_bins=50
)
assert_array_almost_equal(
V.bins,
np.array([4.2, 8.6, 12.8, 17.1, 21.2, 25.5, 29.3, 33.2, 37.4, 43.]),
decimal=0
)
def test_binning_change_nlags(self):
V = Variogram(self.c, self.v, n_lags=5)
# 5 lags are awaited
self.assertTrue(V.n_lags == 5)
# switch to fd rule
V.bin_func = 'fd'
self.assertTrue(V.n_lags == 13)
def test_set_bins_directly(self):
V = Variogram(self.c, self.v, n_lags=5)
# set bins by hand
bins = np.array([4., 20., 21., 25., 40.])
V.bins = bins
# test setting
assert_array_almost_equal(bins, V.bins, decimal=8)
# test cov settings
self.assertIsNone(V.cov)
self.assertIsNone(V.cof)
def test_binning_callable_arg(self):
# define a custom function similar an existing string function
def even_func(distances, n, maxlag):
return np.linspace(0, np.min(np.nanmax(distances), maxlag), n + 1)[1:], None
# run custom function and string function
V = Variogram(self.c, self.v, n_lags=8, bin_func=even_func)
V2 = Variogram(self.c, self.v, n_lags=8, bin_func='even')
# check the binning is indeed the same
assert np.array_equal(V.bins, V2.bins)
def test_binning_iterable_arg(self):
# define a custom iterable with bin edges
custom_bins = np.linspace(5,50,5)
# check that the bins are set according to those edges
V = Variogram(self.c, self.v, bin_func=custom_bins)
assert np.array_equal(V.bins, custom_bins)
assert V.n_lags == len(custom_bins)
assert V.maxlag == max(custom_bins)
# check that custom bins have priority over nlags and maxlag
V = Variogram(self.c, self.v, bin_func=custom_bins, nlags=1000)
assert np.array_equal(V.bins, custom_bins)
assert V.n_lags == len(custom_bins)
assert V.maxlag == max(custom_bins)
V = Variogram(self.c, self.v, bin_func=custom_bins, maxlag=1000)
assert np.array_equal(V.bins, custom_bins)
assert V.n_lags == len(custom_bins)
assert V.maxlag == max(custom_bins)
def test_binning_kmeans_method(self):
V = Variogram(
self.c,
self.v,
n_lags=6,
bin_func='kmeans',
binning_random_state=1306
)
assert_array_almost_equal(
V.bins,
np.array([2.5, 7.7, 12.9, 18.1, 23.7, 30.3]),
decimal=1
)
def test_binning_ward_method(self):
V = Variogram(self.c, self.v, n_lags=6, bin_func='ward')
assert_array_almost_equal(
V.bins,
np.array([2.5, 7.1, 11.1, 16.2, 23., 30.]),
decimal=1
)
def test_estimator_method_setting(self):
"""
Only test if the estimator functions are correctly set. The
estimator functions themselves are tested in a unittest of their own.
"""
V = Variogram(self.c, self.v, n_lags=4)
estimator_list = ('cressie', 'matheron', 'dowd', 'genton', 'minmax',
'percentile', 'entropy')
for estimator in estimator_list:
# set the estimator
V.estimator = estimator
imported_estimator = getattr(estimators, estimator)
self.assertEqual(imported_estimator, V.estimator)
def test_set_estimator_wrong_type(self):
V = Variogram(self.c, self.v)
with self.assertRaises(ValueError) as e:
V.set_estimator(45)
self.assertEqual(
str(e.exception),
'The estimator has to be a string or callable.'
)
def test_set_unknown_estimator(self):
V = Variogram(self.c, self.v)
with self.assertRaises(ValueError) as e:
V.set_estimator('notaestimator')
self.assertEqual(
str(e.exception),
'Variogram estimator notaestimator is not understood, please ' +
'provide the function.'
)
def test_set_dist_func(self):
# The covariance cannot be estimated here - ignore the warning
with warnings.catch_warnings():
warnings.simplefilter('ignore')
V = Variogram([(0, 0), (4, 1), (1, 1)], [1, 2, 3], n_lags=2)
# use Manhattan distance
V.set_dist_function('cityblock')
for d, v in zip([5., 2., 3.], V.distance):
self.assertEqual(d, v)
def test_unknown_dist_func(self):
V = Variogram(self.c, self.v)
with self.assertRaises(ValueError) as e:
V.set_dist_function('notadistance')
self.assertEqual(
str(e.exception),
'Unknown Distance Metric: notadistance'
)
def test_wrong_dist_func_input(self):
V = Variogram(self.c, self.v)
with self.assertRaises(ValueError) as e:
V.set_dist_function(55)
self.assertEqual(
str(e.exception),
'Input not supported. Pass a string or callable.'
)
def test_callable_dist_function(self):
"""Test to pass a callable as dist function, which always returns 1"""
# The covariance cannot be estimated here - ignore the warning
with warnings.catch_warnings():
warnings.simplefilter('ignore')
V = Variogram([(0, 0), (4, 1), (1, 1)], [1, 2, 3], n_lags=2)
def dfunc(u, v):
return 1
V.set_dist_function(dfunc)
# test
self.assertEqual(V.dist_function, dfunc)
self.assertTrue((V.distance==1).all())
self.assertEqual(V.distance_matrix.shape, (3, 3))
@staticmethod
def disabled_test_direct_dist_setting():
# Distance can no longer be explicitly set
# it would require setting the whole MetricSpace, with a
# non-sparse diagonal matrix
V = Variogram([(0, 0), (4, 1), (1, 1)], [1, 2, 3], n_lags=2)
V.distance = np.array([0, 0, 100])
assert_array_almost_equal(V.distance, [0, 0, 100], decimal=0)
def test_maxlag_setting_as_max_ratio(self):
V = Variogram(self.c, self.v)
# set maxlag to 60% of maximum distance
V.maxlag = 0.6
self.assertEqual(V.maxlag, np.max(V.distance) * 0.6)
self.assertAlmostEqual(V.maxlag, 25.38, places=2)
def test_maxlag_custom_value(self):
V = Variogram(self.c, self.v)
V.maxlag = 33.3
self.assertAlmostEqual(V.maxlag, 33.3, places=1)
def test_use_nugget_setting(self):
V = Variogram(self.c, self.v, normalize=True)
# test the property and setter
self.assertEqual(V.use_nugget, False)
self.assertEqual(V.describe()['nugget'], 0)
# set the nugget
V.use_nugget = True
self.assertEqual(V.use_nugget, True)
self.assertEqual(V._use_nugget, True)
self.assertAlmostEqual(
V.describe()['normalized_nugget'],
291.28,
places=2
)
def test_use_nugget_exception(self):
with self.assertRaises(ValueError) as e:
Variogram(self.c, self.v, use_nugget=42)
self.assertEqual(
str(e.exception),
'use_nugget has to be of type bool.'
)
def test_n_lags_change(self):
V = Variogram(self.c, self.v, n_lags=10)
self.assertEqual(len(V.bins), 10)
V.n_lags = 5
self.assertEqual(len(V.bins), 5)
def test_n_lags_exception(self):
for arg in [15.5, -5]:
with self.assertRaises(ValueError) as e:
Variogram(self.c, self.v, n_lags=arg)
self.assertEqual(
str(e.exception),
'n_lags has to be a positive integer'
)
def test_n_lags_not_implemented(self):
with self.assertRaises(NotImplementedError):
Variogram(self.c, self.v, n_lags='auto')
def test_set_values(self):
V = Variogram(self.c, self.v)
# create a new array of same length
_old_vals = V.values
new_vals = np.random.normal(10, 2, size=len(_old_vals))
V.values = new_vals
# values.setter will call set_values
assert_array_almost_equal(V.values, new_vals, decimal=4)
def test_value_matrix(self):
vals = np.array([1, 2, 3, 4])
mat = np.asarray([[0, 1, 2, 3], [1, 0, 1, 2],[2, 1, 0, 1], [3, 2, 1, 0]], dtype=int)
V = Variogram(self.c[:4], vals)
assert_array_almost_equal(V.value_matrix, mat, decimal=1)
def _test_normalize_setter(self):
# TODO: I should fix this behavior
V = Variogram(self.c, self.v, normalize=False)
# make sure biggest bin larger than 1.0
self.assertGreater(np.max(V.bins), 1.0)
# normalize
V.normalize = True
# now, biggest bin should be almost or exactly 1.0
self.assertLessEqual(np.max(V.bins), 1.0)
def test_distance_matrix(self):
"""Test the distance matrix property for correct shape"""
coor = [[0, 0], [1, 0], [0, 1], [1, 1]]
vals = [0, 1, 2, 3]
dist_mat = np.asarray([
[0, 1, 1, 1.414],
[1, 0, 1.414, 1],
[1, 1.414, 0, 1],
[1.414, 1, 1, 0]
])
# The covariance cannot be estimated here - ignore the warning
with warnings.catch_warnings():
warnings.simplefilter('ignore')
V = Variogram(coor, vals)
assert_array_almost_equal(V.distance_matrix, dist_mat, decimal=3)
def test_entropy_as_estimator(self):
"""
Note: This unittest will change in future, as soon as the
bin edges for Entropy calculation can be set on instantiation
"""
V = Variogram(self.c, self.v, estimator='entropy', n_lags=10)
assert_array_almost_equal(
V.experimental,
[2.97, 3.3, 3.45, 2.95, 3.33, 3.28, 3.31, 3.44, 2.65, 1.01],
decimal=2
)
def test_metric_space_property(self):
"""
Test that the MetricSpace is correctly returned
"""
V = Variogram(self.c, self.v)
# get the metric space through property
mc = V.metric_space
# assert the coords are actually the same
assert_array_almost_equal(
mc.coords,
V.coordinates,
decimal=5
)
def test_metric_space_readonly(self):
"""
Verify that metric_space is a read-only property.
"""
V = Variogram(self.c, self.v)
with self.assertRaises(AttributeError) as e:
V.metric_space = self.c
self.assertTrue('read-only' in str(e.exception))
def test_nofit(self):
"""
Verify that providing no fitting method skips the fitting procedure
"""
V = Variogram(self.c, self.v, fit_method=None)
assert V.fit_method is None
assert V.cov is None
assert V.cof is None
def test_model(self):
"""
Test that all types of models instantiate properly
(to complement test_set_model() that only checks already instantiated vario)
"""
# Individual model
for model_name in ['spherical', 'gaussian', 'exponential', 'cubic', 'matern', 'stable']:
V = Variogram(self.c, self.v, model=model_name)
assert V._model_name == model_name
assert V._model == globals()[model_name]
assert V._is_model_custom is False
# Sum of models
for model_name in ['spherical+gaussian', 'cubic+matern+stable']:
V = Variogram(self.c, self.v, model=model_name)
assert V._model_name == model_name
assert V._is_model_custom is False
# Custom model
@variogram
def custom_model(h, r1, c1, x):
return spherical(h, r1, c1) + x
with self.assertWarns(UserWarning):
V = Variogram(self.c, self.v, model=custom_model)
assert V._model_name == "custom_model"
assert V._model == custom_model
assert V._is_model_custom is True
def test_get_bin_count(self):
V = Variogram(self.c, self.v)
# check type
assert isinstance(V.bin_count, np.ndarray)
# check against real bin count
assert np.array_equal(V.bin_count, np.array([22, 54, 87, 65, 77, 47, 46, 24, 10, 2]))
# check property gets updated
old_bin_count = V.bin_count
# when setting binning function
V.bin_func = 'uniform'
assert not np.array_equal(V.bin_count, old_bin_count)
# when setting maxlag
old_bin_count = V.bin_count
V.maxlag = 25
assert not np.array_equal(V.bin_count, old_bin_count)
# when setting nlags
V.n_lags = 5
assert len(V.bin_count) == 5
class TestVariogramFittingProcedure(unittest.TestCase):
def setUp(self):
np.random.seed(1337)
self.c = np.random.gamma(10, 8, (50, 3))
np.random.seed(1337)
self.v = np.random.normal(10, 4, 50)
# build a standard variogram to be used
self.V = Variogram(
self.c, self.v, n_lags=5, normalize=False, use_nugget=True
)
def test_fit_sigma_is_None(self):
self.V.fit_sigma = None
self.assertIsNone(self.V.fit_sigma)
def test_fit_sigma_explicit(self):
sigs = [.8, .5, 2., 2., 5.]
self.V.fit_sigma = sigs
for x, y in zip(sigs, self.V.fit_sigma):
self.assertEqual(x, y)
def test_fit_sigma_raises_AttributeError(self):
self.V.fit_sigma = (0, 1, 2)
with self.assertRaises(AttributeError) as e:
self.V.fit_sigma
self.assertTrue(
'len(fit_sigma)' in str(e.exception)
)
def test_fit_sigma_raises_ValueError(self):
self.V.fit_sigma = 'notAnFunction'
with self.assertRaises(ValueError) as e:
self.V.fit_sigma
self.assertTrue(
"fit_sigma is not understood." in str(e.exception)
)
def test_fit_sigma_linear(self):
self.V.fit_sigma = 'linear'
# test the sigmas
sigma = self.V.fit_sigma
for s, _s in zip(sigma, [.2, .4, .6, .8, 1.]):
self.assertAlmostEqual(s, _s, places=8)
# test parameters:
self.V.fit()
assert_array_almost_equal(
self.V.parameters, [13., 0.3, 18.], decimal=1
)
def test_fit_sigma_exp(self):
self.V.fit_sigma = 'exp'
# test the sigmas
sigma = self.V.fit_sigma
for s, _s in zip(sigma, [0.0067, 0.0821, 0.1889, 0.2865, 0.3679]):
self.assertAlmostEqual(s, _s, places=4)
# test parameters
assert_array_almost_equal(
self.V.parameters, [25., 0.2, 18.5], decimal=1
)
def test_fit_sigma_sqrt(self):
self.V.fit_sigma = 'sqrt'
# test the sigmas
assert_array_almost_equal(
self.V.fit_sigma, [0.447, 0.632, 0.775, 0.894, 1.], decimal=3
)
# test the parameters
assert_array_almost_equal(
self.V.parameters, [19.7, 1.5, 16.4], decimal=1
)
def test_fit_sigma_sq(self):
self.V.fit_sigma = 'sq'
# test the sigmas
assert_array_almost_equal(
self.V.fit_sigma, [0.04, 0.16, 0.36, 0.64, 1.], decimal=2
)
# test the parameters
assert_array_almost_equal(
self.V.parameters, [5.4, 0.1, 18.5], decimal=1
)
def test_fit_sigma_entropy(self):
# load data sample
data = pd.read_csv(os.path.dirname(__file__) + '/sample.csv')
V = Variogram(
data[['x', 'y']].values,
data.z.values,
n_lags=12,
fit_method='ml',
fit_sigma='entropy'
)
assert_array_almost_equal(
V.parameters, [65.9, 1.3, 0], decimal=1
)
def test_fit_sigma_on_the_fly(self):
self.V.fit(sigma='sq')
# test the sigmas
assert_array_almost_equal(
self.V.fit_sigma, [0.04, 0.16, 0.36, 0.64, 1.], decimal=2
)
# test the parameters
assert_array_almost_equal(
self.V.parameters, [5.4, 0.1, 18.5], decimal=1
)
def test_fit_lm(self):
df = pd.read_csv(os.path.dirname(__file__) + '/sample.csv')
V = Variogram(
df[['x', 'y']],
df.z.values,
use_nugget=True,
n_lags=8, fit_method='lm'
)
# test the parameters
assert_array_almost_equal(
V.parameters, [162.3, 0.5, 0.8], decimal=1
)
def test_fitted_model(self):
self.V._fit_method = 'trf'
self.V.fit_sigma = None
fun = self.V.fitted_model
result = np.array([12.48, 17.2, 17.2, 17.2])
assert_array_almost_equal(
result, list(map(fun, np.arange(0, 20, 5))),
decimal=2
)
def test_unavailable_method(self):
with self.assertRaises(AttributeError) as e:
self.V.fit(method='unsupported')
self.assertTrue(
"fit_method has to be one of" in str(e.exception)
)
def test_implicit_run_fit_fitted_model(self):
self.V.fit_sigma = None
self.V._fit_method = 'trf'
result = np.array([12.48, 17.2, 17.2, 17.2])
# remove cof
self.V.cof = None
# test on fitted model
fun = self.V.fitted_model
assert_array_almost_equal(
result, list(map(fun, np.arange(0, 20, 5))), decimal=2
)
def test_implicit_run_fit_transform(self):
self.V.fit_sigma = None
self.V._fit_method = 'trf'
result = np.array([12.48, 17.2, 17.2, 17.2])
# test on transform
self.V.cof = None
res = self.V.transform(np.arange(0, 20, 5))
assert_array_almost_equal(result, res, decimal=2)
def test_harmonize_model(self):
# load data sample
data = pd.read_csv(os.path.dirname(__file__) + '/sample.csv')
V = Variogram(data[['x', 'y']].values, data.z.values)
V.model = 'harmonize'
x = np.linspace(0, np.max(V.bins), 10)
assert_array_almost_equal(
V.transform(x),
[np.nan, 0.57, 1.01, 1.12, 1.15, 1.15, 1.15, 1.15, 1.21, 1.65],
decimal=2
)
def test_ml_default(self):
# load data sample
df = pd.read_csv(os.path.dirname(__file__) + '/sample.csv')
V = Variogram(
df[['x', 'y']],
df.z.values,
use_nugget=True,
n_lags=15,
fit_method='ml'
)
assert_array_almost_equal(
V.parameters, np.array([41.18, 1.2, 0.]), decimal=2
)
def test_ml_sq_sigma(self):
# load data sample
df = pd.read_csv(os.path.dirname(__file__) + '/sample.csv')
V = Variogram(
df[['x', 'y']],
df.z.values,
use_nugget=True,
n_lags=15,
fit_method='ml',
fit_sigma='sq'
)
assert_array_almost_equal(
V.parameters, np.array([42.72, 1.21, 0.]), decimal=2
)
def test_manual_fit(self):
V = Variogram(
self.c,
self.v,
fit_method='manual',
model='spherical',
fit_range=10.,
fit_sill=5.
)
self.assertEqual(V.parameters, [10., 5., 0.0])
def test_manual_fit_change(self):
V = Variogram(
self.c,
self.v,
fit_method='trf',
model='matern',
)
# switch to manual fit
V._fit_method = 'manual'
V.fit(range=10, sill=5, shape=3)
self.assertEqual(V.parameters, [10., 5., 3., 0.0])
def test_manual_raises_missing_params(self):
with self.assertRaises(AttributeError) as e:
Variogram(self.c, self.v, fit_method='manual')
self.assertTrue('For manual fitting' in str(e.exception))
def test_manual_preserve_params(self):
V = Variogram(self.c, self.v, fit_method='trf', n_lags=8)
params = V.parameters
# switch fit method
V._fit_method = 'manual'
V.fit(sill=14)
# expected output
params[1] = 14.
assert_array_almost_equal(
V.parameters,
params,
decimal=1
)
def test_implicit_nugget(self):
V = Variogram(self.c, self.v, use_nugget=False)
# no nugget used
self.assertTrue(V.parameters[-1] < 1e-10)
# switch to manual fitting
V.fit(method='manual', sill=5., nugget=2.)
self.assertTrue(abs(V.parameters[-1] - 2.) < 1e-10)
def test_fit_custom_model(self):
# Define a custom variogram and run the fit
@variogram
def sum_spherical(h, r1, c1, r2, c2, b1, b2):
return spherical(h, r1, c1, b1) + spherical(h, r2, c2, b2)
with self.assertWarns(UserWarning):