Package reference

This is a nearly-exhaustive listing of karta classes and function. Some experimental, deprecated, or private components are excluded.

Raster package (karta.raster)

The karta.raster package provides Grid classes as well as readers for ESRI ASCII grids and GeoTiff files. The most commonly used Grid subclass is RegularGrid, which can efficiently handle gridded datasets with constant offsets between nodes. Grids support geographically-aware clipping, sampling, and profile extraction.

Raster grid representations

class karta.raster.grid.Grid[source]

Grid base class

apply(func, inplace=False, band=None)[source]

Apply a vector function to grid values.

Parameters:

func : callable

function that takes a vector of values and returns an equally-sized vector of values with the same type

inplace : boolean, optional

whether to perform operation in place rather than returning a new grid instance (default False)

band : int, optional

if provided, only apply func to a specific band

Returns:

instance of type(self)

copy()[source]

Return a deep copy

max()[source]

Return the maximum non-nan in self.data

min()[source]

Return the minimum non-nan in self.data

minmax()[source]

Return the minimum and maximum value of data array

RegularGrid

class karta.raster.grid.RegularGrid(transform, values=None, bands=None, crs=None, nodata_value=None, bandclass=None)[source]

Regular structured grid class. A RegularGrid contains a fixed number of rows and columns with a constant spacing and a list of bands representing scalar fields.

Positions on a RegularGrid are referenced to their array indices (i,j) using an affine transform T such that

T = (a, b, c, d, e, f)

x = a + j*c + i*e
y = b + i*d + j*f

or as a matrix transformation,

|e  c  a|   |i|   |x|
|       | * |j| = | |
|d  f  b|   |1|   |y|

where (x,y) are the coordinates of the lower left corner of each pixel.

Meaning:

  • (a,b) defines the lower-left grid cell corner
  • (c,d) defines the resolution in the horizontal and vertical directions
  • (e,f) can be used to define a rotation

In the common case of a “east-right, north-up” grid, e = f = 0.

aschunks(size=(-1, -1), overlap=(0, 0), copy=True)[source]

Generator for grid chunks. This may be useful for parallel or memory-controlled grid processing.

Parameters:

size : tuple of two integers, optional

size of the chunks to return (default approximately one-quarter of each dimension)

overlap : tuple of two integers, optional

number of pixels of overlap (default (0, 0))

copy : bool

whether to force returned grids to be copies warning: output may be a copy regardless, depending on the band class

Yields:

RegularGrid

smaller grids

center_coords()[source]

Return the coordinates of cell centers.

center_llref()[source]

Return the ‘lower-left’ reference in terms of a center coordinate.

clip(xmin, xmax, ymin, ymax, crs=None)[source]

Return a clipped version of grid with cell centers constrained to a bounding box.

Parameters:

xmin : float

xmax : float

ymin : float

ymax : float

crs : karta.crs.CRS subclass, optional

coordinates(crs=None)[source]

Return a CoordinateGenerator instance for computing the coordinates of indices in crs. This behaves like the array returned by center_coords(), but computes coordinates on demand rather than at once.

Parameters:

crs : CRS, optional

Coordinate system of output coordinates. If None (default), output coordinates are not transformed from self.crs.

Returns:

CoordinateGenerator

Notes

This is an experimental replacement for coordmesh() and center_coords().

coordmesh(*args, **kwargs)[source]

Alias for center_coords()

corner_llref()[source]

Return the ‘lower-left’ reference in terms of a center coordinate.

data_mask

8-bit mask of valid data cells, collapsed across bands

data_mask_full

8-bit mask of valid data cells by band

get_data_extent(reference='center', nodata=None, crs=None)[source]

Return the region characteristics as a tuple (xmin, xmax, ymin, ymax).

Parameters:

reference : string

either ‘center’ or ‘edge’.

crs : karta.crs.CRS subclass

coordinate system of output

get_extent(reference='center', crs=None)[source]

Return the region characteristics as a tuple (xmin, xmax, ymin, ymax).

Parameters:

reference : string

either ‘center’ or ‘edge’.

crs : karta.crs.CRS subclass

coordinate system of output

get_indices(x, y)[source]

Return the integer row and column indices for the point nearest geographical coordinates. Unlike get_positions(), this method raises and exception when points are out of range.

Parameters:

x, y : float or vector

vertices of points to compute indices for

Raises:

IndexError

points outside of Grid bbox

get_positions(x, y)[source]

Return the float row and column indices for the point nearest geographical coordinates.

Parameters:

x, y : float or vector

vertices of points to compute indices for

Raises:

ValueError

if inputs have unequal size

mask_by_poly(polys, inplace=False)[source]

Return a grid with all elements outside the bounds of a polygon masked as nodata.

Parameters:

polys : Polygon, Multipolygon or list of Polygon instances

region(s) defining masking boundary

inplace : bool, optional

if True, perform masking in-place (default False)

profile(line, resolution=None, **kw)[source]

Sample along a Line at a specified interval.

Parameters:

line : karta.Line

defines the sampling path

resolution : float, optional

sample spacing, taken to be the minimum grid resolution by default

Additional keyword arguments passed to `RegularGrid.sample` (e.g. to

specify sampling method)

Returns:

Multipoint

sample points

ndarray

grid value at sample points

resample(dx, dy, method='nearest')[source]

Resample array to have spacing dx, dy. The grid origin remains in the same position.

Parameters:

dx : float

cell dimension 1

dy : float

cell dimension 2

method : str, optional

interpolation method, currently ‘nearest’ and ‘linear’ supported

resize(bboxnew)[source]

Return a new grid grid with outer edges given by a bounding box.

If the grid origin shifts by a non-integer factor of the grid resolution, nearest neighbour values are selected.

Parameters:

bboxnew : 4-tuple of floats

(xmin, ymin, xmax, ymax).

sample(*args, **kwargs)[source]

Return the values nearest positions. Positions may be:

  • a karta.Point instance
  • a karta.Multipoint instance, or
  • a pair of x, y coordinate arrays
Parameters:

positions : karta.Point, karta.Multipoint, or two lists of floats

see above

crs : karta.crs.CRS, optional

