API Reference#

Everything below is re-exported from the top-level gradeit package, so from gradeit import gradeit, USGSLocal, Wood2014Filter is the expected import style. The submodules are documented directly to keep each entry in one place.

Core#

gradeit(data, *, elevation_model=None, elevation_filter=Wood2014Filter(interval_ft=100.0, savgol_window_ft=600.0, savgol_polyorder=3, binomial_sigma_ft=100.0, residual_threshold_ft=8.0, residual_grow_ratio=0.5, max_discard_len_ft=2000.0, max_discard_fraction=0.25, max_gap_ft=1000.0, min_node_occupancy=0.35), lat_col='latitude', lon_col='longitude')[source]#

Append elevation and road grade to a sequence of GPS points.

Parameters:
  • data (pd.DataFrame | Mapping[str, Sequence[float]] | Sequence[tuple[float, float]] | Sequence[Coordinate] | ndarray) -- The coordinates to grade. Accepts a pandas DataFrame, a mapping keyed by lat_col / lon_col, a numpy array of shape (n, 2), or an iterable of Coordinate or (latitude, longitude) pairs. See gradeit.io.to_coordinates().

  • elevation_model (ElevationModel | None) -- Model that provides elevation. Defaults to the online USGSApi service. Use USGSLocal with downloaded tiles, or pass a custom ElevationModel.

  • elevation_filter (ElevationFilter | Sequence[ElevationFilter] | None) -- Filter elevation before calculating grade. Pass one ElevationFilter or a sequence, applied in order. Defaults to Wood2014Filter. Pass None or [] to skip filtering. Put BridgeFilter first when using it with other filters.

  • lat_col (str) -- Column/key names for the latitude and longitude, used only for the DataFrame and mapping input forms.

  • lon_col (str) -- Column/key names for the latitude and longitude, used only for the DataFrame and mapping input forms.

Returns:

Numpy arrays for the input coordinates, elevation, distance, and grade. Raw values use the _unfiltered suffix. Filtered values use _filtered when a filter runs. The input is not changed.

Return type:

GradeResult

to_coordinates(data, lat_col='latitude', lon_col='longitude')[source]#

Convert supported input into a list of Coordinate objects.

Accepts a (n, 2) numpy array, a DataFrame, a mapping with latitude and longitude keys, or an iterable of coordinates or (latitude, longitude) pairs. lat_col and lon_col apply to DataFrame and mapping input.

Raises:

InvalidInputError -- If data is not one of the supported forms (or has the wrong shape / missing columns).

Parameters:
  • data (CoordinateInput)

  • lat_col (str)

  • lon_col (str)

Return type:

list[Coordinate]

class GradeResult(coordinates, elevation_ft_unfiltered, distances_ft, grade_dec_unfiltered, elevation_ft_filtered=None, grade_dec_filtered=None)[source]#

Bases: object

The output of gradeit.gradeit().

Stores NumPy arrays and source coordinates. Raw elevation and grade fields end in _unfiltered. Filtered fields end in _filtered and are set only when filtering runs. Use to_dict() or to_dataframe() for tabular output.

Parameters:
  • coordinates (list[Coordinate])

  • elevation_ft_unfiltered (ndarray)

  • distances_ft (ndarray)

  • grade_dec_unfiltered (ndarray)

  • elevation_ft_filtered (ndarray | None)

  • grade_dec_filtered (ndarray | None)

to_dict()[source]#

Return the result as a column-name -> list mapping.

The keys match the result field names. Filtered fields are included when they are available.

Return type:

dict[str, list]

to_dataframe()[source]#

Return the result as a new pandas DataFrame.

Raises:

MissingDependencyError -- If pandas is not installed (pip install gradeit[pandas]).

Return type:

pd.DataFrame

plot_map(**kwargs)[source]#

Render this result on an interactive folium map colored by grade.

Passes all keyword arguments to gradeit.plotting.plot_grade_map(). Requires gradeit[plot].

Return type:

folium.Map

class Coordinate(latitude, longitude)[source]#

Bases: object

A WGS84-style latitude/longitude point.

