network_wrangler.utils
Functions
|
Creates a geometry as a LineString using location reference |
|
Creates a location reference using the node a and node b coordinates |
|
Creates a unique hash id using the coordinates of the geomtery |
|
calculate the bearing (forward azimuth) b/w the two points |
|
Calculates haversine distance between two points |
|
Export pandas dataframe as a json object. |
|
makes a slug from text |
|
Creates a new location reference using the node a and node b of given location reference, offseting it by 90 degree to the bearing of given location reference and distance equals to offset_meters |
|
Get the new lat long (in degrees) given current point (lat/lon), distance and bearing |
|
parse time spans into tuples of seconds from midnight can also be used as an apply function for a pandas series :param times: :type times: tuple(string) or tuple(int) or list(string) or list(int) |
|
Author: Geoff Boeing: https://geoffboeing.com/2015/10/exporting-python-data-geojson/ |
|
Topological sorting for Acyclic Directed Graph |
|
Updates specific fields of a dataframe with another dataframe using a key column. |
- class network_wrangler.utils.Geodesic(a, f)[source]
Bases:
object
Solve geodesic problems
- ArcDirect(lat1, lon1, azi1, a12, outmask=1929)[source]
Solve the direct geodesic problem in terms of spherical arc length
- Parameters:
lat1 – latitude of the first point in degrees
lon1 – longitude of the first point in degrees
azi1 – azimuth at the first point in degrees
a12 – spherical arc length from the first point to the second in degrees
outmask – the output mask
- Returns:
a dict
Compute geodesic starting at (lat1, lon1) with azimuth azi1 and arc length a12. The default value of outmask is STANDARD, i.e., the lat1, lon1, azi1, lat2, lon2, azi2, s12, a12 entries are returned.
- ArcDirectLine(lat1, lon1, azi1, a12, caps=3979)[source]
Define a GeodesicLine object in terms of the direct geodesic problem specified in terms of spherical arc length
- Parameters:
lat1 – latitude of the first point in degrees
lon1 – longitude of the first point in degrees
azi1 – azimuth at the first point in degrees
a12 – spherical arc length from the first point to the second in degrees
caps – the capabilities
- Returns:
a
GeodesicLine
This function sets point 3 of the GeodesicLine to correspond to point 2 of the direct geodesic problem. The default value of caps is STANDARD | DISTANCE_IN, allowing direct geodesic problem to be solved.
- Direct(lat1, lon1, azi1, s12, outmask=1929)[source]
Solve the direct geodesic problem
- Parameters:
lat1 – latitude of the first point in degrees
lon1 – longitude of the first point in degrees
azi1 – azimuth at the first point in degrees
s12 – the distance from the first point to the second in meters
outmask – the output mask
- Returns:
a dict
Compute geodesic starting at (lat1, lon1) with azimuth azi1 and length s12. The default value of outmask is STANDARD, i.e., the lat1, lon1, azi1, lat2, lon2, azi2, s12, a12 entries are returned.
- DirectLine(lat1, lon1, azi1, s12, caps=3979)[source]
Define a GeodesicLine object in terms of the direct geodesic problem specified in terms of spherical arc length
- Parameters:
lat1 – latitude of the first point in degrees
lon1 – longitude of the first point in degrees
azi1 – azimuth at the first point in degrees
s12 – the distance from the first point to the second in meters
caps – the capabilities
- Returns:
a
GeodesicLine
This function sets point 3 of the GeodesicLine to correspond to point 2 of the direct geodesic problem. The default value of caps is STANDARD | DISTANCE_IN, allowing direct geodesic problem to be solved.
- Inverse(lat1, lon1, lat2, lon2, outmask=1929)[source]
Solve the inverse geodesic problem
- Parameters:
lat1 – latitude of the first point in degrees
lon1 – longitude of the first point in degrees
lat2 – latitude of the second point in degrees
lon2 – longitude of the second point in degrees
outmask – the output mask
- Returns:
a dict
Compute geodesic between (lat1, lon1) and (lat2, lon2). The default value of outmask is STANDARD, i.e., the lat1, lon1, azi1, lat2, lon2, azi2, s12, a12 entries are returned.
- InverseLine(lat1, lon1, lat2, lon2, caps=3979)[source]
Define a GeodesicLine object in terms of the invese geodesic problem
- Parameters:
lat1 – latitude of the first point in degrees
lon1 – longitude of the first point in degrees
lat2 – latitude of the second point in degrees
lon2 – longitude of the second point in degrees
caps – the capabilities
- Returns:
a
GeodesicLine
This function sets point 3 of the GeodesicLine to correspond to point 2 of the inverse geodesic problem. The default value of caps is STANDARD | DISTANCE_IN, allowing direct geodesic problem to be solved.
- Line(lat1, lon1, azi1, caps=3979)[source]
Return a GeodesicLine object
- Parameters:
lat1 – latitude of the first point in degrees
lon1 – longitude of the first point in degrees
azi1 – azimuth at the first point in degrees
caps – the capabilities
- Returns:
a
GeodesicLine
This allows points along a geodesic starting at (lat1, lon1), with azimuth azi1 to be found. The default value of caps is STANDARD | DISTANCE_IN, allowing direct geodesic problem to be solved.
- Polygon(polyline=False)[source]
Return a PolygonArea object
- Parameters:
polyline – if True then the object describes a polyline instead of a polygon
- Returns:
a
PolygonArea
- ALL = 32671
All of the above.
- AREA = 16400
Calculate area S12.
- AZIMUTH = 512
Calculate azimuths azi1 and azi2.
- CAP_ALL = 31
- CAP_C1 = 1
- CAP_C1p = 2
- CAP_C2 = 4
- CAP_C3 = 8
- CAP_C4 = 16
- CAP_MASK = 31
- CAP_NONE = 0
- DISTANCE = 1025
Calculate distance s12.
- DISTANCE_IN = 2051
Allow distance s12 to be used as input in the direct geodesic problem.
- EMPTY = 0
No capabilities, no output.
- GEODESICSCALE = 8197
Calculate geodesic scales M12 and M21.
- GEOGRAPHICLIB_GEODESIC_ORDER = 6
- LATITUDE = 128
Calculate latitude lat2.
- LONGITUDE = 264
Calculate longitude lon2.
- LONG_UNROLL = 32768
Unroll longitudes, rather than reducing them to the range [-180d,180d].
- OUT_ALL = 32640
- OUT_MASK = 65408
- REDUCEDLENGTH = 4101
Calculate reduced length m12.
- STANDARD = 1929
All of the above.
- WGS84 = <geographiclib.geodesic.Geodesic object>
- a
The equatorial radius in meters (readonly)
- f
The flattening (readonly)
- maxit1_ = 20
- maxit2_ = 83
- nA1_ = 6
- nA2_ = 6
- nA3_ = 6
- nA3x_ = 6
- nC1_ = 6
- nC1p_ = 6
- nC2_ = 6
- nC3_ = 6
- nC3x_ = 15
- nC4_ = 6
- nC4x_ = 21
- tiny_ = 1.4916681462400413e-154
- tol0_ = 2.220446049250313e-16
- tol1_ = 4.440892098500626e-14
- tol2_ = 1.4901161193847656e-08
- tolb_ = 3.308722450212111e-24
- xthresh_ = 1.4901161193847656e-05
- class network_wrangler.utils.LineString(coordinates=None)[source]
Bases:
BaseGeometry
A geometry type composed of one or more line segments.
A LineString is a one-dimensional feature and has a non-zero length but zero area. It may approximate a curve and need not be straight. Unlike a LinearRing, a LineString is not closed.
- Parameters:
coordinates (sequence) – A sequence of (x, y, [,z]) numeric coordinate pairs or triples, or an array-like with shape (N, 2) or (N, 3). Also can be a sequence of Point objects.
Examples
Create a LineString with two segments
>>> a = LineString([[0, 0], [1, 0], [1, 1]]) >>> a.length 2.0
- almost_equals(other, decimal=6)
True if geometries are equal at all coordinates to a specified decimal place.
Deprecated since version 1.8.0: The ‘almost_equals()’ method is deprecated and will be removed in Shapely 2.1 because the name is confusing. The ‘equals_exact()’ method should be used instead.
Refers to approximate coordinate equality, which requires coordinates to be approximately equal and in the same order for all components of a geometry.
Because of this it is possible for “equals()” to be True for two geometries and “almost_equals()” to be False.
Examples
>>> LineString( ... [(0, 0), (2, 2)] ... ).equals_exact( ... LineString([(0, 0), (1, 1), (2, 2)]), ... 1e-6 ... ) False
- Return type:
bool
- buffer(distance, quad_segs=16, cap_style='round', join_style='round', mitre_limit=5.0, single_sided=False, **kwargs)
Get a geometry that represents all points within a distance of this geometry.
A positive distance produces a dilation, a negative distance an erosion. A very small or zero distance may sometimes be used to “tidy” a polygon.
- Parameters:
distance (float) – The distance to buffer around the object.
resolution (int, optional) – The resolution of the buffer around each vertex of the object.
quad_segs (int, optional) – Sets the number of line segments used to approximate an angle fillet.
cap_style (shapely.BufferCapStyle or {'round', 'square', 'flat'}, default 'round') – Specifies the shape of buffered line endings. BufferCapStyle.round (‘round’) results in circular line endings (see
quad_segs
). Both BufferCapStyle.square (‘square’) and BufferCapStyle.flat (‘flat’) result in rectangular line endings, only BufferCapStyle.flat (‘flat’) will end at the original vertex, while BufferCapStyle.square (‘square’) involves adding the buffer width.join_style (shapely.BufferJoinStyle or {'round', 'mitre', 'bevel'}, default 'round') – Specifies the shape of buffered line midpoints. BufferJoinStyle.ROUND (‘round’) results in rounded shapes. BufferJoinStyle.bevel (‘bevel’) results in a beveled edge that touches the original vertex. BufferJoinStyle.mitre (‘mitre’) results in a single vertex that is beveled depending on the
mitre_limit
parameter.mitre_limit (float, optional) – The mitre limit ratio is used for very sharp corners. The mitre ratio is the ratio of the distance from the corner to the end of the mitred offset corner. When two line segments meet at a sharp angle, a miter join will extend the original geometry. To prevent unreasonable geometry, the mitre limit allows controlling the maximum length of the join corner. Corners with a ratio which exceed the limit will be beveled.
single_side (bool, optional) –
The side used is determined by the sign of the buffer distance:
a positive distance indicates the left-hand side a negative distance indicates the right-hand side
The single-sided buffer of point geometries is the same as the regular buffer. The End Cap Style for single-sided buffers is always ignored, and forced to the equivalent of CAP_FLAT.
quadsegs (int, optional) – Deprecated alias for quad_segs.
- Return type:
Geometry
Notes
The return value is a strictly two-dimensional geometry. All Z coordinates of the original geometry will be ignored.
Examples
>>> from shapely.wkt import loads >>> g = loads('POINT (0.0 0.0)')
16-gon approx of a unit radius circle:
>>> g.buffer(1.0).area 3.1365484905459...
128-gon approximation:
>>> g.buffer(1.0, 128).area 3.141513801144...
triangle approximation:
>>> g.buffer(1.0, 3).area 3.0 >>> list(g.buffer(1.0, cap_style=BufferCapStyle.square).exterior.coords) [(1.0, 1.0), (1.0, -1.0), (-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)] >>> g.buffer(1.0, cap_style=BufferCapStyle.square).area 4.0
- contains(other)
Returns True if the geometry contains the other, else False
- contains_properly(other)
Returns True if the geometry completely contains the other, with no common boundary points, else False
Refer to shapely.contains_properly for full documentation.
- covered_by(other)
Returns True if the geometry is covered by the other, else False
- covers(other)
Returns True if the geometry covers the other, else False
- crosses(other)
Returns True if the geometries cross, else False
- difference(other, grid_size=None)
Returns the difference of the geometries.
Refer to shapely.difference for full documentation.
- disjoint(other)
Returns True if geometries are disjoint, else False
- distance(other)
Unitless distance to other geometry (float)
- dwithin(other, distance)
Returns True if geometry is within a given distance from the other, else False.
Refer to shapely.dwithin for full documentation.
- equals(other)
Returns True if geometries are equal, else False.
This method considers point-set equality (or topological equality), and is equivalent to (self.within(other) & self.contains(other)).
Examples
>>> LineString( ... [(0, 0), (2, 2)] ... ).equals( ... LineString([(0, 0), (1, 1), (2, 2)]) ... ) True
- Return type:
bool
- equals_exact(other, tolerance)
True if geometries are equal to within a specified tolerance.
- Parameters:
other (BaseGeometry) – The other geometry object in this comparison.
tolerance (float) – Absolute tolerance in the same units as coordinates.
equality (This method considers coordinate) –
requires (which) –
components (coordinates to be equal and in the same order for all) –
geometry. (of a) –
two (Because of this it is possible for "equals()" to be True for) –
False. (geometries and "equals_exact()" to be) –
Examples
>>> LineString( ... [(0, 0), (2, 2)] ... ).equals_exact( ... LineString([(0, 0), (1, 1), (2, 2)]), ... 1e-6 ... ) False
- Return type:
bool
- geometryType()
- hausdorff_distance(other)
Unitless hausdorff distance to other geometry (float)
- interpolate(distance, normalized=False)
Return a point at the specified distance along a linear geometry
Negative length values are taken as measured in the reverse direction from the end of the geometry. Out-of-range index values are handled by clamping them to the valid range of values. If the normalized arg is True, the distance will be interpreted as a fraction of the geometry’s length.
Alias of line_interpolate_point.
- intersection(other, grid_size=None)
Returns the intersection of the geometries.
Refer to shapely.intersection for full documentation.
- intersects(other)
Returns True if geometries intersect, else False
- line_interpolate_point(distance, normalized=False)
Return a point at the specified distance along a linear geometry
Negative length values are taken as measured in the reverse direction from the end of the geometry. Out-of-range index values are handled by clamping them to the valid range of values. If the normalized arg is True, the distance will be interpreted as a fraction of the geometry’s length.
Alias of interpolate.
- line_locate_point(other, normalized=False)
Returns the distance along this geometry to a point nearest the specified point
If the normalized arg is True, return the distance normalized to the length of the linear geometry.
Alias of project.
- normalize()
Converts geometry to normal form (or canonical form).
This method orders the coordinates, rings of a polygon and parts of multi geometries consistently. Typically useful for testing purposes (for example in combination with equals_exact).
Examples
>>> from shapely import MultiLineString >>> line = MultiLineString([[(0, 0), (1, 1)], [(3, 3), (2, 2)]]) >>> line.normalize() <MULTILINESTRING ((2 2, 3 3), (0 0, 1 1))>
- offset_curve(distance, quad_segs=16, join_style=BufferJoinStyle.round, mitre_limit=5.0)[source]
Returns a LineString or MultiLineString geometry at a distance from the object on its right or its left side.
The side is determined by the sign of the distance parameter (negative for right side offset, positive for left side offset). The resolution of the buffer around each vertex of the object increases by increasing the quad_segs keyword parameter.
The join style is for outside corners between line segments. Accepted values are JOIN_STYLE.round (1), JOIN_STYLE.mitre (2), and JOIN_STYLE.bevel (3).
The mitre ratio limit is used for very sharp corners. It is the ratio of the distance from the corner to the end of the mitred offset corner. When two line segments meet at a sharp angle, a miter join will extend far beyond the original geometry. To prevent unreasonable geometry, the mitre limit allows controlling the maximum length of the join corner. Corners with a ratio which exceed the limit will be beveled.
Note: the behaviour regarding orientation of the resulting line depends on the GEOS version. With GEOS < 3.11, the line retains the same direction for a left offset (positive distance) or has reverse direction for a right offset (negative distance), and this behaviour was documented as such in previous Shapely versions. Starting with GEOS 3.11, the function tries to preserve the orientation of the original line.
- overlaps(other)
Returns True if geometries overlap, else False
- parallel_offset(distance, side='right', resolution=16, join_style=BufferJoinStyle.round, mitre_limit=5.0)[source]
Alternative method to
offset_curve()
method.Older alternative method to the
offset_curve()
method, but usesresolution
instead ofquad_segs
and aside
keyword (‘left’ or ‘right’) instead of sign of the distance. This method is kept for backwards compatibility for now, but is is recommended to useoffset_curve()
instead.
- point_on_surface()
Returns a point guaranteed to be within the object, cheaply.
Alias of representative_point.
- project(other, normalized=False)
Returns the distance along this geometry to a point nearest the specified point
If the normalized arg is True, return the distance normalized to the length of the linear geometry.
Alias of line_locate_point.
- relate(other)
Returns the DE-9IM intersection matrix for the two geometries (string)
- relate_pattern(other, pattern)
Returns True if the DE-9IM string code for the relationship between the geometries satisfies the pattern, else False
- representative_point()
Returns a point guaranteed to be within the object, cheaply.
Alias of point_on_surface.
- reverse()
Returns a copy of this geometry with the order of coordinates reversed.
If the geometry is a polygon with interior rings, the interior rings are also reversed.
Points are unchanged.
See also
is_ccw
Checks if a geometry is clockwise.
Examples
>>> from shapely import LineString, Polygon >>> LineString([(0, 0), (1, 2)]).reverse() <LINESTRING (1 2, 0 0)> >>> Polygon([(0, 0), (1, 0), (1, 1), (0, 1), (0, 0)]).reverse() <POLYGON ((0 0, 0 1, 1 1, 1 0, 0 0))>
- segmentize(max_segment_length)
Adds vertices to line segments based on maximum segment length.
Additional vertices will be added to every line segment in an input geometry so that segments are no longer than the provided maximum segment length. New vertices will evenly subdivide each segment.
Only linear components of input geometries are densified; other geometries are returned unmodified.
- Parameters:
max_segment_length (float or array_like) – Additional vertices will be added so that all line segments are no longer this value. Must be greater than 0.
Examples
>>> from shapely import LineString, Polygon >>> LineString([(0, 0), (0, 10)]).segmentize(max_segment_length=5) <LINESTRING (0 0, 0 5, 0 10)> >>> Polygon([(0, 0), (10, 0), (10, 10), (0, 10), (0, 0)]).segmentize(max_segment_length=5) <POLYGON ((0 0, 5 0, 10 0, 10 5, 10 10, 5 10, 0 10, 0 5, 0 0))>
- simplify(tolerance, preserve_topology=True)
Returns a simplified geometry produced by the Douglas-Peucker algorithm
Coordinates of the simplified geometry will be no more than the tolerance distance from the original. Unless the topology preserving option is used, the algorithm may produce self-intersecting or otherwise invalid geometries.
- svg(scale_factor=1.0, stroke_color=None, opacity=None)[source]
Returns SVG polyline element for the LineString geometry.
- Parameters:
scale_factor (float) – Multiplication factor for the SVG stroke-width. Default is 1.
stroke_color (str, optional) – Hex string for stroke color. Default is to use “#66cc99” if geometry is valid, and “#ff3333” if invalid.
opacity (float) – Float number between 0 and 1 for color opacity. Default value is 0.8
- symmetric_difference(other, grid_size=None)
Returns the symmetric difference of the geometries.
Refer to shapely.symmetric_difference for full documentation.
- touches(other)
Returns True if geometries touch, else False
- union(other, grid_size=None)
Returns the union of the geometries.
Refer to shapely.union for full documentation.
- within(other)
Returns True if geometry is within the other, else False
- property area
Unitless area of the geometry (float)
- property boundary
Returns a lower dimension geometry that bounds the object
The boundary of a polygon is a line, the boundary of a line is a collection of points. The boundary of a point is an empty (null) collection.
- property bounds
Returns minimum bounding region (minx, miny, maxx, maxy)
- property centroid
Returns the geometric center of the object
- property convex_hull
that’s a convex hull, more or less
The convex hull of a three member multipoint, for example, is a triangular polygon.
- Type:
Imagine an elastic band stretched around the geometry
- property coords
Access to geometry’s coordinates (CoordinateSequence)
- property envelope
A figure that envelopes the geometry
- property geom_type
Name of the geometry’s type, such as ‘Point’
- property has_z
True if the geometry’s coordinate sequence(s) have z values (are 3-dimensional)
- property is_closed
True if the geometry is closed, else False
Applicable only to 1-D geometries.
- property is_empty
True if the set of points in this geometry is empty, else False
- property is_ring
True if the geometry is a closed ring, else False
- property is_simple
True if the geometry is simple, meaning that any self-intersections are only at boundary points, else False
- property is_valid
True if the geometry is valid (definition depends on sub-class), else False
- property length
Unitless length of the geometry (float)
- property minimum_clearance
Unitless distance by which a node could be moved to produce an invalid geometry (float)
- property minimum_rotated_rectangle
Returns the oriented envelope (minimum rotated rectangle) that encloses the geometry.
Unlike envelope this rectangle is not constrained to be parallel to the coordinate axes. If the convex hull of the object is a degenerate (line or point) this degenerate is returned.
Alias of oriented_envelope.
- property oriented_envelope
Returns the oriented envelope (minimum rotated rectangle) that encloses the geometry.
Unlike envelope this rectangle is not constrained to be parallel to the coordinate axes. If the convex hull of the object is a degenerate (line or point) this degenerate is returned.
Alias of minimum_rotated_rectangle.
- property type
- property wkb
WKB representation of the geometry
- property wkb_hex
WKB hex representation of the geometry
- property wkt
WKT representation of the geometry
- property xy
Separate arrays of X and Y coordinate values
Example
>>> x, y = LineString([(0, 0), (1, 1)]).xy >>> list(x) [0.0, 1.0] >>> list(y) [0.0, 1.0]
- network_wrangler.utils.create_line_string(location_reference)[source]
Creates a geometry as a LineString using location reference
- network_wrangler.utils.create_location_reference_from_nodes(node_a, node_b)[source]
Creates a location reference using the node a and node b coordinates
Args: node_a: Node A as Series node_b: Node B as Series
- network_wrangler.utils.create_unique_shape_id(line_string)[source]
Creates a unique hash id using the coordinates of the geomtery
Args: line_string: Line Geometry as a LineString
Returns: string
- network_wrangler.utils.get_bearing(lat1, lon1, lat2, lon2)[source]
calculate the bearing (forward azimuth) b/w the two points
returns: bearing in radians
- network_wrangler.utils.haversine_distance(origin, destination, units='miles')[source]
Calculates haversine distance between two points
Args: origin: lat/lon for point A destination: lat/lon for point B units: either “miles” or “meters”
Returns: string
- network_wrangler.utils.link_df_to_json(df, properties)[source]
Export pandas dataframe as a json object.
Modified from: Geoff Boeing: https://geoffboeing.com/2015/10/exporting-python-data-geojson/
- Parameters:
df – Dataframe to export
properties – list of properties to export
- network_wrangler.utils.offset_location_reference(location_reference, offset_meters=10)[source]
Creates a new location reference using the node a and node b of given location reference, offseting it by 90 degree to the bearing of given location reference and distance equals to offset_meters
returns: new location_reference with offset
- network_wrangler.utils.offset_point_with_distance_and_bearing(lat, lon, distance, bearing)[source]
Get the new lat long (in degrees) given current point (lat/lon), distance and bearing
returns: new lat/long
- network_wrangler.utils.parse_time_spans(times)[source]
parse time spans into tuples of seconds from midnight can also be used as an apply function for a pandas series :param times: :type times: tuple(string) or tuple(int) or list(string) or list(int)
- Returns:
time span as seconds from midnight
- Return type:
tuple(integer)
- network_wrangler.utils.point_df_to_geojson(df, properties, node_foreign_key=None)[source]
Author: Geoff Boeing: https://geoffboeing.com/2015/10/exporting-python-data-geojson/
- network_wrangler.utils.topological_sort(adjacency_list, visited_list)[source]
Topological sorting for Acyclic Directed Graph
- network_wrangler.utils.update_df(base_df, update_df, merge_key=None, left_on=None, right_on=None, update_fields=None, method='update if found')[source]
Updates specific fields of a dataframe with another dataframe using a key column.
- Parameters:
base_df – DataFrame to be updated
update_df – DataFrame with with updated values
merge_key – column to merge on (i.e. model_link_id). If not specified, must have left_on AND right_on.
left_on – key for base_df. Must also specify right_on. If not specified, must specify merge_key.
right_on – key for update_df. Must also specify left_on. If not specified, must specify merge_key.
update_fields – required list of fields to update values for. Must be columns in update_df.
method – string indicating how the dataframe should be updated. One of: - “update if found” (default) which will update the values if the update values are not NaN - “overwrite all” will overwrite the current value with the update value even if it is NaN - “update nan” will only update values that are currently Nan in the base_df
Returns: Dataframe with updated values