topojson.core.topology
Topology
Topology(self,
data: Any,
topology: bool = True,
prequantize: bool | float | topojson._types.Transform = True,
topoquantize: bool | float | topojson._types.Transform = False,
presimplify: bool | float = False,
toposimplify: bool | float = False,
shared_coords: bool = False,
prevent_oversimplify: bool = True,
simplify_with:
typing.Literal['shapely', 'simplification', 'geos'] = 'shapely',
simplify_algorithm: typing.Literal['dp', 'vw'] = 'dp',
winding_order:
typing.Optional[typing.Literal['CW_CCW', 'CCW_CW']] = 'CW_CCW',
object_name: str | list[str] = 'data',
ignore_index: bool = False)
Returns a TopoJSON topology for the specified geometric object. TopoJSON is an extension of GeoJSON providing multiple approaches to compress the geographical input data. These options include simplifying the linestrings or quantizing the coordinates but foremost the computation of a topology.
Parameters
data: any geometric typeGeometric data that should be converted into TopoJSON. It is possible to provide a list of multiple geopandas.GeoDataFrames as separate objects. In this case it is required to provide an equal length list of the names of the objects for parameter
object_name.
topology: booleanSpecify if the topology should be computed for deriving the TopoJSON. Default is
True.
prequantize: boolean, int, dictIf the prequantization parameter is specified, the input geometry is quantized prior to computing the topology, the returned topology is quantized, and its arcs are delta-encoded. Quantization is recommended to improve the quality of the topology if the input geometry is messy (i.e., small floating point error means that adjacent boundaries do not have identical values); typical values are powers of ten, such as
1e4,1e5or1e6. The grid is then derived from the bounding box of the input. Alternatively, provide a fixed TopoJSON transform as a dict ({"scale": [kx, ky], "translate": [x0, y0]}) to quantize on a grid that does not depend on the input, for example thetransformof a previously computed Topology (topo.output["transform"]). The grid then stays the same when features are added or removed. Default isTrue(which correspond to a quantize factor of1e5).
topoquantize: boolean, int or dictIf the topoquantization parameter is specified, the input geometry is quantized after the topology is constructed. If the topology is already quantized this will be resolved first before the topoquantization is applied. As for
prequantize, a fixed TopoJSON transform can be given as a dict. See for more details theprequantizeparameter. Default isFalse.
presimplify: boolean, floatApply presimplify to remove unnecessary points from linestrings before the topology is constructed. This will simplify the input geometries; lines are simplified one by one, so shared borders can drift apart, unless
simplify_withisgeos.Trueuses a tolerance of2. Default isFalse.
toposimplify: boolean, floatApply toposimplify to remove unnecessary points from arcs after the topology is constructed. This will simplify the constructed arcs without altering the topological relations. Sensible values for coordinates stored in degrees are in the range of
0.0001to10. Defaults toFalse.
shared_coords: booleanSets the strategy to detect junctions. When set to
Falsea path is considered shared when coordinates are the same path (path-connected). The path-connected strategy is more ‘correct’, but slightly slower. When set toTruea path is considered shared when all coordinates appear in both paths (coords-connected). Default isFalse.
prevent_oversimplify: booleanIf this setting is set to
True, the simplification is slower, but the likelihood of producing valid geometries is higher as it prevents oversimplification. Simplification happens on paths separately, so this setting is especially relevant for rings with no partial shared paths. This is also known as a topology-preserving variant of simplification. With toposimplify, a ring that would be reduced to fewer than three points keeps the vertices to stay a triangle. Default isTrue.
simplify_with: strSets the package to use for simplifying (both pre- and toposimplify). Choose between
shapely,simplificationorgeos. Shapely adopts solely Douglas-Peucker and simplification both Douglas-Peucker and Visvalingam-Whyatt. The package simplification is known to be quicker than shapely.geosapplies to presimplify only: it simplifies the polygons together as a coverage (shapely.coverage_simplify, Visvalingam-Whyatt), so that shared borders stay matched and each ring stays at least a triangle; other lines are simplified with shapely. The polygons should form a valid coverage (shapely.coverage_is_valid). Default isshapely.
simplify_algorithm: strChoose between
dpandvw, for Douglas-Peucker or Visvalingam-Whyatt respectively.vwwill only be selected ifsimplify_withis set tosimplification. Default isdp.
winding_order: strDetermines the winding order of the features in the output geometry. Choose between
CW_CCWfor clockwise orientation for outer rings and counter- clockwise for interior rings. OrCCW_CWfor counter-clockwise for outer rings and clockwise for interior rings. Default isCW_CCWfor TopoJSON.
object_name: Union[str, list[str]]Name to use as key for the objects in the topojson file. This name is used for writing and reading topojson file formats. It is possible to define multiple objects within the topojson file. In this case it is required to provide a list of the referenced
object_namein combination with an equal length list ofdataobjects. Default is a single object nameddata.
ignore_index: boolIf set to true existing ids/indexes of geojson FeatureCollections will be ignored and overwritten. Otherwise features with ids will use their existing one. If indexes are not ignored and a duplicate id exists an exception will be raised. Default is false.
to_dict
Topology.to_dict(options: bool = False, state: bool = False)
Convert the Topology to a dictionary.
Parameters
to_svg
Topology.to_svg(separate: bool = False)
Display the arcs and junctions as SVG.
Parameters
to_json
Topology.to_json(fp: str | os.PathLike[str] | None = None,
options: bool = False,
pretty: bool = False,
indent: int = 4,
maxlinelength: int = 88,
state: bool = False)
Convert the Topology to a JSON object.
Parameters
fp: strIf set, writes the object to a file on drive. Default is
None.
options: booleanIf
True, the options also will be included. Default isFalse.
pretty: booleanIf
pretty=True, the JSON object will be ‘pretty’, depending on theidentandmaxlinelengthoptions. Ifpretty=False, it willcompact, eliminating whitespace. Default isFalse.
indent: intIf
style='pretty', declares the indentation of the objects. Default is4.
maxlinelength: intIf
style='pretty', declares the maximum length of each line. Default is88.
state: booleanIf
True, the options and a hash of the input geometry of each feature (source_hashes) are included, so thatTopology.read_jsonandsynccan continue from it in a next run. Default isFalse.
to_geojson
Topology.to_geojson(
fp: str | os.PathLike[str] | None = None,
pretty: bool = False,
indent: int = 4,
maxlinelength: int = 88,
validate: bool = False,
winding_order: typing.Literal['CW_CCW', 'CCW_CW'] = 'CCW_CW',
decimals: int | None = None,
object_name: str | int = 0)
Convert the Topology to a GeoJSON object. Remember that this will destroy the computed Topology.
Parameters
fp: strIf set, writes the object to a file on drive. Default is
None
pretty: booleanIf
pretty=True, the JSON object will be ‘pretty’, depending on theidentandmaxlinelengthoptions. Ifpretty=False, it willcompact, eliminating whitespace. Default isFalse.
indent: intIf
pretty=True, declares the indentation of the objects. Default is4.
maxlinelength: intIf
pretty=True, declares the maximum length of each line. Default is88.
validate: booleanSet to
Trueto validate each feature before inclusion in the GeoJSON. Only features that are valid geometries objects will be included. Default isFalse.
winding_order: strDetermines the winding order of the features in the output geometry. Choose between
CW_CCWfor clockwise orientation for outer rings and counter- clockwise for interior rings. OrCCW_CWfor counter-clockwise for outer rings and clockwise for interior rings. Default isCCW_CWfor GeoJSON.
decimals: int or NoneEvenly round the coordinates to the given number of decimals. Default is None, which means no rounding is applied.
object_name: str, intThe name or the index of the object within the Topology to display. Default is index 0.
to_gdf
Topology.to_gdf(
crs: Any = None,
validate: bool = False,
winding_order: typing.Literal['CW_CCW', 'CCW_CW'] = 'CCW_CW',
object_name: str | int = 0)
Convert the Topology to a GeoDataFrame. Remember that this will destroy the computed Topology.
Note: This function use not the TopoJSON driver within Fiona, but a custom implemented more robust variant. See for info the to_geojson() function.
Parameters
crs: str, dictcoordinate reference system to set on the resulting frame. Default tries to use crs from data-input, otherwise is
None.
validate: booleanSet to
Trueto validate each feature before inclusion in the GeoJSON. Only features that are valid geometries objects will be included. Default isFalse.
winding_order: strDetermines the winding order of the features in the output geometry. Choose between
CW_CCWfor clockwise orientation for outer rings and counter- clockwise for interior rings. OrCCW_CWfor counter-clockwise for outer rings and clockwise for interior rings. Default isCCW_CWfor GeoJSON.
object_name: str, intName or index of the object. Default is index
0to select the first object.
to_alt
Topology.to_alt(color: str | None = None,
tooltip: bool = True,
projection: str = 'identity',
object_name: str | int = 0)
Display as Altair visualization.
Parameters
color: strAssign an property attribute to be used for color encoding and renders the Altair visualization as geoshape. Remember that most of the time the wanted attribute is nested within properties. Moreover, specific type declaration is required. Eg
color='properties.name:N'. Default isNone(render as mesh).
tooltip: booleanOption to include or exclude tooltips on geoshape objects Default is
True.
projection: strDefines the projection of the visualization. Defaults to a non-geographic, Cartesian projection (known by Altair as
identity).
object_name: str, intThe name or the index of the object within the Topology to display. Default is index 0.
to_widget
Topology.to_widget(
slider_toposimplify: topojson._types.Slider | None = None,
slider_topoquantize: topojson._types.Slider | None = None,
slider_keep: topojson._types.Slider | None = None)
Create an interactive widget based on Altair. The widget includes sliders to interactively change the toposimplify and topoquantize settings. With an algorithm “share of vertices”, the keep slider sets the share of the vertices to keep instead of the tolerance.
Parameters
slider_toposimplify: dictThe dict should contain the following keys:
min,max,step,value. Default is{"min": 0, "max": 10, "step": 0.01, "value": 0.01}.
slider_topoquantize: dictThe dict should contain the following keys:
min,max,value,base. Default is{"min": 1, "max": 6, "step": 1, "value": 1e5, "base": 10}.
slider_keep: dictThe dict should contain the following keys:
min,max,step,value. Default is{"min": 0, "max": 1, "step": 0.01, "value": 0.1}.
topoquantize
Topology.topoquantize(quant_factor: float | topojson._types.Transform,
inplace: bool = False)
Quantization is recommended to improve the quality of the topology if the input geometry is messy (i.e., small floating point error means that adjacent boundaries do not have identical values); typical values are powers of ten, such as 1e4, 1e5 or 1e6.
Parameters
quant_factor: float or dictQuantization factor: the number of steps on each axis of the bounding box. Or a fixed TopoJSON transform as a dict (
{"scale": [kx, ky], "translate": [x0, y0]}), for example a grid with cells that are a multiple of those ofprequantize, so that each quantized point is also a point of the finer grid.
inplace: bool, optionalIf
True, do operation inplace and returnNone. Default isFalse.
Returns
toposimplify
Topology.toposimplify(
epsilon: float | None = None,
simplify_algorithm: typing.Optional[typing.Literal['dp', 'vw']] = None,
simplify_with:
typing.Optional[typing.Literal['shapely', 'simplification', 'geos']] = None,
prevent_oversimplify: bool | None = None,
inplace: bool = False,
keep: float | None = None)
Apply toposimplify to remove unnecessary points from arcs after the topology is constructed. This will simplify the constructed arcs without altering the topological relations. Sensible values for coordinates stored in degrees are in the range of 0.0001 to 10.
Parameters
epsilon: float, optionaltolerance parameter. Give either
epsilonorkeep.
simplify_algorithm: str, optionalChoose between
dpandvw, for Douglas-Peucker or Visvalingam-Whyatt respectively.vwwill only be selected ifsimplify_withis set tosimplification. Default isNone, meaning that the default (dp) is not overwritten.
simplify_with: str, optionalSets the package to use for simplifying. Choose between
shapelyorsimplification. Shapely adopts solely Douglas-Peucker and simplification both Douglas-Peucker and Visvalingam-Whyatt. The package simplification is known to be quicker than shapely.geosapplies to presimplify only and raises aValueErrorhere. Default isNone, meaning that the default (shapely) is not overwritten.
prevent_oversimplify: boolean, optionalIf this setting is set to
True, the simplification is slower, but the likelihood of producing valid geometries is higher as it prevents oversimplification. Simplification happens on paths separately, so this setting is especially relevant for rings with no partial shared paths. This is also known as a topology-preserving variant of simplification. With toposimplify, a ring that would be reduced to fewer than three points keeps the vertices to stay a triangle. Default isNone, meaning that the default (True) is not overwritten.
inplace: bool, optionalIf
True, do operation inplace and returnNone. Default isFalse.
keep: float, optionalInstead of
epsilon, the share of the vertices to keep, between0and1: the inner vertices of the arcs that the algorithm removes last are kept, the ends of the arcs always. The result is that of the matchingepsilon. Douglas-Peucker uses its own implementation, whateversimplify_with; Visvalingam-Whyatt (simplify_algorithm="vw") uses the package simplification. Withprevent_oversimplifya ring stays at least a triangle.
Returns
read_json
Topology.read_json(
fp: typing.Union[str, os.PathLike[str], typing.IO[str]])
Read a Topology from a TopoJSON file. If the file was written with to_json(..., state=True), the options and source hashes are restored, so that add, remove and sync can continue from it.
Parameters
Returns
Topology
add
Topology.add(data: Any, object_name: str | None = None)
Add features to the Topology without recomputing it. Existing arcs are cut where the new features share a path with them; the result is the same as a full build on the same quantization grid.
Parameters
Returns
remove
Topology.remove(ids: collections.abc.Iterable[collections.abc.Hashable],
object_name: str | None = None)
Remove features from the Topology without recomputing it. Arcs that are no longer used are dropped and arcs are merged where a point is no longer a junction. Compared to a full build, a ring that is no longer cut can start at another vertex, and the bbox (recomputed from the quantized data) can differ by at most half a grid cell.
Parameters
Returns
sync
Topology.sync(data: Any, object_name: str | None = None)
Make the Topology equal to data: features that are new are added, features that are gone are removed and features with a changed geometry are replaced. Unchanged features are left as they are. What happened is stored in self.last_sync.
Comparing uses a hash of the input geometry of each feature. These hashes are kept on the Topology and written with to_json(..., state=True).
Parameters
Returns