pyosmium Documentation

repository·master·Indexed 18 days ago

https://github.com/osmcode/pyosmium

Python bindings for libosmium, a C++ data processing library for OpenStreetMap (OSM) data. Version 4.3.1 provides tools for fast and flexible processing of OSM data, including the SimpleHandler, FileProcessor, and SimpleWriter. The library includes utilities for converting OSM areas to GeoJSON via GeoJSONFactory and various filtering mechanisms such as KeyFilter, TagFilter, and EntityFilter to optimize data processing performance.

Tokens
35.8K
Snippets
100
Records
153
Agent score
63%

What's inside pyosmium

  1. Getting started with pyosmium

    master

    pyosmium is a Python binding for the libosmium C++ library, designed for high-performance processing of OpenStreetMap (OSM) data. To begin using the library, you should follow the structured learning path provided in the user manual, which covers the OSM data model, geometry creation, filtering, and data writing.

    Key learning areas include:

    • The OSM Data Model: Understanding how pyosmium represents and processes OSM objects.
    • Object Data: Inspecting the contents of OSM objects.
    • Geometries: Creating points, line strings, and polygons from OSM data.
    • Filtering: Selecting specific subsets of data for processing.
    • Handlers: Using the callback-based approach for data processing.
    • Writing Data: Creating new OSM files.
    • Advanced Sources: Working with change files (diffs), history files, and replication tools.
  2. How handler-based processing works with osmium.apply

    master

    Handler-based processing involves creating a Python class that implements callback methods for different OSM entity types. You then use osmium.apply() to run these handlers against an OSM file.

    To create a handler, define a class with methods named after the entity types you want to process:

    • node(self, n)
    • way(self, w)
    • relation(self, r)
    • area(self, a)
    • changeset(self, c)

    Once defined, pass an instance of your handler to osmium.apply(filename, handler_instance).

    import osmium
    
    class PrintHandler:
        def node(self, n):
            print(n)
    
        def way(self, w):
            print(w)
    
        def relation(self, r):
            print(r)
    
        def area(self, a):
            print(a)
    
        def changeset(self, c):
            print(c)
    
    my_handler = PrintHandler()
    osmium.apply('buildings.opl', my_handler)
  3. Use mutable OSM objects for data modification

    master

    While standard OSM classes are read-only views, pyosmium provides a set of mutable classes if you need to modify OSM data. These classes allow for changes that can be written back to a file:

    • osmium.osm.mutable.OSMObject
    • osmium.osm.mutable.Node
    • osmium.osm.mutable.Way
    • osmium.osm.mutable.Relation
  4. Use the ReplicationServer for OSM data replication

    master
    The osmium.replication.ReplicationServer class is used to manage the replication of OpenStreetMap data. It works in conjunction with osmium.replication.OsmosisState to track the state of the replication process and osmium.replication.DownloadResult to handle the results of data downloads.
  5. Understand pyosmium indexing abstractions

    master

    pyosmium provides several specialized indexing structures to manage OpenStreetMap data efficiently during processing:

    • osmium.IdTracker: Used for tracking IDs of objects as they are processed.
    • osmium.index.IdSet: A specialized set for managing and looking up object IDs.
    • osmium.index.LocationTable: A table used to associate object IDs with their geographic locations (coordinates).
  6. Full vs. Simplified change files

    master

    When working with replication services, you will encounter two types of change files:

    • Full change files: Contain every intermediate version of an object if it was changed multiple times within the time span. Use these if you need the exact history of changes.
    • Simplified change files: Only keep the latest version of each object. These are typically used for updating a planet file or an extract where intermediate states are irrelevant.

    Tools like pyosmium-get-changes can produce either version.

  7. How Handlers and Handler Functions work in pyosmium

    master

    In pyosmium, data processing is driven by a Handler class. You define a class that inherits from osmium.SimpleHandler and implement specific methods (handler functions) that correspond to the OSM elements you want to process (e.g., node, way, relation).

    When you run the handler using an osmium.apply() call, the library iterates through the OSM data and calls your implemented methods whenever a matching element is encountered. This event-driven model allows you to perform complex operations like spatial filtering, attribute extraction, or data transformation in a single pass over the data.

  8. Determine the type of an OSM object

    master

    When iterating over a file using FileProcessor, you may receive different object types: nodes, ways, relations, areas, or changesets. You can identify them using three methods:

    1. Convenience functions: Use is_node(), is_way(), is_relation(), or is_area() (Note: changesets do not have these).
    2. Type identifier: Use type_str() which returns a single lowercase character.
    3. Python type checking: Use isinstance() with the corresponding osmium.osm class.

    Use type_str() when you need to check for multiple types efficiently (e.g., checking if an object is a way or a relation).

    # Method 1: Convenience functions
    for o in osmium.FileProcessor('buildings.opl'):
        if o.is_relation():
            print('Found a relation.')
    
    # Method 2: type_str()
    for o in osmium.FileProcessor('../data/buildings.opl'):
        if o.type_str() in 'wr':
            print('Found a way or relation.')
    
    # Method 3: isinstance()
    for o in osmium.FileProcessor('buildings.opl'):
        if isinstance(o, osmium.osm.Relation):
            print('Found a relation.')
  9. How filters work in pyosmium

    master

    Filters provide a high-performance way to pre-process or skip OSM data before it reaches your Python processing code.

    Key behaviors:

    • Chaining: Add multiple filters to a FileProcessor using .with_filter(). They are executed in the order they were added.
    • Immediate Dropping: If any filter marks an object for removal, it is immediately dropped and the next object is processed.
    • Side Effects: Filters can add attributes to OSM objects (e.g., GeoInterfaceFilter adds __geo_interface__) which are then visible to subsequent filters and your Python code.
    • Type Restriction: You can restrict a filter to specific OSM object types using .enable_for(). If an object doesn't match the type, the filter is skipped.

    Example: Restricting filters to specific types

    fp = osmium.FileProcessor('../data/liechtenstein.osm.pbf')\\
               .with_filter(osmium.filter.KeyFilter('place').enable_for(osmium.osm.NODE))\\
               .with_filter(osmium.filter.KeyFilter('boundary').enable_for(osmium.osm.WAY | osmium.osm.RELATION))
    fp = osmium.FileProcessor('../data/liechtenstein.osm.pbf')\
               .with_filter(osmium.filter.KeyFilter('place').enable_for(osmium.osm.NODE))\
               .with_filter(osmium.filter.KeyFilter('boundary').enable_for(osmium.osm.WAY | osmium.osm.RELATION))
  10. Handle thread safety when using pyosmium objects

    master

    Pyosmium object instances (such as an index) are not thread-safe for concurrent modifications. If you are sharing these objects across multiple threads, you must protect write accesses using exclusive locks.

    Concurrent read operations are safe and do not require locking. The library functions themselves are reentrant and can be used safely from different threads.

  11. Understand the OpenStreetMap (OSM) data model

    master

    OSM uses a topological model where objects are defined by their relationships to other objects rather than direct geometries.

    Core Components

    • Tags: A key-value store of strings common to all objects. Tags define what an object represents (e.g., building=yes).
    • Nodes: Points on the earth defined by latitude and longitude (WGS84).
    • Ways: Lines formed by a sequence of Node IDs. Ways do not contain coordinates directly; you must look up the referenced nodes to determine geometry.
    • Relations: Ordered collections of members (Nodes, Ways, or other Relations). Members can have a role (a string describing their function within the relation).

    Reference Concepts

    • Forward Reference: When an object is referenced by another (e.g., a Node appearing in a Way). Changing a node requires re-evaluating its forward references.
    • Backward Reference: Moving from a container to its children (e.g., following a Way to its constituent Nodes).
    • Reference Completeness: A state where all backward references in a dataset can be resolved.
  12. Understand the basic pyosmium types: BaseHandler and BaseFilter

    master

    pyosmium provides two primary base classes for interacting with OpenStreetMap data:

    1. osmium.BaseHandler: The primary class used to implement custom handlers for processing OSM data (nodes, ways, relations, etc.) as they are parsed.
    2. osmium.BaseFilter: Used to define filters that determine which OSM elements should be processed during a parse run.