Stores latitude and longitude as floats.

Parameters:
  • latitude (float)

  • longitude (float)

classmethod from_lat_lon(latitude, longitude)[source]#

Create a Coordinate from a latitude and longitude.

Parameters:
  • latitude (float)

  • longitude (float)

Return type:

Coordinate

get_grade(elevation_profile, distances, min_distance_ft=1.0)[source]#

Compute decimal road grade (rise/run) for an elevation profile.

Grade is elevation change / distance between points. Segments shorter than min_distance_ft use the previous valid grade.

Parameters:
  • elevation_profile (List[float]) -- Elevation at each point (n > 1).

  • distances (List[float]) -- Horizontal distance of each segment, length len(elevation_profile) - 1.

  • min_distance_ft (float, optional) -- Segments shorter than this use the previous grade. Default: 1.0.

Return type:

list[float]

get_distances(coordinates)[source]#

Return the distance in feet between each pair of nearby coordinates.

Parameters:

coordinates (list[Coordinate])

Return type:

list[float]

haversine(coord1, coord2, get_bearing=False)[source]#

Return the great-circle distance in kilometers between two coordinates.

Parameters:
Return type:

float

Elevation models#

class ElevationModel[source]#

Bases: object

Base class for models that look up elevation.

abstract get_elevation(trace)[source]#

Return elevation in feet for the trace coordinates.

Parameters:

trace (list[Coordinate])

Return type:

list[float]

Online elevation lookup against the USGS 3DEP service.

Samples points in batches through the 3DEP ImageServer getSamples service.

class USGSApi(batch_size=1000, sampling='nearest', timeout=60.0, max_retries=3)[source]#

Bases: ElevationModel

Look up elevation from the public USGS 3DEP bare-earth service.

Sends up to MAX_POINTS_PER_REQUEST points in each request. Points outside service coverage return NaN.

Parameters:
  • batch_size (int) -- Points per request. Values above MAX_POINTS_PER_REQUEST are capped.

  • sampling (str) -- "nearest" (default) returns the containing cell. "bilinear" interpolates the surrounding cells.

  • timeout (float) -- Per-request timeout in seconds.

  • max_retries (int) -- Attempts for a timeout, connection error, or retryable HTTP status.

  • https (More information is available at)

get_elevation(trace)[source]#

Return elevation in feet for the trace coordinates.

Parameters:

trace (list[Coordinate])

Return type:

list[float]

class USGSLocal(usgs_db_path, sampling='bilinear')[source]#

Bases: ElevationModel

An elevation model to look up elevation by latitude, longitude coordinates. The source data is a locally downloaded raster database containing the USGS 1/3 arc-second Digital Elevation Model.

Parameters:
  • usgs_db_path (pathlib.Path) -- Directory holding the downloaded tiles, laid out as {grid_ref}/USGS_13_{grid_ref}.tif (see scripts/get_usgs_tiles.py).

  • sampling (str) -- "bilinear" (default) interpolates the four surrounding cells. "nearest" returns the containing cell. Points outside a tile and no-data cells return NaN.

get_elevation(trace)[source]#

Return elevation in feet for the trace coordinates.

Parameters:

trace (list[Coordinate])

Return type:

list[float]

get_raster_elev_profile(coordinates, usgs_db_path, sampling='bilinear')[source]#

Look up an elevation profile (in feet) for a list of coordinates from a local USGS 1/3 arc-second raster database.

Points are grouped by the 1-degree tile that contains them so each tile is opened once; results are returned in the original coordinate order, with NaN for points outside the available tiles or over no-data cells.

Parameters:
  • coordinates (list[Coordinate])

  • usgs_db_path (Path | str)

  • sampling (str)

Return type:

list[float]

build_grid_refs(lats, lons)[source]#

Map latitude/longitude values to USGS tile grid-reference IDs (e.g. "n40w105"). Tiles are named for their north-west corner with the longitude zero-padded to three digits. Coverage is the northern/western hemisphere (the USGS product extent); points elsewhere map to "0".

Parameters:

longitudes. (Two iterables of float latitudes and)

