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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
|
%global _empty_manifest_terminate_build 0
Name: python-scikit-mobility
Version: 1.3.1
Release: 1
Summary: A toolbox for analyzing and processing mobility data.
License: new BSD
URL: https://pypi.org/project/scikit-mobility/
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/f6/a9/f15d0496b760985e4c4a47696dbab703394c689c62ebeed26bee918d73d9/scikit-mobility-1.3.1.tar.gz
BuildArch: noarch
Requires: python3-pandas
Requires: python3-igraph
Requires: python3-powerlaw
Requires: python3-tqdm
Requires: python3-requests
Requires: python3-scikit-learn
Requires: python3-folium
Requires: python3-geojson
Requires: python3-h3
Requires: python3-pooch
Requires: python3-statsmodels
Requires: python3-geopandas
%description
[](https://zenodo.org/badge/latestdoi/184337448)




# scikit-mobility - mobility analysis in Python
<img src="logo_skmob.png" width=300/>
###### Try `scikit-mobility` without installing it
[](https://twitter.com/scikitmobility)
- in a MyBinder notebook: [](https://mybinder.org/v2/gh/scikit-mobility/scikit-mobility/master)
- on [Jovian](https://jovian.ai/jonpappalord/collections/scikit-mobility-tutorial)
`scikit-mobility` is a library for human mobility analysis in Python. The library allows to:
- represent trajectories and mobility flows with proper data structures, `TrajDataFrame` and `FlowDataFrame`.
- manage and manipulate mobility data of various formats (call detail records, GPS data, data from social media, survey data, etc.);
- extract mobility metrics and patterns from data, both at individual and collective level (e.g., length of displacements, characteristic distance, origin-destination matrix, etc.)
- generate synthetic individual trajectories using standard mathematical models (random walk models, exploration and preferential return model, etc.)
- generate synthetic mobility flows using standard migration models (gravity model, radiation model, etc.)
- assess the privacy risk associated with a mobility data set
## Table of contents
1. [Documentation](#documentation)
2. [Citing](#citing)
3. [Collaborate with us](#collaborate)
4. [Installation](#installation)
- [with pip](#installation_pip)
- [with conda](#installation_conda)
- [known issues](#known_conda)
- [test installation](#test_installation)
- [Google Colab](#google_colab)
5. [Tutorials](#tutorials)
6. [Examples](#examples)
- [TrajDataFrame](#trajdataframe)
- [FlowDataFrame](#flowdataframe)
- [Preprocessing](#preprocessing)
- [Measures](#measures)
- [Collective generative models](#collective_models)
- [Individual generative models](#individual_models)
- [Privacy](#privacy)
- [Downloading datasets](#data)
<a id='documentation'></a>
## Documentation
The documentation of scikit-mobility's classes and functions is available at: https://scikit-mobility.github.io/scikit-mobility/
<a id='citing'></a>
## Citing
if you use scikit-mobility please cite the following paper:
> Luca Pappalardo, Filippo Simini, Gianni Barlacchi and Roberto Pellungrini.
> **scikit-mobility: a Python library for the analysis, generation and risk assessment of mobility data**,
> 2019, https://arxiv.org/abs/1907.07062
Bibtex:
```
@misc{pappalardo2019scikitmobility,
title={scikit-mobility: a Python library for the analysis, generation and risk assessment of mobility data},
author={Luca Pappalardo and Filippo Simini and Gianni Barlacchi and Roberto Pellungrini},
year={2019},
eprint={1907.07062},
archivePrefix={arXiv},
primaryClass={physics.soc-ph}
}
```
<a id='collaborate'></a>
## Collaborate with us
`scikit-mobility` is an active project and any contribution is welcome.
If you would like to include your algorithm in `scikit-mobility`, feel free to fork the project, open an issue and [contact us](mailto:scikit.mobility@gmail.com).
<a id='installation'></a>
## Installation
scikit-mobility for Python >= 3.8 and all it's dependencies are available from conda-forge and can be installed using
`conda install -c conda-forge scikit-mobility`.
Note that it is **NOT recommended** to install scikit-mobility from PyPI! If you're on Windows or Mac, many GeoPandas / scikit-mobility dependencies cannot be pip installed (for details see the corresponding notes in the GeoPandas documentation).
<a id='installation_pip'></a>
### installation with pip (python >= 3.8 required)
1. Create an environment `skmob`
python3 -m venv skmob
2. Activate
source skmob/bin/activate
3. Install skmob
pip install scikit-mobility
4. OPTIONAL to use `scikit-mobility` on the jupyter notebook
- Activate the virutalenv:
source skmob/bin/activate
- Install jupyter notebook:
pip install jupyter
- Run jupyter notebook
jupyter notebook
- (Optional) install the kernel with a specific name
ipython kernel install --user --name=skmob
<a id='installation_conda'></a>
### installation with conda - miniconda
1. Create an environment `skmob` and install pip
conda create -n skmob pip python=3.9 rtree
2. Activate
conda activate skmob
3. Install skmob
conda install -c conda-forge scikit-mobility
4. OPTIONAL to use `scikit-mobility` on the jupyter notebook
- Install the kernel
conda install jupyter -c conda-forge
- Open a notebook and check if the kernel `skmob` is on the kernel list. If not, run the following:
- On Mac and Linux
env=$(basename `echo $CONDA_PREFIX`)
python -m ipykernel install --user --name "$env" --display-name "Python [conda env:"$env"]"
- On Windows
python -m ipykernel install --user --name skmob --display-name "Python [conda env: skmob]"
:exclamation: You may run into dependency issues if you try to import the package in Python. If so, try installing the following packages as followed.
```
conda install -n skmob pyproj urllib3 chardet markupsafe
```
<a id='test_installation'></a>
### Test the installation
```
> source activate skmob
(skmob)> python
>>> import skmob
>>>
```
<a id='google_colab'></a>
## Google Colab
scikit-mobility can be installed on <a href="https://colab.research.google.com/notebooks/intro.ipynb#recent=true">Google Colab</a> using the following commands:
```
!apt-get install -qq curl g++ make
!curl -L http://download.osgeo.org/libspatialindex/spatialindex-src-1.8.5.tar.gz | tar xz
import os
os.chdir('spatialindex-src-1.8.5')
!./configure
!make
!make install
!pip install rtree
!ldconfig
!pip install scikit-mobility
```
<a id='tutorials'></a>
## Tutorials
You can some tutorials on scikit-mobility here: https://github.com/scikit-mobility/tutorials.
<a id='examples'></a>
## Examples
<a id='trajdataframe'></a>
### Create a `TrajDataFrame`
In scikit-mobility, a set of trajectories is described by a `TrajDataFrame`, an extension of the pandas `DataFrame` that has specific columns names and data types. A `TrajDataFrame` can contain many trajectories, and each row in the `TrajDataFrame` represents a point of a trajectory, described by three mandatory fields (aka columns):
- `latitude` (type: float);
- `longitude` (type: float);
- `datetime` (type: date-time).
Additionally, two optional columns can be specified:
- `uid` (type: string) identifies the object associated with the point of the trajectory. If `uid` is not present, scikit-mobility assumes that the `TrajDataFrame` contains trajectories associated with a single moving object;
- `tid` specifies the identifier of the trajectory to which the point belongs to. If `tid` is not present, scikit-mobility assumes that all rows in the `TrajDataFrame` associated with a `uid` belong to the same trajectory;
Note that, besides the mandatory columns, the user can add to a `TrajDataFrame` as many columns as they want since the data structures in scikit-mobility inherit all the pandas `DataFrame` functionalities.
Create a `TrajDataFrame` from a list:
```python
>>> import skmob
>>> # create a TrajDataFrame from a list
>>> data_list = [[1, 39.984094, 116.319236, '2008-10-23 13:53:05'], [1, 39.984198, 116.319322, '2008-10-23 13:53:06'], [1, 39.984224, 116.319402, '2008-10-23 13:53:11'], [1, 39.984211, 116.319389, '2008-10-23 13:53:16']]
>>> tdf = skmob.TrajDataFrame(data_list, latitude=1, longitude=2, datetime=3)
>>> # print a portion of the TrajDataFrame
>>> print(tdf.head())
```
0 lat lng datetime
0 1 39.984094 116.319236 2008-10-23 13:53:05
1 1 39.984198 116.319322 2008-10-23 13:53:06
2 1 39.984224 116.319402 2008-10-23 13:53:11
3 1 39.984211 116.319389 2008-10-23 13:53:16
```python
>>> print(type(tdf))
```
<class 'skmob.core.trajectorydataframe.TrajDataFrame'>
Create a `TrajDataFrame` from a [pandas](https://pandas.pydata.org/) `DataFrame`:
```python
>>> import pandas as pd
>>> # create a DataFrame from the previous list
>>> data_df = pd.DataFrame(data_list, columns=['user', 'latitude', 'lng', 'hour'])
>>> # print the type of the object
>>> print(type(data_df))
```
<class 'pandas.core.frame.DataFrame'>
```python
>>> # now create a TrajDataFrame from the pandas DataFrame
>>> tdf = skmob.TrajDataFrame(data_df, latitude='latitude', datetime='hour', user_id='user')
>>> # print the type of the object
>>> print(type(tdf))
```
<class 'skmob.core.trajectorydataframe.TrajDataFrame'>
```python
>>> # print a portion of the TrajDataFrame
>>> print(tdf.head())
```
uid lat lng datetime
0 1 39.984094 116.319236 2008-10-23 13:53:05
1 1 39.984198 116.319322 2008-10-23 13:53:06
2 1 39.984224 116.319402 2008-10-23 13:53:11
3 1 39.984211 116.319389 2008-10-23 13:53:16
We can also create a `TrajDataFrame` from a file. For example, in the following we create a `TrajDataFrame` from a portion of a GPS trajectory dataset collected in the context of the [GeoLife](https://www.microsoft.com/en-us/research/publication/geolife-gps-trajectory-dataset-user-guide/) project by 178 users in a period of over four years from April 2007 to October 2011.
```python
>>> # download the file from https://raw.githubusercontent.com/scikit-mobility/scikit-mobility/master/examples/geolife_sample.txt.gz
>>> # read the trajectory data (GeoLife, Beijing, China)
>>> tdf = skmob.TrajDataFrame.from_file('geolife_sample.txt.gz', latitude='lat', longitude='lon', user_id='user', datetime='datetime')
>>> # print a portion of the TrajDataFrame
>>> print(tdf.head())
```
lat lng datetime uid
0 39.984094 116.319236 2008-10-23 05:53:05 1
1 39.984198 116.319322 2008-10-23 05:53:06 1
2 39.984224 116.319402 2008-10-23 05:53:11 1
3 39.984211 116.319389 2008-10-23 05:53:16 1
4 39.984217 116.319422 2008-10-23 05:53:21 1
A `TrajDataFrame` can be plotted on a [folium](https://python-visualization.github.io/folium/) interactive map using the `plot_trajectory` function.
```python
>>> tdf.plot_trajectory(zoom=12, weight=3, opacity=0.9, tiles='Stamen Toner')
```

<a id='flowdataframe'></a>
### Create a `FlowDataFrame`
In scikit-mobility, an origin-destination matrix is described by the `FlowDataFrame` structure, an extension of the pandas `DataFrame` that has specific column names and data types. A row in a `FlowDataFrame` represents a flow of objects between two locations, described by three mandatory columns:
- `origin` (type: string);
- `destination` (type: string);
- `flow` (type: integer).
Again, the user can add to a `FlowDataFrame` as many columns as they want since the `FlowDataFrame` data structure inherits all the pandas `DataFrame` functionalities.
In mobility tasks, the territory is often discretized by mapping the coordinates to a spatial tessellation, i.e., a covering of the bi-dimensional space using a countable number of geometric shapes (e.g., squares, hexagons), called tiles, with no overlaps and no gaps. For instance, for the analysis or prediction of mobility flows, a spatial tessellation is used to aggregate flows of people moving among locations (the tiles of the tessellation). For this reason, each `FlowDataFrame` is associated with a **spatial tessellation**, a [geopandas](http://geopandas.org/) `GeoDataFrame` that contains two mandatory columns:
- `tile_ID` (type: integer) indicates the identifier of a location;
- `geometry` indicates the polygon (or point) that describes the geometric shape of the location on a territory (e.g., a square, a voronoi shape, the shape of a neighborhood).
Note that each location identifier in the `origin` and `destination` columns of a `FlowDataFrame` must be present in the associated spatial tessellation.
Create a spatial tessellation from a file describing counties in New York state:
```python
>>> import skmob
>>> import geopandas as gpd
>>> # load a spatial tessellation
>>> url_tess = skmob.utils.constants.NY_COUNTIES_2011
>>> tessellation = gpd.read_file(url_tess).rename(columns={'tile_id': 'tile_ID'})
>>> # print a portion of the spatial tessellation
>>> print(tessellation.head())
```
tile_ID population geometry
0 36019 81716 POLYGON ((-74.006668 44.886017, -74.027389 44....
1 36101 99145 POLYGON ((-77.099754 42.274215, -77.0996569999...
2 36107 50872 POLYGON ((-76.25014899999999 42.296676, -76.24...
3 36059 1346176 POLYGON ((-73.707662 40.727831, -73.700272 40....
4 36011 79693 POLYGON ((-76.279067 42.785866, -76.2753479999...
Create a `FlowDataFrame` from a spatial tessellation and a file of real flows between counties in New York state:
```python
>>> # load real flows into a FlowDataFrame
>>> fdf = skmob.FlowDataFrame.from_file(skmob.utils.constants.NY_FLOWS_2011,
tessellation=tessellation,
tile_id='tile_ID',
sep=",")
>>> # print a portion of the flows
>>> print(fdf.head())
```
flow origin destination
0 121606 36001 36001
1 5 36001 36005
2 29 36001 36007
3 11 36001 36017
4 30 36001 36019
A `FlowDataFrame` can be visualized on a [folium](https://python-visualization.github.io/folium/) interactive map using the `plot_flows` function, which plots the flows on a geographic map as lines between the centroids of the tiles in the `FlowDataFrame`'s spatial tessellation:
```python
>>> fdf.plot_flows(flow_color='red')
```

Similarly, the spatial tessellation of a `FlowDataFrame` can be visualized using the `plot_tessellation` function. The argument `popup_features` (type:list, default:[`constants.TILE_ID`]) allows to enhance the plot's interactivity displaying popup windows that appear when the user clicks on a tile and includes information contained in the columns of the tessellation's `GeoDataFrame` specified in the argument’s list:
```python
>>> fdf.plot_tessellation(popup_features=['tile_ID', 'population'])
```

The spatial tessellation and the flows can be visualized together using the `map_f` argument, which specifies the folium object on which to plot:
```python
>>> m = fdf.plot_tessellation() # plot the tessellation
>>> fdf.plot_flows(flow_color='red', map_f=m) # plot the flows
```

<a id='preprocessing'></a>
### Trajectory preprocessing
As any analytical process, mobility data analysis requires data cleaning and preprocessing steps. The `preprocessing` module allows the user to perform four main preprocessing steps:
- noise filtering;
- stop detection;
- stop clustering;
- trajectory compression;
Note that, if a `TrajDataFrame` contains multiple trajectories from multiple users, the preprocessing methods automatically apply to the single trajectory and, when necessary, to the single moving object.
#### Noise filtering
In scikit-mobility, the function `filter` filters out a point if the speed from the previous point is higher than the parameter `max_speed`, which is by default set to 500km/h.
```python
>>> from skmob.preprocessing import filtering
>>> # filter out all points with a speed (in km/h) from the previous point higher than 500 km/h
>>> ftdf = filtering.filter(tdf, max_speed_kmh=500.)
>>> print(ftdf.parameters)
```
{'from_file': 'geolife_sample.txt.gz', 'filter': {'function': 'filter', 'max_speed_kmh': 500.0, 'include_loops': False, 'speed_kmh': 5.0, 'max_loop': 6, 'ratio_max': 0.25}}
```python
>>> n_deleted_points = len(tdf) - len(ftdf) # number of deleted points
>>> print(n_deleted_points)
```
54
Note that the `TrajDataFrame` structure as the `parameters` attribute, which indicates the operations that have been applied to the `TrajDataFrame`. This attribute is a dictionary the key of which is the signature of the function applied.
#### Stop detection
Some points in a trajectory can represent Point-Of-Interests (POIs) such as schools, restaurants, and bars, or they can represent user-specific places such as home and work locations. These points are usually called Stay Points or Stops, and they can be detected in different ways. A common approach is to apply spatial clustering algorithms to cluster trajectory points by looking at their spatial proximity. In scikit-mobility, the `stay_locations` function, contained in the `detection` module, finds the stay points visited by a moving object. For instance, to identify the stops where the object spent at least `minutes_for_a_stop` minutes within a distance `spatial_radius_km \time stop_radius_factor`, from a given point, we can use the following code:
```python
>>> from skmob.preprocessing import detection
>>> # compute the stops for each individual in the TrajDataFrame
>>> stdf = detection.stay_locations(tdf, stop_radius_factor=0.5, minutes_for_a_stop=20.0, spatial_radius_km=0.2, leaving_time=True)
>>> # print a portion of the detected stops
>>> print(stdf.head())
```
lat lng datetime uid leaving_datetime
0 39.978030 116.327481 2008-10-23 06:01:37 1 2008-10-23 10:32:53
1 40.013820 116.306532 2008-10-23 11:10:19 1 2008-10-23 23:45:27
2 39.978419 116.326870 2008-10-24 00:21:52 1 2008-10-24 01:47:30
3 39.981166 116.308475 2008-10-24 02:02:31 1 2008-10-24 02:30:29
4 39.981431 116.309902 2008-10-24 02:30:29 1 2008-10-24 03:16:35
```python
>>> print('Points of the original trajectory:\t%s'%len(tdf))
>>> print('Points of stops:\t\t\t%s'%len(stdf))
```
Points of the original trajectory: 217653
Points of stops: 391
A new column `leaving_datetime` is added to the `TrajDataFrame` in order to indicate the time when the user left the stop location. We can then visualize the detected stops using the `plot_stops` function:
```python
>>> m = stdf.plot_trajectory(max_users=1, start_end_markers=False)
>>> stdf.plot_stops(max_users=1, map_f=m)
```

#### Trajectory compression
The goal of trajectory compression is to reduce the number of trajectory points while preserving the structure of the trajectory. This step results in a significant reduction of the number of trajectory points. In scikit-mobility, we can use one of the methods in the `compression` module under the `preprocessing` module. For instance, to merge all the points that are closer than 0.2km from each other, we can use the following code:
```python
>>> from skmob.preprocessing import compression
>>> # compress the trajectory using a spatial radius of 0.2 km
>>> ctdf = compression.compress(tdf, spatial_radius_km=0.2)
>>> # print the difference in points between original and filtered TrajDataFrame
>>> print('Points of the original trajectory:\t%s'%len(tdf))
>>> print('Points of the compressed trajectory:\t%s'%len(ctdf))
```
Points of the original trajectory: 217653
Points of the compressed trajectory: 6281
<a id='measures'></a>
### Mobility measures
Several measures have been proposed in the literature to capture the patterns of human mobility, both at the individual and collective levels. Individual measures summarize the mobility patterns of a single moving object, while collective measures summarize mobility patterns of a population as a whole. scikit-mobility provides a wide set of [mobility measures](https://scikit-mobility.github.io/scikit-mobility/reference/measures.html), each implemented as a function that takes in input a `TrajDataFrame` and outputs a pandas `DataFrame`. Individual and collective measures are implemented the in `skmob.measure.individual` and the `skmob.measures.collective` modules, respectively.
For example, the following code compute the *radius of gyration*, the *jump lengths* and the *home locations* of a `TrajDataFrame`:
```python
>>> from skmob.measures.individual import jump_lengths, radius_of_gyration, home_location
>>> # load a TrajDataFrame from an URL
>>> url = "https://snap.stanford.edu/data/loc-brightkite_totalCheckins.txt.gz"
>>> df = pd.read_csv(url, sep='\t', header=0, nrows=100000,
names=['user', 'check-in_time', 'latitude', 'longitude', 'location id'])
>>> tdf = skmob.TrajDataFrame(df, latitude='latitude', longitude='longitude', datetime='check-in_time', user_id='user')
>>> # compute the radius of gyration for each individual
>>> rg_df = radius_of_gyration(tdf)
>>> print(rg_df)
```
uid radius_of_gyration
0 0 1564.436792
1 1 2467.773523
2 2 1439.649774
3 3 1752.604191
4 4 5380.503250
```python
>>> # compute the jump lengths for each individual
>>> jl_df = jump_lengths(tdf.sort_values(by='datetime'))
>>> print(jl_df.head())
```
uid jump_lengths
0 0 [19.640467328877936, 0.0, 0.0, 1.7434311010381...
1 1 [6.505330424378251, 46.75436600375988, 53.9284...
2 2 [0.0, 0.0, 0.0, 0.0, 3.6410097195943507, 0.0, ...
3 3 [3861.2706300798827, 4.061631313492122, 5.9163...
4 4 [15511.92758595804, 0.0, 15511.92758595804, 1....
Note that for some measures, such as `jump_length`, the `TrajDataFrame` must be order in increasing order by the column `datetime` (see the documentation for the measures that requires this condition https://scikit-mobility.github.io/scikit-mobility/reference/measures.html).
```python
>>> # compute the home location for each individual
>>> hl_df = home_location(tdf)
>>> print(hl_df.head())
```
uid lat lng
0 0 39.891077 -105.068532
1 1 37.630490 -122.411084
2 2 39.739154 -104.984703
3 3 37.748170 -122.459192
4 4 60.180171 24.949728
```python
>>> # now let's visualize a cloropleth map of the home locations
>>> import folium
>>> from folium.plugins import HeatMap
>>> m = folium.Map(tiles = 'openstreetmap', zoom_start=12, control_scale=True)
>>> HeatMap(hl_df[['lat', 'lng']].values).add_to(m)
>>> m
```

<a id='collective_models'></a>
### Collective generative models
Collective generative models estimate spatial flows between a set of discrete locations. Examples of spatial flows estimated with collective generative models include commuting trips between neighborhoods, migration flows between municipalities, freight shipments between states, and phone calls between regions.
In scikit-mobility, a collective generative model takes in input a spatial tessellation, i.e., a geopandas `GeoDataFrame`. To be a valid input for a collective model, the spatial tessellation should contain two columns, `geometry` and `relevance`, which are necessary to compute the two variables used by collective algorithms: the distance between tiles and the importance (aka "attractiveness") of each tile. A collective algorithm produces a `FlowDataFrame` that contains the generated flows and the spatial tessellation. scikit-mobility implements the most common collective generative algorithms:
- the `Gravity` model;
- the `Radiation` model.
#### Gravity model
The class `Gravity`, implementing the Gravity model, has two main methods:
- `fit`, which calibrates the model's parameters using a `FlowDataFrame`;
- `generate`, which generates the flows on a given spatial tessellation.
Load the spatial tessellation and a data set of real flows in a `FlowDataFrame`:
```python
>>> from skmob.utils import utils, constants
>>> import geopandas as gpd
>>> from skmob.models.gravity import Gravity
>>> import numpy as np
>>> # load a spatial tessellation
>>> url_tess = skmob.utils.constants.NY_COUNTIES_2011
>>> tessellation = gpd.read_file(url_tess).rename(columns={'tile_id': 'tile_ID'})
>>> # load the file with the real fluxes
>>> fdf = skmob.FlowDataFrame.from_file(skmob.utils.constants.NY_FLOWS_2011,
tessellation=tessellation,
tile_id='tile_ID',
sep=",")
>>> # compute the total outflows from each location of the tessellation (excluding self loops)
>>> tot_outflows = fdf[fdf['origin'] != fdf['destination']].groupby(by='origin', axis=0)[['flow']].sum().fillna(0)
>>> tessellation = tessellation.merge(tot_outflows, left_on='tile_ID', right_on='origin').rename(columns={'flow': 'tot_outflow'})
```
Instantiate a Gravity model object and generate synthetic flows:
```python
>>> # instantiate a singly constrained Gravity model
>>> gravity_singly = Gravity(gravity_type='singly cons/tetrained')
>>> print(gravity_singly)
```
Gravity(name="Gravity model", deterrence_func_type="power_law", deterrence_func_args=[-2.0], origin_exp=1.0, destination_exp=1.0, gravity_type="singly constrained")
```python
>>> # start the generation of the synthetic flows
>>> np.random.seed(0)
>>> synth_fdf = gravity_singly.generate(tessellation,
tile_id_column='tile_ID',
tot_outflows_column='tot_outflow',
relevance_column= 'population',
out_format='flows')
>>> # print a portion of the synthetic flows
>>> print(synth_fdf.head())
```
origin destination flow
0 36019 36101 101
1 36019 36107 66
2 36019 36059 1041
3 36019 36011 151
4 36019 36123 33
Fit the parameters of the Gravity model from the `FlowDataFrame` and generate the synthetic flows:
```python
>>> # instantiate a Gravity object (with default parameters)
>>> gravity_singly_fitted = Gravity(gravity_type='singly constrained')
>>> print(gravity_singly_fitted)
```
Gravity(name="Gravity model", deterrence_func_type="power_law", deterrence_func_args=[-2.0], origin_exp=1.0, destination_exp=1.0, gravity_type="singly constrained")
```python
>>> # fit the parameters of the Gravity from the FlowDataFrame
>>> gravity_singly_fitted.fit(fdf, relevance_column='population')
>>> print(gravity_singly_fitted)
```
Gravity(name="Gravity model", deterrence_func_type="power_law", deterrence_func_args=[-1.9947152031914186], origin_exp=1.0, destination_exp=0.6471759552223144, gravity_type="singly constrained")
```python
>>> # generate the synthetics flows
>>> np.random.seed(0)
>>> synth_fdf_fitted = gravity_singly_fitted.generate(tessellation,
tile_id_column='tile_ID',
tot_outflows_column='tot_outflow',
relevance_column= 'population',
out_format='flows')
>>> # print a portion of the synthetic flows
>>> print(synth_fdf_fitted.head())
```
origin destination flow
0 36019 36101 102
1 36019 36107 66
2 36019 36059 1044
3 36019 36011 152
4 36019 36123 33
Plot the real flows and the synthetic flows:
```python
>>> m = fdf.plot_flows(min_flow=100, flow_exp=0.01, flow_color='blue')
>>> synth_fdf_fitted.plot_flows(min_flow=1000, flow_exp=0.01, map_f=m)
```

#### Radiation model
The Radiation model is parameter-free and has only one method: `generate`. Given a spatial tessellation, the synthetic flows can be generated using the `Radiation` class as follows:
```python
>>> from skmob.models.radiation import Radiation
>>> # instantiate a Radiation object
>>> radiation = Radiation()
>>> # start the simulation
>>> np.random.seed(0)
>>> rad_flows = radiation.generate(tessellation,
tile_id_column='tile_ID',
tot_outflows_column='tot_outflow',
relevance_column='population',
out_format='flows_sample')
>>> # print a portion of the synthetic flows
>>> print(rad_flows.head())
```
origin destination flow
0 36019 36033 11648
1 36019 36031 4232
2 36019 36089 5598
3 36019 36113 1596
4 36019 36041 117
<a id='individual_models'></a>
### Individual generative models
The goal of individual generative models of human mobility is to create a population of agents whose mobility patterns are statistically indistinguishable from those of real individuals. An individual generative model typically generates a synthetic trajectory corresponding to a single moving object, assuming that an object is independent of the others.
scikit-mobility implements the most common individual generative models, such as the [Exploration and Preferential Return](https://www.nature.com/articles/nphys1760) model and its variants, and [DITRAS](https://link.springer.com/article/10.1007/s10618-017-0548-4). Each generative model is a python class with a public method `generate`, which starts the generation of synthetic trajectories.
The following code generate synthetic trajectories using the `DensityEPR` model:
```python
>>> from skmob.models.epr import DensityEPR
>>> # load a spatial tesellation on which to perform the simulation
>>> url = skmob.utils.constants.NY_COUNTIES_2011
>>> tessellation = gpd.read_file(url)
>>> # starting and end times of the simulation
>>> start_time = pd.to_datetime('2019/01/01 08:00:00')
>>> end_time = pd.to_datetime('2019/01/14 08:00:00')
>>> # instantiate a DensityEPR object
>>> depr = DensityEPR()
>>> # start the simulation
>>> tdf = depr.generate(start_time, end_time, tessellation, relevance_column='population', n_agents=100)
>>> print(tdf.head())
```
uid datetime lat lng
0 1 2019-01-01 08:00:00.000000 42.452018 -76.473618
1 1 2019-01-01 08:32:30.108708 42.170344 -76.306260
2 1 2019-01-01 09:09:11.760703 43.241550 -75.435903
3 1 2019-01-01 10:00:22.832309 42.170344 -76.306260
4 1 2019-01-01 14:00:25.923314 42.267915 -77.383591
```python
>>> print(tdf.parameters)
```
{'model': {'class': <function DensityEPR.__init__ at 0x7f70ce0a7e18>, 'generate': {'start_date': Timestamp('2019-01-01 08:00:00'), 'end_date': Timestamp('2019-01-14 08:00:00'), 'gravity_singly': {}, 'n_agents': 100, 'relevance_column': 'population', 'random_state': None, 'verbose': True}}}
<a id='privacy'></a>
### Privacy
Mobility data is sensitive since the movements of individuals can reveal confidential personal information or allow the re-identification of individuals in a database, creating serious privacy risks. In the literature, privacy risk assessment relies on the concept of re-identification of a moving object in a database through an attack by a malicious adversary. A common framework for privacy risk assessment assumes that during the attack a malicious adversary acquires, in some way, the access to an anonymized mobility data set, i.e., a mobility data set in which the moving object associated with a trajectory is not known. Moreover, it is assumed that the malicious adversary acquires, in some way, information about the trajectory (or a portion of it) of an individual represented in the acquired data set. Based on this information, the risk of re-identification of that individual is computed estimating how unique that individual's mobility data are with respect to the mobility data of the other individuals represented inthe acquired data set.
scikit-mobility provides several attack models, each implemented as a python class. For example in a location attack model, implemented in the `LocationAttack` class, the malicious adversary knows a certain number of locations visited by an individual, but they do not know the temporal order of the visits. To instantiate a `LocationAttack` object we can run the following code:
```python
>>> import skmob
>>> from skmob.privacy import attacks
>>> at = attacks.LocationAttack(knowledge_length=2)
```
The argument `knowledge_length` specifies how many locations the malicious adversary knows of each object's movement. The re-identification risk is computed based on the worst possible combination of `knowledge_length` locations out of all possible combinations of locations.
To assess the re-identification risk associated with a mobility data set, represented as a `TrajDataFrame`, we specify it as input to the `assess_risk` method, which returns a pandas `DataFrame` that contains the `uid` of each object in the `TrajDataFrame` and the associated re-identification risk as the column `risk` (type: float, range: $[0,1]$ where 0 indicates minimum risk and 1 maximum risk).
```python
>>> tdf = skmob.TrajDataFrame.from_file(filename="privacy_toy.csv")
>>> tdf_risk = at.assess_risk(tdf)
>>> print(tdf_risk.head())
```
uid risk
0 1 0.333333
1 2 0.500000
2 3 0.333333
3 4 0.333333
4 5 0.250000
Since risk assessment may be time-consuming for more massive datasets, scikit-mobility provides the option to focus only on a subset of the objects with the argument `targets`. For example, in the following code, we compute the re-identification risk for the object with `uid` 1 and 2 only:
```python
>>> tdf_risk = at.assess_risk(tdf, targets=[1,2])
>>> print(tdf_risk)
```
uid risk
0 1 0.333333
1 2 0.500000
<a id="data"></a>
### Downloading datasets
The `data` module of scikit-mobility provides users with an easy way to: 1) Download ready-to-use mobility data (e.g., trajectories, flows, spatial tessellations, and auxiliary data); 2) Load and transform the downloaded dataset into standard skmob structures (TrajDataFrame, GeoDataFrame, FlowDataFrame, DataFrame); 3) Allow developers and contributors to add new datasets to the library.
The `data` module provides three functions:
- `list_datasets`
- `get_dataset_info`
- `load_dataset`
The user can download the list of all datasets currently available in the library using `list_datasets`:
```python
>>> import skmob
>>> from skmob.data.load import list_datasets
>>> list_datasets()
```
['flow_foursquare_nyc',
'foursquare_nyc',
'nyc_boundaries',
'parking_san_francisco',
'taxi_san_francisco']
The user can retrieve information about a specific dataset in the library using `get_dataset_info`:
```python
>>> import skmob
>>> from skmob.data.load import get_dataset_info
>>> get_dataset_info("foursquare_nyc")
```
{'name': 'Foursquare_NYC',
'description': 'Dataset containing the Foursquare checkins of individuals moving in New York City',
'url': 'http://www-public.it-sudparis.eu/~zhang_da/pub/dataset_tsmc2014.zip',
'hash': 'cbe3fdab373d24b09b5fc53509c8958c77ff72b6c1a68589ce337d4f9a80235b',
'auth': 'no',
'data_type': 'trajectory',
'download_format': 'zip',
'sep': ' ',
'encoding': 'ISO-8859-1'}
Finally, the user can download a specific dataset using `load_dataset`:
```python
>>> import skmob
>>> from skmob.data.load import load_dataset, list_datasets
>>> tdf_nyc = load_dataset("foursquare_nyc", drop_columns=True)
>>> print(tdf_nyc.head())
```
uid lat lng datetime
0 470 40.719810 -74.002581 2012-04-03 18:00:09+00:00
1 979 40.606800 -74.044170 2012-04-03 18:00:25+00:00
2 69 40.716162 -73.883070 2012-04-03 18:02:24+00:00
3 395 40.745164 -73.982519 2012-04-03 18:02:41+00:00
4 87 40.740104 -73.989658 2012-04-03 18:03:00+00:00
# Related packages
[*movingpandas*](https://github.com/anitagraser/movingpandas) is a similar package that deals with movement data. Instead of implementing new data structures tailored for trajectories (`TrajDataFrame`) and mobility flows (`FlowDataFrame`), *movingpandas* describes a trajectory using a *geopandas* `GeoDataFrame`. There is little overlap in the covered use cases and implemented functionality (comparing [*scikit-mobility* tutorials](https://github.com/scikit-mobility/tutorials) and [*movingpandas* tutorials](https://github.com/anitagraser/movingpandas/tree/master/tutorials)): *scikit-mobility* focuses on computing human mobility metrics, generating synthetic trajectories and assessing privacy risks of mobility datasets. *movingpandas* on the other hand focuses on spatio-temporal data exploration with corresponding functions for data manipulation and analysis.
%package -n python3-scikit-mobility
Summary: A toolbox for analyzing and processing mobility data.
Provides: python-scikit-mobility
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-scikit-mobility
[](https://zenodo.org/badge/latestdoi/184337448)




# scikit-mobility - mobility analysis in Python
<img src="logo_skmob.png" width=300/>
###### Try `scikit-mobility` without installing it
[](https://twitter.com/scikitmobility)
- in a MyBinder notebook: [](https://mybinder.org/v2/gh/scikit-mobility/scikit-mobility/master)
- on [Jovian](https://jovian.ai/jonpappalord/collections/scikit-mobility-tutorial)
`scikit-mobility` is a library for human mobility analysis in Python. The library allows to:
- represent trajectories and mobility flows with proper data structures, `TrajDataFrame` and `FlowDataFrame`.
- manage and manipulate mobility data of various formats (call detail records, GPS data, data from social media, survey data, etc.);
- extract mobility metrics and patterns from data, both at individual and collective level (e.g., length of displacements, characteristic distance, origin-destination matrix, etc.)
- generate synthetic individual trajectories using standard mathematical models (random walk models, exploration and preferential return model, etc.)
- generate synthetic mobility flows using standard migration models (gravity model, radiation model, etc.)
- assess the privacy risk associated with a mobility data set
## Table of contents
1. [Documentation](#documentation)
2. [Citing](#citing)
3. [Collaborate with us](#collaborate)
4. [Installation](#installation)
- [with pip](#installation_pip)
- [with conda](#installation_conda)
- [known issues](#known_conda)
- [test installation](#test_installation)
- [Google Colab](#google_colab)
5. [Tutorials](#tutorials)
6. [Examples](#examples)
- [TrajDataFrame](#trajdataframe)
- [FlowDataFrame](#flowdataframe)
- [Preprocessing](#preprocessing)
- [Measures](#measures)
- [Collective generative models](#collective_models)
- [Individual generative models](#individual_models)
- [Privacy](#privacy)
- [Downloading datasets](#data)
<a id='documentation'></a>
## Documentation
The documentation of scikit-mobility's classes and functions is available at: https://scikit-mobility.github.io/scikit-mobility/
<a id='citing'></a>
## Citing
if you use scikit-mobility please cite the following paper:
> Luca Pappalardo, Filippo Simini, Gianni Barlacchi and Roberto Pellungrini.
> **scikit-mobility: a Python library for the analysis, generation and risk assessment of mobility data**,
> 2019, https://arxiv.org/abs/1907.07062
Bibtex:
```
@misc{pappalardo2019scikitmobility,
title={scikit-mobility: a Python library for the analysis, generation and risk assessment of mobility data},
author={Luca Pappalardo and Filippo Simini and Gianni Barlacchi and Roberto Pellungrini},
year={2019},
eprint={1907.07062},
archivePrefix={arXiv},
primaryClass={physics.soc-ph}
}
```
<a id='collaborate'></a>
## Collaborate with us
`scikit-mobility` is an active project and any contribution is welcome.
If you would like to include your algorithm in `scikit-mobility`, feel free to fork the project, open an issue and [contact us](mailto:scikit.mobility@gmail.com).
<a id='installation'></a>
## Installation
scikit-mobility for Python >= 3.8 and all it's dependencies are available from conda-forge and can be installed using
`conda install -c conda-forge scikit-mobility`.
Note that it is **NOT recommended** to install scikit-mobility from PyPI! If you're on Windows or Mac, many GeoPandas / scikit-mobility dependencies cannot be pip installed (for details see the corresponding notes in the GeoPandas documentation).
<a id='installation_pip'></a>
### installation with pip (python >= 3.8 required)
1. Create an environment `skmob`
python3 -m venv skmob
2. Activate
source skmob/bin/activate
3. Install skmob
pip install scikit-mobility
4. OPTIONAL to use `scikit-mobility` on the jupyter notebook
- Activate the virutalenv:
source skmob/bin/activate
- Install jupyter notebook:
pip install jupyter
- Run jupyter notebook
jupyter notebook
- (Optional) install the kernel with a specific name
ipython kernel install --user --name=skmob
<a id='installation_conda'></a>
### installation with conda - miniconda
1. Create an environment `skmob` and install pip
conda create -n skmob pip python=3.9 rtree
2. Activate
conda activate skmob
3. Install skmob
conda install -c conda-forge scikit-mobility
4. OPTIONAL to use `scikit-mobility` on the jupyter notebook
- Install the kernel
conda install jupyter -c conda-forge
- Open a notebook and check if the kernel `skmob` is on the kernel list. If not, run the following:
- On Mac and Linux
env=$(basename `echo $CONDA_PREFIX`)
python -m ipykernel install --user --name "$env" --display-name "Python [conda env:"$env"]"
- On Windows
python -m ipykernel install --user --name skmob --display-name "Python [conda env: skmob]"
:exclamation: You may run into dependency issues if you try to import the package in Python. If so, try installing the following packages as followed.
```
conda install -n skmob pyproj urllib3 chardet markupsafe
```
<a id='test_installation'></a>
### Test the installation
```
> source activate skmob
(skmob)> python
>>> import skmob
>>>
```
<a id='google_colab'></a>
## Google Colab
scikit-mobility can be installed on <a href="https://colab.research.google.com/notebooks/intro.ipynb#recent=true">Google Colab</a> using the following commands:
```
!apt-get install -qq curl g++ make
!curl -L http://download.osgeo.org/libspatialindex/spatialindex-src-1.8.5.tar.gz | tar xz
import os
os.chdir('spatialindex-src-1.8.5')
!./configure
!make
!make install
!pip install rtree
!ldconfig
!pip install scikit-mobility
```
<a id='tutorials'></a>
## Tutorials
You can some tutorials on scikit-mobility here: https://github.com/scikit-mobility/tutorials.
<a id='examples'></a>
## Examples
<a id='trajdataframe'></a>
### Create a `TrajDataFrame`
In scikit-mobility, a set of trajectories is described by a `TrajDataFrame`, an extension of the pandas `DataFrame` that has specific columns names and data types. A `TrajDataFrame` can contain many trajectories, and each row in the `TrajDataFrame` represents a point of a trajectory, described by three mandatory fields (aka columns):
- `latitude` (type: float);
- `longitude` (type: float);
- `datetime` (type: date-time).
Additionally, two optional columns can be specified:
- `uid` (type: string) identifies the object associated with the point of the trajectory. If `uid` is not present, scikit-mobility assumes that the `TrajDataFrame` contains trajectories associated with a single moving object;
- `tid` specifies the identifier of the trajectory to which the point belongs to. If `tid` is not present, scikit-mobility assumes that all rows in the `TrajDataFrame` associated with a `uid` belong to the same trajectory;
Note that, besides the mandatory columns, the user can add to a `TrajDataFrame` as many columns as they want since the data structures in scikit-mobility inherit all the pandas `DataFrame` functionalities.
Create a `TrajDataFrame` from a list:
```python
>>> import skmob
>>> # create a TrajDataFrame from a list
>>> data_list = [[1, 39.984094, 116.319236, '2008-10-23 13:53:05'], [1, 39.984198, 116.319322, '2008-10-23 13:53:06'], [1, 39.984224, 116.319402, '2008-10-23 13:53:11'], [1, 39.984211, 116.319389, '2008-10-23 13:53:16']]
>>> tdf = skmob.TrajDataFrame(data_list, latitude=1, longitude=2, datetime=3)
>>> # print a portion of the TrajDataFrame
>>> print(tdf.head())
```
0 lat lng datetime
0 1 39.984094 116.319236 2008-10-23 13:53:05
1 1 39.984198 116.319322 2008-10-23 13:53:06
2 1 39.984224 116.319402 2008-10-23 13:53:11
3 1 39.984211 116.319389 2008-10-23 13:53:16
```python
>>> print(type(tdf))
```
<class 'skmob.core.trajectorydataframe.TrajDataFrame'>
Create a `TrajDataFrame` from a [pandas](https://pandas.pydata.org/) `DataFrame`:
```python
>>> import pandas as pd
>>> # create a DataFrame from the previous list
>>> data_df = pd.DataFrame(data_list, columns=['user', 'latitude', 'lng', 'hour'])
>>> # print the type of the object
>>> print(type(data_df))
```
<class 'pandas.core.frame.DataFrame'>
```python
>>> # now create a TrajDataFrame from the pandas DataFrame
>>> tdf = skmob.TrajDataFrame(data_df, latitude='latitude', datetime='hour', user_id='user')
>>> # print the type of the object
>>> print(type(tdf))
```
<class 'skmob.core.trajectorydataframe.TrajDataFrame'>
```python
>>> # print a portion of the TrajDataFrame
>>> print(tdf.head())
```
uid lat lng datetime
0 1 39.984094 116.319236 2008-10-23 13:53:05
1 1 39.984198 116.319322 2008-10-23 13:53:06
2 1 39.984224 116.319402 2008-10-23 13:53:11
3 1 39.984211 116.319389 2008-10-23 13:53:16
We can also create a `TrajDataFrame` from a file. For example, in the following we create a `TrajDataFrame` from a portion of a GPS trajectory dataset collected in the context of the [GeoLife](https://www.microsoft.com/en-us/research/publication/geolife-gps-trajectory-dataset-user-guide/) project by 178 users in a period of over four years from April 2007 to October 2011.
```python
>>> # download the file from https://raw.githubusercontent.com/scikit-mobility/scikit-mobility/master/examples/geolife_sample.txt.gz
>>> # read the trajectory data (GeoLife, Beijing, China)
>>> tdf = skmob.TrajDataFrame.from_file('geolife_sample.txt.gz', latitude='lat', longitude='lon', user_id='user', datetime='datetime')
>>> # print a portion of the TrajDataFrame
>>> print(tdf.head())
```
lat lng datetime uid
0 39.984094 116.319236 2008-10-23 05:53:05 1
1 39.984198 116.319322 2008-10-23 05:53:06 1
2 39.984224 116.319402 2008-10-23 05:53:11 1
3 39.984211 116.319389 2008-10-23 05:53:16 1
4 39.984217 116.319422 2008-10-23 05:53:21 1
A `TrajDataFrame` can be plotted on a [folium](https://python-visualization.github.io/folium/) interactive map using the `plot_trajectory` function.
```python
>>> tdf.plot_trajectory(zoom=12, weight=3, opacity=0.9, tiles='Stamen Toner')
```

<a id='flowdataframe'></a>
### Create a `FlowDataFrame`
In scikit-mobility, an origin-destination matrix is described by the `FlowDataFrame` structure, an extension of the pandas `DataFrame` that has specific column names and data types. A row in a `FlowDataFrame` represents a flow of objects between two locations, described by three mandatory columns:
- `origin` (type: string);
- `destination` (type: string);
- `flow` (type: integer).
Again, the user can add to a `FlowDataFrame` as many columns as they want since the `FlowDataFrame` data structure inherits all the pandas `DataFrame` functionalities.
In mobility tasks, the territory is often discretized by mapping the coordinates to a spatial tessellation, i.e., a covering of the bi-dimensional space using a countable number of geometric shapes (e.g., squares, hexagons), called tiles, with no overlaps and no gaps. For instance, for the analysis or prediction of mobility flows, a spatial tessellation is used to aggregate flows of people moving among locations (the tiles of the tessellation). For this reason, each `FlowDataFrame` is associated with a **spatial tessellation**, a [geopandas](http://geopandas.org/) `GeoDataFrame` that contains two mandatory columns:
- `tile_ID` (type: integer) indicates the identifier of a location;
- `geometry` indicates the polygon (or point) that describes the geometric shape of the location on a territory (e.g., a square, a voronoi shape, the shape of a neighborhood).
Note that each location identifier in the `origin` and `destination` columns of a `FlowDataFrame` must be present in the associated spatial tessellation.
Create a spatial tessellation from a file describing counties in New York state:
```python
>>> import skmob
>>> import geopandas as gpd
>>> # load a spatial tessellation
>>> url_tess = skmob.utils.constants.NY_COUNTIES_2011
>>> tessellation = gpd.read_file(url_tess).rename(columns={'tile_id': 'tile_ID'})
>>> # print a portion of the spatial tessellation
>>> print(tessellation.head())
```
tile_ID population geometry
0 36019 81716 POLYGON ((-74.006668 44.886017, -74.027389 44....
1 36101 99145 POLYGON ((-77.099754 42.274215, -77.0996569999...
2 36107 50872 POLYGON ((-76.25014899999999 42.296676, -76.24...
3 36059 1346176 POLYGON ((-73.707662 40.727831, -73.700272 40....
4 36011 79693 POLYGON ((-76.279067 42.785866, -76.2753479999...
Create a `FlowDataFrame` from a spatial tessellation and a file of real flows between counties in New York state:
```python
>>> # load real flows into a FlowDataFrame
>>> fdf = skmob.FlowDataFrame.from_file(skmob.utils.constants.NY_FLOWS_2011,
tessellation=tessellation,
tile_id='tile_ID',
sep=",")
>>> # print a portion of the flows
>>> print(fdf.head())
```
flow origin destination
0 121606 36001 36001
1 5 36001 36005
2 29 36001 36007
3 11 36001 36017
4 30 36001 36019
A `FlowDataFrame` can be visualized on a [folium](https://python-visualization.github.io/folium/) interactive map using the `plot_flows` function, which plots the flows on a geographic map as lines between the centroids of the tiles in the `FlowDataFrame`'s spatial tessellation:
```python
>>> fdf.plot_flows(flow_color='red')
```

Similarly, the spatial tessellation of a `FlowDataFrame` can be visualized using the `plot_tessellation` function. The argument `popup_features` (type:list, default:[`constants.TILE_ID`]) allows to enhance the plot's interactivity displaying popup windows that appear when the user clicks on a tile and includes information contained in the columns of the tessellation's `GeoDataFrame` specified in the argument’s list:
```python
>>> fdf.plot_tessellation(popup_features=['tile_ID', 'population'])
```

The spatial tessellation and the flows can be visualized together using the `map_f` argument, which specifies the folium object on which to plot:
```python
>>> m = fdf.plot_tessellation() # plot the tessellation
>>> fdf.plot_flows(flow_color='red', map_f=m) # plot the flows
```

<a id='preprocessing'></a>
### Trajectory preprocessing
As any analytical process, mobility data analysis requires data cleaning and preprocessing steps. The `preprocessing` module allows the user to perform four main preprocessing steps:
- noise filtering;
- stop detection;
- stop clustering;
- trajectory compression;
Note that, if a `TrajDataFrame` contains multiple trajectories from multiple users, the preprocessing methods automatically apply to the single trajectory and, when necessary, to the single moving object.
#### Noise filtering
In scikit-mobility, the function `filter` filters out a point if the speed from the previous point is higher than the parameter `max_speed`, which is by default set to 500km/h.
```python
>>> from skmob.preprocessing import filtering
>>> # filter out all points with a speed (in km/h) from the previous point higher than 500 km/h
>>> ftdf = filtering.filter(tdf, max_speed_kmh=500.)
>>> print(ftdf.parameters)
```
{'from_file': 'geolife_sample.txt.gz', 'filter': {'function': 'filter', 'max_speed_kmh': 500.0, 'include_loops': False, 'speed_kmh': 5.0, 'max_loop': 6, 'ratio_max': 0.25}}
```python
>>> n_deleted_points = len(tdf) - len(ftdf) # number of deleted points
>>> print(n_deleted_points)
```
54
Note that the `TrajDataFrame` structure as the `parameters` attribute, which indicates the operations that have been applied to the `TrajDataFrame`. This attribute is a dictionary the key of which is the signature of the function applied.
#### Stop detection
Some points in a trajectory can represent Point-Of-Interests (POIs) such as schools, restaurants, and bars, or they can represent user-specific places such as home and work locations. These points are usually called Stay Points or Stops, and they can be detected in different ways. A common approach is to apply spatial clustering algorithms to cluster trajectory points by looking at their spatial proximity. In scikit-mobility, the `stay_locations` function, contained in the `detection` module, finds the stay points visited by a moving object. For instance, to identify the stops where the object spent at least `minutes_for_a_stop` minutes within a distance `spatial_radius_km \time stop_radius_factor`, from a given point, we can use the following code:
```python
>>> from skmob.preprocessing import detection
>>> # compute the stops for each individual in the TrajDataFrame
>>> stdf = detection.stay_locations(tdf, stop_radius_factor=0.5, minutes_for_a_stop=20.0, spatial_radius_km=0.2, leaving_time=True)
>>> # print a portion of the detected stops
>>> print(stdf.head())
```
lat lng datetime uid leaving_datetime
0 39.978030 116.327481 2008-10-23 06:01:37 1 2008-10-23 10:32:53
1 40.013820 116.306532 2008-10-23 11:10:19 1 2008-10-23 23:45:27
2 39.978419 116.326870 2008-10-24 00:21:52 1 2008-10-24 01:47:30
3 39.981166 116.308475 2008-10-24 02:02:31 1 2008-10-24 02:30:29
4 39.981431 116.309902 2008-10-24 02:30:29 1 2008-10-24 03:16:35
```python
>>> print('Points of the original trajectory:\t%s'%len(tdf))
>>> print('Points of stops:\t\t\t%s'%len(stdf))
```
Points of the original trajectory: 217653
Points of stops: 391
A new column `leaving_datetime` is added to the `TrajDataFrame` in order to indicate the time when the user left the stop location. We can then visualize the detected stops using the `plot_stops` function:
```python
>>> m = stdf.plot_trajectory(max_users=1, start_end_markers=False)
>>> stdf.plot_stops(max_users=1, map_f=m)
```

#### Trajectory compression
The goal of trajectory compression is to reduce the number of trajectory points while preserving the structure of the trajectory. This step results in a significant reduction of the number of trajectory points. In scikit-mobility, we can use one of the methods in the `compression` module under the `preprocessing` module. For instance, to merge all the points that are closer than 0.2km from each other, we can use the following code:
```python
>>> from skmob.preprocessing import compression
>>> # compress the trajectory using a spatial radius of 0.2 km
>>> ctdf = compression.compress(tdf, spatial_radius_km=0.2)
>>> # print the difference in points between original and filtered TrajDataFrame
>>> print('Points of the original trajectory:\t%s'%len(tdf))
>>> print('Points of the compressed trajectory:\t%s'%len(ctdf))
```
Points of the original trajectory: 217653
Points of the compressed trajectory: 6281
<a id='measures'></a>
### Mobility measures
Several measures have been proposed in the literature to capture the patterns of human mobility, both at the individual and collective levels. Individual measures summarize the mobility patterns of a single moving object, while collective measures summarize mobility patterns of a population as a whole. scikit-mobility provides a wide set of [mobility measures](https://scikit-mobility.github.io/scikit-mobility/reference/measures.html), each implemented as a function that takes in input a `TrajDataFrame` and outputs a pandas `DataFrame`. Individual and collective measures are implemented the in `skmob.measure.individual` and the `skmob.measures.collective` modules, respectively.
For example, the following code compute the *radius of gyration*, the *jump lengths* and the *home locations* of a `TrajDataFrame`:
```python
>>> from skmob.measures.individual import jump_lengths, radius_of_gyration, home_location
>>> # load a TrajDataFrame from an URL
>>> url = "https://snap.stanford.edu/data/loc-brightkite_totalCheckins.txt.gz"
>>> df = pd.read_csv(url, sep='\t', header=0, nrows=100000,
names=['user', 'check-in_time', 'latitude', 'longitude', 'location id'])
>>> tdf = skmob.TrajDataFrame(df, latitude='latitude', longitude='longitude', datetime='check-in_time', user_id='user')
>>> # compute the radius of gyration for each individual
>>> rg_df = radius_of_gyration(tdf)
>>> print(rg_df)
```
uid radius_of_gyration
0 0 1564.436792
1 1 2467.773523
2 2 1439.649774
3 3 1752.604191
4 4 5380.503250
```python
>>> # compute the jump lengths for each individual
>>> jl_df = jump_lengths(tdf.sort_values(by='datetime'))
>>> print(jl_df.head())
```
uid jump_lengths
0 0 [19.640467328877936, 0.0, 0.0, 1.7434311010381...
1 1 [6.505330424378251, 46.75436600375988, 53.9284...
2 2 [0.0, 0.0, 0.0, 0.0, 3.6410097195943507, 0.0, ...
3 3 [3861.2706300798827, 4.061631313492122, 5.9163...
4 4 [15511.92758595804, 0.0, 15511.92758595804, 1....
Note that for some measures, such as `jump_length`, the `TrajDataFrame` must be order in increasing order by the column `datetime` (see the documentation for the measures that requires this condition https://scikit-mobility.github.io/scikit-mobility/reference/measures.html).
```python
>>> # compute the home location for each individual
>>> hl_df = home_location(tdf)
>>> print(hl_df.head())
```
uid lat lng
0 0 39.891077 -105.068532
1 1 37.630490 -122.411084
2 2 39.739154 -104.984703
3 3 37.748170 -122.459192
4 4 60.180171 24.949728
```python
>>> # now let's visualize a cloropleth map of the home locations
>>> import folium
>>> from folium.plugins import HeatMap
>>> m = folium.Map(tiles = 'openstreetmap', zoom_start=12, control_scale=True)
>>> HeatMap(hl_df[['lat', 'lng']].values).add_to(m)
>>> m
```

<a id='collective_models'></a>
### Collective generative models
Collective generative models estimate spatial flows between a set of discrete locations. Examples of spatial flows estimated with collective generative models include commuting trips between neighborhoods, migration flows between municipalities, freight shipments between states, and phone calls between regions.
In scikit-mobility, a collective generative model takes in input a spatial tessellation, i.e., a geopandas `GeoDataFrame`. To be a valid input for a collective model, the spatial tessellation should contain two columns, `geometry` and `relevance`, which are necessary to compute the two variables used by collective algorithms: the distance between tiles and the importance (aka "attractiveness") of each tile. A collective algorithm produces a `FlowDataFrame` that contains the generated flows and the spatial tessellation. scikit-mobility implements the most common collective generative algorithms:
- the `Gravity` model;
- the `Radiation` model.
#### Gravity model
The class `Gravity`, implementing the Gravity model, has two main methods:
- `fit`, which calibrates the model's parameters using a `FlowDataFrame`;
- `generate`, which generates the flows on a given spatial tessellation.
Load the spatial tessellation and a data set of real flows in a `FlowDataFrame`:
```python
>>> from skmob.utils import utils, constants
>>> import geopandas as gpd
>>> from skmob.models.gravity import Gravity
>>> import numpy as np
>>> # load a spatial tessellation
>>> url_tess = skmob.utils.constants.NY_COUNTIES_2011
>>> tessellation = gpd.read_file(url_tess).rename(columns={'tile_id': 'tile_ID'})
>>> # load the file with the real fluxes
>>> fdf = skmob.FlowDataFrame.from_file(skmob.utils.constants.NY_FLOWS_2011,
tessellation=tessellation,
tile_id='tile_ID',
sep=",")
>>> # compute the total outflows from each location of the tessellation (excluding self loops)
>>> tot_outflows = fdf[fdf['origin'] != fdf['destination']].groupby(by='origin', axis=0)[['flow']].sum().fillna(0)
>>> tessellation = tessellation.merge(tot_outflows, left_on='tile_ID', right_on='origin').rename(columns={'flow': 'tot_outflow'})
```
Instantiate a Gravity model object and generate synthetic flows:
```python
>>> # instantiate a singly constrained Gravity model
>>> gravity_singly = Gravity(gravity_type='singly cons/tetrained')
>>> print(gravity_singly)
```
Gravity(name="Gravity model", deterrence_func_type="power_law", deterrence_func_args=[-2.0], origin_exp=1.0, destination_exp=1.0, gravity_type="singly constrained")
```python
>>> # start the generation of the synthetic flows
>>> np.random.seed(0)
>>> synth_fdf = gravity_singly.generate(tessellation,
tile_id_column='tile_ID',
tot_outflows_column='tot_outflow',
relevance_column= 'population',
out_format='flows')
>>> # print a portion of the synthetic flows
>>> print(synth_fdf.head())
```
origin destination flow
0 36019 36101 101
1 36019 36107 66
2 36019 36059 1041
3 36019 36011 151
4 36019 36123 33
Fit the parameters of the Gravity model from the `FlowDataFrame` and generate the synthetic flows:
```python
>>> # instantiate a Gravity object (with default parameters)
>>> gravity_singly_fitted = Gravity(gravity_type='singly constrained')
>>> print(gravity_singly_fitted)
```
Gravity(name="Gravity model", deterrence_func_type="power_law", deterrence_func_args=[-2.0], origin_exp=1.0, destination_exp=1.0, gravity_type="singly constrained")
```python
>>> # fit the parameters of the Gravity from the FlowDataFrame
>>> gravity_singly_fitted.fit(fdf, relevance_column='population')
>>> print(gravity_singly_fitted)
```
Gravity(name="Gravity model", deterrence_func_type="power_law", deterrence_func_args=[-1.9947152031914186], origin_exp=1.0, destination_exp=0.6471759552223144, gravity_type="singly constrained")
```python
>>> # generate the synthetics flows
>>> np.random.seed(0)
>>> synth_fdf_fitted = gravity_singly_fitted.generate(tessellation,
tile_id_column='tile_ID',
tot_outflows_column='tot_outflow',
relevance_column= 'population',
out_format='flows')
>>> # print a portion of the synthetic flows
>>> print(synth_fdf_fitted.head())
```
origin destination flow
0 36019 36101 102
1 36019 36107 66
2 36019 36059 1044
3 36019 36011 152
4 36019 36123 33
Plot the real flows and the synthetic flows:
```python
>>> m = fdf.plot_flows(min_flow=100, flow_exp=0.01, flow_color='blue')
>>> synth_fdf_fitted.plot_flows(min_flow=1000, flow_exp=0.01, map_f=m)
```

#### Radiation model
The Radiation model is parameter-free and has only one method: `generate`. Given a spatial tessellation, the synthetic flows can be generated using the `Radiation` class as follows:
```python
>>> from skmob.models.radiation import Radiation
>>> # instantiate a Radiation object
>>> radiation = Radiation()
>>> # start the simulation
>>> np.random.seed(0)
>>> rad_flows = radiation.generate(tessellation,
tile_id_column='tile_ID',
tot_outflows_column='tot_outflow',
relevance_column='population',
out_format='flows_sample')
>>> # print a portion of the synthetic flows
>>> print(rad_flows.head())
```
origin destination flow
0 36019 36033 11648
1 36019 36031 4232
2 36019 36089 5598
3 36019 36113 1596
4 36019 36041 117
<a id='individual_models'></a>
### Individual generative models
The goal of individual generative models of human mobility is to create a population of agents whose mobility patterns are statistically indistinguishable from those of real individuals. An individual generative model typically generates a synthetic trajectory corresponding to a single moving object, assuming that an object is independent of the others.
scikit-mobility implements the most common individual generative models, such as the [Exploration and Preferential Return](https://www.nature.com/articles/nphys1760) model and its variants, and [DITRAS](https://link.springer.com/article/10.1007/s10618-017-0548-4). Each generative model is a python class with a public method `generate`, which starts the generation of synthetic trajectories.
The following code generate synthetic trajectories using the `DensityEPR` model:
```python
>>> from skmob.models.epr import DensityEPR
>>> # load a spatial tesellation on which to perform the simulation
>>> url = skmob.utils.constants.NY_COUNTIES_2011
>>> tessellation = gpd.read_file(url)
>>> # starting and end times of the simulation
>>> start_time = pd.to_datetime('2019/01/01 08:00:00')
>>> end_time = pd.to_datetime('2019/01/14 08:00:00')
>>> # instantiate a DensityEPR object
>>> depr = DensityEPR()
>>> # start the simulation
>>> tdf = depr.generate(start_time, end_time, tessellation, relevance_column='population', n_agents=100)
>>> print(tdf.head())
```
uid datetime lat lng
0 1 2019-01-01 08:00:00.000000 42.452018 -76.473618
1 1 2019-01-01 08:32:30.108708 42.170344 -76.306260
2 1 2019-01-01 09:09:11.760703 43.241550 -75.435903
3 1 2019-01-01 10:00:22.832309 42.170344 -76.306260
4 1 2019-01-01 14:00:25.923314 42.267915 -77.383591
```python
>>> print(tdf.parameters)
```
{'model': {'class': <function DensityEPR.__init__ at 0x7f70ce0a7e18>, 'generate': {'start_date': Timestamp('2019-01-01 08:00:00'), 'end_date': Timestamp('2019-01-14 08:00:00'), 'gravity_singly': {}, 'n_agents': 100, 'relevance_column': 'population', 'random_state': None, 'verbose': True}}}
<a id='privacy'></a>
### Privacy
Mobility data is sensitive since the movements of individuals can reveal confidential personal information or allow the re-identification of individuals in a database, creating serious privacy risks. In the literature, privacy risk assessment relies on the concept of re-identification of a moving object in a database through an attack by a malicious adversary. A common framework for privacy risk assessment assumes that during the attack a malicious adversary acquires, in some way, the access to an anonymized mobility data set, i.e., a mobility data set in which the moving object associated with a trajectory is not known. Moreover, it is assumed that the malicious adversary acquires, in some way, information about the trajectory (or a portion of it) of an individual represented in the acquired data set. Based on this information, the risk of re-identification of that individual is computed estimating how unique that individual's mobility data are with respect to the mobility data of the other individuals represented inthe acquired data set.
scikit-mobility provides several attack models, each implemented as a python class. For example in a location attack model, implemented in the `LocationAttack` class, the malicious adversary knows a certain number of locations visited by an individual, but they do not know the temporal order of the visits. To instantiate a `LocationAttack` object we can run the following code:
```python
>>> import skmob
>>> from skmob.privacy import attacks
>>> at = attacks.LocationAttack(knowledge_length=2)
```
The argument `knowledge_length` specifies how many locations the malicious adversary knows of each object's movement. The re-identification risk is computed based on the worst possible combination of `knowledge_length` locations out of all possible combinations of locations.
To assess the re-identification risk associated with a mobility data set, represented as a `TrajDataFrame`, we specify it as input to the `assess_risk` method, which returns a pandas `DataFrame` that contains the `uid` of each object in the `TrajDataFrame` and the associated re-identification risk as the column `risk` (type: float, range: $[0,1]$ where 0 indicates minimum risk and 1 maximum risk).
```python
>>> tdf = skmob.TrajDataFrame.from_file(filename="privacy_toy.csv")
>>> tdf_risk = at.assess_risk(tdf)
>>> print(tdf_risk.head())
```
uid risk
0 1 0.333333
1 2 0.500000
2 3 0.333333
3 4 0.333333
4 5 0.250000
Since risk assessment may be time-consuming for more massive datasets, scikit-mobility provides the option to focus only on a subset of the objects with the argument `targets`. For example, in the following code, we compute the re-identification risk for the object with `uid` 1 and 2 only:
```python
>>> tdf_risk = at.assess_risk(tdf, targets=[1,2])
>>> print(tdf_risk)
```
uid risk
0 1 0.333333
1 2 0.500000
<a id="data"></a>
### Downloading datasets
The `data` module of scikit-mobility provides users with an easy way to: 1) Download ready-to-use mobility data (e.g., trajectories, flows, spatial tessellations, and auxiliary data); 2) Load and transform the downloaded dataset into standard skmob structures (TrajDataFrame, GeoDataFrame, FlowDataFrame, DataFrame); 3) Allow developers and contributors to add new datasets to the library.
The `data` module provides three functions:
- `list_datasets`
- `get_dataset_info`
- `load_dataset`
The user can download the list of all datasets currently available in the library using `list_datasets`:
```python
>>> import skmob
>>> from skmob.data.load import list_datasets
>>> list_datasets()
```
['flow_foursquare_nyc',
'foursquare_nyc',
'nyc_boundaries',
'parking_san_francisco',
'taxi_san_francisco']
The user can retrieve information about a specific dataset in the library using `get_dataset_info`:
```python
>>> import skmob
>>> from skmob.data.load import get_dataset_info
>>> get_dataset_info("foursquare_nyc")
```
{'name': 'Foursquare_NYC',
'description': 'Dataset containing the Foursquare checkins of individuals moving in New York City',
'url': 'http://www-public.it-sudparis.eu/~zhang_da/pub/dataset_tsmc2014.zip',
'hash': 'cbe3fdab373d24b09b5fc53509c8958c77ff72b6c1a68589ce337d4f9a80235b',
'auth': 'no',
'data_type': 'trajectory',
'download_format': 'zip',
'sep': ' ',
'encoding': 'ISO-8859-1'}
Finally, the user can download a specific dataset using `load_dataset`:
```python
>>> import skmob
>>> from skmob.data.load import load_dataset, list_datasets
>>> tdf_nyc = load_dataset("foursquare_nyc", drop_columns=True)
>>> print(tdf_nyc.head())
```
uid lat lng datetime
0 470 40.719810 -74.002581 2012-04-03 18:00:09+00:00
1 979 40.606800 -74.044170 2012-04-03 18:00:25+00:00
2 69 40.716162 -73.883070 2012-04-03 18:02:24+00:00
3 395 40.745164 -73.982519 2012-04-03 18:02:41+00:00
4 87 40.740104 -73.989658 2012-04-03 18:03:00+00:00
# Related packages
[*movingpandas*](https://github.com/anitagraser/movingpandas) is a similar package that deals with movement data. Instead of implementing new data structures tailored for trajectories (`TrajDataFrame`) and mobility flows (`FlowDataFrame`), *movingpandas* describes a trajectory using a *geopandas* `GeoDataFrame`. There is little overlap in the covered use cases and implemented functionality (comparing [*scikit-mobility* tutorials](https://github.com/scikit-mobility/tutorials) and [*movingpandas* tutorials](https://github.com/anitagraser/movingpandas/tree/master/tutorials)): *scikit-mobility* focuses on computing human mobility metrics, generating synthetic trajectories and assessing privacy risks of mobility datasets. *movingpandas* on the other hand focuses on spatio-temporal data exploration with corresponding functions for data manipulation and analysis.
%package help
Summary: Development documents and examples for scikit-mobility
Provides: python3-scikit-mobility-doc
%description help
[](https://zenodo.org/badge/latestdoi/184337448)




# scikit-mobility - mobility analysis in Python
<img src="logo_skmob.png" width=300/>
###### Try `scikit-mobility` without installing it
[](https://twitter.com/scikitmobility)
- in a MyBinder notebook: [](https://mybinder.org/v2/gh/scikit-mobility/scikit-mobility/master)
- on [Jovian](https://jovian.ai/jonpappalord/collections/scikit-mobility-tutorial)
`scikit-mobility` is a library for human mobility analysis in Python. The library allows to:
- represent trajectories and mobility flows with proper data structures, `TrajDataFrame` and `FlowDataFrame`.
- manage and manipulate mobility data of various formats (call detail records, GPS data, data from social media, survey data, etc.);
- extract mobility metrics and patterns from data, both at individual and collective level (e.g., length of displacements, characteristic distance, origin-destination matrix, etc.)
- generate synthetic individual trajectories using standard mathematical models (random walk models, exploration and preferential return model, etc.)
- generate synthetic mobility flows using standard migration models (gravity model, radiation model, etc.)
- assess the privacy risk associated with a mobility data set
## Table of contents
1. [Documentation](#documentation)
2. [Citing](#citing)
3. [Collaborate with us](#collaborate)
4. [Installation](#installation)
- [with pip](#installation_pip)
- [with conda](#installation_conda)
- [known issues](#known_conda)
- [test installation](#test_installation)
- [Google Colab](#google_colab)
5. [Tutorials](#tutorials)
6. [Examples](#examples)
- [TrajDataFrame](#trajdataframe)
- [FlowDataFrame](#flowdataframe)
- [Preprocessing](#preprocessing)
- [Measures](#measures)
- [Collective generative models](#collective_models)
- [Individual generative models](#individual_models)
- [Privacy](#privacy)
- [Downloading datasets](#data)
<a id='documentation'></a>
## Documentation
The documentation of scikit-mobility's classes and functions is available at: https://scikit-mobility.github.io/scikit-mobility/
<a id='citing'></a>
## Citing
if you use scikit-mobility please cite the following paper:
> Luca Pappalardo, Filippo Simini, Gianni Barlacchi and Roberto Pellungrini.
> **scikit-mobility: a Python library for the analysis, generation and risk assessment of mobility data**,
> 2019, https://arxiv.org/abs/1907.07062
Bibtex:
```
@misc{pappalardo2019scikitmobility,
title={scikit-mobility: a Python library for the analysis, generation and risk assessment of mobility data},
author={Luca Pappalardo and Filippo Simini and Gianni Barlacchi and Roberto Pellungrini},
year={2019},
eprint={1907.07062},
archivePrefix={arXiv},
primaryClass={physics.soc-ph}
}
```
<a id='collaborate'></a>
## Collaborate with us
`scikit-mobility` is an active project and any contribution is welcome.
If you would like to include your algorithm in `scikit-mobility`, feel free to fork the project, open an issue and [contact us](mailto:scikit.mobility@gmail.com).
<a id='installation'></a>
## Installation
scikit-mobility for Python >= 3.8 and all it's dependencies are available from conda-forge and can be installed using
`conda install -c conda-forge scikit-mobility`.
Note that it is **NOT recommended** to install scikit-mobility from PyPI! If you're on Windows or Mac, many GeoPandas / scikit-mobility dependencies cannot be pip installed (for details see the corresponding notes in the GeoPandas documentation).
<a id='installation_pip'></a>
### installation with pip (python >= 3.8 required)
1. Create an environment `skmob`
python3 -m venv skmob
2. Activate
source skmob/bin/activate
3. Install skmob
pip install scikit-mobility
4. OPTIONAL to use `scikit-mobility` on the jupyter notebook
- Activate the virutalenv:
source skmob/bin/activate
- Install jupyter notebook:
pip install jupyter
- Run jupyter notebook
jupyter notebook
- (Optional) install the kernel with a specific name
ipython kernel install --user --name=skmob
<a id='installation_conda'></a>
### installation with conda - miniconda
1. Create an environment `skmob` and install pip
conda create -n skmob pip python=3.9 rtree
2. Activate
conda activate skmob
3. Install skmob
conda install -c conda-forge scikit-mobility
4. OPTIONAL to use `scikit-mobility` on the jupyter notebook
- Install the kernel
conda install jupyter -c conda-forge
- Open a notebook and check if the kernel `skmob` is on the kernel list. If not, run the following:
- On Mac and Linux
env=$(basename `echo $CONDA_PREFIX`)
python -m ipykernel install --user --name "$env" --display-name "Python [conda env:"$env"]"
- On Windows
python -m ipykernel install --user --name skmob --display-name "Python [conda env: skmob]"
:exclamation: You may run into dependency issues if you try to import the package in Python. If so, try installing the following packages as followed.
```
conda install -n skmob pyproj urllib3 chardet markupsafe
```
<a id='test_installation'></a>
### Test the installation
```
> source activate skmob
(skmob)> python
>>> import skmob
>>>
```
<a id='google_colab'></a>
## Google Colab
scikit-mobility can be installed on <a href="https://colab.research.google.com/notebooks/intro.ipynb#recent=true">Google Colab</a> using the following commands:
```
!apt-get install -qq curl g++ make
!curl -L http://download.osgeo.org/libspatialindex/spatialindex-src-1.8.5.tar.gz | tar xz
import os
os.chdir('spatialindex-src-1.8.5')
!./configure
!make
!make install
!pip install rtree
!ldconfig
!pip install scikit-mobility
```
<a id='tutorials'></a>
## Tutorials
You can some tutorials on scikit-mobility here: https://github.com/scikit-mobility/tutorials.
<a id='examples'></a>
## Examples
<a id='trajdataframe'></a>
### Create a `TrajDataFrame`
In scikit-mobility, a set of trajectories is described by a `TrajDataFrame`, an extension of the pandas `DataFrame` that has specific columns names and data types. A `TrajDataFrame` can contain many trajectories, and each row in the `TrajDataFrame` represents a point of a trajectory, described by three mandatory fields (aka columns):
- `latitude` (type: float);
- `longitude` (type: float);
- `datetime` (type: date-time).
Additionally, two optional columns can be specified:
- `uid` (type: string) identifies the object associated with the point of the trajectory. If `uid` is not present, scikit-mobility assumes that the `TrajDataFrame` contains trajectories associated with a single moving object;
- `tid` specifies the identifier of the trajectory to which the point belongs to. If `tid` is not present, scikit-mobility assumes that all rows in the `TrajDataFrame` associated with a `uid` belong to the same trajectory;
Note that, besides the mandatory columns, the user can add to a `TrajDataFrame` as many columns as they want since the data structures in scikit-mobility inherit all the pandas `DataFrame` functionalities.
Create a `TrajDataFrame` from a list:
```python
>>> import skmob
>>> # create a TrajDataFrame from a list
>>> data_list = [[1, 39.984094, 116.319236, '2008-10-23 13:53:05'], [1, 39.984198, 116.319322, '2008-10-23 13:53:06'], [1, 39.984224, 116.319402, '2008-10-23 13:53:11'], [1, 39.984211, 116.319389, '2008-10-23 13:53:16']]
>>> tdf = skmob.TrajDataFrame(data_list, latitude=1, longitude=2, datetime=3)
>>> # print a portion of the TrajDataFrame
>>> print(tdf.head())
```
0 lat lng datetime
0 1 39.984094 116.319236 2008-10-23 13:53:05
1 1 39.984198 116.319322 2008-10-23 13:53:06
2 1 39.984224 116.319402 2008-10-23 13:53:11
3 1 39.984211 116.319389 2008-10-23 13:53:16
```python
>>> print(type(tdf))
```
<class 'skmob.core.trajectorydataframe.TrajDataFrame'>
Create a `TrajDataFrame` from a [pandas](https://pandas.pydata.org/) `DataFrame`:
```python
>>> import pandas as pd
>>> # create a DataFrame from the previous list
>>> data_df = pd.DataFrame(data_list, columns=['user', 'latitude', 'lng', 'hour'])
>>> # print the type of the object
>>> print(type(data_df))
```
<class 'pandas.core.frame.DataFrame'>
```python
>>> # now create a TrajDataFrame from the pandas DataFrame
>>> tdf = skmob.TrajDataFrame(data_df, latitude='latitude', datetime='hour', user_id='user')
>>> # print the type of the object
>>> print(type(tdf))
```
<class 'skmob.core.trajectorydataframe.TrajDataFrame'>
```python
>>> # print a portion of the TrajDataFrame
>>> print(tdf.head())
```
uid lat lng datetime
0 1 39.984094 116.319236 2008-10-23 13:53:05
1 1 39.984198 116.319322 2008-10-23 13:53:06
2 1 39.984224 116.319402 2008-10-23 13:53:11
3 1 39.984211 116.319389 2008-10-23 13:53:16
We can also create a `TrajDataFrame` from a file. For example, in the following we create a `TrajDataFrame` from a portion of a GPS trajectory dataset collected in the context of the [GeoLife](https://www.microsoft.com/en-us/research/publication/geolife-gps-trajectory-dataset-user-guide/) project by 178 users in a period of over four years from April 2007 to October 2011.
```python
>>> # download the file from https://raw.githubusercontent.com/scikit-mobility/scikit-mobility/master/examples/geolife_sample.txt.gz
>>> # read the trajectory data (GeoLife, Beijing, China)
>>> tdf = skmob.TrajDataFrame.from_file('geolife_sample.txt.gz', latitude='lat', longitude='lon', user_id='user', datetime='datetime')
>>> # print a portion of the TrajDataFrame
>>> print(tdf.head())
```
lat lng datetime uid
0 39.984094 116.319236 2008-10-23 05:53:05 1
1 39.984198 116.319322 2008-10-23 05:53:06 1
2 39.984224 116.319402 2008-10-23 05:53:11 1
3 39.984211 116.319389 2008-10-23 05:53:16 1
4 39.984217 116.319422 2008-10-23 05:53:21 1
A `TrajDataFrame` can be plotted on a [folium](https://python-visualization.github.io/folium/) interactive map using the `plot_trajectory` function.
```python
>>> tdf.plot_trajectory(zoom=12, weight=3, opacity=0.9, tiles='Stamen Toner')
```

<a id='flowdataframe'></a>
### Create a `FlowDataFrame`
In scikit-mobility, an origin-destination matrix is described by the `FlowDataFrame` structure, an extension of the pandas `DataFrame` that has specific column names and data types. A row in a `FlowDataFrame` represents a flow of objects between two locations, described by three mandatory columns:
- `origin` (type: string);
- `destination` (type: string);
- `flow` (type: integer).
Again, the user can add to a `FlowDataFrame` as many columns as they want since the `FlowDataFrame` data structure inherits all the pandas `DataFrame` functionalities.
In mobility tasks, the territory is often discretized by mapping the coordinates to a spatial tessellation, i.e., a covering of the bi-dimensional space using a countable number of geometric shapes (e.g., squares, hexagons), called tiles, with no overlaps and no gaps. For instance, for the analysis or prediction of mobility flows, a spatial tessellation is used to aggregate flows of people moving among locations (the tiles of the tessellation). For this reason, each `FlowDataFrame` is associated with a **spatial tessellation**, a [geopandas](http://geopandas.org/) `GeoDataFrame` that contains two mandatory columns:
- `tile_ID` (type: integer) indicates the identifier of a location;
- `geometry` indicates the polygon (or point) that describes the geometric shape of the location on a territory (e.g., a square, a voronoi shape, the shape of a neighborhood).
Note that each location identifier in the `origin` and `destination` columns of a `FlowDataFrame` must be present in the associated spatial tessellation.
Create a spatial tessellation from a file describing counties in New York state:
```python
>>> import skmob
>>> import geopandas as gpd
>>> # load a spatial tessellation
>>> url_tess = skmob.utils.constants.NY_COUNTIES_2011
>>> tessellation = gpd.read_file(url_tess).rename(columns={'tile_id': 'tile_ID'})
>>> # print a portion of the spatial tessellation
>>> print(tessellation.head())
```
tile_ID population geometry
0 36019 81716 POLYGON ((-74.006668 44.886017, -74.027389 44....
1 36101 99145 POLYGON ((-77.099754 42.274215, -77.0996569999...
2 36107 50872 POLYGON ((-76.25014899999999 42.296676, -76.24...
3 36059 1346176 POLYGON ((-73.707662 40.727831, -73.700272 40....
4 36011 79693 POLYGON ((-76.279067 42.785866, -76.2753479999...
Create a `FlowDataFrame` from a spatial tessellation and a file of real flows between counties in New York state:
```python
>>> # load real flows into a FlowDataFrame
>>> fdf = skmob.FlowDataFrame.from_file(skmob.utils.constants.NY_FLOWS_2011,
tessellation=tessellation,
tile_id='tile_ID',
sep=",")
>>> # print a portion of the flows
>>> print(fdf.head())
```
flow origin destination
0 121606 36001 36001
1 5 36001 36005
2 29 36001 36007
3 11 36001 36017
4 30 36001 36019
A `FlowDataFrame` can be visualized on a [folium](https://python-visualization.github.io/folium/) interactive map using the `plot_flows` function, which plots the flows on a geographic map as lines between the centroids of the tiles in the `FlowDataFrame`'s spatial tessellation:
```python
>>> fdf.plot_flows(flow_color='red')
```

Similarly, the spatial tessellation of a `FlowDataFrame` can be visualized using the `plot_tessellation` function. The argument `popup_features` (type:list, default:[`constants.TILE_ID`]) allows to enhance the plot's interactivity displaying popup windows that appear when the user clicks on a tile and includes information contained in the columns of the tessellation's `GeoDataFrame` specified in the argument’s list:
```python
>>> fdf.plot_tessellation(popup_features=['tile_ID', 'population'])
```

The spatial tessellation and the flows can be visualized together using the `map_f` argument, which specifies the folium object on which to plot:
```python
>>> m = fdf.plot_tessellation() # plot the tessellation
>>> fdf.plot_flows(flow_color='red', map_f=m) # plot the flows
```

<a id='preprocessing'></a>
### Trajectory preprocessing
As any analytical process, mobility data analysis requires data cleaning and preprocessing steps. The `preprocessing` module allows the user to perform four main preprocessing steps:
- noise filtering;
- stop detection;
- stop clustering;
- trajectory compression;
Note that, if a `TrajDataFrame` contains multiple trajectories from multiple users, the preprocessing methods automatically apply to the single trajectory and, when necessary, to the single moving object.
#### Noise filtering
In scikit-mobility, the function `filter` filters out a point if the speed from the previous point is higher than the parameter `max_speed`, which is by default set to 500km/h.
```python
>>> from skmob.preprocessing import filtering
>>> # filter out all points with a speed (in km/h) from the previous point higher than 500 km/h
>>> ftdf = filtering.filter(tdf, max_speed_kmh=500.)
>>> print(ftdf.parameters)
```
{'from_file': 'geolife_sample.txt.gz', 'filter': {'function': 'filter', 'max_speed_kmh': 500.0, 'include_loops': False, 'speed_kmh': 5.0, 'max_loop': 6, 'ratio_max': 0.25}}
```python
>>> n_deleted_points = len(tdf) - len(ftdf) # number of deleted points
>>> print(n_deleted_points)
```
54
Note that the `TrajDataFrame` structure as the `parameters` attribute, which indicates the operations that have been applied to the `TrajDataFrame`. This attribute is a dictionary the key of which is the signature of the function applied.
#### Stop detection
Some points in a trajectory can represent Point-Of-Interests (POIs) such as schools, restaurants, and bars, or they can represent user-specific places such as home and work locations. These points are usually called Stay Points or Stops, and they can be detected in different ways. A common approach is to apply spatial clustering algorithms to cluster trajectory points by looking at their spatial proximity. In scikit-mobility, the `stay_locations` function, contained in the `detection` module, finds the stay points visited by a moving object. For instance, to identify the stops where the object spent at least `minutes_for_a_stop` minutes within a distance `spatial_radius_km \time stop_radius_factor`, from a given point, we can use the following code:
```python
>>> from skmob.preprocessing import detection
>>> # compute the stops for each individual in the TrajDataFrame
>>> stdf = detection.stay_locations(tdf, stop_radius_factor=0.5, minutes_for_a_stop=20.0, spatial_radius_km=0.2, leaving_time=True)
>>> # print a portion of the detected stops
>>> print(stdf.head())
```
lat lng datetime uid leaving_datetime
0 39.978030 116.327481 2008-10-23 06:01:37 1 2008-10-23 10:32:53
1 40.013820 116.306532 2008-10-23 11:10:19 1 2008-10-23 23:45:27
2 39.978419 116.326870 2008-10-24 00:21:52 1 2008-10-24 01:47:30
3 39.981166 116.308475 2008-10-24 02:02:31 1 2008-10-24 02:30:29
4 39.981431 116.309902 2008-10-24 02:30:29 1 2008-10-24 03:16:35
```python
>>> print('Points of the original trajectory:\t%s'%len(tdf))
>>> print('Points of stops:\t\t\t%s'%len(stdf))
```
Points of the original trajectory: 217653
Points of stops: 391
A new column `leaving_datetime` is added to the `TrajDataFrame` in order to indicate the time when the user left the stop location. We can then visualize the detected stops using the `plot_stops` function:
```python
>>> m = stdf.plot_trajectory(max_users=1, start_end_markers=False)
>>> stdf.plot_stops(max_users=1, map_f=m)
```

#### Trajectory compression
The goal of trajectory compression is to reduce the number of trajectory points while preserving the structure of the trajectory. This step results in a significant reduction of the number of trajectory points. In scikit-mobility, we can use one of the methods in the `compression` module under the `preprocessing` module. For instance, to merge all the points that are closer than 0.2km from each other, we can use the following code:
```python
>>> from skmob.preprocessing import compression
>>> # compress the trajectory using a spatial radius of 0.2 km
>>> ctdf = compression.compress(tdf, spatial_radius_km=0.2)
>>> # print the difference in points between original and filtered TrajDataFrame
>>> print('Points of the original trajectory:\t%s'%len(tdf))
>>> print('Points of the compressed trajectory:\t%s'%len(ctdf))
```
Points of the original trajectory: 217653
Points of the compressed trajectory: 6281
<a id='measures'></a>
### Mobility measures
Several measures have been proposed in the literature to capture the patterns of human mobility, both at the individual and collective levels. Individual measures summarize the mobility patterns of a single moving object, while collective measures summarize mobility patterns of a population as a whole. scikit-mobility provides a wide set of [mobility measures](https://scikit-mobility.github.io/scikit-mobility/reference/measures.html), each implemented as a function that takes in input a `TrajDataFrame` and outputs a pandas `DataFrame`. Individual and collective measures are implemented the in `skmob.measure.individual` and the `skmob.measures.collective` modules, respectively.
For example, the following code compute the *radius of gyration*, the *jump lengths* and the *home locations* of a `TrajDataFrame`:
```python
>>> from skmob.measures.individual import jump_lengths, radius_of_gyration, home_location
>>> # load a TrajDataFrame from an URL
>>> url = "https://snap.stanford.edu/data/loc-brightkite_totalCheckins.txt.gz"
>>> df = pd.read_csv(url, sep='\t', header=0, nrows=100000,
names=['user', 'check-in_time', 'latitude', 'longitude', 'location id'])
>>> tdf = skmob.TrajDataFrame(df, latitude='latitude', longitude='longitude', datetime='check-in_time', user_id='user')
>>> # compute the radius of gyration for each individual
>>> rg_df = radius_of_gyration(tdf)
>>> print(rg_df)
```
uid radius_of_gyration
0 0 1564.436792
1 1 2467.773523
2 2 1439.649774
3 3 1752.604191
4 4 5380.503250
```python
>>> # compute the jump lengths for each individual
>>> jl_df = jump_lengths(tdf.sort_values(by='datetime'))
>>> print(jl_df.head())
```
uid jump_lengths
0 0 [19.640467328877936, 0.0, 0.0, 1.7434311010381...
1 1 [6.505330424378251, 46.75436600375988, 53.9284...
2 2 [0.0, 0.0, 0.0, 0.0, 3.6410097195943507, 0.0, ...
3 3 [3861.2706300798827, 4.061631313492122, 5.9163...
4 4 [15511.92758595804, 0.0, 15511.92758595804, 1....
Note that for some measures, such as `jump_length`, the `TrajDataFrame` must be order in increasing order by the column `datetime` (see the documentation for the measures that requires this condition https://scikit-mobility.github.io/scikit-mobility/reference/measures.html).
```python
>>> # compute the home location for each individual
>>> hl_df = home_location(tdf)
>>> print(hl_df.head())
```
uid lat lng
0 0 39.891077 -105.068532
1 1 37.630490 -122.411084
2 2 39.739154 -104.984703
3 3 37.748170 -122.459192
4 4 60.180171 24.949728
```python
>>> # now let's visualize a cloropleth map of the home locations
>>> import folium
>>> from folium.plugins import HeatMap
>>> m = folium.Map(tiles = 'openstreetmap', zoom_start=12, control_scale=True)
>>> HeatMap(hl_df[['lat', 'lng']].values).add_to(m)
>>> m
```

<a id='collective_models'></a>
### Collective generative models
Collective generative models estimate spatial flows between a set of discrete locations. Examples of spatial flows estimated with collective generative models include commuting trips between neighborhoods, migration flows between municipalities, freight shipments between states, and phone calls between regions.
In scikit-mobility, a collective generative model takes in input a spatial tessellation, i.e., a geopandas `GeoDataFrame`. To be a valid input for a collective model, the spatial tessellation should contain two columns, `geometry` and `relevance`, which are necessary to compute the two variables used by collective algorithms: the distance between tiles and the importance (aka "attractiveness") of each tile. A collective algorithm produces a `FlowDataFrame` that contains the generated flows and the spatial tessellation. scikit-mobility implements the most common collective generative algorithms:
- the `Gravity` model;
- the `Radiation` model.
#### Gravity model
The class `Gravity`, implementing the Gravity model, has two main methods:
- `fit`, which calibrates the model's parameters using a `FlowDataFrame`;
- `generate`, which generates the flows on a given spatial tessellation.
Load the spatial tessellation and a data set of real flows in a `FlowDataFrame`:
```python
>>> from skmob.utils import utils, constants
>>> import geopandas as gpd
>>> from skmob.models.gravity import Gravity
>>> import numpy as np
>>> # load a spatial tessellation
>>> url_tess = skmob.utils.constants.NY_COUNTIES_2011
>>> tessellation = gpd.read_file(url_tess).rename(columns={'tile_id': 'tile_ID'})
>>> # load the file with the real fluxes
>>> fdf = skmob.FlowDataFrame.from_file(skmob.utils.constants.NY_FLOWS_2011,
tessellation=tessellation,
tile_id='tile_ID',
sep=",")
>>> # compute the total outflows from each location of the tessellation (excluding self loops)
>>> tot_outflows = fdf[fdf['origin'] != fdf['destination']].groupby(by='origin', axis=0)[['flow']].sum().fillna(0)
>>> tessellation = tessellation.merge(tot_outflows, left_on='tile_ID', right_on='origin').rename(columns={'flow': 'tot_outflow'})
```
Instantiate a Gravity model object and generate synthetic flows:
```python
>>> # instantiate a singly constrained Gravity model
>>> gravity_singly = Gravity(gravity_type='singly cons/tetrained')
>>> print(gravity_singly)
```
Gravity(name="Gravity model", deterrence_func_type="power_law", deterrence_func_args=[-2.0], origin_exp=1.0, destination_exp=1.0, gravity_type="singly constrained")
```python
>>> # start the generation of the synthetic flows
>>> np.random.seed(0)
>>> synth_fdf = gravity_singly.generate(tessellation,
tile_id_column='tile_ID',
tot_outflows_column='tot_outflow',
relevance_column= 'population',
out_format='flows')
>>> # print a portion of the synthetic flows
>>> print(synth_fdf.head())
```
origin destination flow
0 36019 36101 101
1 36019 36107 66
2 36019 36059 1041
3 36019 36011 151
4 36019 36123 33
Fit the parameters of the Gravity model from the `FlowDataFrame` and generate the synthetic flows:
```python
>>> # instantiate a Gravity object (with default parameters)
>>> gravity_singly_fitted = Gravity(gravity_type='singly constrained')
>>> print(gravity_singly_fitted)
```
Gravity(name="Gravity model", deterrence_func_type="power_law", deterrence_func_args=[-2.0], origin_exp=1.0, destination_exp=1.0, gravity_type="singly constrained")
```python
>>> # fit the parameters of the Gravity from the FlowDataFrame
>>> gravity_singly_fitted.fit(fdf, relevance_column='population')
>>> print(gravity_singly_fitted)
```
Gravity(name="Gravity model", deterrence_func_type="power_law", deterrence_func_args=[-1.9947152031914186], origin_exp=1.0, destination_exp=0.6471759552223144, gravity_type="singly constrained")
```python
>>> # generate the synthetics flows
>>> np.random.seed(0)
>>> synth_fdf_fitted = gravity_singly_fitted.generate(tessellation,
tile_id_column='tile_ID',
tot_outflows_column='tot_outflow',
relevance_column= 'population',
out_format='flows')
>>> # print a portion of the synthetic flows
>>> print(synth_fdf_fitted.head())
```
origin destination flow
0 36019 36101 102
1 36019 36107 66
2 36019 36059 1044
3 36019 36011 152
4 36019 36123 33
Plot the real flows and the synthetic flows:
```python
>>> m = fdf.plot_flows(min_flow=100, flow_exp=0.01, flow_color='blue')
>>> synth_fdf_fitted.plot_flows(min_flow=1000, flow_exp=0.01, map_f=m)
```

#### Radiation model
The Radiation model is parameter-free and has only one method: `generate`. Given a spatial tessellation, the synthetic flows can be generated using the `Radiation` class as follows:
```python
>>> from skmob.models.radiation import Radiation
>>> # instantiate a Radiation object
>>> radiation = Radiation()
>>> # start the simulation
>>> np.random.seed(0)
>>> rad_flows = radiation.generate(tessellation,
tile_id_column='tile_ID',
tot_outflows_column='tot_outflow',
relevance_column='population',
out_format='flows_sample')
>>> # print a portion of the synthetic flows
>>> print(rad_flows.head())
```
origin destination flow
0 36019 36033 11648
1 36019 36031 4232
2 36019 36089 5598
3 36019 36113 1596
4 36019 36041 117
<a id='individual_models'></a>
### Individual generative models
The goal of individual generative models of human mobility is to create a population of agents whose mobility patterns are statistically indistinguishable from those of real individuals. An individual generative model typically generates a synthetic trajectory corresponding to a single moving object, assuming that an object is independent of the others.
scikit-mobility implements the most common individual generative models, such as the [Exploration and Preferential Return](https://www.nature.com/articles/nphys1760) model and its variants, and [DITRAS](https://link.springer.com/article/10.1007/s10618-017-0548-4). Each generative model is a python class with a public method `generate`, which starts the generation of synthetic trajectories.
The following code generate synthetic trajectories using the `DensityEPR` model:
```python
>>> from skmob.models.epr import DensityEPR
>>> # load a spatial tesellation on which to perform the simulation
>>> url = skmob.utils.constants.NY_COUNTIES_2011
>>> tessellation = gpd.read_file(url)
>>> # starting and end times of the simulation
>>> start_time = pd.to_datetime('2019/01/01 08:00:00')
>>> end_time = pd.to_datetime('2019/01/14 08:00:00')
>>> # instantiate a DensityEPR object
>>> depr = DensityEPR()
>>> # start the simulation
>>> tdf = depr.generate(start_time, end_time, tessellation, relevance_column='population', n_agents=100)
>>> print(tdf.head())
```
uid datetime lat lng
0 1 2019-01-01 08:00:00.000000 42.452018 -76.473618
1 1 2019-01-01 08:32:30.108708 42.170344 -76.306260
2 1 2019-01-01 09:09:11.760703 43.241550 -75.435903
3 1 2019-01-01 10:00:22.832309 42.170344 -76.306260
4 1 2019-01-01 14:00:25.923314 42.267915 -77.383591
```python
>>> print(tdf.parameters)
```
{'model': {'class': <function DensityEPR.__init__ at 0x7f70ce0a7e18>, 'generate': {'start_date': Timestamp('2019-01-01 08:00:00'), 'end_date': Timestamp('2019-01-14 08:00:00'), 'gravity_singly': {}, 'n_agents': 100, 'relevance_column': 'population', 'random_state': None, 'verbose': True}}}
<a id='privacy'></a>
### Privacy
Mobility data is sensitive since the movements of individuals can reveal confidential personal information or allow the re-identification of individuals in a database, creating serious privacy risks. In the literature, privacy risk assessment relies on the concept of re-identification of a moving object in a database through an attack by a malicious adversary. A common framework for privacy risk assessment assumes that during the attack a malicious adversary acquires, in some way, the access to an anonymized mobility data set, i.e., a mobility data set in which the moving object associated with a trajectory is not known. Moreover, it is assumed that the malicious adversary acquires, in some way, information about the trajectory (or a portion of it) of an individual represented in the acquired data set. Based on this information, the risk of re-identification of that individual is computed estimating how unique that individual's mobility data are with respect to the mobility data of the other individuals represented inthe acquired data set.
scikit-mobility provides several attack models, each implemented as a python class. For example in a location attack model, implemented in the `LocationAttack` class, the malicious adversary knows a certain number of locations visited by an individual, but they do not know the temporal order of the visits. To instantiate a `LocationAttack` object we can run the following code:
```python
>>> import skmob
>>> from skmob.privacy import attacks
>>> at = attacks.LocationAttack(knowledge_length=2)
```
The argument `knowledge_length` specifies how many locations the malicious adversary knows of each object's movement. The re-identification risk is computed based on the worst possible combination of `knowledge_length` locations out of all possible combinations of locations.
To assess the re-identification risk associated with a mobility data set, represented as a `TrajDataFrame`, we specify it as input to the `assess_risk` method, which returns a pandas `DataFrame` that contains the `uid` of each object in the `TrajDataFrame` and the associated re-identification risk as the column `risk` (type: float, range: $[0,1]$ where 0 indicates minimum risk and 1 maximum risk).
```python
>>> tdf = skmob.TrajDataFrame.from_file(filename="privacy_toy.csv")
>>> tdf_risk = at.assess_risk(tdf)
>>> print(tdf_risk.head())
```
uid risk
0 1 0.333333
1 2 0.500000
2 3 0.333333
3 4 0.333333
4 5 0.250000
Since risk assessment may be time-consuming for more massive datasets, scikit-mobility provides the option to focus only on a subset of the objects with the argument `targets`. For example, in the following code, we compute the re-identification risk for the object with `uid` 1 and 2 only:
```python
>>> tdf_risk = at.assess_risk(tdf, targets=[1,2])
>>> print(tdf_risk)
```
uid risk
0 1 0.333333
1 2 0.500000
<a id="data"></a>
### Downloading datasets
The `data` module of scikit-mobility provides users with an easy way to: 1) Download ready-to-use mobility data (e.g., trajectories, flows, spatial tessellations, and auxiliary data); 2) Load and transform the downloaded dataset into standard skmob structures (TrajDataFrame, GeoDataFrame, FlowDataFrame, DataFrame); 3) Allow developers and contributors to add new datasets to the library.
The `data` module provides three functions:
- `list_datasets`
- `get_dataset_info`
- `load_dataset`
The user can download the list of all datasets currently available in the library using `list_datasets`:
```python
>>> import skmob
>>> from skmob.data.load import list_datasets
>>> list_datasets()
```
['flow_foursquare_nyc',
'foursquare_nyc',
'nyc_boundaries',
'parking_san_francisco',
'taxi_san_francisco']
The user can retrieve information about a specific dataset in the library using `get_dataset_info`:
```python
>>> import skmob
>>> from skmob.data.load import get_dataset_info
>>> get_dataset_info("foursquare_nyc")
```
{'name': 'Foursquare_NYC',
'description': 'Dataset containing the Foursquare checkins of individuals moving in New York City',
'url': 'http://www-public.it-sudparis.eu/~zhang_da/pub/dataset_tsmc2014.zip',
'hash': 'cbe3fdab373d24b09b5fc53509c8958c77ff72b6c1a68589ce337d4f9a80235b',
'auth': 'no',
'data_type': 'trajectory',
'download_format': 'zip',
'sep': ' ',
'encoding': 'ISO-8859-1'}
Finally, the user can download a specific dataset using `load_dataset`:
```python
>>> import skmob
>>> from skmob.data.load import load_dataset, list_datasets
>>> tdf_nyc = load_dataset("foursquare_nyc", drop_columns=True)
>>> print(tdf_nyc.head())
```
uid lat lng datetime
0 470 40.719810 -74.002581 2012-04-03 18:00:09+00:00
1 979 40.606800 -74.044170 2012-04-03 18:00:25+00:00
2 69 40.716162 -73.883070 2012-04-03 18:02:24+00:00
3 395 40.745164 -73.982519 2012-04-03 18:02:41+00:00
4 87 40.740104 -73.989658 2012-04-03 18:03:00+00:00
# Related packages
[*movingpandas*](https://github.com/anitagraser/movingpandas) is a similar package that deals with movement data. Instead of implementing new data structures tailored for trajectories (`TrajDataFrame`) and mobility flows (`FlowDataFrame`), *movingpandas* describes a trajectory using a *geopandas* `GeoDataFrame`. There is little overlap in the covered use cases and implemented functionality (comparing [*scikit-mobility* tutorials](https://github.com/scikit-mobility/tutorials) and [*movingpandas* tutorials](https://github.com/anitagraser/movingpandas/tree/master/tutorials)): *scikit-mobility* focuses on computing human mobility metrics, generating synthetic trajectories and assessing privacy risks of mobility datasets. *movingpandas* on the other hand focuses on spatio-temporal data exploration with corresponding functions for data manipulation and analysis.
%prep
%autosetup -n scikit-mobility-1.3.1
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-scikit-mobility -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Fri May 05 2023 Python_Bot <Python_Bot@openeuler.org> - 1.3.1-1
- Package Spec generated
|