Skip to main content

Crate kinavis

Crate kinavis 

Source
Expand description

Marine navigation algorithms: compass and deviation, sailings, dead reckoning, position fixing, passage planning and guidance, tides, the sun, and state estimation.

magnetic course = compass course  + deviation(compass course)
true course     = magnetic course + variation

§Type guarantees

Angles carry their reference frame: CompassCourse, MagneticCourse, TrueCourse, GyroCourse, Variation, Deviation, RelativeBearing. Passing a magnetic course where a true one is expected, or a variation where a course is expected, does not compile. Distance and Speed are types, so knots cannot be passed as m/s.

Each type enforces its range: a Direction is finite and in [0°, 360°), a Latitude in [-90°, 90°], so pure corrections return values, not Result.

No panics on caller data; invalid input returns a NavigationError.

§Example

use kinavis::{
    navigation_solutions::{
        convert_compass_course_to_true_course, convert_true_course_to_compass_course,
    },
    CompassCourse, DeviationTable, InterpolationMethod, TrueCourse, Variation,
};

// A swing: deviation observed on every tenth of the compass, 000° to 350°.
let table = DeviationTable::from_deviations(&[
    -2.5, -0.5, 1.6, 4.4, -1.7, 0.0, 1.0, 0.3, -0.9, // 000°..080°
    0.5, -1.2, 0.8, -0.3, 1.7, -2.1, 0.4, -0.6, 1.2, // 090°..170°
    -1.3, 0.0, 0.9, -1.1, 1.5, -0.7, -13.2, -15.7, -17.9, // 180°..260°
    -19.2, -18.1, 1.8, -0.4, 0.7, -0.2, 1.4, -4.4, -2.9, // 270°..350°
])?;

let variation = Variation::new(-2.7)?;

// What is the ship actually making good, steering 003° by the compass?
let solution = convert_compass_course_to_true_course(
    CompassCourse::new(3.0)?,
    variation,
    &table,
    InterpolationMethod::Cubic,
)?;
assert_eq!(format!("{}", solution.course), "358.2°T");

// And back again: the inverse solves for the compass course the table is
// indexed by, so the two directions agree.
let back = convert_true_course_to_compass_course(
    solution.course,
    variation,
    &table,
    InterpolationMethod::Cubic,
)?;
assert!((back.course.degrees() - 3.0).abs() < 1e-9);

// This swing jumps 12.5° between 230° and 240°, steeper than a compass
// can be steered by; the result flags it.
assert!(solution.advisories.non_invertible_table);

§Modules

Value types come from kinavis_kernel and are re-exported under this crate’s paths; the algorithms are this crate’s own. Adapters that must not pull in the algorithms depend on the kernel alone.

  • angle — frame-tagged angles.
  • units — angles, distances, speeds, rate of turn.
  • position — latitude, longitude, notation.
  • time — instants with the time scale in the type; leap-second port.
  • observation — a value with its time and quality.
  • gnss — satellite fix.
  • geodesy — ellipsoids, heights with datum, ECEF, chart datums and their transformation to WGS 84.
  • local — NED and other local frames; vectors typed by frame and unit.
  • snapshot — read model: position, motion, uncertainty, age.
  • state — navigation state aggregate.
  • estimation — estimator ports.
  • environment — environment ports and the resolved sample.
  • conditions — constant and timetabled current and wind, fixed leeway.
  • tides — rule of twelfths, secondary ports, tidal diamonds as a current model.
  • sun — solar azimuth and altitude, sunrise, sunset, twilights.
  • event — events of this crate’s use cases.
  • deviation — deviation tables, periodic interpolation, coefficient fitting.
  • navigation_solutions — course and bearing conversions, gyro error, current triangle.
  • sailings — rhumb line, great circle, WGS 84 geodesic, cross-track error.
  • dead_reckoning — DR and EP, traverses, leeway.
  • fix — position lines, fixes, cocked hats, distance off.
  • relative_motion — CPA, radar plotting, avoiding manoeuvre.
  • route — passage plans: legs, distances, progress along track.
  • turning — leg-to-leg turns: radius or rate of turn, advance and transfer, wheel-over point.
  • guidance — what to steer now: track, course to steer, XTE, next wheel-over, events.
  • schedule — speed per leg, ETD and ETA, time to go, ahead/behind, required speed.
  • clearance — squat (Barrass) and under-keel clearance against the vessel’s policy.
  • composite — composite great-circle sailing below a limiting latitude, as rhumb legs.
  • anchor — anchor watch: swinging circle and dragging detection.
  • mob — man overboard datum drifted by current and wind.
  • gnss_intake — position from a GNSS fix stream: rejection, loss, acquisition, snapshot.
  • estimator — extended Kalman filter over the navigation state: pure steps and a thin shell.
  • observations — standard observations: position, velocity, heading, speed through water.
  • error — the error type.

