Skip to content

blm.py

DistanceAddrs

DistanceAddrs(osmuri, routing)

Bases: DBExtract

Parameters:

Name Type Description Default
osmuri str

The OSM database to use

required
routing str

The PGRoutinh database to use

required

Returns:

Name Type Description
DistanceAddrs

An instance of this class

Source code in osm_merge/utilities/egress.py
 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
def __init__(self,
             osmuri: str,
             routing: str,
             ):
    """
    Initialize the database connection.

    Args:
        osmuri (str): The OSM database to use
        routing (str): The PGRoutinh database to use

    Returns:
        DistanceAddrs: An instance of this class
    """
    self.curs = None
    self.db = None
    if osmuri:
        super().__init__(osmuri)

    if routing:
        host = routing.split('/')[0]
        db = routing.split('/')[1]
        try:
            pargs = f"dbname={db}"
            if host != "localhost":
                pargs+= f" host={host}"
            self.pgrdb = psycopg2.connect(pargs)
            self.pgrcurs = self.pgrdb.cursor()
            log.info(f"Connected to database {db} on {host}")
            self.pgrdb.autocommit = True
        except Exception as e:
            log.error(f"Couldn't connect to database: {e}")
    # self.pgr = PGRouting(dbname='gilpin_routing', user='rob')
    # if self.pgr._conn   is None:
    #     log.error(f"Failed to connect to {routing} database")
    # else:
    #     log.info(f"Connected to {routing} database")

    # self.pgr.set_meta_data(cost='cost_s', reverse_cost='reverse_cost_s', directed=True)
    self.sources = list()
    self.targets = list()
    self.highways = dict()

find_nearest_vertex

find_nearest_vertex(node)

Query the PGRouting table to find the nearest node, which we assume is the driveway nearest the house. This table is only the intersections of highways, so the found node won't be something else.

Parameters:

Name Type Description Default
node str

A geometry in WKT format.

required

Returns:

Type Description
dict

The nearest node

Source code in osm_merge/utilities/egress.py
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
def find_nearest_vertex(self,
                      node: Point,
                 ) -> dict:
    """
    Query the PGRouting table to find the nearest node, which
    we assume is the driveway nearest the house. This table is
    only the intersections of highways, so the found node won't
    be something else.

    Args:
        node (str): A geometry in WKT format.

    Returns:
        (dict): The nearest node
    """
    poly = self.make_boundary(node)
    sql = f"CREATE OR REPLACE TEMP VIEW pg_view AS SELECT * FROM ways_vertices_pgr WHERE ST_CONTAINS(ST_GeomFromEWKT('SRID=4326;{poly.wkt}'), geom)"
    # print(sql)
    self.pgrcurs.execute(sql)

    threshold = 3000 # in meters
    sql = f"SELECT row_to_json(pg_view) as row FROM pg_view WHERE ST_Distance(geom, ST_GeomFromEWKT('SRID=4326;{node.wkt}')::geography) < {threshold} ORDER BY ST_Distance(geom, ST_GeomFromEWKT('SRID=4326;{node.wkt}')) LIMIT 1;"

    self.pgrcurs.execute(sql)
    result = self.pgrcurs.fetchall()

    if len(result) == 0:
        log.warning(f"No nearby verticies found within {threshold} meters!")
        return dict()

    return result[0][0]

make_buffer

make_buffer(highway, radius=1e-05)
Source code in osm_merge/utilities/egress.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def make_buffer (self,
                 highway: LineString,
                 radius: int = 0.00001,
                 ) -> Polygon:
    """
    """
    # sql = f"SELECT ST_AsText(ST_Buffer(ST_GeomFromText('SRID=4326;{highway.wkt}::geography'), {radius}, 'join=bevel'));"
    # self.pgrcurs.execute(sql)
    # result = self.pgrcurs.fetchall()
    # poly =  shapely.wkt.loads(result[0][0])

    poly = buffer(highway, radius)

    return poly

make_boundary

