forked from pysal/momepy
/
diversity.py
936 lines (788 loc) · 29.6 KB
/
diversity.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# diversity.py
# definitions of diversity characters
import numpy as np
import pandas as pd
import scipy as sp
from tqdm.auto import tqdm # progress bar
__all__ = [
"Range",
"Theil",
"Simpson",
"Gini",
"Shannon",
"Unique",
"simpson_diversity",
"shannon_diversity",
"Percentiles",
]
class Range:
"""
Calculates the range of values within neighbours defined in ``spatial_weights``.
Uses ``scipy.stats.iqr`` under the hood.
Adapted from :cite:`dibble2017`.
Parameters
----------
gdf : GeoDataFrame
GeoDataFrame containing morphological tessellation
values : str, list, np.array, pd.Series
the name of the dataframe column, ``np.array``, or ``pd.Series`` where is
stored character value.
spatial_weights : libpysal.weights
spatial weights matrix
unique_id : str
name of the column with unique id used as ``spatial_weights`` index
rng : Two-element sequence containing floats in range of [0,100], optional
Percentiles over which to compute the range. Each must be
between 0 and 100, inclusive. The order of the elements is not important.
**kwargs : keyword arguments
optional arguments for ``scipy.stats.iqr``
verbose : bool (default True)
if True, shows progress bars in loops and indication of steps
Attributes
----------
series : Series
Series containing resulting values
gdf : GeoDataFrame
original GeoDataFrame
values : Series
Series containing used values
sw : libpysal.weights
spatial weights matrix
id : Series
Series containing used unique ID
rng : tuple
range
kwargs : dict
kwargs
Examples
--------
>>> sw = momepy.sw_high(k=3, gdf=tessellation_df, ids='uID')
>>> tessellation_df['area_IQR_3steps'] = mm.Range(tessellation_df,
... 'area',
... sw,
... 'uID',
... rng=(25, 75)).series
100%|██████████| 144/144 [00:00<00:00, 722.50it/s]
"""
def __init__(
self,
gdf,
values,
spatial_weights,
unique_id,
rng=(0, 100),
verbose=True,
**kwargs,
):
self.gdf = gdf
self.sw = spatial_weights
self.id = gdf[unique_id]
self.rng = rng
self.kwargs = kwargs
data = gdf.copy()
if values is not None:
if not isinstance(values, str):
data["mm_v"] = values
values = "mm_v"
self.values = data[values]
data = data.set_index(unique_id)[values]
results_list = []
for index in tqdm(data.index, total=data.shape[0], disable=not verbose):
if index in spatial_weights.neighbors.keys():
neighbours = [index]
neighbours += spatial_weights.neighbors[index]
values_list = data.loc[neighbours]
results_list.append(sp.stats.iqr(values_list, rng=rng, **kwargs))
else:
results_list.append(np.nan)
self.series = pd.Series(results_list, index=gdf.index)
class Theil:
"""
Calculates the Theil measure of inequality of values within neighbours defined in
``spatial_weights``.
Uses ``inequality.theil.Theil`` under the hood. Requires '`inequality`' package.
.. math::
T = \sum_{i=1}^n \left( \\frac{y_i}{\sum_{i=1}^n y_i} \ln \left[ N \\frac{y_i}
{\sum_{i=1}^n y_i}\\right] \\right)
Parameters
----------
gdf : GeoDataFrame
GeoDataFrame containing morphological tessellation
values : str, list, np.array, pd.Series
the name of the dataframe column, ``np.array``, or ``pd.Series`` where is
stored character value.
spatial_weights : libpysal.weights
spatial weights matrix
unique_id : str
name of the column with unique id used as ``spatial_weights`` index
rng : Two-element sequence containing floats in range of [0,100], optional
Percentiles over which to compute the range. Each must be
between 0 and 100, inclusive. The order of the elements is not important.
verbose : bool (default True)
if True, shows progress bars in loops and indication of steps
Attributes
----------
series : Series
Series containing resulting values
gdf : GeoDataFrame
original GeoDataFrame
values : Series
Series containing used values
sw : libpysal.weights
spatial weights matrix
id : Series
Series containing used unique ID
rng : tuple, optional
range
Examples
--------
>>> sw = momepy.sw_high(k=3, gdf=tessellation_df, ids='uID')
>>> tessellation_df['area_Theil'] = mm.Theil(tessellation_df,
... 'area',
... sw,
... 'uID').series
100%|██████████| 144/144 [00:00<00:00, 597.37it/s]
"""
def __init__(self, gdf, values, spatial_weights, unique_id, rng=None, verbose=True):
try:
from inequality.theil import Theil
except ImportError:
raise ImportError("The 'inequality' package is required.")
self.gdf = gdf
self.sw = spatial_weights
self.id = gdf[unique_id]
self.rng = rng
data = gdf.copy()
if values is not None:
if not isinstance(values, str):
data["mm_v"] = values
values = "mm_v"
self.values = data[values]
data = data.set_index(unique_id)[values]
if rng:
from momepy import limit_range
results_list = []
for index in tqdm(data.index, total=data.shape[0], disable=not verbose):
if index in spatial_weights.neighbors.keys():
neighbours = [index]
neighbours += spatial_weights.neighbors[index]
values_list = data.loc[neighbours]
if rng:
values_list = limit_range(values_list, rng=rng)
results_list.append(Theil(values_list).T)
else:
results_list.append(np.nan)
self.series = pd.Series(results_list, index=gdf.index)
class Simpson:
"""
Calculates the Simpson\'s diversity index of values within neighbours defined in
``spatial_weights``.
Uses ``mapclassify.classifiers`` under the hood for binning. Requires
``mapclassify>=.2.1.0`` dependency.
.. math::
\\lambda=\\sum_{i=1}^{R} p_{i}^{2}
Adapted from :cite:`feliciotti2018`.
Parameters
----------
gdf : GeoDataFrame
GeoDataFrame containing morphological tessellation
values : str, list, np.array, pd.Series
the name of the dataframe column, ``np.array``, or ``pd.Series`` where is
stored character value.
spatial_weights : libpysal.weights, optional
spatial weights matrix - If None, Queen contiguity matrix of set order will be
calculated based on objects.
unique_id : str
name of the column with unique id used as ``spatial_weights`` index
binning : str (default 'HeadTailBreaks')
One of mapclassify classification schemes. For details see
`mapclassify API documentation <http://pysal.org/mapclassify/api.html>`_.
gini_simpson : bool (default False)
return Gini-Simpson index instead of Simpson index (``1 - λ``)
inverse : bool (default False)
return Inverse Simpson index instead of Simpson index (``1 / λ``)
categorical : bool (default False)
treat values as categories (will not use ``binning``)
categories : list-like (default None)
list of categories. If None ``values.unique()`` is used.
verbose : bool (default True)
if True, shows progress bars in loops and indication of steps
**classification_kwds : dict
Keyword arguments for classification scheme
For details see `mapclassify documentation <https://pysal.org/mapclassify>`_.
Attributes
----------
series : Series
Series containing resulting values
gdf : GeoDataFrame
original GeoDataFrame
values : Series
Series containing used values
sw : libpysal.weights
spatial weights matrix
id : Series
Series containing used unique ID
binning : str
binning method
bins : mapclassify.classifiers.Classifier
generated bins
classification_kwds : dict
classification_kwds
Examples
--------
>>> sw = momepy.sw_high(k=3, gdf=tessellation_df, ids='uID')
>>> tessellation_df['area_Simpson'] = mm.Simpson(tessellation_df,
... 'area',
... sw,
... 'uID').series
100%|██████████| 144/144 [00:00<00:00, 455.83it/s]
See also
--------
momepy.simpson_diversity : Calculates the Simpson\'s diversity index of data
"""
def __init__(
self,
gdf,
values,
spatial_weights,
unique_id,
binning="HeadTailBreaks",
gini_simpson=False,
inverse=False,
categorical=False,
categories=None,
verbose=True,
**classification_kwds,
):
if not categorical:
try:
from mapclassify import classify
except ImportError:
raise ImportError("The 'mapclassify >= 2.4.2` package is required.")
self.gdf = gdf
self.sw = spatial_weights
self.id = gdf[unique_id]
self.binning = binning
self.gini_simpson = gini_simpson
self.inverse = inverse
self.categorical = categorical
self.categories = categories
self.classification_kwds = classification_kwds
data = gdf.copy()
if values is not None:
if not isinstance(values, str):
data["mm_v"] = values
values = "mm_v"
self.values = data[values]
data = data.set_index(unique_id)[values]
if not categories:
categories = data.unique()
if not categorical:
self.bins = classify(data, scheme=binning, **classification_kwds).bins
else:
self.bins = categories
results_list = []
for index in tqdm(data.index, total=data.shape[0], disable=not verbose):
if index in spatial_weights.neighbors.keys():
neighbours = [index]
neighbours += spatial_weights.neighbors[index]
values_list = data.loc[neighbours]
results_list.append(
simpson_diversity(
values_list,
self.bins,
categorical=categorical,
categories=categories,
)
)
else:
results_list.append(np.nan)
if gini_simpson:
self.series = 1 - pd.Series(results_list, index=gdf.index)
elif inverse:
self.series = 1 / pd.Series(results_list, index=gdf.index)
else:
self.series = pd.Series(results_list, index=gdf.index)
def simpson_diversity(data, bins=None, categorical=False, categories=None):
"""
Calculates the Simpson\'s diversity index of data. Helper function for
:py:class:`momepy.Simpson`.
.. math::
\\lambda=\\sum_{i=1}^{R} p_{i}^{2}
Formula adapted from https://gist.github.com/martinjc/f227b447791df8c90568.
Parameters
----------
data : GeoDataFrame
GeoDataFrame containing morphological tessellation
bins : array, optional
array of top edges of classification bins. Result of binnng.bins.
categorical : bool (default False)
treat values as categories (will not use ``bins``)
categories : list-like (default None)
list of categories
Returns
-------
float
Simpson's diversity index
See also
--------
momepy.Simpson : Calculates the Simpson\'s diversity index
"""
if not categorical:
try:
import mapclassify as mc
except ImportError:
raise ImportError("The 'mapclassify' package is required")
def p(n, N):
"""Relative abundance"""
if n == 0:
return 0
return float(n) / N
if categorical:
counts = data.value_counts().to_dict()
for c in categories:
if c not in counts.keys():
counts[c] = 0
else:
sample_bins = mc.UserDefined(data, bins)
counts = dict(zip(bins, sample_bins.counts))
N = sum(counts.values())
return sum(p(n, N) ** 2 for n in counts.values() if n != 0)
class Gini:
"""
Calculates the Gini index of values within neighbours defined in
``spatial_weights``.
Uses ``inequality.gini.Gini`` under the hood. Requires '`inequality`' package.
.. math::
Parameters
----------
gdf : GeoDataFrame
GeoDataFrame containing morphological tessellation
values : str, list, np.array, pd.Series
the name of the dataframe column, ``np.array``, or ``pd.Series`` where is
stored character value.
spatial_weights : libpysal.weights
spatial weights matrix
unique_id : str
name of the column with unique id used as ``spatial_weights`` index
rng : Two-element sequence containing floats in range of [0,100], optional
Percentiles over which to compute the range. Each must be
between 0 and 100, inclusive. The order of the elements is not important.
verbose : bool (default True)
if True, shows progress bars in loops and indication of steps
Attributes
----------
series : Series
Series containing resulting values
gdf : GeoDataFrame
original GeoDataFrame
values : Series
Series containing used values
sw : libpysal.weights
spatial weights matrix
id : Series
Series containing used unique ID
rng : tuple
range
Examples
--------
>>> sw = momepy.sw_high(k=3, gdf=tessellation_df, ids='uID')
>>> tessellation_df['area_Gini'] = mm.Gini(tessellation_df,
... 'area',
... sw,
... 'uID').series
100%|██████████| 144/144 [00:00<00:00, 597.37it/s]
"""
def __init__(self, gdf, values, spatial_weights, unique_id, rng=None, verbose=True):
try:
from inequality.gini import Gini
except ImportError:
raise ImportError("The 'inequality' package is required.")
self.gdf = gdf
self.sw = spatial_weights
self.id = gdf[unique_id]
self.rng = rng
data = gdf.copy()
if values is not None:
if not isinstance(values, str):
data["mm_v"] = values
values = "mm_v"
self.values = data[values]
if self.values.min() < 0:
raise ValueError(
"Values contain negative numbers. Normalise data before"
"using momepy.Gini."
)
data = data.set_index(unique_id)[values]
if rng:
from momepy import limit_range
results_list = []
for index in tqdm(data.index, total=data.shape[0], disable=not verbose):
if index in spatial_weights.neighbors.keys():
neighbours = spatial_weights.neighbors[index].copy()
if neighbours:
neighbours.append(index)
values_list = data.loc[neighbours].values
if rng:
values_list = limit_range(values_list, rng=rng)
results_list.append(Gini(values_list).g)
else:
results_list.append(0)
else:
results_list.append(np.nan)
self.series = pd.Series(results_list, index=gdf.index)
class Shannon:
"""
Calculates the Shannon index of values within neighbours defined in
``spatial_weights``.
Uses ``mapclassify.classifiers`` under the hood for binning.
Requires ``mapclassify>=.2.1.0`` dependency.
.. math::
H^{\\prime}=-\\sum_{i=1}^{R} p_{i} \\ln p_{i}
Parameters
----------
gdf : GeoDataFrame
GeoDataFrame containing morphological tessellation
values : str, list, np.array, pd.Series
the name of the dataframe column, ``np.array``, or ``pd.Series`` where
is stored character value.
spatial_weights : libpysal.weights, optional
spatial weights matrix - If None, Queen contiguity matrix of set order
will be calculated based on objects.
unique_id : str
name of the column with unique id used as ``spatial_weights`` index
binning : str
One of mapclassify classification schemes. For details see
`mapclassify API documentation <http://pysal.org/mapclassify/api.html>`_.
categorical : bool (default False)
treat values as categories (will not use binning)
categories : list-like (default None)
list of categories. If None values.unique() is used.
verbose : bool (default True)
if True, shows progress bars in loops and indication of steps
**classification_kwds : dict
Keyword arguments for classification scheme
For details see `mapclassify documentation <https://pysal.org/mapclassify>`_.
Attributes
----------
series : Series
Series containing resulting values
gdf : GeoDataFrame
original GeoDataFrame
values : Series
Series containing used values
sw : libpysal.weights
spatial weights matrix
id : Series
Series containing used unique ID
binning : str
binning method
bins : mapclassify.classifiers.Classifier
generated bins
classification_kwds : dict
classification_kwds
Examples
--------
>>> sw = momepy.sw_high(k=3, gdf=tessellation_df, ids='uID')
>>> tessellation_df['area_Shannon'] = mm.Shannon(tessellation_df,
... 'area',
... sw,
... 'uID').series
100%|██████████| 144/144 [00:00<00:00, 455.83it/s]
"""
def __init__(
self,
gdf,
values,
spatial_weights,
unique_id,
binning="HeadTailBreaks",
categorical=False,
categories=None,
verbose=True,
**classification_kwds,
):
if not categorical:
try:
from mapclassify import classify
except ImportError:
raise ImportError("The 'mapclassify >= 2.4.2` package is required.")
self.gdf = gdf
self.sw = spatial_weights
self.id = gdf[unique_id]
self.binning = binning
self.categorical = categorical
self.categories = categories
self.classification_kwds = classification_kwds
data = gdf.copy()
if values is not None:
if not isinstance(values, str):
data["mm_v"] = values
values = "mm_v"
self.values = data[values]
data = data.set_index(unique_id)[values]
if not categories:
categories = data.unique()
if not categorical:
self.bins = classify(data, scheme=binning, **classification_kwds).bins
else:
self.bins = categories
results_list = []
for index in tqdm(data.index, total=data.shape[0], disable=not verbose):
if index in spatial_weights.neighbors.keys():
neighbours = [index]
neighbours += spatial_weights.neighbors[index]
values_list = data.loc[neighbours]
results_list.append(
shannon_diversity(
values_list,
self.bins,
categorical=categorical,
categories=categories,
)
)
else:
results_list.append(np.nan)
self.series = pd.Series(results_list, index=gdf.index)
def shannon_diversity(data, bins=None, categorical=False, categories=None):
"""
Calculates the Shannon\'s diversity index of data. Helper function for
:py:class:`momepy.Shannon`.
.. math::
\\lambda=\\sum_{i=1}^{R} p_{i}^{2}
Formula adapted from https://gist.github.com/audy/783125
Parameters
----------
data : GeoDataFrame
GeoDataFrame containing morphological tessellation
bins : array, optional
array of top edges of classification bins. Result of binnng.bins.
categorical : bool (default False)
treat values as categories (will not use ``bins``)
categories : list-like (default None)
list of categories
Returns
-------
float
Shannon's diversity index
See also
--------
momepy.Shannon : Calculates the Shannon's diversity index
momepy.Simpson : Calculates the Simpson's diversity index
momepy.simpson_diversity : Calculates the Simpson's diversity index
"""
from math import log as ln
if not categorical:
try:
import mapclassify as mc
except ImportError:
raise ImportError("The 'mapclassify' package is required")
def p(n, N):
"""Relative abundance"""
if n == 0:
return 0
return (float(n) / N) * ln(float(n) / N)
if categorical:
counts = data.value_counts().to_dict()
for c in categories:
if c not in counts.keys():
counts[c] = 0
else:
sample_bins = mc.UserDefined(data, bins)
counts = dict(zip(bins, sample_bins.counts))
N = sum(counts.values())
return -sum(p(n, N) for n in counts.values() if n != 0)
class Unique:
"""
Calculates the number of unique values within neighbours defined in
``spatial_weights``.
.. math::
Parameters
----------
gdf : GeoDataFrame
GeoDataFrame containing morphological tessellation
values : str, list, np.array, pd.Series
the name of the dataframe column, ``np.array``, or ``pd.Series`` where
is stored character value.
spatial_weights : libpysal.weights
spatial weights matrix
unique_id : str
name of the column with unique id used as ``spatial_weights`` index
dropna : bool (default True)
Don’t include NaN in the counts of unique values.
verbose : bool (default True)
if True, shows progress bars in loops and indication of steps
Attributes
----------
series : Series
Series containing resulting values
gdf : GeoDataFrame
original GeoDataFrame
values : Series
Series containing used values
sw : libpysal.weights
spatial weights matrix
id : Series
Series containing used unique ID
Examples
--------
>>> sw = momepy.sw_high(k=3, gdf=tessellation_df, ids='uID')
>>> tessellation_df['cluster_unique'] = mm.Unique(tessellation_df,
... 'cluster',
... sw,
... 'uID').series
100%|██████████| 144/144 [00:00<00:00, 722.50it/s]
"""
def __init__(
self, gdf, values, spatial_weights, unique_id, dropna=True, verbose=True
):
self.gdf = gdf
self.sw = spatial_weights
self.id = gdf[unique_id]
data = gdf.copy()
if values is not None:
if not isinstance(values, str):
data["mm_v"] = values
values = "mm_v"
self.values = data[values]
data = data.set_index(unique_id)[values]
results_list = []
for index in tqdm(data.index, total=data.shape[0], disable=not verbose):
if index in spatial_weights.neighbors.keys():
neighbours = [index]
neighbours += spatial_weights.neighbors[index]
values_list = data.loc[neighbours]
results_list.append(values_list.nunique(dropna=dropna))
else:
results_list.append(np.nan)
self.series = pd.Series(results_list, index=gdf.index)
class Percentiles:
"""
Calculates the percentiles of values within neighbours defined in
``spatial_weights``.
Parameters
----------
gdf : GeoDataFrame
GeoDataFrame containing source geometry
values : str, list, np.array, pd.Series
the name of the dataframe column, ``np.array``, or ``pd.Series``
where is stored character value.
spatial_weights : libpysal.weights
spatial weights matrix
unique_id : str
name of the column with unique id used as ``spatial_weights`` index
percentiles : array-like (default [25, 50, 75])
percentiles to return
interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'}
This optional parameter specifies the interpolation method to
use when the desired percentile lies between two data points
``i < j``:
* ``'linear'``
* ``'lower'``
* ``'higher'``
* ``'nearest'``
* ``'midpoint'``
See the documentation of ``numpy.percentile`` for details.
verbose : bool (default True)
if True, shows progress bars in loops and indication of steps
weighted : {'linear', None} (default None)
Distance decay weighting. If None, each neighbor within
`spatial_weights` has equal weight. If `linear`, linear
inverse distance between centroids is used as a weight.
Attributes
----------
frame : DataFrame
DataFrame containing resulting values
gdf : GeoDataFrame
original GeoDataFrame
values : Series
Series containing used values
sw : libpysal.weights
spatial weights matrix
id : Series
Series containing used unique ID
Examples
--------
>>> sw = momepy.sw_high(k=3, gdf=tessellation_df, ids='uID')
>>> percentiles_df = mm.Percentiles(tessellation_df,
... 'area',
... sw,
... 'uID').frame
100%|██████████| 144/144 [00:00<00:00, 722.50it/s]
"""
def __init__(
self,
gdf,
values,
spatial_weights,
unique_id,
percentiles=[25, 50, 75],
interpolation="midpoint",
verbose=True,
weighted=None,
):
self.gdf = gdf
self.sw = spatial_weights
self.id = gdf[unique_id]
data = gdf.copy()
if values is not None:
if not isinstance(values, str):
data["mm_v"] = values
values = "mm_v"
self.values = data[values]
results_list = []
if weighted == "linear":
data = data.set_index(unique_id)[[values, data.geometry.name]]
data.geometry = data.centroid
for i, geom in tqdm(
data.geometry.iteritems(), total=data.shape[0], disable=not verbose
):
if i in spatial_weights.neighbors.keys():
neighbours = spatial_weights.neighbors[i]
vicinity = data.loc[neighbours]
distance = vicinity.distance(geom)
distance_decay = 1 / distance
vals = vicinity[values].values
sorter = np.argsort(vals)
vals = vals[sorter]
nan_mask = np.isnan(vals)
if nan_mask.all():
results_list.append(np.array([np.nan] * len(percentiles)))
else:
sample_weight = distance_decay.values[sorter][~nan_mask]
weighted_quantiles = (
np.cumsum(sample_weight) - 0.5 * sample_weight
)
weighted_quantiles /= np.sum(sample_weight)
interpolate = np.interp(
[x / 100 for x in percentiles],
weighted_quantiles,
vals[~nan_mask],
)
results_list.append(interpolate)
else:
results_list.append(np.array([np.nan] * len(percentiles)))
self.frame = pd.DataFrame(
results_list, columns=percentiles, index=gdf.index
)
elif weighted is None:
data = data.set_index(unique_id)[values]
for index in tqdm(data.index, total=data.shape[0], disable=not verbose):
if index in spatial_weights.neighbors.keys():
neighbours = [index]
neighbours += spatial_weights.neighbors[index]
values_list = data.loc[neighbours]
results_list.append(
np.nanpercentile(
values_list, percentiles, interpolation=interpolation
)
)
else:
results_list.append(np.nan)
self.frame = pd.DataFrame(
results_list, columns=percentiles, index=gdf.index
)
else:
raise ValueError(f"'{weighted}' is not a valid option.")