§Models

Spherical sailings use a mean Earth radius of 6371.0088 km; sailings::geodesic uses the WGS 84 ellipsoid. Position lines are rhumb lines and intersect exactly on a Mercator chart; range fixes and relative motion are planar. Each function documents its model.

§Memory

No allocation. Deviation tables, routes and error excerpts are stored inline with bounds MAX_TABLE_NODES, MAX_WAYPOINTS and EXCERPT_BYTES; exceeding them returns KernelError::CapacityExceeded. Batch computations write into caller-owned buffers (*_into). The crate runs on bare metal without an allocator, with memory use known at compile time.

Aggregates are therefore large: pass DeviationTable and Route by reference.

§Feature flags

  • std (default) — standard library floating-point maths; implies alloc.
  • alloc — Vec-returning companions of the *_into calls.
  • libm — for no_std targets: --no-default-features --features libm.
  • serde — serialisation of the value types; deserialisation applies construction-time validation (no latitude of 500°, no duplicate headings in a table). Implies alloc.

No dependencies in the default configuration.

Re-exports§

pub use anchor::anchor_position;
pub use anchor::swinging_radius;
pub use anchor::AnchorView;
pub use anchor::AnchorWatch;
pub use clearance::height_of_tide_needed;
pub use clearance::squat;
pub use clearance::under_keel_clearance;
pub use clearance::Clearance;
pub use clearance::ClearancePolicy;
pub use clearance::Hull;
pub use clearance::Waterway;
pub use composite::composite_sailing;
pub use composite::CompositeSailing;
pub use composite::ParallelRun;
pub use conditions::Constant;
pub use conditions::FixedLeeway;
pub use conditions::Timetable;
pub use dead_reckoning::EstimatedPosition;
pub use dead_reckoning::Leg;
pub use deviation::DeviationAnalysis;
pub use deviation::DeviationCoefficients;
pub use deviation::DeviationNode;
pub use deviation::DeviationTable;
pub use deviation::InterpolatedTable;
pub use deviation::Interpolation;
pub use deviation::InterpolationMethod;
pub use deviation::SmithCoefficients;
pub use deviation::SwingObservation;
pub use deviation::MAX_TABLE_NODES;
pub use deviation::STANDARD_TABLE_LEN;
pub use error::NavigationError;
pub use error::Result;
pub use estimator::Estimator;
pub use estimator::EstimatorConfig;
pub use estimator::LatePolicy;
pub use estimator::Outcome;
pub use estimator::SteadyMotion;
pub use estimator::UpdateReport;
pub use estimator::MAX_HISTORY;
pub use estimator::MAX_SENSORS;
pub use event::AnchorEvent;
pub use event::ClearanceEvent;
pub use event::GuidanceEvent;
pub use fix::CockedHat;
pub use fix::Fix;
pub use fix::PositionLine;
pub use fix::TwoBearingDistance;
pub use gnss_intake::GnssIntake;
pub use gnss_intake::IntakeConfig;
pub use gnss_intake::IntakeOutcome;
pub use guidance::guide;
pub use guidance::GuidanceConfig;
pub use guidance::GuidanceView;
pub use mob::ManOverboard;
pub use mob::MobDatum;
pub use navigation_solutions::Advisories;
pub use navigation_solutions::CourseSolution;
pub use navigation_solutions::SteeringSolution;
pub use navigation_solutions::COARSE_TABLE_GAP_DEG;
pub use navigation_solutions::LARGE_DEVIATION_DEG;
pub use navigation_solutions::LARGE_VARIATION_DEG;
pub use navigation_solutions::MAX_BISECTIONS_INVERSE_DEVIATION;
pub use navigation_solutions::MAX_ITERATIONS_INVERSE_DEVIATION;
pub use navigation_solutions::TOLERANCE_INVERSE_DEVIATION_DEG;
pub use observations::HeadingObservation;
pub use observations::PositionObservation;
pub use observations::SpeedThroughWaterObservation;
pub use observations::VelocityObservation;
pub use relative_motion::Approach;
pub use relative_motion::Avoidance;
pub use relative_motion::Contact;
pub use relative_motion::Cpa;
pub use relative_motion::TargetSolution;
pub use relative_motion::Vessel;
pub use route::LegCursor;
pub use route::LegKind;
pub use route::Progress;
pub use route::Route;
pub use route::RouteLeg;
pub use route::MAX_WAYPOINTS;
pub use sailings::Arrival;
pub use sailings::CrossTrack;
pub use sailings::Sailing;
pub use sailings::TrackSide;
pub use sailings::EARTH_RADIUS;
pub use sailings::MAX_ITERATIONS_GEODESIC;
pub use sailings::TOLERANCE_GEODESIC_RAD;
pub use schedule::RouteEstimate;
pub use schedule::RouteSchedule;
pub use schedule::ScheduledLeg;
pub use sun::Crossing;
pub use sun::Horizon;
pub use sun::SolarPosition;
pub use tides::SecondaryPort;
pub use tides::StreamHour;
pub use tides::TidalCycle;
pub use tides::TidalStream;
pub use tides::TideEvent;
pub use turning::wheel_over_point;
pub use turning::Turn;
pub use turning::TurnMode;
pub use turning::TurnParameters;

