2.9.1.15. pycsamt.seg.survey#
Classes
|
Profile helper for one or many |
|
Lightweight table view for station metadata derived from |
|
Elevation profile helper. |
- class pycsamt.seg.survey.EDIProfile(items, *, verbose=0)[source]
Bases:
SurveyBaseProfile helper for one or many
EDIFileobjects. Computes small-area geometry (easting/northing), cumulative distance along line, profile azimuth, and exposes utilities to adjust coordinates and push them back into EDI headers.The class accepts a single file, an iterable of files, or an
EDICollection. Coordinates are read from>HEADand converted to working planar coordinates. For short lines the equirectangular approximation is used, and distances/azimuth are computed in that local frame.- Parameters:
- Variables:
stations (list of str) – Station identifiers resolved from
DATAIDor file name.lon (lat,) – Geographic coordinates (degrees).
elev (ndarray of float) – Elevations when present, missing values become
0.distance (ndarray of float) – Cumulative distance from the first site (meters).
azimuth (float) – Bearing of the profile in degrees, clockwise from North, in
[0, 360).xy (tuple of ndarray) – Working (easting, northing) arrays in meters.
table (list of dict) – Row-wise view exposing station, lat, lon, elev, easting, northing, and UTM zone (when available).
- get_bearing(method='endpoints')[source]
Compute bearing from either endpoints or a PCA-like fit of the track.
- get_step()[source]
Return cumulative distance and cache it for reuse.
- adjust(origin=None, azimuth=None, spacing=None, use_mean=True)[source]
Build an idealized straight profile and compute adjusted positions and lat/lon.
- update(use_adjusted=True, update_elev=False)[source]
Write back adjusted coordinates to each site’s header.
- Parameters:
- Return type:
- plot_profile(use_adjusted=False, annotate=True, title=None)[source]
Plot elevation against along-profile distance.
- plot_track(use_adjusted=False, title=None)[source]
Plot plan-view easting/northing track.
Notes
The small-area equirectangular frame is adequate for short profiles. For long lines or large latitude spans prefer a full projection workflow. When the UTM zone can be determined, adjusted coordinates are converted back to geographic using that zone.
Examples
Load two sites and compute azimuth and distance:
prof = EDIProfile([ed1, ed2]) print(float(prof.azimuth)) d = prof.distance
Adjust to a regular spacing and push back to headers:
prof.adjust(spacing=50.0).update()
See also
StationsTabular view of station metadata and projected coordinates.
TopographyElevation profile builder with smoothing and trend tools.
References
[EDIProfile-1]SEG EDI MT/EMAP standard (1987), MTNet. https://www.mtnet.info/docs/seg_mt_emap_1987.pdf
[EDIProfile-2]Snyder, J. P. (1987). Map Projections – A Working Manual, USGS Prof. Paper 1395.
- get_bearing(*, method='endpoints')[source]
Estimate the survey bearing (azimuth) in degrees.
- Parameters:
method ({‘endpoints’, ‘linear’}, default
'endpoints') – With'endpoints'the azimuth is computed from the first to the last station. With'linear'a best-fit axis is estimated by SVD of centered coordinates.- Returns:
Bearing in
[0, 360)(clockwise from north), orNoneif fewer than two valid stations exist.- Return type:
float or None
Notes
Uses working projected coordinates (easting/northing), suitable for small-area profiles.
- get_step(*, method='mean', as_array=False)[source]
Derive the inter-station spacing from the track.
- Parameters:
method ({‘mean’, ‘median’}, default
'mean') – Aggregation used when returning a scalar spacing.as_array (bool, default
False) – IfTrue, return the pairwise segment lengths as a 1-D array of sizen-1. IfFalse, return a single spacing computed withmethod.
- Returns:
Either a scalar spacing or the per-segment distances.
- Return type:
float or ndarray
Notes
Distances are computed from consecutive projected coordinates; missing stations are ignored.
- adjust(*, origin=None, azimuth=None, spacing=None, step=None, use_mean=True)[source]
Build an idealized, straightened profile and store the adjusted coordinates.
- Parameters:
origin (tuple(float, float), optional) – Reference
(easting, northing)for the first station. Defaults to the first raw station.azimuth (float, optional) – Bearing of the adjusted line in degrees. Defaults to
get_bearing().spacing (float, optional) – Fixed spacing between consecutive stations (meters).
step (float, optional) – Alias for
spacingfor convenience.use_mean (bool, default
True) – When bothspacingandstepareNone, compute spacing from observed distances using mean ifTrueor median ifFalse.
- Returns:
The instance (allows chaining).
- Return type:
Notes
Adjusted easting/northing are projected back to latitude and longitude using the dominant UTM zone of the track. Results are stored in
_adj_e/_adj_n/_adj_lat/_adj_lon.
- update(*, use_adjusted=True, update_elev=False)[source]
Push current coordinates back into the underlying EDI headers.
- Parameters:
use_adjusted (bool, default
True) – IfTruewrite adjusted lat/lon (fromadjust()). If no adjusted coordinates exist, fall back to raw lat/lon.update_elev (bool, default
False) – Also write elevations when present in the profile table.
- Returns:
The instance (allows chaining).
- Return type:
Notes
This mutates the in-memory
EDIFileobjects held by the profile; it does not write to disk.
- plot_profile(*, ax=None, use_adjusted=False, annotate=True, title=None)[source]
Plot elevation versus along-profile distance.
- Parameters:
ax (matplotlib.axes.Axes, optional) – Target axes. If omitted, a new figure/axes is made.
use_adjusted (bool, default
False) – IfTruerecompute distances from adjusted coordinates for the overlay. Raw elevation values are used in both cases.annotate (bool, default
True) – Draw station labels next to points.title (str, optional) – Axes title.
- Returns:
The axes with the profile plot.
- Return type:
Notes
Uses the profile’s cached cumulative distances. Call
adjust()first to visualize an adjusted line.
- plot_track(*, ax=None, use_adjusted=False, title=None)[source]
Plot plan-view station positions (easting vs. northing).
- Parameters:
ax (matplotlib.axes.Axes, optional) – Target axes. If omitted, a new figure/axes is made.
use_adjusted (bool, default
False) – Plot the straightened track if adjusted coordinates exist; otherwise plot raw positions.title (str, optional) – Axes title.
- Returns:
The axes with the track plot.
- Return type:
Notes
Axes aspect is set to equal for a faithful plan view.
- class pycsamt.seg.survey.Stations(items, *, verbose=0)[source]
Bases:
SurveyBaseLightweight table view for station metadata derived from
EDIFileobjects. Provides quick access to names, geographic coordinates, optional elevations, and working projected coordinates to support survey tasks.- Parameters:
- Variables:
- table()[source]
Materialize the rows as a list of dicts with keys
station,lat,lon,elev,e(east),n(north),zoneandpath.
- to_dataframe()[source]
Convert the table to a pandas DataFrame when pandas is available.
- bounds()
Geographic bounding box as
(min_lat, min_lon, max_lat, max_lon).
- select(keys=None, pattern=None, regex=None, pred=None)[source]
Return a filtered view. Multiple filters are combined with logical AND. See the method docstring for details.
- sort(by='station', reverse=False, inplace=True)[source]
Sort rows by a column (e.g.
'station','lat','lon','elev','e','n'). Returns this instance or a new view depending oninplace.
- offsets(origin=None, azimuth=None)[source]
Compute along-line and cross-line offsets in meters from projected coordinates. The profile axis is set by
azimuthor inferred from endpoints.
- set_coords(key, \*, lat=None, lon=None, elev=None)[source]
Update coordinates for a single station. When the backing
EDIFileis available its>HEADvalues are kept in sync.
Notes
The class performs minimal validation. Rows missing lat/lon are skipped. Projected coordinates are intended for short-range work; for mapping at scale prefer the GIS utilities provided elsewhere in the package.
Examples
Build a table and print a compact view:
sts = Stations(coll) for r in sts.table(): print(r["station"], r["lat"], r["lon"])
Filter, sort, and compute offsets:
sel = sts.select(pattern="K*", pred=lambda r: r["elev"] > 800) sel.sort(by="e") along, across = sel.offsets()
See also
EDIProfileTrack-aware helper that computes distance and azimuth.
TopographyProduces elevation profiles from stations or profiles.
References
[Stations-1]SEG EDI MT/EMAP standard (1987), MTNet. https://www.mtnet.info/docs/seg_mt_emap_1987.pdf
- select(*, keys=None, pattern=None, regex=None, pred=None)[source]
Return a filtered view of the stations table.
Multiple filters are combined with logical AND. When no filter is given the original view is returned.
- Parameters:
keys (sequence of str, optional) – Station identifiers to keep. Unknown ids are ignored.
pattern (str, optional) – Glob-like pattern matched against station ids (e.g.
'AB*'). Case-sensitive.regex (str, optional) – Regular expression matched against station ids using
re.search().pred (callable, optional) – A predicate
pred(row) -> boolevaluated on each row dict. Keep rows for which the predicate returnsTrue.
- Returns:
A new
Stationsview with rows that match the filters.- Return type:
Notes
Filtering does not modify the original container. Rows lacking a station id are always dropped.
Examples
Keep stations starting with
'K'and above 800 m:sel = sts.select(pattern="K*", pred=lambda r: r["elev"] > 800)
- sort(*, by='station', reverse=False, inplace=True)[source]
Sort the stations table by a column.
- Parameters:
by (str, default
'station') – Column name to sort by (e.g.'station','lat','lon','elev','e','n').reverse (bool, default
False) – IfTruesort in descending order.inplace (bool, default
True) – IfTruemodify this instance and return it. Otherwise return a new sorted view.
- Returns:
The sorted
Stationsobject (self or a copy).- Return type:
Notes
Missing values are placed at the end. Unknown columns raise a
KeyError.
- offsets(*, origin=None, azimuth=None)[source]
Compute along-line and cross-line offsets (meters).
Offsets are computed from projected coordinates. The along-line axis is defined by the given
azimuth; the cross-line axis is perpendicular to it.- Parameters:
- Returns:
along (ndarray of float) – Distances projected on the profile axis.
across (ndarray of float) – Signed distances perpendicular to the profile axis.
- Return type:
Notes
Rows without valid projected coordinates are skipped in the computation and do not contribute to the result.
- set_coords(key, *, lat=None, lon=None, elev=None)[source]
Update coordinates for a single station.
- Parameters:
- Return type:
None
Notes
The in-memory row is updated. If the backing
EDIFileis attached for that station, its>HEADvalues are also updated to keep them in sync. Unknown station ids raise aKeyError.
- to_dataframe(*, columns=None, index='station', coerce_numeric=True)[source]
Return a pandas
DataFrameview of the station table.- Parameters:
columns (sequence of str, optional) – Subset and ordering of columns to include. When omitted, a sensible default is used:
('station','lat','lon','elev','e','n','zone', 'path'). Missing names are ignored.index (str or None, default
'station') – Column to set as the DataFrame index. If the name is not present, no index is set. UseNoneto leave the default RangeIndex.coerce_numeric (bool, default
True) – Try converting known numeric columns (lat,lon,elev,e,n) to numeric dtypes. Non convertible values becomeNaN.
- Returns:
A DataFrame with one row per station.
- Return type:
Notes
pandasis imported lazily. If it is not available, anImportErroris raised. The method is read-only and does not mutate the underlying table.Examples
Basic usage:
df = Stations(coll).to_dataframe() print(df.head())
Custom subset and index:
df = Stations(coll).to_dataframe( columns=("station", "elev", "e", "n"), index="station", )
See also
tableList-of-dicts representation of the rows.
boundsGeographic bounding box.
selectFilter rows prior to conversion.
- class pycsamt.seg.survey.Topography(items, *, use_profile_step=True, verbose=0)[source]
Bases:
SurveyBaseElevation profile helper. Builds paired arrays of distance and elevation from an
EDIProfile,Stations, a collection, or rawEDIFileinputs. Includes smoothing, detrending, resampling, and quick plotting.- Parameters:
items (EDIProfile or Stations or EDICollection or EDIFile ) – or iterable of EDIFile Source of station positions and elevations. When an
EDIProfileis given, along-line distances are reused by default.use_profile_step (bool, default
True) – IfTrueanditemsis anEDIProfile, copy its along-profile distances; otherwise recompute distances from planar coordinates.verbose (int, default
0) – Verbosity level for diagnostics.
- Variables:
- smooth(window=5, method='median')[source]
Apply moving median or mean smoothing to elevation.
- Parameters:
- Return type:
- detrend()[source]
Remove a best-fit linear trend and keep it for plotting.
- Return type:
- resample(step)[source]
Resample to a fixed distance step using interpolation.
- Parameters:
step (float)
- Return type:
- gradient(as_degrees=False)[source]
First derivative of elevation vs distance; optionally in degrees.
- plot(ax=None, title=None, show_trend=True)[source]
Quick plot of elevation vs distance.
Notes
If the input is an
EDIProfilethat has not yet computed distances, they are derived automatically. When distances or elevations are missing the result is empty.Examples
From a profile and detrend before plotting:
topo = Topography(prof).detrend().smooth(window=7) ax = topo.plot(title="Detrended topography")
From a list of files, resampled every 25 m:
topo = Topography(edis).resample(step=25.0)
See also
EDIProfileProvides distances and azimuth and can adjust station positions.
StationsTabular access to station metadata.
References
[Topography-1]SEG EDI MT/EMAP standard (1987), MTNet. https://www.mtnet.info/docs/seg_mt_emap_1987.pdf
- smooth(*, window=5, method='median')[source]
Smooth the elevation series with a sliding window.
- Parameters:
window (int, default
5) – Window length (samples). Values<=1skip smoothing.method ({‘median’, ‘mean’}, default
'median') – Smoothing kernel.'median'is robust to spikes;'mean'uses a simple moving average.
- Returns:
The instance (in place), allowing chaining.
- Return type:
Notes
Edge handling is performed by shrinking the window near the bounds. This modifies the internal elevation array.
- detrend()[source]
- Return type:
- resample(*, step)[source]
Resample distance/elevation to a fixed along-line step.
- Parameters:
step (float) – Target spacing in meters for the resampled profile.
- Returns:
The instance (in place), allowing chaining.
- Return type:
Notes
Distances are regridded on
[dmin, dmax]with uniform spacing and elevations are linearly interpolated.
- gradient(*, as_degrees=False)[source]
Compute local slope between consecutive samples.
- Parameters:
as_degrees (bool, default
False) – IfTrue, return the slope angle in degrees. IfFalse, return the rise-over-run ratio.- Returns:
Array of length
len(distance) - 1with per-segment slopes (or angles when requested).- Return type:
ndarray
- plot(*, ax=None, title=None, show_trend=True)[source]
Plot elevation versus distance.
- Parameters:
ax (matplotlib.axes.Axes, optional) – Target axes. A new figure/axes is created when omitted.
title (str, optional) – Title for the axes.
show_trend (bool, default
True) – Overlay the last computed trend line (fromdetrend()) when available.
- Returns:
The axes with the rendered profile.
- Return type: