forked from fossgis2021/A2_GRASS_GIS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
population.py
85 lines (80 loc) · 2.48 KB
/
population.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
import sys
import subprocess
import numpy as np
import grass.script as gscript
import grass.script.array as garray
def main():
region = gscript.region()
res = (region["ewres"], region["nsres"])
delta = (1, 1)
size = (250, 250)
for i in range(len(res)):
if not size[i] - delta[i] < ewres < size[i] + delta[i]:
raise ValueError(f"Resolution mismatch, should be {size[0]}+-{delta}")
# Create one vector feature to improve speed for calculations
print("Preparing data...", flush=True)
gscript.run_command(
"v.buffer",
input="motorways@PERMANENT",
output=f"motorway",
distance=0.001,
overwrite=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
distances = {
250: None,
500: None,
1000: None,
2500: None,
5000: None,
}
for i in distances.keys():
print(f"Starting calculation for {i}m distance", flush=True)
print("Creating buffer", flush=True)
gscript.run_command(
"v.buffer",
input="motorway@PERMANENT",
output=f"motorway_buf_{i}",
distance=i,
overwrite=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
gscript.run_command(
"g.region",
vector=f"motorway_buf_{i}",
overwrite=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
print("Rasterizing buffer", flush=True)
gscript.run_command(
"v.to.rast",
input=f"motorway_buf_{i}@PERMANENT",
output=f"motorway_rast_{i}",
use="val",
overwrite=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
print("Counting population", flush=True)
gscript.run_command(
"r.stats.zonal",
base=f"motorway_rast_{i}@PERMANENT",
cover="GHS_POP_E2015_GLOBE_R2019A_54009_250_V1_0_18_3@PERMANENT",
method="sum",
output=f"pop_motorway_{i}",
overwrite=True,
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
a = garray.array(f"pop_motorway_{i}@PERMANENT")
distances[i] = np.amax(a)
print("Populations:")
for i, pop in distances.items():
if pop is None: continue
print(f"{i}m\t {pop}")
if __name__ == '__main__':
main()