-
Notifications
You must be signed in to change notification settings - Fork 0
/
setBuildingHeights.py
executable file
·935 lines (809 loc) · 31.8 KB
/
setBuildingHeights.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
#!/usr/bin/env python
# -*- coding: latin-1 -*-
"""
******************************************************************
Name: setBuildingHeights.py
Created: 22 Mar 2013
Author: David Segersson
Description
------------------------------------------------------------------
Set building height as attribute to 3D line features
Height is read from z-coordinate of lines, and from a raster DEM
Difference between building z and DEM z is calculated for all vertices
Average height difference is added as attribute BUILDHGT to result
polyline feature class
"""
# Standard modules
from os import path
import sys
import logging
import argparse
from math import ceil
# pyAirviro-modules
from pyAirviro.other.utilities import ProgressBar
from pyAirviro.geo.raster import readGDAL
from pyAirviro.other import logging
from pyAirviro.tools import utils
# help module for this script
from geometry import Segment, intersect2D_2Segments
# plot modules
from matplotlib import pyplot as plt
# from matplotlib.path import Path
# import matplotlib.patches as Patches
import numpy as np
try:
from osgeo import ogr
from osgeo.gdalconst import *
__gdal_loaded__=True
except:
__gdal_loaded__=False
log = logging.getLogger('pyAirviro.' + __name__)
# Docstrings for the option parser
usage = "usage: %prog [options] "
version = "%prog 1.0"
CELLSIZE = 75 # Cellsize of spatial index for building contours
MAXDIST = 100 # Maximal dist from road within which buildings are processed
CSDIST = 40 # Max distance between cross-sections
HEIGHTCORR = 1 # Added height to buildings to account for non-flat roofs
PLOTIND = -1 # Index To plot for debugging
CSIND = 1 # cross section index to plot for debugging
def splitRoad(inRoadFeature, splitLimit, layerDefn):
"""
Split road in sections with same direction
Returns list of features with same field values as original feature
@param inRoadFeature: road feature to split
@param splitLimit: threshold for splitting the road
@param outRoadLayer: layer to create new features in
"""
outRoadFeatures = []
inRoadGeom = inRoadFeature.GetGeometryRef()
nPoints = inRoadGeom.GetPointCount()
if splitLimit is None or nPoints <= 2:
outRoadFeatures.append(ogr.Feature(layerDefn))
outRoadFeatures[0].SetGeometry(inRoadGeom)
outRoadFeatures[0].SetFrom(inRoadFeature)
return outRoadFeatures
x1 = inRoadGeom.GetX(0)
y1 = inRoadGeom.GetY(0)
z1 = inRoadGeom.GetZ(0)
x2 = inRoadGeom.GetX(1)
y2 = inRoadGeom.GetY(1)
z2 = inRoadGeom.GetZ(1)
# Direction vector of first segment
Ulast = np.array([x2-x1,y2-y1])
Ulast = Ulast / np.linalg.norm(Ulast)
# Convert to polar
# lastAng = np.degrees(np.arctan2(U[1], U[0]))
# Create new feature
outRoadFeatures.append(ogr.Feature(layerDefn))
# create new geometry and add first point
newGeom = ogr.Geometry(type=ogr.wkbLineString)
newGeom.AddPoint(x1, y1, z1)
for pInd in range(1, nPoints):
x1 = inRoadGeom.GetX(pInd - 1)
y1 = inRoadGeom.GetY(pInd - 1)
z1 = inRoadGeom.GetZ(pInd - 1)
x2 = inRoadGeom.GetX(pInd)
y2 = inRoadGeom.GetY(pInd)
z2 = inRoadGeom.GetZ(pInd)
# Estimate direction vector
U = np.array([x2 - x1,y2 - y1])
U = U / np.linalg.norm(U)
diff = np.degrees(np.arccos(np.dot(U, Ulast)))
if np.isnan(diff):
diff = 0
if diff > 180:
diff -= 180
# If direction change is acceptable,
# point is added to existing features geometry
if abs(diff) <= splitLimit:
newGeom.AddPoint(x2, y2, z2)
# If to large change, a new feature and geometry is created
else:
outRoadFeatures[-1].SetFrom(inRoadFeature)
outRoadFeatures[-1].SetGeometryDirectly(newGeom)
outRoadFeatures.append(ogr.Feature(layerDefn))
newGeom = ogr.Geometry(type=ogr.wkbLineString)
newGeom.AddPoint(x1, y1, z1)
newGeom.AddPoint(x2, y2, z2)
Ulast = U
# if last point, set geometry
if pInd == nPoints - 1:
outRoadFeatures[-1].SetFrom(inRoadFeature)
outRoadFeatures[-1].SetGeometryDirectly(newGeom)
return outRoadFeatures
def bheight2sect(hgt1, hgt2, angle1):
"""
Returns string list of buildingsheights in 12 sectors relative to north
@param: building height on side 1
@param: building height in side 2
@param: angle relative north to buildings on side 1
"""
nSec = 12
if hgt1 is None or hgt2 is None:
return None
elif hgt1 == hgt2:
sectHgt = [hgt1] * nSec
sectStr = " ".join(map(str, sectHgt))
return sectStr
elif angle1 is None:
return None
sectHgt = [None] * nSec
secSize = 360 / nSec
i = 0
indicesSide1 = []
if hgt1 is None or hgt2 is None:
return None
i = int(angle1 / secSize)
rest = angle1 / float(secSize) - i
if rest > 0.5:
i += 1
if i >= nSec:
i -= nSec
for j in range(3):
if i + j <= 11:
sectHgt[i + j] = hgt1
indicesSide1.append(i + j)
else:
sectHgt[i + j - nSec] = hgt1
indicesSide1.append(i + j - nSec)
for j in range(-1, -4, -1):
if i + j >= 0:
sectHgt[i + j] = hgt1
indicesSide1.append(i + j)
else:
sectHgt[i + j + nSec] = hgt1
indicesSide1.append(i + j + nSec)
for ind in range(nSec):
if ind not in indicesSide1:
sectHgt[ind] = hgt2
sectStr = " ".join(map(str, sectHgt))
return sectStr
def plotSegments(ax, segments, color="black", style="-", width=0.5):
for seg in segments:
X = [seg.P0[0], seg.P1[0]]
Y = [seg.P0[1], seg.P1[1]]
ax.plot(X, Y, color=color, linestyle=style, linewidth=width)
def getBuildingSegments(building):
"""
Return list of segments in building contour
@param building: ogr geometry reference for building contour
"""
nPoints = building.GetPointCount()
segments = []
for i in range(1, nPoints):
x1 = building.GetX(i - 1)
y1 = building.GetY(i - 1)
z1 = building.GetZ(i - 1)
x2 = building.GetX(i)
y2 = building.GetY(i)
z2 = building.GetZ(i)
P1 = np.array([x1, y1, z1])
P2 = np.array([x2, y2, z2])
segments.append(Segment(P1, P2))
return segments
def getIntersectingFacade(ax, cs, segments, plot=False):
"""
Get nearest instersecting facade for cs
@param cs: cross section expressed as a Segment instance
"""
minDist = MAXDIST
nearestIntersection = None
log.debug("Found %i segments" %len(segments))
for segInd, seg in enumerate(segments):
if plot and segInd == 9:
ax.text(0.5 * (seg.P0[0] + seg.P1[0]),
0.5 * (seg.P0[1] + seg.P1[1]),
'%i' % segInd, fontsize=10)
Pintersect, Poverlap = intersect2D_2Segments(cs, seg)
if Pintersect is not None:
# add segement z-level to intersection
Pintersect = np.append(Pintersect, seg.P1[2])
# evaluate horizontal distance
dist = np.linalg.norm(Pintersect[:-1] - cs.P0)
if dist <= minDist:
minDist = dist
nearestIntersection = Pintersect
return (minDist, nearestIntersection)
class SpatialIndex:
def __init__(self, xmin, ymin, nrows, ncols, cellsize):
"""
@param xmin: min x of extent
@param ymin: min y of extent
@param ncols: number of index columns
@param nrows: number of index rows
@param cellsize: resolution of spatial index
"""
self.xmin = xmin
self.xmax = xmin + ncols * cellsize
self.ymin = ymin
self.ymax = ymin + nrows * cellsize
self.nrows = nrows
self.ncols = ncols
self.cellsize = cellsize
self.ind = {}
def inside(self, road):
Pll, Pur = road.getBoundingBox()
try:
row, col = self.getInd(Pll[0] - 100, Pll[1] - 100)
row, col = self.getInd(Pur[0] + 100, Pur[1] + 100)
except ValueError:
return False
else:
return True
def plotCell(self, ax, row, col, color="grey", style="--", width=0.5):
# plot index grid cell
# indexing clockwise from lower left corner
x1 = x2 = x5 = self.xmin + col * self.cellsize
x3 = x4 = self.xmin + (col + 1) * self.cellsize
y1 = y4 = y5 = self.ymax - (row + 1) * self.cellsize
y2 = y3 = self.ymax - row * self.cellsize
S1 = Segment(np.array([x1, y1]), (np.array([x2, y2])))
S2 = Segment(np.array([x2, y2]), (np.array([x3, y3])))
S3 = Segment(np.array([x3, y3]), (np.array([x4, y4])))
S4 = Segment(np.array([x4, y4]), (np.array([x5, y5])))
gridSegments = [S1, S2, S3, S4]
plotSegments(ax, gridSegments, color=color, style=style, width=width)
def plot(self, ax):
buildSegments = []
for row in self.ind:
for col in self.ind[row]:
buildSegments += self.ind[row][col]
self.plotCell(ax, row, col)
ax.text(self.xmin + (col + 0.5) * self.cellsize,
self.ymax - (row + 0.5) * self.cellsize,
'%i' % len(self.ind[row][col]), fontsize=10)
plotSegments(ax, buildSegments, color="grey", style="-", width=1.0)
def getBuildingSegments(self, x, y):
"""
Building segments from index cells close to given point are returned
Also segments in neighbouring index cells are included
@param x: x coord of point to find segments for
@param y: y coord of point to find segments for
"""
row, col = self.getInd(x, y)
try:
segments = self.ind[row][col][:]
except KeyError:
segments = []
if col > 0:
try:
segments += self.ind[row][col - 1]
except KeyError:
pass
if col < self.ncols - 1:
try:
segments += self.ind[row][col + 1]
except KeyError:
pass
if row > 0:
try:
segments += self.ind[row - 1][col]
except KeyError:
pass
if col > 0:
try:
segments += self.ind[row - 1][col - 1]
except KeyError:
pass
if col < self.ncols - 1:
try:
segments += self.ind[row - 1][col + 1]
except KeyError:
pass
if row < self.nrows - 1:
try:
segments += self.ind[row + 1][col]
except KeyError:
pass
if col > 0:
try:
segments += self.ind[row + 1][col - 1]
except KeyError:
pass
if col < self.ncols - 1:
try:
segments += self.ind[row + 1][col + 1]
except KeyError:
pass
return segments
def getInd(self, x, y):
"""
Function to estimate row and col of spatial index
@param x: x coordinate to retrieve index for
@param y: y coordinate to retrieve index for
"""
if x < self.xmin or y < self.ymin or x > self.xmax or y > self.ymax:
raise ValueError("Outside extent")
col = int((x - self.xmin) / self.cellsize)
row = self.nrows - int(ceil((y - self.ymin) / self.cellsize))
# If on boundary of extent
if row == self.nrows:
row -= 1
if col == self.ncols:
col -= 1
return (row, col)
def indexBuildingContours(self, buildingFile):
"""
Read building contours from shape file and create a spatial indexing.
The indexing is implemented as a nested dict
cols={row1,row2,row3}, where row1..n = {cell1,cell2,...,celln},
and cell1...n = [contour_1,contour_2,...,contour_n]
Extent of index is set to extent of the used DEM (topo)
@param buildingFile: shapefile with 3D building contours
"""
# open building contours shape-file
log.info("Reading building contours")
# Init reading of shape-files using OGR
shapeDriver = ogr.GetDriverByName('ESRI Shapefile')
buildings = shapeDriver.Open(buildingFile, update=0)
if buildings is None:
log.error("Could not open file with building contours")
return 1
buildingsLayer = buildings.GetLayer()
self.ind = {}
# set up progress indicator
pg = ProgressBar(buildingsLayer.GetFeatureCount(), sys.stdout)
contourInd = 0 # Counter for building contour
buildHeights = [] # List to store building height for plotting
noGeom = 0 # Counter for invalid features without geometry reference
# Read and process building contours
contour = buildingsLayer.GetNextFeature() # get first feature
while contour:
if log.level == 0:
pg.update(contourInd)
log.debug("Contour %i" % contourInd)
contourGeom = contour.GetGeometryRef()
if contourGeom is None or contourGeom.GetPointCount()==0:
noGeom += 1
else:
for i in range(1,contourGeom.GetPointCount()):
x1 = contourGeom.GetX(i - 1)
y1 = contourGeom.GetY(i - 1)
z1 = contourGeom.GetZ(i - 1)
x2 = contourGeom.GetX(i)
y2 = contourGeom.GetY(i)
z2 = contourGeom.GetZ(i)
P1 = np.array([x1, y1, z1])
P2 = np.array([x2, y2, z2])
try:
row, col = self.getInd(
(x2 + x1) / 2.0,
(y1 + y2) / 2.0
)
except ValueError: # outside extent
row = col = None
if row is not None and col is not None:
if row not in self.ind:
self.ind[row] = {}
self.ind[row][col] = []
elif col not in self.ind[row]:
self.ind[row][col] = []
self.ind[row][col].append(Segment(P1, P2))
contour.Destroy()
contour = buildingsLayer.GetNextFeature()
contourInd += 1
# close datasource for building contours
buildings.Destroy()
pg.finished()
if noGeom > 0:
log.warning("Found %i building contours without geometry" % noGeom)
def getBuildingHeight(self, x, y, z, topo):
try:
groundLevel = topo.getVal(x, y)
except ValueError:
buildhgt = -9999
else:
buildhgt = z - groundLevel
if buildhgt < 0:
buildhgt = 0
return buildhgt
def plotBuildHgtDistr(self):
fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(111)
binLims = np.arange(-20, 60, 1)
n, bins, patches = ax.hist(heights, bins=binLims, normed=0)
plt.setp(patches, 'facecolor', 'black', 'alpha', 0.75)
plt.title("Building height distribution")
plt.xlabel('Height [m]')
plt.axis([-20, 60, 0, max(n)*1.1])
plt.show()
class Road:
def __init__(self, road):
self.nPoints = road.GetPointCount()
self.points = []
for i in range(self.nPoints):
self.points.append(np.array([road.GetX(i), road.GetY(i)]))
def normalAngles(self):
x1 = self.points[-1][0]
y1 = self.points[0][1]
x2 = self.points[-1][0]
y2 = self.points[-1][1]
roadSegLen = np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
U = self.points[-1] - self.points[0]
roadDir = U / roadSegLen
roadNormal1 = np.array([-1 * roadDir[1], roadDir[0]])
roadNormal2 = np.array([roadDir[1], -1 * roadDir[0]])
ang1 = np.degrees(np.arctan2(roadNormal1[1], roadNormal1[0]))
ang2 = np.degrees(np.arctan2(roadNormal2[1], roadNormal2[0]))
ang1 -= 90 # relative to north
if ang1 < 0:
ang1 += 360 # Make sure angle is given in positive direction
ang2 -= 90 # relative to north
if ang2 < 0:
ang2 += 360 # Make sure angle is given in positive direction
if np.isnan(ang1) or np.isnan(ang2):
return (None, None)
return (ang1, ang2)
def getBoundingBox(self):
"""
Get bounding box for road
returns (minPoint, maxPoint)
"""
P1 = np.array([min(self.points[0][0], self.points[-1][0]),
min(self.points[0][1], self.points[-1][1]), ])
P2 = np.array([max(self.points[0][0], self.points[-1][0]),
max(self.points[0][1], self.points[-1][1]), ])
return (P1, P2)
def getSegments(self):
segments = []
for i in range(1, self.nPoints):
segments.append(Segment(self.points[i - 1], self.points[i]))
return segments
def defineCrossSections(self):
"""
Define cross-sections as two lists of segments,
one for each side of the road
returns ("segment list side1","segment list side 2")
"""
cs1 = []
cs2 = []
for i in range(1, self.nPoints):
x1 = self.points[i - 1][0]
y1 = self.points[i-1][1]
x2 = self.points[i][0]
y2 = self.points[i][1]
roadSegLen = np.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
nCS = int(np.ceil(roadSegLen / float(CSDIST)))
segFrac = 1 / float(nCS)
P0 = self.points[i - 1]
P1 = self.points[i]
U = P1 - P0
roadDir = U / roadSegLen
roadNormal1 = np.array([-1 * roadDir[1], roadDir[0]])
roadNormal2 = np.array([roadDir[1], -1 * roadDir[0]])
for csInd in range(0, nCS):
Pi = P0 + U * (csInd + 0.5) * segFrac
cs1.append(Segment(Pi, Pi + roadNormal1 * MAXDIST))
cs2.append(Segment(Pi, Pi + roadNormal2 * MAXDIST))
return (cs1, cs2)
def main():
# Parse command line arguments
parser = argparse.ArgumentParser(description=__doc__)
utils.add_standard_command_options(parser)
parser.add_argument(
"-f", "--format",
action="store", dest="format", default="ESRI Shapefile",
help="Format of road network"
)
parser.add_argument(
"--inRoads", required=True,
action="store", dest="inRoads",
help="Input road network"
)
parser.add_argument(
"--outRoads", required=True,
action="store", dest="outRoads",
help="Output road network"
)
parser.add_argument(
"--buildings", required=True,
action="store", dest="buildings",
help="Input building roof contours (3D)"
)
parser.add_argument(
"--topo", required=True,
action="store", dest="topo",
help="Input raster DEM"
)
parser.add_argument(
"--split", type=int,
action="store", dest="split",
help="Threshold in changed road direction (degrees)" +
" for when to split road"
)
args = parser.parse_args()
if not path.exists(args.topo):
log.error("Input raster does not exist")
sys.exit(1)
if not path.exists(args.buildings):
log.error("Input building contours does not exist")
sys.exit(1)
return 1
log.info("Reading DEM")
topo = readGDAL(args.topo, bandIndex=1)[0]
# Opening driver for road networks
try:
driver = ogr.GetDriverByName(args.format)
except:
log.error(
"Invalid format for road networks, check ogr documentation"
)
sys.exit(1)
if args.split is None:
log.info("Do not split roads")
splitLimit = None
else:
splitLimit = float(args.split)
log.info(
"Split roads that change direction" +
" more than %f" % splitLimit
)
# extract extent from topo raster
xmin = topo.xll
ymin = topo.yll
xmax = topo.xur()
ymax = topo.yur()
# Calculate dimensions of spatial index
ncols = int((xmax - xmin) / CELLSIZE)
nrows = int((ymax - ymin) / CELLSIZE)
# Init spatial index of building contours
spatInd = SpatialIndex(
xmin, ymin, nrows, ncols, CELLSIZE
)
log.info("Reading and indexing building contours")
# Read buildings and store using spatial indices
spatInd.indexBuildingContours(args.buildings)
# open road network shape-file
log.info("Reading road network")
inRoadFile = driver.Open(args.inRoads, update=0)
if path.exists(args.outRoads):
driver.DeleteDataSource(args.outRoads)
outRoadFile = driver.CreateDataSource(args.outRoads)
if inRoadFile is None:
log.error("Could not open file with input road network")
sys.exit(1)
if outRoadFile is None:
log.error("Could not open file with output road network")
sys.exit(1)
# Get layer definition and first feature of input road network
inRoadLayer = inRoadFile.GetLayer()
inRoadLayerDefn = inRoadLayer.GetLayerDefn()
outRoadLayer = outRoadFile.CreateLayer(
"first_layer",
geom_type=inRoadLayer.GetGeomType()
)
# create fields on output road file
for fieldInd in range(inRoadLayerDefn.GetFieldCount()):
fieldDefn = inRoadLayerDefn.GetFieldDefn(fieldInd)
outRoadLayer.CreateField(fieldDefn)
outRoadLayerDefn = outRoadLayer.GetLayerDefn()
fieldNames = [outRoadLayerDefn.GetFieldDefn(i).GetName()
for i in range(outRoadLayerDefn.GetFieldCount())]
log.info("Adding attributes to road feature (if missing)")
# Add attributes for street canyon geometry
if "BHGT1" not in fieldNames:
outRoadLayer.CreateField(ogr.FieldDefn("BHGT1", ogr.OFTInteger))
if "BHGT2" not in fieldNames:
outRoadLayer.CreateField(ogr.FieldDefn("BHGT2", ogr.OFTInteger))
if "BHGT1W" not in fieldNames:
outRoadLayer.CreateField(ogr.FieldDefn("BHGT1W", ogr.OFTInteger))
if "BHGT2W" not in fieldNames:
outRoadLayer.CreateField(ogr.FieldDefn("BHGT2W", ogr.OFTInteger))
if "BANG1" not in fieldNames:
outRoadLayer.CreateField(ogr.FieldDefn("BANG1", ogr.OFTInteger))
if "BANG2" not in fieldNames:
outRoadLayer.CreateField(ogr.FieldDefn("BANG2", ogr.OFTInteger))
if "BDIST" not in fieldNames:
outRoadLayer.CreateField(ogr.FieldDefn("BDIST", ogr.OFTInteger))
if "BSECT" not in fieldNames:
fieldDefn = ogr.FieldDefn("BSECT", ogr.OFTString)
fieldDefn.SetWidth(40)
outRoadLayer.CreateField(fieldDefn)
if "BSECTW" not in fieldNames:
fieldDefn = ogr.FieldDefn("BSECTW", ogr.OFTString)
fieldDefn.SetWidth(40)
outRoadLayer.CreateField(fieldDefn)
fig1 = plt.figure(1)
ax1 = plt.subplot(111)
ax1.axis('equal')
if PLOTIND > 0:
spatInd.plot(ax1)
roadInd = 0
noGeom = 0
nsplit = 0
# get first road feature
inRoadFeature = inRoadLayer.GetNextFeature()
# Loop over all roads
log.info("Finding nearest facades, setting heights...")
pg = ProgressBar(inRoadLayer.GetFeatureCount(), sys.stdout)
while inRoadFeature:
pg.update(roadInd)
outRoadFeatures = splitRoad(
inRoadFeature, splitLimit, outRoadLayer.GetLayerDefn()
)
if len(outRoadFeatures) > 1:
log.debug(
"Raod split into %s parts" % len(outRoadFeatures)
)
nsplit += len(outRoadFeatures) - 1
for outRoadFeature in outRoadFeatures:
intersections = []
outRoadGeom = outRoadFeature.GetGeometryRef()
road = Road(outRoadGeom)
if outRoadGeom is None or \
outRoadGeom.GetPointCount() == 0 or not spatInd.inside(road):
noGeom += 1
maxHeight1 = None
maxHeight2 = None
avgDist = None
bAngle1 = None
bAngle2 = None
avgHeight1 = None
avgHeight2 = None
else:
sumHeight1 = 0
sumHeight2 = 0
maxHeight1 = 0
maxHeight2 = 0
sumDist = 0
# Define crossections along the road,
# Defined by start and endpoints at both side of the road
cs1List, cs2List = road.defineCrossSections()
nCS = len(cs1List)
log.debug("Defined %i cross sections" % nCS)
# Check intersections with building contours for all cross-sections
for csInd in range(nCS):
cs1 = cs1List[csInd]
cs2 = cs2List[csInd]
cs1MidPoint = cs1.P0 + 0.5 * (cs1.P1 - cs1.P0)
buildingSegments = spatInd.getBuildingSegments(
cs1MidPoint[0], cs1MidPoint[1])
log.debug("Calculating intersection")
if PLOTIND == roadInd and CSIND == csInd:
dist1, Pint1 = getIntersectingFacade(
ax1, cs1, buildingSegments, True
)
else:
dist1, Pint1 = getIntersectingFacade(
ax1,cs1,buildingSegments,False
)
if Pint1 is None:
log.debug("No intersection on side 1")
height1 = 0
dist1 = MAXDIST
else:
log.debug(
"Intersection1 in (%f, %f, %f)" % (
Pint1[0], Pint1[1], Pint1[2])
)
height1 = spatInd.getBuildingHeight(
Pint1[0], Pint1[1], Pint1[2], topo) + HEIGHTCORR
intersections.append(Pint1[:2])
if PLOTIND == roadInd and csInd == CSIND:
plotSegments(
ax1, buildingSegments, color='red', width=2.0
)
row, col = spatInd.getInd(
cs1MidPoint[0], cs1MidPoint[1]
)
spatInd.plotCell(
ax1, row, col, color="purple", width=2.0
)
plotSegments(
ax1,[cs1List[csInd]],color="pink",style="-",width=1.0
)
plt.draw()
cs2MidPoint = cs2.P0 + 0.5 * (cs2.P1 - cs2.P0)
buildingSegments = spatInd.getBuildingSegments(
cs2MidPoint[0], cs2MidPoint[1])
if PLOTIND == roadInd and csInd == CSIND:
plotSegments(
ax1, buildingSegments, color='red', width=2.0
)
row, col = spatInd.getInd(
cs2MidPoint[0], cs2MidPoint[1]
)
spatInd.plotCell(
ax1, row, col, color="brown", width=2.0
)
plotSegments(
ax1, [cs2List[csInd]],
color="red", style="-", width=1.0
)
plt.draw()
log.debug("Calculating intersection")
if PLOTIND == roadInd and CSIND == csInd:
dist2, Pint2 = getIntersectingFacade(
ax1, cs2, buildingSegments, True
)
else:
dist2, Pint2 = getIntersectingFacade(
ax1, cs2, buildingSegments, False
)
if Pint2 is None:
log.debug("No intersection on side 2")
height2 = 0
else:
log.debug(
"Intersection2 in (%f, %f, %f)" % (
Pint2[0], Pint2[1], Pint2[2]
)
)
height2 = spatInd.getBuildingHeight(
Pint2[0], Pint2[1], Pint2[2], topo) + HEIGHTCORR
intersections.append(Pint2[:2])
sumHeight1 += height1
sumHeight2 += height2
sumDist += dist1 + dist2
maxHeight1 = int(max(height1, maxHeight1))
maxHeight2 = int(max(height2, maxHeight2))
if PLOTIND == roadInd and CSIND == csInd:
if Pint1 is not None:
ax1.text(Pint1[0], Pint1[1], "Distance=%f" % dist1)
if Pint2 is not None:
ax1.text(Pint2[0], Pint2[1], "Distance=%f" % dist2)
avgHeight1 = int(sumHeight1 / float(nCS))
avgHeight2 = int(sumHeight2 / float(nCS))
# averaging over both sides of street
# distance refers to between facades on opposite sides
avgDist = int(round(sumDist / float(nCS)))
bAngle1, bAngle2 = road.normalAngles()
if PLOTIND > 0:
plotSegments(
ax1, road.getSegments(), color='grey', width=0.3
)
if PLOTIND == roadInd:
plotSegments(
ax1, road.getSegments(),
color='black', width=2.0
)
plotSegments(
ax1, cs1List, color="green",
style="--", width=0.5
)
plotSegments(
ax1, cs2List, color="green",
style="--", width=0.5
)
X = [intersect[0] for intersect in intersections]
Y = [intersect[1] for intersect in intersections]
if len(X) > 0:
ax1.plot(X, Y, "*")
plt.title("Road %i, cross-section %i" % (PLOTIND, CSIND))
plt.draw()
# building height as list of sectors
bsect = bheight2sect(avgHeight1, avgHeight2, bAngle1)
bsectw = bheight2sect(maxHeight1, maxHeight2, bAngle1)
outRoadFeature.SetField("BSECT", bsect)
outRoadFeature.SetField("BSECTW", bsectw)
outRoadFeature.SetField("BHGT1", avgHeight1)
outRoadFeature.SetField("BHGT2", avgHeight2)
outRoadFeature.SetField("BHGT1W", maxHeight1)
outRoadFeature.SetField("BHGT2W", maxHeight2)
outRoadFeature.SetField("BANG1", bAngle1)
outRoadFeature.SetField("BANG2", bAngle2)
outRoadFeature.SetField("BDIST", avgDist)
outRoadLayer.CreateFeature(outRoadFeature)
outRoadFeature.Destroy()
inRoadFeature.Destroy()
inRoadFeature = inRoadLayer.GetNextFeature()
roadInd += 1
inRoads = inRoadLayer.GetFeatureCount()
outRoads = outRoadLayer.GetFeatureCount()
# close datasource for building contours
inRoadFile.Destroy()
outRoadFile.Destroy()
pg.finished()
if PLOTIND > 0:
plt.show()
log.info(
"Read %i roads, wrote %i roads (created %i by splitting)" % (
inRoads, outRoads, nsplit)
)
if noGeom > 0:
log.warning("Found %i roads without geometry" % noGeom)
log.info("Finished")
if __name__ == "__main__":
sys.exit(main())