layer module

Application layers

class layer.AddressLayer(path='Point', baseName='address', providerLib='memory', source_date=None)[source]

Bases: layer.BaseLayer

Class for address

conflate(current_address)[source]

Delete address existing in current_address

Parameters:current_address (OSM) – dataset
static create_shp(name, crs, fields=<qgis._core.QgsFields object>, geom_type=1)[source]
get_highway_names(highway=None)[source]

Returns a dictionary with the translation for each street name.

Parameters:
  • highway (HighwayLayer) – Current OSM highway data for conflation.
  • highway is None, only parse names. (If) –
Returns:

(dict) highway names translations

to_osm(data=None, tags={}, upload='never')[source]

Export to OSM

class layer.BaseLayer(path, baseName, providerLib='ogr')[source]

Bases: qgis._core.QgsVectorLayer

Base class for application layers

append(layer, rename=None, resolve=None, query=None, **kwargs)[source]

Copy all features from layer.

Parameters:
  • layer (QgsVectorLayer) – Source layer
  • rename (dict) – Translation of attributes names
  • resolve (dict) – xlink reference fields
  • query (func) – function with args feature and kwargs that returns a boolean deciding if each feature will be included or not
  • kwargs – aditional arguments for query function

Examples

>>> query = lambda feat, kwargs: feat['foo']=='bar'
Will copy only features with a value 'bar' in the field 'foo'.
>>> query = lambda feat, kwargs: layer.is_inside(feat, kwargs['zone'])
Will copy only features inside zone.

See also copy_feature().

bounding_box()[source]
copy_feature(feature, rename=None, resolve=None)[source]

Return a copy of feature renaming attributes or resolving xlink references.

Parameters:
  • feature (QgsFeature) – Source feature
  • rename (dict) – Translation of attributes names
  • resolve (dict) – xlink reference fields

Examples

With this:

>>> rename = {'spec': 'specification'}
>>> resolve = {
...     'PD_id': ('component_href', '[\w\.]+PD[\.0-9]+'),
...     'TN_id': ('component_href', '[\w\.]+TN[\.0-9]+'),
...     'AU_id': ('component_href', '[\w\.]+AU[\.0-9]+')
... }

You get:

>>> original_attributes = ['localId', 'specification', 'component_href']
>>> original_values = [
...     '38.012.1.12.0295603CS6109N',
...     'Parcel',
...     '(3:#ES.SDGC.PD.38.012.38570,#ES.SDGC.TN.38.012.1,#ES.SDGC.AU.38.012)'
... ]
>>> final_attributes = ['localId', 'spec', 'PD_id', 'TN_id', 'AU_id']
>>> final_values = [
...     '38.012.1.12.0295603CS6109N',
...     'Parcel',
...     'ES.SDGC.PD.38.012.38570',
...     'ES.SDGC.TN.38.012.1',
...     'ES.SDGC.AU.38.012'
... ]
count(expression)[source]

Returns number of features for this search expression

static create_shp(name, crs, fields=<qgis._core.QgsFields object>, geom_type=6)[source]
static delete_shp(path)[source]
export(path, driver_name='ESRI Shapefile', overwrite=True, target_crs_id=None)[source]

Write layer to file

Parameters:
  • path (str) – Path of the output file
  • driver_name (str) – Defaults to ESRI Shapefile.
  • overwrite (bool) – Defaults to True
  • target_crs_id (int) – Defaults to source CRS
get_index()[source]

Returns a QgsSpatialIndex of all features in this layer (overpass QGIS exception for void layers)

join_field(source_layer, target_field_name, join_field_name, field_names_subset, prefix='')[source]

Replaces qgis table join mechanism becouse I’m not able to work with it in standalone script mode (without GUI).

Parameters:
  • source_layer (QgsVectorLayer) – Source layer.
  • target_field_name (str) – Join field in the target layer.
  • join_fieldsName (str) – Join field in the source layer.
  • field_names_subset (list) – List of field name strings for the target layer.
  • prefix (str) – An optional prefix to add to the target fields names
reproject(target_crs=None)[source]

Reproject all features in this layer to a new CRS.

Parameters:target_crs (QgsCoordinateReferenceSystem) – New CRS to apply.
search(expression)[source]

Returns a features iterator for this search expression

to_osm(tags_translation=<function all_tags>, data=None, tags={}, upload='never', comment=None)[source]