make_boundary(node, radius=100)
Source code in osm_merge/utilities/egress.py
149
150
151
152
153
154
155
156
157
158
159
def make_boundary(self,
                 node: Point,
                 radius: int = 100,
                 ) -> Polygon:
    """
    """
    sql = f"SELECT ST_AsText(ST_Buffer(ST_GeomFromText('{node.wkt}'), {radius}));"
    self.pgrcurs.execute(sql)
    result = self.pgrcurs.fetchall()
    poly =  shapely.wkt.loads(result[0][0])
    return poly

find_major_highways

find_major_highways()

Extract all major highways.

Source code in osm_merge/utilities/egress.py
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
def find_major_highways(self,
                    ) -> dict:
    """
    Extract all major highways.

    """
    highways = dict()
    # sql = f"SELECT osm_id,tags,ST_AsText(geom) FROM highway_view WHERE tags->>'highway'='primary' OR tags->>'highway'='tertiary' OR tags->>'highway'='secondary'"
    sql = f"SELECT osm_id,tags,ST_AsText(geom) FROM highway_view WHERE tags->>'highway'='primary' OR tags->>'highway'='secondary'"
    print(f"ROUTE: {sql}")
    major = self.execute_query(sql)

    tags = ["osm_id", "tags", "geom", "distance"]
    # Combine all the LineStrings
    for entry in major:
        highway = dict(zip(tags, entry))
        key = str()
        if "name" not in highway["tags"]:
            name = "unknown"
        elif "name" in highway["tags"]:
            name = highway["tags"]["name"]
        elif "ref" in highway["tags"]:
            name = highway["tags"]["ref"]

        if name not in highways:
            highways[name] = dict()
            highways[name]["lines"] = list()
            highways[name]["tags"] = highway["tags"]

        highways[name]["lines"].append(highway["geom"])
    for name, segments in highways.items():
        multi = list()
        for line in segments["lines"]:
            multi.append(shapely.wkt.loads(line))
        all = MultiLineString(multi)
        highline = ops.linemerge(all)
        highways[name]["buffer"] = self.make_buffer(highline)
        verts = self.get_vertics(name)

    return highways

get_targets

get_targets(node, highways, threshold=10.0)
Source code in osm_merge/utilities/egress.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def get_targets(self,
                node: Point,
                highways: MultiPolygon,
                threshold: float = 10.0,
                ) -> list:
    """
    """
    targets = list()
    # sql = f"SELECT id,ST_DISTANCE(ST_GeomFromEWKT('SRID=4326;POINT (-105.4970686 39.917249)'), geom) AS distance FROM ways_vertices_pgr WHERE ST_DISTANCE(ST_GeomFromEWKT('SRID=4326;{node.wkt}'), geom) < {threshold} ORDER BY distance;"
    sql = f"SELECT id,ST_DISTANCE(ST_GeomFromEWKT('SRID=4326;{node.wkt}'), geom::geography) AS distance FROM ways_vertices_pgr WHERE ST_Contains(ST_GeomFromEWKT('SRID=4326;{highways.wkt}'), geom) ORDER BY distance LIMIT 10;"
    # sql = f"SELECT id,ST_DISTANCE(ST_GeomFromEWKT('SRID=4326;{highways.wkt}'), geom) AS distance FROM ways_vertices_pgr WHERE ST_Contains(ST_GeomFromEWKT('SRID=4326;{highways.wkt}'), geom) ORDER BY distance;"
    # print(sql)
    self.pgrcurs.execute(sql)

    result = self.pgrcurs.fetchall()
    vertices = dict()
    for row in result:
        vertices[row[0]] = row[1]

    return vertices

make_route

make_route(source, targets)

Use PGRouting to generate a list of rouing options.

Parameters:

Name Type Description Default
source int

The ID of the target in the ways_vertices_pgr table

required
targets dict

The list of target IDs in the ways_vertices_pgr table

required

Returns:

Type Description
list

the list of possible routes to analyze