Modules§

anchor
Anchor watch: swinging circle and dragging detection.
angle
Angles tagged with their reference frame.
clearance
Squat and under-keel clearance.
composite
Composite sailing: great circle limited to a maximum latitude.
conditions
Current, wind and leeway models implementing the kernel’s environment ports.
dead_reckoning
Dead reckoning and estimated position.
deviation
Deviation tables and their interpolation.
environment
Environment ports and the resolved sample.
error
Navigation computation errors.
estimation
Estimator ports: process model and observation.
estimator
Extended Kalman filter over the navigation state.
event
Events of this crate’s use cases.
fix
Position fixing from bearings, ranges and angles.
geodesy
Earth figure, points with height, Earth-centred Cartesian coordinates.
gnss
Satellite fix, independent of the sentence it arrived in.
gnss_intake
Position from a GNSS fix stream.
guidance
Route guidance: what to steer now, and route events.
guide
Guide to the crate: frame-tagged angles, sailings, fixing, deviation tables and the inverse problem, errors, serialisation, and memory footprint.
local
Local Cartesian frames and vectors typed by frame and unit.
mob
Man overboard datum.
navigation_solutions
Course and bearing conversions; current triangle.
observation
Observed value: time and quality.
observations
Standard observations for the estimator.
position
Geographic position: latitude, longitude, position.
relative_motion
Relative motion: CPA, radar plotting, avoiding manoeuvre.
route
Passage planning: waypoint chains and progress along them.
sailings
Sailings: course and distance between positions.
schedule
Passage schedule: ETD, ETA, and progress against plan.
snapshot
Read model of the navigation solution.
state
Navigation state: the estimator’s belief as one aggregate.
sun
Solar position, sunrise, sunset and twilights.
tides
Tides: height between high and low water, secondary port corrections, tidal stream as a CurrentModel.
time
Navigation time with the time scale in the type.
turning
Leg-to-leg turns: the wheel-over point.
units
Angles, distances, speeds and rates of turn as types.

Structs§