used when coordinate lists are provided, otherwise the coordinate system is taken from the crs attribute of the geometry

method : string, optional

may be one of ‘nearest’, ‘bilinear’ (default).

Returns:

float or vector

The size of the output has one more dimension than the input. If the input are scalar, the output is a p-vector representing band values. If the input is a n-vector, the ouput is p x n. If the input is an m x n array, the output is p x m x n.

Raises:

IndexError

points outside of Grid bbox

sample_bilinear(x, y)[source]

Return the value nearest to coordinates using a bi-linear sampling scheme.

Parameters:

x, y : float or vector

vertices of points to compute indices for

Returns:

float or vector

the size of the output has one more dimension than the input. if the input are scalar, the output is a vector length p representing band values. if the input is a vector length n, the ouput is p x n. if the input is an m x n array, the output is p x m x n.

Raises:

IndexError

points outside of Grid bbox

sample_nearest(x, y)[source]

Return the value nearest to coordinates using a nearest grid center sampling scheme.

Parameters:

x, y : float or vector

vertices of points to compute indices for

Returns:

float or vector

the size of the output has one more dimension than the input. if the input are scalar, the output is a vector length p representing band values. if the input is a vector length n, the ouput is p x n. if the input is an m x n array, the output is p x m x n.

Raises:

IndexError

points outside of Grid bbox

set_nodata_value(val)[source]

Redefine value used to indicate nodata.

Parameters:val : number
to_aai(f, reference='corner', nodata_value=-9999)[source]