Source code in osm_merge/utilities/egress.py
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
def make_route(self,
               source: int,
               targets: dict,
               ) -> list:
    """
    Use PGRouting to generate a list of rouing options.

    Args:
        source (int): The ID of the target in the ways_vertices_pgr table
        targets (dict): The list of target IDs in the ways_vertices_pgr table

    Returns:
        (list): the list of possible routes to analyze
    """
    routes = list()
    nodes = list()
    for id, dist in targets.items():
        nodes.append(id)

    if len(targets) == 0:
        log.warning(f"No targets for source {source}!")
        return routes
    sql = f"SELECT res.path_seq, res.node, res.edge, ST_AsText(e.geom), res.cost, e.reverse_cost, e.reverse_cost_s FROM pgr_dijkstra('SELECT id as id, source, target, cost_s AS cost FROM ways', {source}, ARRAY{nodes}, directed := false) AS res JOIN ways e ON res.edge = e.id;"
    # sql = f"SELECT res.end_vid, res.node, e.cost_s, ST_AsText(e.geom) FROM pgr_dijkstra('SELECT id as id, source, target, length_m as cost FROM ways', {source}, {target}, directed := false) AS res JOIN ways e ON res.edge = e.id;"
    self.pgrcurs.execute(sql)
    result = self.pgrcurs.fetchall()
    # print(sql)

    tags = ["sequence", "node", "edge", "geom", "cost", "reverse_cost", "reverse_cost_s"]
    route = list()
    previous = 1
    # Multiple routes are in the result, so we have to check for the transition
    # and store them all seperately.
    for row in result:
        data = dict(zip(tags, row))
        if int(data["sequence"]) < previous:
            routes.append(route)
        if int(data["sequence"]) == 1:
            route = list()
        previous = int(data["sequence"])
        route.append(data)

    return routes

get_vertics

get_vertics(name)
Source code in osm_merge/utilities/egress.py
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
def get_vertics(self,
                name: str,
                ) -> bool:
    """
    """
    sources = list()
    targets = list()
    try:
        sql = f"SELECT id, source, target, ST_AsText(geom) FROM ways WHERE name='{name}'"
        self.pgrcurs.execute(sql)
        result = self.pgrcurs.fetchall()
    except:
        breakpoint()
    for row in result:
        if name not in self.highways:
            self.highways[name] = dict()
            self.highways[name]["sources"] = list()
            self.highways[name]["targets"] = list()
        self.highways[name]["sources"].append(row[1])
        self.highways[name]["targets"].append(row[2])

    # if len(self.sources) == 0 or len(self.targets) == 0:
    #     log.error(f"No source or targets found!")
    #     return False

    return True

get_addrs

get_addrs(street)

Get all the addresses in the boundary.

Parameters:

Name Type Description Default
street str

The street name from OSM

required

Returns:

Type Description
list

All the addresses on this street

Source code in osm_merge/utilities/egress.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
def get_addrs(self,
              street: str,
              ) -> list:
    """
    Get all the addresses in the boundary.

    Args:
        street (str): The street name from OSM

    Returns:
        (list): All the addresses on this street
    """
    addrs = list()
    sql = f"SELECT tags->>'addr:housenumber', ST_AsText(geom) AS geom FROM address_view WHERE tags->>'addr:street'='{street}';"
    result = self.execute_query(sql, "address_view")
    if len(result) > 0:
        for entry in result:
            number = entry[0]
            geom = entry[1]
            addrs.append({"street": street, "number": number, "geom": geom})

    return addrs

get_highways

get_highways(name)
Source code in osm_merge/utilities/egress.py
317
318
319
320
321
322
def get_highways(self,
                name: str,
                ) -> list:
    """
    """
    sql = "SELECT "

make_track