Angle
Angular magnitude in degrees.
Body
Forward, right, down: the vessel body frame.
Civil
Calendar reading.
Compass
Compass north of the ship’s magnetic compass.
Current
Current: set and drift.
Datum
Horizontal geodetic datum: ellipsoid and its transformation to WGS 84.
Deviation
Compass deviation: angle from magnetic north to compass north.
Direction
Direction in [0°, 360°), tagged with its reference frame.
Distance
Distance, stored in nautical miles.
Dop
Dilution of precision: geometry factor from range error to position error.
EcefPoint
Earth-centred, Earth-fixed Cartesian point, metres.
Ellipsoid
Reference ellipsoid.
Enu
East, north, up: surveying and mapping frame.
EnvironmentSample
Environment resolved for one point and instant.
ErrorEllipse
1σ horizontal position error ellipse.
EventList
Events of one operation, in order.
GeocentricUnit
Unit vector from the Earth’s centre.
GeodeticPoint
Position with height.
GnssFix
Satellite fix: position, time, method and other receiver data.
GnssFixBuilder
Builder for the optional parts of a GnssFix.
GnssQuality
Receiver-reported fix quality.
Gps
GPS time: continuous, 19 s behind TAI.
GroundTrack
Course and speed over ground.
Gyro
Gyrocompass north.
Height
Height with its vertical datum.
Helmert
Seven-parameter Helmert transformation between geocentric frames: translation, small rotation, scale.
InlineStr
Short inline string.
Instant
Instant on one time scale, nanosecond resolution.
Latitude
Latitude in [-90°, 90°], north positive.
LocalFrame
NED frame anchored at a point.
Longitude
Longitude in [-180°, 180°), east positive.
Magnetic
Magnetic north.
MagneticField
Earth’s magnetic field at a point: north, east, down components in nT.
NavigationSnapshot
Vessel state at an instant, as far as the producer knows.
NavigationState
Estimator belief about the vessel at one instant.
Ned
North, east, down: the navigation frame.
Observed
Value with its observation time and quality.
Position
Position on the Earth’s surface (WGS 84).
Quality
Reading quality: status and optional 1σ uncertainty.
RateOfTurn
Rate of turn in °/min, as shown by the ROT indicator.
RelativeBearing
Bearing clockwise from the ship’s head, in [0°, 360°).
SensorId
Observation source identifier: the source’s name, truncated to SENSOR_NAME_BYTES so events stay plain values.
Speed
Speed, stored in knots. Negative is sternway.
StatePriors
Initial 1σ priors where the fix provides none.
Tai
International Atomic Time: continuous reference scale.
TargetId
Target identifier: radar track number or AIS MMSI.
True
True (geographic) north.
Utc
Coordinated Universal Time, with leap seconds.
Variation
Magnetic variation: angle from true north to magnetic north.
Vector3
Three components of one quantity in one frame.
VesselMotion
Motion through the water, as input to a leeway model.
Wind
True wind: direction from and speed.

Enums§

CardinalPoint
Cardinal or intercardinal compass point.
EastWest
Longitude hemisphere.
FixType
Fix method.
KernelError
Kernel operation failure.
NavigationEvent
Kernel event.
NavigationIntegrity
Integrity of the navigation solution as a whole.
NorthSouth
Latitude hemisphere.
ObservationStatus
Source-reported validity of a reading.
PositionSource
Position source.
RejectionReason
Observation rejection reason.
SensorHealth
Health of one observation source, as judged by its consumer.
Side
Side relative to the bow.
StateComponent
State vector component, by name.
VerticalDatum
Vertical datum.

Constants§

EXCERPT_BYTES
Maximum bytes of offending input carried by an error.
MAX_DEVIATION_DEG
Maximum magnitude of a compass deviation, degrees.
MAX_EVENTS
Default per-operation event capacity.
MAX_FIELD_NANOTESLA
Maximum magnitude of a field component, nT.
MAX_VARIATION_DEG
Maximum magnitude of a magnetic variation, degrees.
SENSOR_NAME_BYTES
Maximum sensor name length in an event, bytes.

Traits§

CompassModel
Ship’s magnetism as compass deviation.
CurrentModel
Current: constant, tidal, GRIB, ocean model.
Event
Type storable in an EventList: something that happened at an instant.
Frame
Reference frame of a Direction.
LeapSeconds
Leap-second table: TAI − UTC at a given instant.
LeewayModel
Leeway model for a hull.
MagneticModel
Earth’s magnetic field: WMM, IGRF, compass rose, constant.
TideModel
Tide: tables, harmonic prediction, gauge.
TimeScale
Time scale of an Instant.
VectorFrame
Frame of a Vector3.
VectorUnit
Quantity carried by each Vector3 component.
WindModel
True wind: forecast, observation, constant.

Functions§

wrap180
Normalises a finite angle into [-180.0, 180.0).
wrap360
Normalises a finite angle into [0.0, 360.0).

Type Aliases§

CompassBearing
Bearing, compass. Alias of CompassCourse.
CompassCourse
Course or bearing, compass.
Excerpt
Excerpt of offending input.
GyroBearing
Bearing, gyro. Alias of GyroCourse.
GyroCourse
Course, gyro.
MagneticBearing
Bearing, magnetic. Alias of MagneticCourse.
MagneticCourse
Course or bearing, magnetic.
TrueBearing
Bearing, true. Alias of TrueCourse.
TrueCourse
Course or bearing, true.