weather

package
v0.0.0-...-487d92c Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 24 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package weather reads forecast fields (wind, waves, currents) from GRIB2 files such as ECMWF open data. Decoding is pure Go: CCSDS packing (GRIB2 template 5.42, used by ECMWF) is handled by a port of libaec, so the build needs no C toolchain.

Index

Constants

View Source
const (
	MaxTrackPoints = 20000
	MaxVoyageHours = 2000
	MinSpeedKn     = 6
	MaxSpeedKn     = 30
)

Limits on a voyage request.

View Source
const Credit = "Forecast data: ECMWF IFS open data, CC BY 4.0"

Credit is the attribution shown wherever forecast data is displayed.

View Source
const DefaultBaseURL = "https://data.ecmwf.int/forecasts"

DefaultBaseURL is the ECMWF open data site.

View Source
const MaxTileZoom = 8

MaxTileZoom is the deepest zoom level tiles are rendered at. The forecast grid is 0.25 degrees, so deeper tiles would only show enlarged pixels.

View Source
const NoValue int16 = -32768

NoValue marks a missing sample (land, or a field that was never written).

Variables

View Source
var ErrBadVoyage = errors.New("bad voyage request")

ErrBadVoyage wraps every error PlanVoyage gives for an unusable request.

View Source
var ErrNotFound = errors.New("weather: tile not found")

ErrNotFound means a tile request names no tile: an unknown field, an hour that is not a forecast step, or a position outside the tile pyramid.

View Source
var Scales = map[string][]ScaleStop{
	"wind": {
		{0, "#440154"}, {10, "#414487"}, {20, "#2a788e"}, {30, "#22a884"},
		{40, "#7ad151"}, {50, "#fde725"}, {60, "#ffb000"},
	},
	"waves": {
		{0, "#440154"}, {2, "#414487"}, {4, "#2a788e"}, {6, "#22a884"},
		{8, "#7ad151"}, {10, "#fde725"}, {12, "#ffb000"},
	},
	"current": {
		{0, "#440154"}, {0.5, "#414487"}, {1, "#2a788e"}, {1.5, "#22a884"},
		{2, "#7ad151"}, {3, "#fde725"}, {4, "#ffb000"},
	},
}

Scales gives the colour scale of each tile field: "wind" in knots, "waves" in metres and "current" in knots. They are sequential, dark to light with a hue shift, so they stay readable with the common colour-vision deficiencies.

Functions

func DefaultSteps

func DefaultSteps() []int

DefaultSteps returns the forecast hours stored per run: every 3 hours to hour 144, then every 6 hours to hour 360 (85 steps).

func RunID

func RunID(t time.Time) string

RunID names a forecast run by its reference time, e.g. "2026110212".

Types

type Conditions

type Conditions struct {
	WindKn       *float64 `json:"wind_kn"`
	WindFromDeg  *float64 `json:"wind_from_deg"`
	GustKn       *float64 `json:"gust_kn"`
	PressureHPa  *float64 `json:"pressure_hpa"`
	CurrentKn    *float64 `json:"current_kn"`
	CurrentToDeg *float64 `json:"current_to_deg"`
	WaveM        *float64 `json:"wave_m"`
	WaveFromDeg  *float64 `json:"wave_from_deg"`
	WavePeriodS  *float64 `json:"wave_period_s"`
}

Conditions is Values converted for display: knots, hPa and compass degrees. A nil field has no value.

type Fetcher

type Fetcher struct {
	BaseURL string
	Client  *http.Client
	Steps   []int
	Workers int
	Now     func() time.Time
	// contains filtered or unexported fields
}

Fetcher downloads forecast runs from ECMWF open data. Zero values pick defaults: DefaultBaseURL, a client with a 60 s timeout, DefaultSteps, 4 workers and time.Now.

func (*Fetcher) Fetch

func (f *Fetcher) Fetch(ctx context.Context, run time.Time, path string) error

Fetch downloads the run into a new run file at path. On any error the partial file is removed.

func (*Fetcher) Latest

func (f *Fetcher) Latest(ctx context.Context) (time.Time, error)

Latest returns the newest run (00z or 12z, among the last four at or before Now) whose index for the last step exists in both streams.

type Field

type Field struct {
	Grid
	Ref    time.Time // model run (analysis) time, UTC
	Valid  time.Time // time the values apply to, UTC
	Values []float32 // natural order; NaN where the field has no value (land for sea fields)
}

Field is one decoded GRIB2 message: one parameter at one forecast time.