Export this layer to an Osm data set

Parameters:
  • tags_translation (function) – Function to translate fields to tags. By defaults convert all fields.
  • data (Osm) – OSM data set to append. By default creates a new one.
  • upload (str) – upload attribute of the osm dataset, default ‘never’
  • tags (dict) – tags to update setup.changeset_tags
Returns:

OSM data set

Return type:

Osm

translate_field(field_name, translations, clean=True)[source]

Transform the values of a field

Parameters:
  • field_name (str) – Name of the field to transform
  • translations (dict) – A dictionary used to transform field values
  • clean (bool) – If true (default), delete features without translation
class layer.ConsLayer(path='Polygon', baseName='building', providerLib='memory', source_date=None)[source]

Bases: layer.PolygonLayer

Class for constructions

append_zone(layer, zone, processed, index)[source]

Append features of layer inside zone excluding processed localId’s’

clean()[source]

Delete invalid geometries and close vertices, add topological points, merge building parts and simplify vertices.

conflate(current_bu_osm, delete=True)[source]

Removes from current_bu_osm the buildings that don’t have conflicts. If delete=False, only mark buildings with conflicts

explode_multi_parts(address=False)[source]
get_parts(footprint, parts)[source]

Given a building footprint and its parts, for the parts inside the footprint returns a dictionary of parts for levels, the maximum and minimum levels

index_of_building_and_parts()[source]

Constructs some utility dicts. buildings index building by localid (call before explode_multi_parts). parts index parts of building by building localid.

index_of_parts()[source]

Index parts of building by building localid.

index_of_pools()[source]

Index pools in building parcel by building localid.

static is_building(feature)[source]

Building features have not any underscore in its localId field

static is_part(feature)[source]

Part features have ‘_part’ in its localId field

static is_pool(feature)[source]

Pool features have ‘_PI.’ in its localId field

merge_adjacent_parts(footprint, parts)[source]

Given a building footprint and its parts, for the parts inside the footprint:

  • Translates the maximum values of number of levels above and below ground to the footprint and deletes all the parts in that level.
  • Merges the adjacent parts in the rest of the levels.
merge_building_parts()[source]

Detect pools contained in a building and assign layer=1. Detect buildings/parts with geometry equals to a pool geometry and delete them. Detect inner rings of buildings/parts with geometry equals to a pool geometry and remove them. Apply merge_adjacent_parts to each set of building and its parts.

move_address(address)[source]

Move each address to the nearest point in the footprint of its associated building (same cadastral reference), but only if:

  • The address specification is Entrance.
  • The new position is enough close and is not a corner

Delete the address if the number of associated buildings is not one.

remove_inner_rings(feat1, feat2)[source]

Auxiliary method to remove feat1 or of its inner rings if equals to feat2 Returns True if feat1 must be deleted and new geometry if any ring is removed.

remove_outside_parts()[source]

Remove parts without levels above ground. Create footprint for parts without associated building. Remove parts outside the footprint of it building. Precondition: Called before merge_greatest_part.

set_tasks(uzoning, rzoning)[source]

Assings to each building and pool the task label of the zone in witch it is containd. Parts receives the label of the building it belongs. Parts without associated building are ignored

to_osm(data=None, tags={}, upload='never')[source]

Export to OSM

validate(max_level, min_level)[source]

Put fixmes to buildings with not valid geometry, too small or big. Returns distribution of floors

class layer.DebugWriter(filename, layer, driver_name='ESRI Shapefile')[source]

Bases: qgis._core.QgsVectorFileWriter

A QgsVectorFileWriter for debugging purposess.

add_point(point, note=None)[source]

Adds a point to the layer with the attribute note.

class layer.HighwayLayer(path='LineString', baseName='highway', providerLib='memory')[source]

Bases: layer.BaseLayer

Class for OSM highways

read_from_osm(data)[source]

Get features from a osm dataset

class layer.ParcelLayer(path='Polygon', baseName='cadastralparcel', providerLib='memory', source_date=None)[source]

Bases: layer.BaseLayer

Class for cadastral parcels

class layer.Point(arg1, arg2=None)[source]

Bases: qgis._core.QgsPoint

Extends QgsPoint with some utility methods

boundingBox(radius)[source]

Returns a bounding box of 2*radius centered in point.

get_angle(geom)[source]

For the vertex in a geometry nearest to this point, give the angle between its adjacent vertexs.