Save internal data as an ASCII grid. Based on the ESRI standard, only isometric grids (i.e. hdr[‘dx’] == hdr[‘dy’] can be saved.

Parameters:

f : str

a file-like object or a filename

reference : str

specify a header reference (‘center’ | ‘corner’)

nodata_value : number

specify how NaNs should be represented

Raises:

GridError

input grid is not isometric and can therefore not be saved

to_geotiff(fnm, compress='PACKBITS', tiled=False, **kw)[source]

Write data to a GeoTiff file using GDAL.

Parameters:

fnm : str

output file name

compress: str or None, optional

“PACKBITS” (default), “DEFLATE”, “LZW”, “LZMA”, or None

to_gtiff(*args, **kwargs)[source]

Alias for to_geotiff

vertex_coords()[source]

Return the coordinates of cell vertices.

SimpleBand

class karta.raster.band.SimpleBand(size, dtype, initval=None)[source]

SimpleBand wraps a numpy.ndarray for storage.

CompressedBand

class karta.raster.band.CompressedBand(size, dtype, chunksize=(256, 256), initval=0)[source]

CompressedBand is a chunked, blosc-compressed array.

getblock(yoff, xoff, ny, nx)[source]

Retrieve values with dimensions size, starting at offset yoff, xoff.

setblock(yoff, xoff, array)[source]

Store block of values in array starting at offset yoff, xoff.

Miscellaneous raster functions

2D raster functions

karta.raster.misc.aspect(grid, band=0)[source]

Compute grid aspect.

Parameters:

grid : RegularGrid

band : int, optional

band to compute aspect for (default 0)

Returns:

RegularGrid

karta.raster.misc.divergence(grid, bands=(0, 1))[source]

Compute divergence from a grid.

Parameters:

grid : RegularGrid

band : tuple of ints, optional

indicates orthogonal velocity bands (default (0, 1))

Returns:

RegularGrid

karta.raster.misc.gradient(grid, band=0)[source]

Compute gradient field from a grid.

Parameters:

grid : RegularGrid

band : int, optional

(default 0)

Returns:

(RegularGrid, RegularGrid)

karta.raster.misc.hillshade(grid, azimuth=330.0, elevation=60.0, band=0)[source]

Return a hill-shaded version of grid.

Parameters:

grid : RegularGrid

azimuth : float, optional

direction of light source (default 330.0)

elevation : float, optional

height of light source (default 60.0)

band : int, optional

band to compute hillshade for (default 0)

Returns:

RegularGrid

Notes

Currently assumes orthogonal coordinates.

karta.raster.misc.normed_potential_vectors(grid, band=0)[source]

Computes a U,V vector field of a potential grid. Scalar components of U,V are normalized to max(|U, V|).

Parameters:

grid : RegularGrid

band : int, optional (default 0)

Returns:

(RegularGrid, RegularGrid)

karta.raster.misc.slope(grid, band=0)[source]

Return the scalar slope at each pixel using the neighbourhood method.

Parameters:

grid : RegularGrid

band : int, optional

band to compute slope for (default 0)

Returns:

RegularGrid

Notes

http://webhelp.esri.com/arcgisdesktop/9.2/index.cfm?TopicName=How%20Slope%20works

Raster IO modules

Functions for reading raster data sources as RegularGrid objects

karta.raster.read.from_geotiffs(*fnms, **kw)[source]

Read multiple GeoTiff files as bands within a single grid. Reads the first band within each GeoTiff, and checks that grids share the same spatial transform and coordinate system.

Parameters:

fnm : list of str

GeoTiff file paths

in_memory : bool

if True (default), read entire dataset into memory

bandclass : Band class, optional

class of band used by returned grid (default karta.band.CompressedBand) if in_memory is True, this parameter is ignored and the returned grid will have bands of type karta.raster._gdal.GdalFileBand

karta.raster.read.read_aai(fnm)[source]

Convenience function to open a ESRI ASCII grid and return a RegularGrid instance.

karta.raster.read.read_geotiff(fnm, in_memory=True, ibands=-1, **kw)[source]

Convenience function to open a GeoTIFF and return a RegularGrid instance.

Parameters:

fnm : str

GeoTiff file path

in_memory : bool

if True (default), read entire dataset into memory

ibands : int | list of ints, optional

band(s) to open (default all)

bandclass : Band class, optional

class of band used by returned grid (default karta.band.CompressedBand) if in_memory is True, this parameter is ignored and the returned grid will have bands of type karta.raster._gdal.GdalFileBand

karta.raster.read.read_gtiff(fnm, in_memory=True, ibands=-1, **kw)

Convenience function to open a GeoTIFF and return a RegularGrid instance.

Parameters:

fnm : str

GeoTiff file path

in_memory : bool

if True (default), read entire dataset into memory

ibands : int | list of ints, optional

band(s) to open (default all)

bandclass : Band class, optional

class of band used by returned grid (default karta.band.CompressedBand) if in_memory is True, this parameter is ignored and the returned grid will have bands of type karta.raster._gdal.GdalFileBand

GeoTiff (GDAL interface)

IO interface to GeoTiffs using GDAL.

class karta.raster._gdal.GdalFileBand(band, dataset)[source]

Read-only raster Band interface the reads data from a disk-bound datasource.

karta.raster._gdal.SRS_from_WKT(s)[source]

Return Proj.4 string, semimajor axis, and flattening

karta.raster._gdal.gdal_type(dtype)[source]

Return a GDAL type that most closely matches numpy dtype

Notes

Returns GDT_Int32 for np.int64, which may result in overflow.

karta.raster._gdal.numpy_dtype(dt_int)[source]

Return a numpy dtype that matches the band data type.

karta.raster._gdal.read(fnm, in_memory, ibands=-1, bandclass=<class 'karta.raster.band.CompressedBand'>)[source]

Read a GeoTiff file and return a numpy array and a dictionary of header information.

Parameters:

fnm : str

input datasource

in_memory : boolean

indicates whether array should be read fully into memory

ibands : int or list of ints

band number (1...)

bandclass : karta.raster.band class

if in_memory is False, use this class for band storage

Returns an band object and a dictionary of metadata

karta.raster._gdal.write(fnm, grid, compress=None, tiled=False, **kw)[source]

Write a grid-like object to fnm

ESRI ASCII grids

Low-level functions for reading ESRI ASCII grids

karta.raster._aai.aairead(fnm)[source]

Read an existing ASCII grid file and return a Numpy array and a dictionary of header information.

karta.raster._aai.check_header(hdr)[source]

Make sure that all required header records are present, as well as both centered and corner spatial references.

Vector package (karta.vector)

The package karta.vector provides a Geometry class, subclasses for Point, Line, and Polygon types and their multipart counterparts, as well as readers and writers for ESRI shapefiles, GeoJSON, and GPX files.

All concrete geometries support the __geo_interface__ attribute, and map to Feature types.

Geometry

Geographical measurement and analysis

Provides Point, Line, and Polygon classes, and their Multipart equivalents, with methods for simple measurements such as distance, area, and direction.

Geometry

class karta.vector.geometry.Geometry(properties=None, crs=<karta.crs.CartesianCRS object>)[source]

Abstract base class for all geometry types

Point

class karta.vector.Point(coords, properties=None, **kwargs)[source]

Point object instantiated with:

Parameters:

coords : 2-tuple or 3-tuple

properties : dict, optional

geometry specific metadata (default None)

crs : karta.crs.CRS, optional

coordinate system for geometry (default Cartesian)

apply_transform(M)[source]

Apply an affine transform given by matrix M to data and return a new Point.

Parameters:

M : ndarray

2x3 or 3x4 affine transformation matrix, representing a two-dimensional or a three-dimensional transformation, respectively.

Returns:

Geometry

Notes

The output coordinates are computed as:

xnew        x
      = M * y
ynew        1

or:

xnew        x
ynew  = M * y
znew        z
            1
as_geojson(indent=None, urn=None, force_wgs84=True)

Output representation of internal data as a GeoJSON string.

Parameters:

indent : int, optional

indentation of generated GeoJSON (default 2)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

azimuth(other, projected=True)[source]

Returns the compass azimuth from self to other in degrees, measured clockwise with north at 0.

Parameters:

other : Point

second point defining direction

projected : bool, optional

If True and self.crs is a ProjectedCRS, return the azimuth in the projected cooridnate system. If False, return the geodetic azimuth. if self.crs is a GeographicalCRS, result is always geodetic and this option has no effect.

Returns:

float

Notes

  • Return value is NaN if points are coincident
  • If CRS is geographical, returns azimuth as defined by the CRS instance.
distance(other, projected=True)[source]

Returns a distance to another Point. Distances is computed in one of three ways:

1. If self is in a geographical coordinate system, other is inverse projected to geographical coordinates if necessary, and the geodetic distance is computed on the ellipsoid of self.

2. If projected is True, other is projected to the same coordinate system as self and flat-earth distance is computed.

3. If projected is `False`, both *self and other are inverse projected to geographical coordinates, and the geodetic distance is computed on the ellipsoid of self.

If the coordinate system is geographical and a third (z) coordinate exists, it is assumed to have the same units as the real-world horizontal coordinates (e.g. meters).

Parameters:

other : Point

point to compute distance to

projected : bool, optional

If True and self.crs is a ProjectedCRS, return the flat distance in the projected coordinate system. If False, return the ellipsoidal distance. if self.crs is a GeographicalCRS, result is always ellipsoidal/geodetic and this switch is ignored.

Returns:

float

Notes

  • If CRS is Geographical, returns distance as computed by the CRS instance (e.g. ellipsoidal or spherical).
get_vertex(crs=None)[source]

Return the Point vertex as a tuple.

rotate(thetad, origin=(0, 0))

Rotate rank 2 geometry.

Parameters:

thetad : float

degreesof rotation

origin : tuple of two floats, optional

pivot for rotation (default (0, 0))

shift(shift_vector)[source]

Shift point in space.

Parameters:

shift_vector : iterable

vector with length equal to Geometry rank defining the shift

inplace : bool

whether shift should be in place (default False)

to_geojson(f, indent=None, urn=None, force_wgs84=True)

Write data as a GeoJSON string to a file-like object f.

Parameters:

f : str or file-like object

file to receive GeoJSON string

indent : int, optional

indentation of generated GeoJSON (default None)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

to_shapefile(fnm)

Save line to a shapefile

walk(distance, azimuth, projected=True)[source]

Returns the point reached when moving in a given direction for a given distance from a specified starting location.

Parameters:

distance : float

distance to shift point

azimuth: float

shift azimuth (clockwise with north at 0)

projected: bool, optional

If True and self.crs is a ProjectedCRS, return the compute new position using the projected cooridnate system. If False, return the geodetically correct new position. if self.crs is a GeographicalCRS, result is always geodetic and this option has no effect.

Line

class karta.vector.Line(vertices, **kwargs)[source]

Line composed of connected vertices.

Parameters:

coords : list of 2-tuples or 3-tuples

vertex coordinates

properties : dict, optional

geometry specific metadata

crs : karta.CRS, optional

(default Cartesian)

any_within_poly(poly)

Return whether any vertices are inside poly

apply_transform(M)

Apply an affine transform given by matrix M to data and return a new geometry.

Parameters:

M : ndarray

2x3 or 3x4 affine transformation matrix, representing a two-dimensional or a three-dimensional transformation, respectively.

Returns:

Geometry

Notes

The output coordinates are computed as:

xnew        x
      = M * y
ynew        1

or:

xnew        x
ynew  = M * y
znew        z
            1
as_geojson(indent=None, urn=None, force_wgs84=True)

Output representation of internal data as a GeoJSON string.

Parameters:

indent : int, optional

indentation of generated GeoJSON (default 2)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

convex_hull()

Return a Polygon representing the convex hull.

Notes

  • If CRS is Geographical, returns hull computed using a spherical approximation. Failure may occur if the vertices are not in euclidian position.
crosses_dateline()

Return a boolean that indicates whether any segment crosses the dateline.

cumulength()[source]

Returns the cumulative length by vertex.

Notes

  • If CRS is Geographical, uses distance defined by the CRS instance.
displacement()[source]

Returns the distance between the first and last vertex.

Notes

  • If CRS is Geographical, uses distance defined by the CRS instance.
distances_to(pt)

Return the distance from each vertex to a point.

extend(other)[source]

Combine two lines, provided that that the data formats are similar.

flat_distances_to(pt)

Return the “flat Earth” distance from each vertex to a point.

get_coordinate_lists(crs=None)

Return horizontal coordinate lists.

Parameters:

crs : karta.CRS, optional

coordinate system of output vertices

get_vertices(crs=None, drop_z=False)

Return vertices as an array.

Parameters:

crs : karta.CRS, optional

coordinate system of output vertices

drop_z : bool, optional

whether to discard third dimension for rank 3 geometries

intersections(other, keep_duplicates=False)

Return the intersections with another geometry as a Multipoint.

Parameters:

other : Geometry

another geometry with multipl connected vertices

keep_duplicates : bool, optional

whether to retain duplicate intersections [default False]

Notes

  • If CRS is Geographical, uses a spherical approximation.
intersects(other)

Return whether an intersection exists with another geometry.

Parameters:

other : Geometry

another geometry with multiple connected vertices

Notes

  • If CRS is Geographical, uses a spherical approximation.
nearest_on_boundary(point)

Returns the position on the geometry boundary that is nearest to a point. If two points are equidistant, only one will be returned.

Parameters:point : Point

Notes

  • If CRS is Geographical, uses distance defined by the CRS instance.
nearest_vertex_to(point)

Returns the index of the vertex that is nearest to a point. If two points are equidistant, only one will be returned.

Parameters:

point : Point

target point

Returns:

int

rotate(thetad, origin=(0, 0))

Rotate rank 2 geometry.

Parameters:

thetad : float

degreesof rotation

origin : tuple of two floats, optional

pivot for rotation (default (0, 0))

segment_tuples

Returns an generator of adjacent line segments as coordinate tuples.

segments

Returns an generator of adjacent line segments.

shift(shift_vector)

Shift geometry in space.

Parameters:

shift_vector : iterable

vector with length equal to Geometry rank defining the shift

shortest_distance_to(pt)

Return the shortest distance from any position on the geometry boundary to a point.

Parameters:point : Point

Notes

  • If CRS is Geographical, uses distance defined by the CRS instance.
to_geojson(f, indent=None, urn=None, force_wgs84=True)

Write data as a GeoJSON string to a file-like object f.

Parameters:

f : str or file-like object

file to receive GeoJSON string

indent : int, optional

indentation of generated GeoJSON (default None)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

to_npoints(n)[source]

Return n equally spaced Point instances along line.

Parameters:

n : int

number of points to return

to_points(dx)[source]

Return equally spaced Point instances along line.

Parameters:

dx : float

spacing of points

to_polygon()[source]

Returns a polygon.

to_shapefile(fnm)

Save line to a shapefile

within_distance(point, distance)

Test whether a point is within distance geometry.

Parameters:

point : Point

distance : float

Notes

  • If CRS is Geographical, uses distance defined by the CRS instance.

Polygon

class karta.vector.Polygon(vertices, subs=None, **kwargs)[source]

Polygon, composed of a closed sequence of vertices.

Parameters:

coords : list of 2-tuples or 3-tuples

vertex coordinates

subs : list of Polygon instances, optional

sub-polygons [default None]

properties : dict, optional

geometry specific metadata

crs : karta.CRS, optional

(default Cartesian)

any_within_poly(poly)

Return whether any vertices are inside poly

apply_transform(M)

Apply an affine transform given by matrix M to data and return a new geometry.

Parameters:

M : ndarray

2x3 or 3x4 affine transformation matrix, representing a two-dimensional or a three-dimensional transformation, respectively.

Returns:

Geometry

Notes

The output coordinates are computed as:

xnew        x
      = M * y
ynew        1

or:

xnew        x
ynew  = M * y
znew        z
            1
area

Return the two-dimensional area of the polygon, excluding sub-polygons.

Notes

  • If CRS is Geographical, uses either a spherical or an ellipsoidal calculation.
as_geojson(indent=None, urn=None, force_wgs84=True)

Output representation of internal data as a GeoJSON string.

Parameters:

indent : int, optional

indentation of generated GeoJSON (default 2)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

centroid

Return Polygon centroid as a Point, ignoring sub-polygons.

contains(point)[source]

Returns True if point is inside or on the boundary of the polygon, and False otherwise. Uses a crossing number scheme.

Notes

  • When the polygon is polar in a geographical coordinate system, a less efficient algorithm is used. For better performance, consider projecting to an appropriate coordinate system such as NSIDCNorth or NSIDCSouth beforehand.
  • Otherwise, a planar algorithm is used.
convex_hull()

Return a Polygon representing the convex hull.

Notes

  • If CRS is Geographical, returns hull computed using a spherical approximation. Failure may occur if the vertices are not in euclidian position.
crosses_dateline()

Return a boolean that indicates whether any segment crosses the dateline.

distances_to(pt)

Return the distance from each vertex to a point.

flat_distances_to(pt)

Return the “flat Earth” distance from each vertex to a point.

get_coordinate_lists(crs=None)

Return horizontal coordinate lists.

Parameters:

crs : karta.CRS, optional

coordinate system of output vertices

get_vertices(crs=None, drop_z=False)

Return vertices as an array.

Parameters:

crs : karta.CRS, optional

coordinate system of output vertices

drop_z : bool, optional

whether to discard third dimension for rank 3 geometries

intersections(other, keep_duplicates=False)

Return the intersections with another geometry as a Multipoint.

Parameters:

other : Geometry

another geometry with multipl connected vertices

keep_duplicates : bool, optional

whether to retain duplicate intersections [default False]

Notes

  • If CRS is Geographical, uses a spherical approximation.
intersects(other)

Return whether an intersection exists with another geometry.

Parameters:

other : Geometry

another geometry with multiple connected vertices

Notes

  • If CRS is Geographical, uses a spherical approximation.
isclockwise()[source]

Return whether polygon winds clockwise around its interior.

ispolar(pole=None)[source]

Return True if polygon contains one pole. If the polygon contains neither or both poles, returns False.

Parameters:

pole : Point, optional

(default point on a sphere at 0 longitude, 90 latitude)

nearest_on_boundary(point)

Returns the position on the geometry boundary that is nearest to a point. If two points are equidistant, only one will be returned.

Parameters:point : Point

Notes

  • If CRS is Geographical, uses distance defined by the CRS instance.
nearest_vertex_to(point)

Returns the index of the vertex that is nearest to a point. If two points are equidistant, only one will be returned.

Parameters:

point : Point

target point

Returns:

int

perimeter

Return the perimeter of the polygon. If there are sub-polygons, their perimeters are added recursively.

Notes

  • If CRS is Geographical, uses distance defined by the CRS instance.
rotate(thetad, origin=(0, 0))

Rotate rank 2 geometry.

Parameters:

thetad : float

degreesof rotation

origin : tuple of two floats, optional

pivot for rotation (default (0, 0))

segment_tuples

Returns a generator of adjacent line segments as coordinate tuples.

segments

Returns a generator of adjacent line segments.

shift(shift_vector)

Shift geometry in space.

Parameters:

shift_vector : iterable

vector with length equal to Geometry rank defining the shift

shortest_distance_to(pt)

Return the shortest distance from any position on the geometry boundary to a point.

Parameters:point : Point

Notes

  • If CRS is Geographical, uses distance defined by the CRS instance.
to_geojson(f, indent=None, urn=None, force_wgs84=True)

Write data as a GeoJSON string to a file-like object f.

Parameters:

f : str or file-like object

file to receive GeoJSON string

indent : int, optional

indentation of generated GeoJSON (default None)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

to_line()[source]

Returns a self-closing polyline. Discards sub-polygons.

to_shapefile(fnm)

Save line to a shapefile

within_distance(point, distance)

Test whether a point is within distance geometry.

Parameters:

point : Point

distance : float

Notes

  • If CRS is Geographical, uses distance defined by the CRS instance.

Multipoint

class karta.vector.Multipoint(vertices, build_index=True, **kwargs)[source]

Point cloud with associated attributes.

Parameters:

coords : list

list of 2-tuples or 3-tuples defining vertices

data : list, dict, Table object, or None

point-specific data [default None]

properties : dict or None

geometry specific data [default None]

crs : karta.crs.CRS subclass

[default Cartesian]

any_within_poly(poly)

Return whether any vertices are inside poly

apply_transform(M)

Apply an affine transform given by matrix M to data and return a new geometry.

Parameters:

M : ndarray

2x3 or 3x4 affine transformation matrix, representing a two-dimensional or a three-dimensional transformation, respectively.

Returns:

Geometry

Notes

The output coordinates are computed as:

xnew        x
      = M * y
ynew        1

or:

xnew        x
ynew  = M * y
znew        z
            1
as_geojson(indent=None, urn=None, force_wgs84=True)

Output representation of internal data as a GeoJSON string.

Parameters:

indent : int, optional

indentation of generated GeoJSON (default 2)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

convex_hull()

Return a Polygon representing the convex hull.

Notes

  • If CRS is Geographical, returns hull computed using a spherical approximation. Failure may occur if the vertices are not in euclidian position.
distances_to(pt)

Return the distance from each vertex to a point.

flat_distances_to(pt)

Return the “flat Earth” distance from each vertex to a point.

get_coordinate_lists(crs=None)

Return horizontal coordinate lists.

Parameters:

crs : karta.CRS, optional

coordinate system of output vertices

get_vertices(crs=None, drop_z=False)

Return vertices as an array.

Parameters:

crs : karta.CRS, optional

coordinate system of output vertices

drop_z : bool, optional

whether to discard third dimension for rank 3 geometries

nearest_vertex_to(point)

Returns the index of the vertex that is nearest to a point. If two points are equidistant, only one will be returned.

Parameters:

point : Point

target point

Returns:

int

rotate(thetad, origin=(0, 0))

Rotate rank 2 geometry.

Parameters:

thetad : float

degreesof rotation

origin : tuple of two floats, optional

pivot for rotation (default (0, 0))

shift(shift_vector)

Shift geometry in space.

Parameters:

shift_vector : iterable

vector with length equal to Geometry rank defining the shift

to_geojson(f, indent=None, urn=None, force_wgs84=True)

Write data as a GeoJSON string to a file-like object f.

Parameters:

f : str or file-like object

file to receive GeoJSON string

indent : int, optional

indentation of generated GeoJSON (default None)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

to_shapefile(fnm)

Save line to a shapefile

within_bbox(bbox)[source]

Return Multipoint subset that is within a square bounding box given by (xmin, xymin, xmax, ymax).

within_polygon(poly)[source]

Return Multipoint subset that is within a polygon.

within_radius(point, radius)[source]

Return subset of Multipoint within a radius. Items on the border are excluded.

Parameters:

point : Point

point to to center filter at

radius : float

maximum distance from point

Returns:

Multipoint

Multiline

class karta.vector.Multiline(vertices, build_index=True, **kwargs)[source]

Collection of lines with associated attributes.

Parameters:

coords : list

list of lists of 2-tuples or 3-tuples defining lines

data : list, dict, Table object, or None

point-specific data [default None]

properties : dict or None

geometry specific data [default None]

crs : karta.crs.CRS subclass

[default Cartesian]

apply_transform(M)

Apply an affine transform given by matrix M to data and return a new Point.

Parameters:

M : ndarray

2x3 or 3x4 affine transformation matrix, representing a two-dimensional or a three-dimensional transformation, respectively.

Returns:

Geometry

Notes

The output coordinates are computed as:

xnew        x
      = M * y
ynew        1

or:

xnew        x
ynew  = M * y
znew        z
            1
as_geojson(indent=None, urn=None, force_wgs84=True)

Output representation of internal data as a GeoJSON string.

Parameters:

indent : int, optional

indentation of generated GeoJSON (default 2)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

get_coordinate_lists(crs=None)[source]

Returns a list of 2xn arrays representing lists of coordinates

get_vertices(crs=None)[source]

Return vertices as a list of arrays.

Parameters:

crs : karta.CRS, optional

coordinate system of output vertices

to_geojson(f, indent=None, urn=None, force_wgs84=True)

Write data as a GeoJSON string to a file-like object f.

Parameters:

f : str or file-like object

file to receive GeoJSON string

indent : int, optional

indentation of generated GeoJSON (default None)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

to_shapefile(fnm)

Save line to a shapefile

touching(geom)

Return a Multipart geometry representing member geometries that touch a Line or Polygon.

Touching is defined as intersecting a Line or Polygon boundary, or being contained within a Polygon.

Parameters:geom : Line or Polygon
touching_bbox(bbox, max_results=-1)

Return Multipart geometry representing member geometries that touch a bounding box.

Parameters:

bbox : tuple

(xmin, ymin, xmax, ymax)

within(geom)

Return a Multipart geometry representing member geometries contained within a Polygon.

Parameters:geom : Polygon
within_bbox(bbox, max_results=-1)

Return Multipart geometry representing member geometries that are contained by a bounding box.

Parameters:

bbox : tuple

(xmin, ymin, xmax, ymax)

Multipolygon

class karta.vector.Multipolygon(vertices, build_index=True, **kwargs)[source]

Collection of polygons with associated attributes.

Parameters:

coords : list

list of lists of polygon rings, each consisting of 2-tuples or 3-tuples

data : list, dict, Table object, or None

point-specific data [default None]

properties : dict or None

geometry specific data [default None]

crs : karta.crs.CRS subclass

[default Cartesian]

apply_transform(M)

Apply an affine transform given by matrix M to data and return a new Point.

Parameters:

M : ndarray

2x3 or 3x4 affine transformation matrix, representing a two-dimensional or a three-dimensional transformation, respectively.

Returns:

Geometry

Notes

The output coordinates are computed as:

xnew        x
      = M * y
ynew        1

or:

xnew        x
ynew  = M * y
znew        z
            1
as_geojson(indent=None, urn=None, force_wgs84=True)

Output representation of internal data as a GeoJSON string.

Parameters:

indent : int, optional

indentation of generated GeoJSON (default 2)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

get_coordinate_lists(crs=None)[source]

Returns a list of 2xn arrays representing lists of coordinates

get_vertices(crs=None)[source]

Return vertices as a list of arrays.

Parameters:

crs : karta.CRS, optional

coordinate system of output vertices

to_geojson(f, indent=None, urn=None, force_wgs84=True)

Write data as a GeoJSON string to a file-like object f.

Parameters:

f : str or file-like object

file to receive GeoJSON string

indent : int, optional

indentation of generated GeoJSON (default None)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

to_shapefile(fnm)

Save line to a shapefile

touching(geom)

Return a Multipart geometry representing member geometries that touch a Line or Polygon.

Touching is defined as intersecting a Line or Polygon boundary, or being contained within a Polygon.

Parameters:geom : Line or Polygon
touching_bbox(bbox, max_results=-1)

Return Multipart geometry representing member geometries that touch a bounding box.

Parameters:

bbox : tuple

(xmin, ymin, xmax, ymax)

within(geom)

Return a Multipart geometry representing member geometries contained within a Polygon.

Parameters:geom : Polygon
within_bbox(bbox, max_results=-1)

Return Multipart geometry representing member geometries that are contained by a bounding box.

Parameters:

bbox : tuple

(xmin, ymin, xmax, ymax)

Metadata tables

Metadata tables for vector data

class karta.vector.table.Table(data=None, fields=None, size=None, checktypes=False)[source]

Represents a metadata table.

asjson()[source]

Return a JSON-serialized string.

extend(other)[source]

Extend Table from another Table instance. If other has field f in self, it is copied. Otherwise, the None is appended.

get(i)[source]

Return a dictionary for a single entry

getfield(field)[source]

Return list of data corresponding to field

setfield(field, values)[source]

Modify or add a field with values

class karta.vector.table.Indexer(table)[source]

Provides a pleasanter syntax for querying a Table.

The Indexer object can be used with standard indexing syntax, with integer, slice, or string keys.

  • Indexer[int] returns the table row at position int as a dictionary. It is equivalent to Table.get(int).
  • Indexer[slice] returns the table rows at slice as a dictionary. It is equivalent to Table.get(slice).
  • Indexer[str] returns the vector under column str as a list. It is equivalent to Table.getfield(str).

Trees

Quadtree

Cython wrapper quadtree

R-Tree

Cython wrapper for rtree

Vector IO modules

Data input functions for Karta

Used available drivers to read input data and return Karta geometry objects.

karta.vector.read.from_shape(obj, properties=None)[source]

Read a __geo_interface__ dictionary and return an appropriate karta object

karta.vector.read.get_filenames(stem, check=False)[source]

Given a filename basename, return the associated shapefile paths. If check is True, ensure that the files exist.

karta.vector.read.ogr_parse_srs(lyr)[source]

Given an OGR type with a GetSpatialRef method, return a matching CRS object.

karta.vector.read.read_geojson(f, crs=<karta.crs.GeographicalCRS object>)[source]

Parse GeoJSON and return a list of geometries.

f : file-like object or str
file object to read from or a GeoJSON string
crs : karta.crs.CRS
CRS object to bind to new geometries

GeoJSON

class karta.vector._geojson.GeoJSONOutMixin[source]

Mixin class to be added to geometry objects, adding geojson functionality.

as_geojson(indent=None, urn=None, force_wgs84=True)[source]

Output representation of internal data as a GeoJSON string.

Parameters:

indent : int, optional

indentation of generated GeoJSON (default 2)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

to_geojson(f, indent=None, urn=None, force_wgs84=True)[source]

Write data as a GeoJSON string to a file-like object f.

Parameters:

f : str or file-like object

file to receive GeoJSON string

indent : int, optional

indentation of generated GeoJSON (default None)

force_wgs84 : bool, optional

Forces output to use geographical coordinates with the WGS84 datum, as recommended by the GeoJSON draft specification (https://datatracker.ietf.org/doc/draft-ietf-geojson/). If urn is not set, “urn:ogc:def:crs:OGC:1.3:CRS84” is used. (default True)

urn : str, optional

overrides GeoJSON CRS with provided URN string

ESRI shapefile (GDAL interface)

Shapefile driver for Karta using OGR backend

Overview

ogr_write takes geointerface dictionaries or Karta objects and writes to ESRI shapefile

ogr_read_geometry converts an OGR geometry object to a geointerface dictionary

class karta.vector._shp.ShapefileOutMixin[source]

Mixin class to be added to geometry objects, adding shapefile functionality.

to_shapefile(fnm)[source]

Save line to a shapefile

karta.vector._shp.get_geometry_type(gi)[source]

Return the geometry type from a __geo_interface__ dictionary

karta.vector._shp.ogr_get_fieldtype(val)[source]

Returns a tuple of - an OGR type integer that describes the type of a - a default width that should work for most cases

karta.vector._shp.ogr_get_polygon_points(poly)[source]

Return a list of lists of ogr.Polygon coordinate rings.

karta.vector._shp.ogr_read_attributes(lyr)[source]

Given an ogr.Layer instance, return a list of dictionaries with feature property data.

karta.vector._shp.ogr_read_geometries(lyr)[source]

Given an ogr.Layer instance, return a list of __geo_interface__ dictionaries.

karta.vector._shp.ogr_read_geometry(geom)[source]

Convert an ogr.Geometry to a __geo_interface__ dictionary.

karta.vector._shp.ogr_write(fnm, *objs)[source]

Write features to shapefile using OGR backend. Features are __geo_interface__ Feature mappings.

karta.vector._shp.ogr_write_feature(lyr, gi, id=0)[source]

Write the geometry encoded in a __geointerface__ dictionary to an OGR Layer.

GPS Exchange

GPX IO and manipulation (UNDER DEVELOPMENT)

Overview

GPX represents a GPX document that can be written to or read from

To do:
  • XML namespaces aren’t really handled properly
  • metadata node not addressed
class karta.vector._gpx.GPX(f=None, waypoints=None, tracks=None, routes=None)[source]

Represents a GPX document, with an internal representation of waypoints, tracks, and route that loosely approximates the XML structure. Provides methods to easily add Point-like and Line-like objects as GPX types.

add_route(route)[source]

Add a Multipoint-like object as a route. Properties and extension types for the route are taken from the properties attribute of the Multipoint-like object.

Properties and extensions types for each route point are taken from the data attribute of each Line-like object.

INCOMPLETE:

Needs to distinguish between properties and extensions at the trkseg and trkpt levels

Needs to properly add and <ele> property for Lines of rank 3

add_track(*tracks, **kw)[source]

Add Multipoint-like objects as segments of a track. Dictionaries of properties and extension types for the track are accepted as keyword arguments.

Properties and extension types for the track segments are taken from the properties attribute of each Multipoint-like object.

Properties and extensions types for each track point are taken from the data attribute of each Multipoint-like object.

INCOMPLETE:

Needs to distinguish between properties and extensions at the trkseg and trkpt levels

Needs to properly add and <ele> property for Lines of rank 3

add_waypoint(waypoint)[source]

Add a Point-like object as a waypoint. Properties and extension types are taken from waypoint.properties attribute.

as_string(waypts=True, tracks=True, routes=True)[source]

Write GPX object to a string. Writes all waypoints, tracks, and routes by default, which can be changed by changing the kwargs to False.

fromfile(f)[source]

Read a GPX document from f, which may be a filename or a file-like object.

parse_trk(trk)[source]

Parse a <trk> node, updating self.tracks.

parse_wpt(wpt)[source]

Parse a <wpt> node, updating self.waypoints.

class karta.vector._gpx.Point(lonlat, properties, extensions)
extensions

Alias for field number 2

lonlat

Alias for field number 0

properties

Alias for field number 1

class karta.vector._gpx.Route(rtepts, properties, extensions)
extensions

Alias for field number 2

properties

Alias for field number 1

rtepts

Alias for field number 0

class karta.vector._gpx.Track(trksegs, properties, extensions)
extensions

Alias for field number 2

properties

Alias for field number 1

trksegs

Alias for field number 0

class karta.vector._gpx.Trkseg(trkpts, properties, extensions)
extensions

Alias for field number 2

properties

Alias for field number 1

trkpts

Alias for field number 0

Managing coordinate systems

CRS (karta.crs)

Coordinate reference systems

Implements CRS bass class and subclasses for different kinds of spatial reference systems:

  • CartesianCRS
  • GeographicalCRS
  • ProjectedCRS

Coordinate reference system (CRS) objects represent mappings geographical positions to an x, y representation, and contain both projection and geodetic information. See CRS for information on subclassing.

CRS objects should be immutable. It is possible for multiple CRS objects to implement the same system, and tests for equality may fail.

class karta.crs.CRS[source]

Base class for coordinate system instances.

Subclasses should define:

  • name attribute
  • project(x, y, inverse=False) method
  • transform(other, x, y) method
  • forward(x, y, azimuth, distance) method
  • inverse(x0, y0, x1, y1) method

project transforms between world and projected coordinates, and takes the optional boolean parameter inverse (default False)

transform converts from own CRS coordinates to coordinates in another CRS

forward performs a forward geodetic calculation and returns coordinates

inverse performs an inverse geodetic calculation and returns an azimuth, a back azimuth, and a distance

A CRS subclass may optionally also provide string attributes to provide interoperability with other systems.

  • ref_proj4
  • ref_wkt
class karta.crs.CartesianCRS[source]

Cartesian (flat-earth) reference systems with (x, y) coordinates

static forward(x, y, az, dist, radians=False)[source]

Forward geodetic problem from a point

static inverse(x1, y1, x2, y2, radians=False)[source]

Inverse geodetic problem to find the geodesic between points

class karta.crs.GeographicalCRS(spheroid, name, datum='+datum=WGS84')[source]

Reference systems with longitude-latitude (θ, φ) coordinates.

Parameters:

spheroid : string

proj.4 spheroid identifier, e.g. “+ellps=WGS84”

name : string

datum : string, optional

proj.4 datum identifier, default “+datum=WGS84”

forward(*args, **kwargs)[source]

Forward geodetic problem from a point

inverse(*args, **kwargs)[source]

Inverse geodetic problem to find the geodesic between points

class karta.crs.ProjectedCRS(proj, name=None)[source]

Projected reference systems backed by a pypoj.Proj instance or a custom projection function.

Parameters:

proj : string

proj.4 string

name : string or None

forward(*args, **kwargs)[source]

Forward geodetic problem from a point

inverse(*args, **kwargs)[source]

Inverse geodetic problem to find the geodesic between points

Geodesy (karta.geodesy)

Functions from karta.geodesy should generally be accessed through a CRS subclass rather than directly.

Defines basic geodetic operations on a spheres and ellipsoids.

karta.geodesy.check_in_segment_range(pt, segment)[source]

Test whether pt is within the lon/lat range of segment

karta.geodesy.ellipsoidal_area(a, b, x1, y1, x2, y2)[source]

Area of a single quadrilateral defined by two meridians, the equator, and another geodesic.

Parameters:

a : float

equatorial radius

b : float

polar radius

x1 : float (degrees)

longitude of geodesic segment start

y1 : float (degrees)

latitude of geodesic segment start

x2 : float (degrees)

longitude of geodesic segment end

y2 : float (degrees)

latitude of geodesic segment end

karta.geodesy.ellipsoidal_forward(a, b, x, y, azimuth, distance)[source]

Compute the destination reached starting from a point and travelling in a specified direction.

Parameters:

a: float

equatorial radius

b: float

polar radius

x: float (degrees)

longitude at start

y: float (degrees)

latitude at start

azimuth: float (radians)

direction travelled from point

distnce: float

distance travelled

Returns:

x2: float (degrees)

longitude at destination

y2: float (degrees)

latitude at destination

back_az: float (degrees)

back azimuth from destination

Algorithm due to Karney, C.F.F. “Algorithms for geodesics”, J. Geod (2013)

karta.geodesy.ellipsoidal_inverse(a, b, x1, y1, x2, y2, tol=None)[source]

Compute the shortest path (geodesic) between two points.

Parameters:

a: float

equatorial radius

b: float

polar radius

x1: float (degrees)

first longitude

y1: float (degrees)

first latitude

x2: float (degrees)

second longitude

y2: float (degrees)

second latitude

Returns:

az: float (degrees)

forward azimuth from first point

back_az: float (degrees)

back azimuth from second point

distance: float

distance between points

Algorithm due to Karney, C.F.F. “Algorithms for geodesics”, J. Geod (2013)

karta.geodesy.eulerpole(pt1, pt2)[source]

Return the Euler pole of a geodesic passing through two points.

karta.geodesy.fzero_brent(a, b, f, tol)[source]

Evaluate a function to find a bracketed root

Parameters:

a : float

left bracket

b : float

right bracket

f : callable

function to find zero of

tol : float

error tolerance

Raises:

ValueError

if root is not bracketed

RuntimeError

if maximum iterations exceeded

karta.geodesy.intersection_spherical(segment1, segment2)[source]

compute the intersection between two great circle segments on a sphere

Parameters:

segment1, segment2 : tuple of tuples

Tuples of the form ((x1, y1), (x2, y2)) describing line segements

karta.geodesy.isbetween_circular(x, x0, x1)[source]

Tests whether x is between x0 and x1 on a circle [-180, 180)

karta.geodesy.reduce_deg(deg)[source]

Return deg in the range [-180, 180)

karta.geodesy.solve_astroid(a, f, lambda12, phi1, phi2)[source]

Used to provide an initial guess to the inverse problem in the case of nearly antipodal points.

Parameters:

a: float

equatorial radius

f: float

flattening

lambda12: float (radians)

difference in longitudes

phi1: float (radians)

first latitude

phi2: float (radians)

second latitude

Returns:

alpha1: float (radians)

estimated forward azimuth at first point

see Karney (2013) J. Geod. for details

karta.geodesy.solve_vincenty(a, f, lambda12, phi1, phi2)[source]

Used to provide an initial guess to the inverse problem by solving the corresponding problem on a sphere.

Parameters:

a: float

equatorial radius

f: float

flattening

lambda12: flat(radians)

difference in longitudes

phi1: float (radians)

first latitude

phi2: float (radians)

second latitude

Returns:

alpha1: float (radians)

forward azimuth at first point

alpha2: float (radians)

forward azimuth at second point

s12: float

distance between points

see Karney (2013) J. Geod. for details

karta.geodesy.spherical_area(r, x1, y1, x2, y2)[source]

Area between a geodesic and the equator on a sphere

karta.geodesy.unroll_deg(deg)[source]

Return deg in the range [0, 360)