make_track(route, targets)
Source code in osm_merge/utilities/egress.py
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
def make_track(self,
              route: list,
              targets: list,
              ):
    """

    """
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    for segment in route:
        source = int(segment["edge"])
        target = segment["node"]
        line = shapely.wkt.loads(segment["geom"])
        sql = f"SELECT ST_AsText(geom) FROM ways WHERE ST_CONTAINS(geom, ST_GeomFromEWKT('SRID=4326;{segment["geom"]}'));"
        self.pgrcurs.execute(sql)
        result = self.pgrcurs.fetchall()
        # sql = f"SELECT ST_AsText(geom), refs FROM ways_line WHERE ST_CONTAINS(geom, ST_GeomFromEWKT('{segment["geom"]}'));"
        # self.curs.execute(sql)
        # result = self.curs.fetchall()
        node = line.coords[0]
        # multi = list()
        if len(result) > 0:
            osm = shapely.wkt.loads(result[0][0])
            # for point in osm.coords:
            inter = line.intersection(osm)
            if inter.geom_type == 'MultiLineString':
                inter = ops.linemerge(inter)
            # print(f"BARRRRR: {inter}")
            #for pt in inter.coords:
            #    gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(pt[1], pt[0]))
            #if line.contains(Point(point)):
            # multi.append(line.intersection(osm))
            # print(f"FOOOO: {point} {line.contains(Point(point))}")
            # gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(point[1], point[0]))
        # all = MultiLineString(multi)
        # highline = ops.linemerge(all)

        # for pt in inter.coords:
            #gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(pt[1], pt[0]))
        gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(node[1], node[0]))
        for name, data in self.highways.items():
            if segment["node"] in data["targets"]:
                # print(f"FOO: {name} {segment["node"]} {start}, {end}: {segment["node"] in data["targets"]}")
                return gpx_segment, True

    return gpx_segment, True
        #segline = shapely.wkt.loads(segment["geom"])
        # try:
        #     highline = shapely.wkt.loads(highway["geom"])
        # except:
        #     breakpoint()
        # print(f"LEN: {highway.length}")
    # geom = shapely.wkt.loads(segment[4])
    # print(f"FIXME:  {target}: {target in verts}")
    # print(f"FIXME:  {target}: {highline.touches(segline)}")
    # print(f"FIXME1: {target}: {segline.intersects(highline)}")
    # print(f"FIXME2: {target}: {segline.within(highline)}")

    sql = f"SELECT name, osm_id, source, target, length, x1,y1,x2,y2, cost, cost_s FROM ways WHERE target='{target}' AND source!='{source}'"
    self.pgrcurs.execute(sql)
    result = self.pgrcurs.fetchall()
    tags = ["name", "osm_id", "source", "target", "length", "x1", "y1", "x2", "y2", "cost", "cost_s"]
    if len(result) != 0:
        data = dict(zip(tags, result[0]))
    else:
        data = dict(zip(tags, [0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]))
    done = False
    print(f"DATA: {data}")

    return gpx_segment, done

main

main()

This program queries a postgres database as to plot potenial emergency egress routes.