Parameters:geom (QgsGeometry) – Geometry to test.
Returns:(float) Angle between the vertex and their adjacents,
get_corner_context(geom, acute_thr=10, straight_thr=2, cath_thr=0.02)[source]

For the vertex in a geometry nearest to this point, give context to determine if it is a corner (the angle differs by more than straight_thr of 180 and if the distance from the vertex to the segment formed by their adjacents is greater than cath_thr).

Parameters:
  • geom (QgsGeometry) – Geometry to test.
  • acute_thr (float) – Acute angle threshold.
  • straight_thr (float) – Straight angle threshold.
  • cath_thr (float) – Cathetus threshold.
Returns:

(float) Angle between the vertex and their adjacents. (bool) True if the angle is too low (< acute_thr). (bool) True for a corner (float) Distance from the vertex to the segment formed by their adjacents.

get_spike_context(geom, acute_thr=5, straight_thr=2, threshold=0.1)[source]

For the vertex in a geometry nearest to this point, give context to determine if its a zig-zag or a spike. It’s a zig-zag if both the angles of this vertex and the closest adjacents are acute. It’s a spike if the angle of this vertex is acute and the angle of the closest vertex is not straight.

Parameters:
  • geom (QgsGeometry) – Geometry to test.
  • acute_thr (float) – Acute angle threshold.
  • straight_thr (float) – Straight angle threshold.
  • threshold (float) – # Filter for angles.
Returns:

(float) angle_v = angle between the vertex and their adjacents. (float) angle_a = angle between the closest adjacent and their adjacents. (int) ndx = index of the vertex (int) ndxa = index of the closest adjacent (bool) is_acute = True if the angle is too low (< acute_thr). (bool) is_zigzag = True if both angle_v and angle_a are acute and the distance from va to the segment v-vb is lower than threshold. (bool) is_spike = True if is_acute and angle_a is not straight and the distance from va to the segment v-vb is lower than threshold. (QgsPoint) vx = projection of va over the segment v-vb.

class layer.PolygonLayer(path, baseName, providerLib='ogr')[source]

Bases: layer.BaseLayer

Base class for polygon layers

clean()[source]

Delete invalid geometries and close vertices, add topological points and simplify vertices.

delete_invalid_geometries()[source]

Delete invalid geometries testing if any of it acute angle vertex could be deleted. Also removes zig-zag and spike vertex (see Point.get_spike_context).

difference(layer)[source]

Calculate the difference of each geometry with those in layer

explode_multi_parts(request=<qgis._core.QgsFeatureRequest object>)[source]

Creates a new WKBPolygon feature for each part of any WKBMultiPolygon feature in request. This avoid relations with may ‘outer’ members in OSM data set. From this moment, localId will not be a unique identifier for buildings.

get_adjacents_and_geometries()[source]
Returns:(list) groups of adjacent polygons
get_area()[source]

Returns total area

static get_multipolygon(feature)[source]

Returns feature geometry always as a multipolgon

static get_outer_vertices(feature)[source]

Returns list of all distinct vertices in feature geometry outer rings

get_parents_per_vertex_and_geometries()[source]
Returns:(dict) parent fids for each vertex, (dict) geometry for each fid.
static get_vertices_list(feature)[source]

Returns list of all distinct vertices in feature geometry

static merge_adjacent_features(group)[source]

Combine all geometries in group of features

merge_adjacents()[source]

Merge polygons with shared segments

simplify()[source]

Reduces the number of vertices in a polygon layer according to:

  • Delete vertex if the angle with its adjacents is near of the straight angle for less than ‘straight_thr’ degrees in all its parents.
  • Delete vertex if the distance to the segment formed by its parents is less than ‘cath_thr’ meters.
topology()[source]

For each vertex in a polygon layer, adds it to nearest segments.

class layer.ZoningLayer(pattern='{}', path='Polygon', baseName='cadastralzoning', providerLib='memory', source_date=None)[source]

Bases: layer.PolygonLayer

Class for cadastral zoning

append(layer, level=None)[source]

Append features of layer with levelName ‘M’ for rustic or ‘P’ for urban

export_poly(filename)[source]

Export as polygon file for Osmosis

set_tasks(zip_code)[source]

Assings a unique task label to each zone by overriding splitted multiparts and merged adjacent zones

layer.get_attributes(feat)
layer.is_inside(f1, f2)