func DecodeField

func DecodeField(msg []byte) (Field, error)

DecodeField decodes a single GRIB2 message. Only regular lat/lon grids are accepted; the data is treated as untrusted.

func (*Field) At

func (f *Field) At(lat, lon float64) float32

At returns the value at the grid point nearest to (lat, lon), or NaN when the point lies outside the grid or the field has no value there.

type FieldID

type FieldID int

FieldID identifies one stored forecast field.

const (
	U10  FieldID = iota // 10 m wind, eastward component, m/s
	V10                 // 10 m wind, northward component, m/s
	Gust                // 10 m wind gust, m/s
	MSL                 // mean sea level pressure, Pa
	CurE                // ocean current, eastward component, m/s
	CurN                // ocean current, northward component, m/s
	SWH                 // significant wave height, m
	MWD                 // mean wave direction, degrees
	MWP                 // mean wave period, s
	NumFields
)

The fields kept in a run file, in storage order.

type Grid

type Grid struct {
	NX, NY     int
	Lat0, Lon0 float64 // north-west grid point, degrees
	DLat, DLon float64
}

Grid is a regular latitude/longitude grid in natural order: row 0 is the northernmost row, column 0 the westernmost. The value at index row*NX+col sits at (Lat0 + row*DLat, Lon0 + col*DLon). DLat is negative, DLon positive.

type LegSummary

type LegSummary struct {
	Leg          int       `json:"leg"`
	Start        time.Time `json:"start"`
	End          time.Time `json:"end"`
	MaxWindKn    *float64  `json:"max_wind_kn"`
	MaxGustKn    *float64  `json:"max_gust_kn"`
	MaxWaveM     *float64  `json:"max_wave_m"`
	MaxCurrentKn *float64  `json:"max_current_kn"`
	ForecastFrac float64   `json:"forecast_frac"` // share of the leg's time that has weather
}

LegSummary describes one leg of the track. The maxima are nil when no sample on the leg has that value.

type Run

type Run struct {
	ID    string
	Ref   time.Time
	Grid  Grid
	Steps []int
	// contains filtered or unexported fields
}

Run is a read-only view of one run file. Rows are read on demand with ReadAt, so a run never has to fit in memory.

func OpenRun

func OpenRun(path string) (*Run, error)

OpenRun opens a run file. The file is untrusted: the header is bounded and checked, and the size must match the header exactly.

func (*Run) At

func (r *Run) At(lat, lon float64, t time.Time) Values

At returns the forecast at a position and time: bilinear in space, linear in time between the two surrounding steps. Times outside [Ref, End] give all NaN. A field that is missing on either side of the time step is NaN.

func (*Run) Close

func (r *Run) Close() error

Close releases the file.

func (*Run) End

func (r *Run) End() time.Time

End is the valid time of the last step.

func (*Run) ValidTime

func (r *Run) ValidTime(stepIdx int) time.Time

ValidTime is the time forecast step stepIdx applies to.

type RunWriter

type RunWriter struct {
	// contains filtered or unexported fields
}

RunWriter fills a new run file. Fields may be written in any order; slots never written read back as NoValue after Close.

func CreateRun

func CreateRun(path string, ref time.Time, g Grid, steps []int) (*RunWriter, error)

CreateRun creates (or replaces) the run file at path, sized for every field and step. The caller must finish with Close or Abort.

func (*RunWriter) Abort

func (w *RunWriter) Abort()

Abort closes and deletes the partly written file. It does nothing once Close has succeeded, so `defer w.Abort()` is safe.

func (*RunWriter) Close

func (w *RunWriter) Close() error

Close fills every slot that was never written with NoValue, syncs and closes the file.

func (*RunWriter) Put

func (w *RunWriter) Put(f FieldID, stepIdx int, vals []float32) error

Put quantizes one field at one step (len(vals) must be NX*NY, natural order) and writes it. NaN becomes NoValue; out-of-range values are clamped.

type Sample

type Sample struct {
	Time      time.Time   `json:"time"`
	Lon       float64     `json:"lon"`
	Lat       float64     `json:"lat"`
	Leg       int         `json:"leg"`
	DistNM    float64     `json:"dist_nm"`
	CourseDeg float64     `json:"course_deg"`
	Weather   *Conditions `json:"weather"` // nil outside the forecast
}

Sample is the ship's place and the weather there at one moment.

type ScaleStop

type ScaleStop struct {
	Value float64 `json:"value"`
	Color string  `json:"color"` // "#rrggbb"
}