Returns:

A numpy array of grid-reference ID strings, one per input point.

Return type:

ndarray

Filters#

class ElevationFilter[source]#

Bases: object

Base class for elevation-profile filters.

abstract filter(elevation_profile, coordinates)[source]#

Return a filtered elevation profile in feet.

Parameters:
  • elevation_profile (list[float])

  • coordinates (list[Coordinate])

Return type:

list[float]

Filter elevation with the Wood et al. (2014) method.

The filter resamples elevation onto a distance grid, smooths it, replaces large errors, smooths again, and returns values at the original points.

binomial_kernel(order)[source]#

The normalized binomial (Pascal's triangle) kernel of a given order.

The result has an odd length, sums to 1, and has an order of at least 2.

Parameters:

order (int)

Return type:

ndarray

binomial_filter(x, order)[source]#

Apply a binomial smoothing filter to a 1-D signal.

Uses odd reflection at both ends to preserve the local slope.

Parameters:
  • x (Sequence[float] | ndarray)

  • order (int)

Return type:

ndarray

class Wood2014Filter(interval_ft=100.0, savgol_window_ft=600.0, savgol_polyorder=3, binomial_sigma_ft=100.0, residual_threshold_ft=8.0, residual_grow_ratio=0.5, max_discard_len_ft=2000.0, max_discard_fraction=0.25, max_gap_ft=1000.0, min_node_occupancy=0.35)[source]#

Bases: ElevationFilter

Elevation filtration per Wood et al. (2014), NLR/TP-5400-61109.

Resamples elevation onto a uniform distance grid, smooths it, replaces large residuals, smooths again, and restores the original point spacing.

Parameters:
  • interval_ft (float) -- Target distance between grid nodes. Default: 100 ft. The actual grid includes the first and last trace points.

  • savgol_window_ft (float) -- Savitzky-Golay window width and polynomial order. The width is in feet.

  • savgol_polyorder (int) -- Savitzky-Golay window width and polynomial order. The width is in feet.

  • binomial_sigma_ft (float) -- Width of the binomial stage in feet.

  • residual_threshold_ft (float) -- Replace a node when its smoothed residual exceeds this value. Default: 8 ft.

  • residual_grow_ratio (float) -- Include nearby nodes when their residual exceeds this fraction of the threshold. Set to 1.0 to disable this expansion.

  • max_discard_len_ft (float) -- Do not replace runs longer than this distance.

  • max_discard_fraction (float) -- Maximum fraction of measured nodes that may be replaced.

  • max_gap_ft (float) -- Split the trace at missing-elevation gaps longer than this distance.

  • min_node_occupancy (float) -- Warn when fewer than this fraction of grid nodes contain a GPS point. Set to 0.0 to disable the warning.

filter(elevation_profile, coordinates)[source]#

Return a filtered elevation profile in feet.

Parameters:
  • elevation_profile (list[float])

  • coordinates (list[Coordinate])

Return type:

list[float]

resolve_parameters(f, total_ft, n_nodes=None)[source]#

Return (delta_ft, savgol_window, savgol_polyorder, binomial_order).

Parameters:
Return type:

tuple[float, int, int, int]

Bridge correction as an ElevationFilter.

USGS bare-earth elevation data may show a dip under a bridge or overpass. This filter finds short dips and fills them with a straight elevation line. Apply it before Wood2014Filter.

class BridgeFilter(baseline_radius_ft=5280.0, min_dip_depth_ft=5.0, min_peak_depth_ft=10.0, min_bridge_len_ft=50.0, max_bridge_len_ft=7920.0, max_aspect_ratio=50.0, grade_plausibility_tol=0.05)[source]#

Bases: ElevationFilter

Interpolate elevation across bare-earth-DEM bridge artifacts.

Compares each point with the highest elevation on both sides. A point that is much lower than both sides can be part of a bridge artifact.

Parameters:
  • baseline_radius_ft (float) -- Distance, in feet, checked on each side of a point. Default: 1 mile. Set it wider than the bridge, but narrow enough to avoid treating a valley as a bridge.

  • min_dip_depth_ft (float) -- Per-point threshold for inclusion in a candidate dip run. Points where baseline - elevation is at most this value are not dip candidates.

  • min_peak_depth_ft (float) -- A run needs at least one point this deep to be accepted.

  • min_bridge_len_ft (float) -- Minimum and maximum length in feet for an accepted run. Length includes the clean point on each side used for interpolation.

  • max_bridge_len_ft (float) -- Minimum and maximum length in feet for an accepted run. Length includes the clean point on each side used for interpolation.

  • max_aspect_ratio (float) -- Reject runs whose length divided by peak depth is too large.

  • grade_plausibility_tol (float) -- Reject a correction when its grade differs too much from nearby road grade.

filter(elevation_profile, coordinates)[source]#

Return a filtered elevation profile in feet.

Parameters:
  • elevation_profile (list[float])

  • coordinates (list[Coordinate])

Return type:

list[float]

savgol_filter(x, window_length, polyorder=3)[source]#

Apply a Savitzky-Golay filter to a 1-D signal.

Parameters:
  • x (Sequence[float] | ndarray) -- the signal to smooth.

  • window_length (int) -- the (odd) length of the filter window.

  • polyorder (int) -- the order of the polynomial fit within each window.

Returns:

The smoothed signal as a float64 array the same length as x.

Return type:

ndarray

Uses interpolated values at both ends of the signal.

Plotting#

Interactive map plotting for a GradeResult.

Provides plot_grade_map(), which colors each GPS segment by road grade.

folium is an optional dependency; install via pip install gradeit[plot].

plot_grade_map(result, *, grade='auto', grade_range_pct=None, weight=5, opacity=0.85, tiles='CartoDB positron', show_endpoints=True)[source]#

Render the trace on an interactive folium map, colored by grade.

Each segment is colored by its grade. Hovering shows its index, grade, elevation, and length.

Parameters:
  • result (GradeResult) -- The output of gradeit.gradeit().

  • grade (GradeChoice) --

    Which grade profile to plot.

    • "auto" (default) -- plot both raw and filtered as toggleable layers when filtering ran, else just raw.

    • "raw" -- always plot the raw, unfiltered grade.

    • "filtered" -- plot only the filtered grade (requires that gradeit() was called with a filter).

    • "both" -- plot raw and filtered as toggleable layers (requires that gradeit() was called with a filter).

  • grade_range_pct (tuple[float, float] | None) -- (vmin, vmax) percent-grade limits for the color scale. Grades beyond this range use the end colors. If None, the range is centered on zero using the largest absolute grade.

  • weight (int) -- Stroke width of each polyline segment, in pixels.

  • opacity (float) -- Stroke opacity in [0, 1].

  • tiles (str) -- Base map tile source passed through to folium.Map. Defaults to "CartoDB positron". Other options include "CartoDB Voyager", "CartoDB dark_matter", and "OpenStreetMap".

  • show_endpoints (bool) -- If true, add Start/End markers at the first and last coordinates.

Returns:

A folium map fitted to the trace bounds, with a color scale legend and (when more than one layer is shown) a layer control.

Return type:

folium.Map

Raises:

Exceptions#

Exception and warning hierarchy for gradeit.

All package errors inherit from GradeitError. Specific errors also inherit from the matching built-in error type.

exception GradeitError[source]#

Bases: Exception

Base class for all gradeit errors.

exception InvalidInputError[source]#

Bases: GradeitError, ValueError

The coordinate input could not be interpreted (wrong type or shape).

exception MissingDependencyError[source]#

Bases: GradeitError, ImportError

An optional dependency (e.g. pandas, requests) is needed but not installed.

exception ElevationLookupError[source]#

Bases: GradeitError

An elevation source failed to return a usable value.

exception GradeitWarning[source]#

Bases: UserWarning

Base class for all gradeit warnings.

Warnings do not inherit from GradeitError.

exception SparseGridWarning[source]#

Bases: GradeitWarning

A filter's distance grid is finer than the GPS points can support.

This warning is raised when most filter grid nodes have no GPS point.