Source code in osm_merge/utilities/egress.py
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
def main():
    """
    This program queries a postgres database as to plot potenial emergency egress routes.
    """
    parser = argparse.ArgumentParser(
        prog="egress",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        description="Calculate route to the nearest decent highway",
        epilog="""
This program uses OpenStreetMap data to calculate egress routes to ther nearest
decent hoghway for mass evacuation during an emergency. Decent being primary,
secondary, or tertiary. This produces a GPX file with the route suggestions, one
for each address in the AOI.

  For example:

	egress.py -v -u localhost/colorado -r localhost/gilpin_routing -b boundaries/Gilpin.geojson

    --boundary
        Must be a MultiPolygon or Polygon.
    --osmuri
        OSM data imported with osm-rawdata's importer program
    --routedb
        Imported with the osm2pgrouting program in PGRouting

""",
    )
    parser.add_argument("-v", "--verbose", nargs="?", const="0", help="verbose output")
    parser.add_argument("-b","--boundary", help='Optional boundary to clip the data')
    parser.add_argument("-o","--outfile", default='out.csv', help='The output file')
    parser.add_argument("-u", "--osmuri", help="OSM Database URI")
    parser.add_argument("-r", "--routedb", help="PGRouting Database URI")

    args = parser.parse_args()

    # Need at least one operation
    if len(argv) == 1:
        parser.print_help()
        quit()

    # if verbose, dump to the terminal
    if args.verbose is not None:
        logging.basicConfig(
            level=logging.DEBUG,
            format=("%(threadName)10s - %(name)s - %(levelname)s - %(message)s"),
            datefmt="%y-%m-%d %H:%M:%S",
            stream=sys.stdout,
        )

    db = DistanceAddrs(args.osmuri, args.routedb)

    # Make a temporary view to reduce the data size
    if args.boundary:
        db.create_highway_view(args.boundary)
        db.create_address_view(args.boundary)
    else:
        db.create_highway_view()
        db.create_address_view()

    highway_views = db.list_views("highway")
    # print(highway_views)

    addr_views = db.list_views("address")
    # print(addr_views)
    if len(highway_views) == 0 and len(addr_views) == 0:
        log.error(f"No data in the database views!")

    # Query the database for what we want
    sql = f"SELECT osm_id,version,timestamp,refs,tags,ST_AsTEXT(geom) FROM "
    rows = db.execute_query(sql)
    if len(rows) == 0:
        log.error(f"No data returned from the query!")
        return

    highset = set()
    for highway in rows:
        tags = highway[4]
        # FIXME: only needed for non OSM data
        if "name" in tags:
            #     new = ca.convert(tags["name"])
            highset.add(tags["name"])

    # colors = {"route1": "#ff5020", "route2": "#ff5020", "route 3": "#a71de1"}

    # Use GPX instead of GeoJson so we can specify the line color
    major = db.find_major_highways()
    polys = list()
    for name, values in major.items():
        polys.append(values["buffer"])
        db.get_vertics(name)
        aoi = unary_union(polys)

    nsmap = {'gpxx': 'http://www.garmin.com/xmlschemas/GpxExtensions/v3'}
    for name in sorted(highset):
        # Embedded single quotes are evil
        name = name.replace("'", "\"")
        addrs = db.get_addrs(name)
        if len(addrs) == 0:
            log.warning(f"No addresses found on {name}")
            continue
        else:
            log.debug(f"Found {len(addrs)} addresses for {name}")
        for addr in addrs:
            gpx = gpxpy.gpx.GPX()
            gpx.nsmap = {'gpxx': 'http://www.garmin.com/xmlschemas/GpxExtensions/v3'}
            gpx.creator = "distance_addrs 0.1"
            # print(f"ADDR: {addr}")
            node = shapely.wkt.loads(addr["geom"])
            # print(f"NODE: {node.y}, {node.x}")
            nearest = db.find_nearest_vertex(node)
            # print(f"NEAREST: {nearest}")
            # highway = db.find_nearest_highway(nearest)
            # print(f"HIGHWAY: {highway}")
            if node is None or len(highway) == 0:
                log.warning(f"No suitable highways were found near {node}")
                continue
            pt = shape(nearest["geom"])
            targets = db.get_targets(pt, aoi)

            # print(f"TARGETS: {targets}")
            if targets == 0:
                log.warning(f"No targets found for {highway}")
                continue
            routes = db.make_route(nearest["id"], targets)
            log.debug(f"There are {len(routes)} routes in the result.")
            length = 0
            for route in routes:
                gpx_track = gpxpy.gpx.GPXTrack()
                gpx_track.name = f"{addr["number"]} {addr["street"]} Track #{routes.index(route)}"
                gpx.tracks.append(gpx_track)
                cnt = len(route) - 1
                # print(f"ROUTE: {route[0]["node"]}, {route[0]["edge"]} : {route[cnt]["node"]}, {route[cnt]["edge"]}")
                part, done = db.make_track(route, targets)
                gpx_track.segments.append(part)
                # Make the first point in the track be the address node so it's clear
                # which house uses which route.
            try:
                gpx.tracks[0].segments[0].points.insert(0, gpxpy.gpx.GPXTrackPoint(node.y, node.x))
            except:
                # breakpoint()
                pass
            outfile = f"{addr["number"]}_{addr["street"].replace(" ", "_")}.gpx"
            dist = etree.Element("{gpxx}length", nsmap=nsmap)
            dist.text = f"Length {gpx_track.length_2d():.3f} meters or {(gpx_track.length_2d() / 0.3048):.3f} feet"
            gpx_track.extensions.append(dist)
            with open(outfile, "w") as gpxfile:
                gpxfile.write(gpx.to_xml())
            log.debug(f"Wrote {outfile}")

options: show_source: false heading_level: 3