ScaleStop is one colour of a legend: the colour at Value, in display units. Colours between stops are blended linearly.

type Status

type Status struct {
	Enabled     bool       `json:"enabled"`
	Run         string     `json:"run,omitempty"`
	RunTime     *time.Time `json:"run_time,omitempty"`
	End         *time.Time `json:"end,omitempty"`
	LastAttempt *time.Time `json:"last_attempt,omitempty"`
	LastError   string     `json:"last_error,omitempty"`
}

Status describes the store for the API: whether weather is available, which run is loaded, and how the last refresh went.

type Store

type Store struct {
	// contains filtered or unexported fields
}

Store keeps the newest forecast run open and replaces it atomically when a newer one has been downloaded. It is safe for concurrent use.

The run before the current one stays open, because a request that fetched it just before a swap may still be reading from it.

func NewStore

func NewStore(dir string) (*Store, error)

NewStore prepares dir (creating it if needed), removes leftover partial downloads and opens the newest valid run file. Invalid run files are logged and deleted. Unrelated files are left alone.

func (*Store) Current

func (s *Store) Current() *Run

Current returns the newest run, or nil when none is loaded. The run stays valid for reading until two newer runs have been installed.

func (*Store) Install

func (s *Store) Install(path string) error

Install opens the finished run file at path, makes it current, closes the run from the swap before last and deletes the files of runs that are neither current nor previous.

func (*Store) Loop

func (s *Store) Loop(ctx context.Context, f *Fetcher, every time.Duration)

Loop refreshes immediately and then every interval until ctx is done. Errors are logged and retried at the next tick.

func (*Store) Refresh

func (s *Store) Refresh(ctx context.Context, f *Fetcher) error

Refresh downloads the latest forecast run if it is newer than the current one and installs it. The outcome is recorded in Status. On failure the current run stays in place and no partial file is left behind.

func (*Store) Status

func (s *Store) Status() Status

Status reports the loaded run and the outcome of the last refresh.

type Tiles

type Tiles struct {
	// contains filtered or unexported fields
}

Tiles renders and caches map tiles of forecast fields. It is safe for concurrent use.

func NewTiles

func NewTiles(maxBytes int64, workers int) *Tiles

NewTiles returns a tile cache that keeps at most maxBytes of PNG data and renders at most workers tiles at a time.

func (*Tiles) Get

func (t *Tiles) Get(ctx context.Context, r *Run, field string, stepHour, z, x, y int) ([]byte, error)

Get returns the PNG for tile (z, x, y) of field ("wind", "waves" or "current") at forecast hour stepHour of run r. Tiles are 256x256 and use the Web Mercator layout; x is taken modulo 2^z. The returned slice is shared and must not be modified. A request waiting for a render slot gives up when ctx is done; cache hits ignore ctx.

type Values

type Values [NumFields]float32

Values holds one value per field at a point and time. NaN means no value (land, outside the forecast, or a field missing from the run). Units are as stored: SI, pressure in Pa, and Values[MWD] in degrees.

func (Values) Conditions

func (v Values) Conditions() *Conditions

Conditions converts v for display. It is nil when every value is missing; a field is nil when any of its inputs is missing.

type Voyage

type Voyage struct {
	Run         *string      `json:"run"`
	RunTime     *time.Time   `json:"run_time"`
	ForecastEnd *time.Time   `json:"forecast_end"`
	Departure   time.Time    `json:"departure"`
	ETA         time.Time    `json:"eta"`
	DistanceNM  float64      `json:"distance_nm"`
	Samples     []Sample     `json:"samples"`
	Legs        []LegSummary `json:"legs"`

	// Scales are the tile colour scales, so a legend matches the tiles.
	Scales map[string][]ScaleStop `json:"scales"`
}

Voyage is a planned passage with the weather along it. Run, RunTime and ForecastEnd are nil when no forecast run was given.

func PlanVoyage

func PlanVoyage(run *Run, req VoyageRequest) (Voyage, error)

PlanVoyage sails req.Track at a constant speed and samples the ship every whole hour, at each track point and at departure and arrival. Each sample carries the forecast from run, or nil weather when run is nil or the time is outside it.

type VoyageRequest

type VoyageRequest struct {
	Track     []route.Position `json:"track"` // [lon, lat] points; legs run between neighbours
	Departure time.Time        `json:"departure"`
	SpeedKn   float64          `json:"speed_kn"`
}

VoyageRequest is a track to sail at a constant speed.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL