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 ¶
const ( MaxTrackPoints = 20000 MaxVoyageHours = 2000 MinSpeedKn = 6 MaxSpeedKn = 30 )
Limits on a voyage request.
const Credit = "Forecast data: ECMWF IFS open data, CC BY 4.0"
Credit is the attribution shown wherever forecast data is displayed.
const DefaultBaseURL = "https://data.ecmwf.int/forecasts"
DefaultBaseURL is the ECMWF open data site.
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.
const NoValue int16 = -32768
NoValue marks a missing sample (land, or a field that was never written).
Variables ¶
var ErrBadVoyage = errors.New("bad voyage request")
ErrBadVoyage wraps every error PlanVoyage gives for an unusable request.
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.
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).
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.
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 ¶
DecodeField decodes a single GRIB2 message. Only regular lat/lon grids are accepted; the data is treated as untrusted.
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 ¶
OpenRun opens a run file. The file is untrusted: the header is bounded and checked, and the size must match the header exactly.
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 ¶
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Loop refreshes immediately and then every interval until ctx is done. Errors are logged and retried at the next tick.
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 ¶
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 ¶
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.