-
Notifications
You must be signed in to change notification settings - Fork 0
/
polyneigh.jl
173 lines (132 loc) · 5.18 KB
/
polyneigh.jl
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
# This file contains functions for creating spatial weights from polygon data
# Auxiliar function to return the points from a vector of polygons, multipolygon, or a mix of the two
function _getpointsPoligon(::GI.PolygonTrait, P)::Tuple{Vector{Float64}, Vector{Float64}}
c = GI.coordinates(P)
ppointsx = Array{Float64}(undef, length(c[1]))
ppointsy = Array{Float64}(undef, length(c[1]))
ppointsx = map(a -> a[1], c[1])
ppointsy = map(a -> a[2], c[1])
return ppointsx, ppointsy
end
function _getpointsPoligon(::GI.MultiPolygonTrait, P)::Tuple{Vector{Float64}, Vector{Float64}}
c = GI.coordinates(P)
ppointsx = Array{Float64}(undef, length(c[1]))
ppointsy = Array{Float64}(undef, length(c[1]))
xy = reduce(vcat,
map(1:length(c)) do i
x = map(a -> a[1], c[i][1])
y = map(a -> a[2], c[i][1])
hcat(x, y)
end
)
ppointsx = xy[:,1]
ppointsy = xy[:,2]
return ppointsx, ppointsy
end
_getpointsPoligon(::Any, P) = throw(ArgumentError("Missing geometry or not PolygonTrait or MultiPolygonTrait"));
# Auxiliar function to return the number of times the points of two polygons hits
function _hits(icoords::Vector{Vector{Float64}}, jcoords::Vector{Vector{Float64}}, critthr::Int64, tol::Float64)::Bool
nhits = 0
nicoords = length(icoords[1])
njcoords = length(jcoords[1])
for pti in 1:nicoords
for ptj in 1:njcoords
@inbounds xd = icoords[1][pti] - jcoords[1][ptj]
if abs(xd) > tol continue end
@inbounds yd = icoords[2][pti] - jcoords[2][ptj]
if abs(yd) > tol continue end
dist = hypot(xd, yd)
if dist <= tol
nhits = nhits + 1
end
# Leave if number of hits is larger than the required by the criterion
if nhits >= critthr
return true
end
end
end
return false
end
"""
polyneigh(P, criterion = :Queen)
Build a spatial weights object from a vector of polygons `P`.
# Optional Arguments
- `criterion=:Queen`: neighbour criterion. `:Queen` or `:Rook`.
- `tol=0.0`: tolerance for polygon contiguity.
"""
function polyneigh(P::Vector; criterion::Symbol = :Queen, tol::Float64 = 0.0)::SpatialWeights
all(GI.isgeometry.(P)) || throw(ArgumentError("Unknown geometry"))
gtrait = GI.geomtrait.(P)
n = length(P)
xy = _getpointsPoligon.(gtrait, P)
x = map(a -> a[1], xy)
y = map(a -> a[2], xy)
# Bounding box
xmin, ymin = minimum.(x) .- tol, minimum.(y) .- tol
xmax, ymax = maximum.(x) .+ tol, maximum.(y) .+ tol
BBpols = hcat(xmin, ymin, xmax, ymax, [1:n;])
# Select candidates if bouning box overlaps or touches
BBpols = sortslices(BBpols, dims=1)
candidates = copy.(fill(Int[], n))
Threads.@threads for i in 1:n-1
for j in (i+1):n
if (BBpols[j,1] <= BBpols[i,3]) && # xmin[j] <= xmax[i]
(BBpols[j,2] <= BBpols[i,4]) && # ymin[j] <= ymax[i]
(BBpols[j,3] >= BBpols[i,1]) && # xmax[j] >= xmin[i]
(BBpols[j,4] >= BBpols[i,2]) # ymax[j] >= ymin[i]
push!(candidates[Int(BBpols[i,5])], BBpols[j,5])
end
end
end
# Check neighbours
neighs = copy.(fill(Int[], n))
weights = copy.(fill(Float64[], n))
nneighs = zeros(Int,n)
if criterion == :Queen critthr = 1 end
if criterion == :Rook critthr = 2 end
# Use multithreading to calculate polygons hits
neighssingle = copy.(fill(Int[], n))
Threads.@threads for i in 1:n
@inbounds for j in candidates[i]
p1 = [x[i], y[i]]
p2 = [x[j], y[j]]
polhits = _hits(p1, p2, critthr, tol)
if polhits
push!(neighssingle[i], j)
end
end
end
# Makes neighbors bilateral
for i in 1:n
for j in neighssingle[i]
push!(neighs[i], j)
push!(neighs[j], i)
nneighs[i] += 1
nneighs[j] += 1
end
end
# Sort neighbours lists and compute weights
for i in 1:n
sort!(neighs[i])
weights[i] = ones(nneighs[i]) ./ nneighs[i]
end
SpatialWeights(n, neighs, weights, nneighs, :row)
end
"""
polyneigh(A, criterion = :Queen)
Build a spatial weights object from table A that contains a geometry column.
# Optional Arguments
- `criterion=:Queen`: neighbour criterion. `:Queen` or `:Rook`.
- `tol=0.0`: tolerance for polygon contiguity.
"""
function polyneigh(A::Any; criterion::Symbol = :Queen, tol::Float64 = 0.0)::SpatialWeights
istable(A) || throw(ArgumentError("Argument must be a table with geometry or a vector of polygons"))
geomcol = _geomFromTable(A)
return polyneigh(geomcol, criterion = criterion, tol = tol)
end
# Internal function to get the geometry column from a Table
function _geomFromTable(A::Any)
geomcol = first(GeoInterface.geometrycolumns(A))
geomcol in propertynames(A) || throw(ArgumentError("table does not have geometry information :$geomcol"))
return getcolumn(A, geomcol)
end