grib2

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2026 License: MIT Imports: 14 Imported by: 0

README

grib2

A pure Go library for reading and writing GRIB2 (WMO FM 92 GRIB Edition 2) files.

Go Reference

Overview

GRIB2 is the World Meteorological Organization's binary format for gridded meteorological data, used by weather services worldwide (NOAA, ECMWF, JMA, DWD, etc.). This library provides a complete, idiomatic Go implementation for both decoding and encoding GRIB2 messages -- no CGo, no external C libraries, no system dependencies.

Features

Packing Formats
Format Template Decode Encode
Simple packing 5.0 Yes Yes
Complex packing 5.2 Yes Yes
Complex packing + spatial differencing 5.3 Yes Yes
IEEE floating point (32/64-bit) 5.4 Yes Yes
JPEG2000 5.40 Yes Yes
PNG 5.41 Yes Yes
CCSDS/AEC (Adaptive Entropy Coding) 5.42 Yes Yes
Run-length packing with level values 5.200 Yes --
Grid Definition Templates (Section 3)
Grid Type Template
Latitude/Longitude (equidistant cylindrical) 3.0
Rotated Latitude/Longitude 3.1
Mercator 3.10
Polar Stereographic 3.20
Lambert Conformal 3.30
Gaussian Latitude/Longitude (regular and reduced) 3.40
Space View Perspective (geostationary satellite) 3.90
Product Definition Templates (Section 4)
Product Type Template
Analysis or forecast at a point in time 4.0
Individual ensemble forecast 4.1
Derived ensemble forecast 4.2
Statistically processed values over time interval 4.8
Ensemble forecast over time interval 4.11
Derived ensemble over time interval 4.12
High-Level API
  • Bitmap support -- automatic expansion of bitmap-masked fields (NaN for missing points)
  • Scanning mode reordering -- all 16 scanning mode combinations normalized to canonical west-to-east, north-to-south order
  • Grid coordinates -- GridCoordinates() returns lat/lon arrays for all supported grid types, including projected grids (Lambert, Polar Stereographic, Mercator, Space View)
  • Nearest-neighbour lookup -- NearestValue(lat, lon) with O(1) direct index computation for regular grids, haversine fallback for others
  • Bilinear interpolation -- BilinearValue(lat, lon) for smooth value estimation between grid points
  • Code table lookups -- human-readable names for disciplines, centres, parameters, surface types, and all template numbers
  • Multi-message files -- Decoder reads files containing any number of concatenated GRIB2 messages
  • Byte-perfect round-trips -- ReadMessage followed by WriteMessage produces identical bytes

Installation

go get github.com/dmarkham/grib2

Requires Go 1.25 or later. Zero external dependencies outside the standard library.

Quick Start

Read a GRIB2 file and extract values
package main

import (
	"fmt"
	"os"

	"github.com/dmarkham/grib2"
)

func main() {
	f, err := os.Open("forecast.grib2")
	if err != nil {
		panic(err)
	}
	defer f.Close()

	dec := grib2.NewDecoder(f)
	for {
		msg, err := dec.Decode()
		if err != nil {
			break // io.EOF or parse error
		}

		fmt.Printf("Discipline: %s\n", grib2.DisciplineName(msg.Section0.Discipline))
		fmt.Printf("Centre:     %s\n", grib2.CentreName(msg.Section1.Centre))
		fmt.Printf("Reference:  %s\n", msg.Section1.ReferenceTime())

		for i, field := range msg.Fields {
			values, err := field.Values()
			if err != nil {
				fmt.Printf("  field %d: unpack error: %v\n", i, err)
				continue
			}
			fmt.Printf("  field %d: %d values, grid template %d, packing template %d\n",
				i, len(values), field.Section3.TemplateNumber, field.Section5.TemplateNumber)
		}
	}
}
Query a specific location (nearest-neighbour)
field := msg.Fields[0]

// Find the grid point closest to Denver, CO
value, idx, lat, lon, err := field.NearestValue(39.7392, -104.9903)
if err != nil {
	panic(err)
}
fmt.Printf("Nearest grid point: (%.4f, %.4f) index=%d value=%.2f\n", lat, lon, idx, value)

// Or use bilinear interpolation for smoother results
interpolated, err := field.BilinearValue(39.7392, -104.9903)
if err != nil {
	panic(err)
}
fmt.Printf("Interpolated value: %.2f\n", interpolated)
Write a GRIB2 file
package main

import (
	"os"

	"github.com/dmarkham/grib2"
)

func main() {
	// Create a simple 4x3 temperature grid
	values := []float64{
		280.0, 281.0, 282.0, 283.0,
		279.0, 280.5, 281.5, 282.5,
		278.0, 279.5, 280.5, 281.0,
	}

	// Pack with simple packing at 16 bits per value
	packed, tmpl50, err := grib2.PackSimple(values, 16)
	if err != nil {
		panic(err)
	}

	msg := &grib2.Message{
		Section0: grib2.Section0{
			Discipline: 0, // Meteorological
			Edition:    2,
		},
		Section1: grib2.Section1{
			Centre:              7,  // NCEP
			MasterTablesVersion: 2,
			Year:                2025, Month: 1, Day: 15,
			Hour: 12, Minute: 0, Second: 0,
		},
		Fields: []grib2.Field{{
			Section3: grib2.Section3{
				NumberOfDataPoints: 12,
				TemplateNumber:     0,
				Template: grib2.Template30{
					Ni: 4, Nj: 3,
					LatitudeOfFirstGridPoint:  40000000,  // 40.0N
					LongitudeOfFirstGridPoint: 350000000, // 350.0E (-10.0)
					LatitudeOfLastGridPoint:   38000000,  // 38.0N
					LongitudeOfLastGridPoint:  353000000, // 353.0E (-7.0)
					IDirectionIncrement:       1000000,   // 1.0 degree
					JDirectionIncrement:       1000000,   // 1.0 degree
				},
			},
			Section4: grib2.Section4{
				TemplateNumber: 0,
				Template: grib2.Template40{
					ParameterCategory: 0, // Temperature
					ParameterNumber:   0, // Temperature (K)
				},
			},
			Section5: grib2.Section5{
				NumberOfValues:  12,
				TemplateNumber: 0,
				Template:       tmpl50,
			},
			Section6: grib2.Section6{Indicator: 255}, // no bitmap
			Section7: grib2.Section7{Data: packed},
		}},
	}

	out, err := os.Create("output.grib2")
	if err != nil {
		panic(err)
	}
	defer out.Close()

	if err := grib2.WriteMessage(out, msg); err != nil {
		panic(err)
	}
}

API Reference

Reading
Function/Type Description
NewDecoder(r io.Reader) *Decoder Create a decoder for reading multiple messages from a stream
(*Decoder).Decode() (*Message, error) Read the next GRIB2 message (returns io.EOF when done)
ReadMessage(r io.Reader) (*Message, error) Convenience function to read a single message
Message Structure
Message
  Section0    -- Indicator (discipline, edition, total length)
  Section1    -- Identification (centre, reference time, production status)
  Section2    -- Local Use (optional, centre-specific data)
  Fields[]    -- One or more data fields, each containing:
    Section3  -- Grid Definition (template defining the grid geometry)
    Section4  -- Product Definition (what the data represents)
    Section5  -- Data Representation (packing method and parameters)
    Section6  -- Bitmap (missing data mask)
    Section7  -- Data (packed values)
Field Methods
Method Description
Values() ([]float64, error) Unpack, apply bitmap, reorder by scanning mode
GridCoordinates() (lats, lons []float64, error) Lat/lon of every grid point in data order
NearestValue(lat, lon float64) Value at closest grid point (O(1) for regular grids)
BilinearValue(lat, lon float64) Bilinear interpolation from 4 surrounding points
Writing
Function Description
WriteMessage(w io.Writer, msg *Message) error Write a complete GRIB2 message (patches total length automatically)
PackSimple(values, bpv) Encode with simple packing (Template 5.0)
PackComplex(values, bpv) Encode with complex packing (Template 5.2)
PackComplexSpatialDiff(values, bpv, order) Encode with complex packing + spatial differencing (Template 5.3)
PackIEEE(values, precision) Encode as IEEE 32-bit or 64-bit floats (Template 5.4)
PackJPEG2000(values, bpv) Encode with JPEG2000 lossless compression (Template 5.40)
PackPNG(values, bpv, width, height) Encode with PNG compression (Template 5.41)
PackCCSDS(values, bpv, blockSize, rsi) Encode with CCSDS/AEC compression (Template 5.42)
Code Table Lookups
Function Table
DisciplineName(d uint8) Table 0.0
CentreName(c uint16) Common Code Table C-11
ParameterName(discipline, category, number uint8) Table 4.2.x.x
ParameterUnit(discipline, category, number uint8) Units for Table 4.2
ParameterCategoryName(discipline, category uint8) Table 4.1.x
SurfaceTypeName(t uint8) Table 4.5
GridDefinitionTemplateName(n uint16) Table 3.1
ProductDefinitionTemplateName(n uint16) Table 4.0
DataRepresentationTemplateName(n uint16) Table 5.0
ReferenceTimeName(t uint8) Table 1.2
ProductionStatusName(s uint8) Table 1.3
DataTypeName(t uint8) Table 1.4

Compression Format Details

Format Template Decode Encode Notes
Simple 5.0 Yes Yes Fast paths for 8/16/32-bit aligned widths; arbitrary bit widths supported
Complex 5.2 Yes Yes Full group splitting with eccodes-compatible merge optimization
Complex + Spatial Diff 5.3 Yes Yes Order 1 and 2 spatial differencing; missing value management
IEEE Float 5.4 Yes Yes 32-bit and 64-bit precision
JPEG2000 5.40 Yes Yes Pure Go J2K codec (internal/j2k); lossless mode
PNG 5.41 Yes Yes Uses Go standard library image/png; 8-bit and 16-bit grayscale
CCSDS/AEC 5.42 Yes Yes Pure Go AEC codec (internal/aec); CCSDS 121.0-B-3 compliant
Run-length 5.200 Yes -- Variable-base run-length decoding with level values

All decode paths are cross-validated against eccodes reference output at tolerances from 1e-4 to 1e-10 depending on the format.

Testing

The test suite contains 138 unit tests and 7 fuzz targets covering:

  • Byte-perfect round-trips: read a GRIB2 file, write it back, compare bytes
  • Cross-validation against eccodes: decoded values compared to eccodes grib_get_data output for every supported packing format (simple, complex, complex+spatial diff, JPEG2000, PNG, CCSDS, IEEE, run-length)
  • Encode/decode round-trips: pack values, unpack them, verify they match within quantization tolerance
  • Grid coordinate validation: lat/lon arrays compared against eccodes for regular lat/lon, Mercator, Gaussian, Lambert, Polar Stereographic, and Space View grids
  • Section-level parsing: individual tests for all section readers and writers (Sections 0-8)
  • Template coverage: dedicated tests for all grid, product, and data representation templates
  • Fuzz testing: 7 fuzz targets covering the full message parser and each individual unpacker (JPEG2000, CCSDS, Complex, Run-length, Simple, PNG)
  • Hardening: all allocations are capped (100M elements max), all bit extractions are bounds-checked, section sizes are limited to 256 MiB

Performance

  • Pure Go, zero CGo -- no overhead from C interop, straightforward cross-compilation, no system library requirements
  • Fast paths for common bit widths (8, 16, 32-bit aligned simple packing)
  • Streaming decoder -- reads messages one at a time via Decoder, suitable for large multi-message files
  • O(1) nearest-neighbour for regular lat/lon and regular Gaussian grids (direct index computation instead of brute-force search)
  • Fuzz-tested and hardened -- safe to use on untrusted input; allocation caps and bounds checks prevent resource exhaustion

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotGRIB     = errors.New("grib2: not a GRIB file (missing GRIB magic)")
	ErrNotEdition2 = errors.New("grib2: not GRIB edition 2")
	ErrTruncated   = errors.New("grib2: message truncated")
)
View Source
var ErrInvalidEndSection = errors.New("grib2: invalid end section (expected 7777)")

Functions

func CentreName

func CentreName(c uint16) string

CentreName returns the human-readable name for a WMO originating centre (Common Code Table C-11).

func DataRepresentationTemplateName

func DataRepresentationTemplateName(n uint16) string

DataRepresentationTemplateName returns the human-readable name for a data representation template number (Table 5.0).

func DataTypeName

func DataTypeName(t uint8) string

DataTypeName returns the human-readable type of processed data (Table 1.4).

func DisciplineName

func DisciplineName(d uint8) string

DisciplineName returns the human-readable name for a GRIB2 discipline (Table 0.0: Discipline of processed data).

func GridDefinitionTemplateName

func GridDefinitionTemplateName(n uint16) string

GridDefinitionTemplateName returns the human-readable name for a grid definition template number (Table 3.1).

func ParameterCategoryName

func ParameterCategoryName(discipline, category uint8) string

ParameterCategoryName returns the human-readable name for a parameter category given the discipline (Table 4.1.x).

func ParameterName

func ParameterName(discipline, category, number uint8) string

ParameterName returns the human-readable name for a parameter given discipline, category, and number (Table 4.2.x.x).

func ParameterUnit

func ParameterUnit(discipline, category, number uint8) string

ParameterUnit returns the unit string for a parameter given discipline, category, and number.

func ProductDefinitionTemplateName

func ProductDefinitionTemplateName(n uint16) string

ProductDefinitionTemplateName returns the human-readable name for a product definition template number (Table 4.0).

func ProductionStatusName

func ProductionStatusName(s uint8) string

ProductionStatusName returns the human-readable production status (Table 1.3).

func ReadSection8

func ReadSection8(r io.Reader) error

ReadSection8 reads and validates the 4-byte end marker.

func ReferenceTimeName

func ReferenceTimeName(t uint8) string

ReferenceTimeName returns the human-readable significance of reference time (Table 1.2).

func SurfaceTypeName

func SurfaceTypeName(t uint8) string

SurfaceTypeName returns the human-readable name for a fixed surface type (Table 4.5).

func UnpackCCSDS

func UnpackCCSDS(data []byte, tmpl Template542, numValues uint32) ([]float64, error)

UnpackCCSDS decodes data packed with Template 5.42 (CCSDS/AEC).

The packed data in Section 7 is a CCSDS-121.0-B compressed bitstream. Each decoded sample is an unsigned integer. The same scaling formula as simple packing applies: Y = (X * 2^E + R) * 10^(-D)

func UnpackComplex

func UnpackComplex(data []byte, tmpl52 Template52, numValues uint32,
	orderOfSpatialDiff uint8, numOctetsExtra uint8) ([]float64, error)

UnpackComplex decodes data packed with Template 5.2 (complex packing) or Template 5.3 (complex packing with spatial differencing).

The algorithm: 1. Read group reference values, group widths, and group lengths from the data stream 2. For each group, decode the per-value deviations and add the group reference 3. If spatial differencing, apply the inverse differencing operator 4. Apply the scaling: Y = (X * 2^E + R) * 10^(-D)

Missing values (when MissingValueManagement != 0) are returned as math.NaN(). Use UnpackComplexWithSubstitution to get template-specified substitute values instead.

func UnpackComplexWithSubstitution

func UnpackComplexWithSubstitution(data []byte, tmpl52 Template52, numValues uint32,
	orderOfSpatialDiff uint8, numOctetsExtra uint8) ([]float64, error)

UnpackComplexWithSubstitution is like UnpackComplex but substitutes the template's missing value placeholders instead of NaN.

When MissingValueManagement is 1, primary missing values are replaced with PrimaryMissingValueSubstitute (interpreted as IEEE 754 float32 bits). When MissingValueManagement is 2, primary and secondary missing values are replaced with their respective substitutes.

If MissingValueManagement is 0, this behaves identically to UnpackComplex.

func UnpackIEEE

func UnpackIEEE(data []byte, tmpl Template54, numValues uint32) ([]float64, error)

UnpackIEEE decodes data packed with Template 5.4 (IEEE floating point).

func UnpackJPEG2000

func UnpackJPEG2000(data []byte, tmpl Template540, numValues uint32) ([]float64, error)

UnpackJPEG2000 decodes data packed with Template 5.40 (JPEG2000).

The packed data in Section 7 is a raw JPEG2000 codestream (J2K, not JP2). Each pixel value is an unsigned integer. The same scaling formula as simple packing applies: Y = (X * 2^E + R) * 10^(-D)

func UnpackPNG

func UnpackPNG(data []byte, tmpl Template50, numValues uint32) ([]float64, error)

UnpackPNG decodes data packed with Template 5.41 (PNG packing).

The packed data in Section 7 is a complete PNG image where each pixel value represents a scaled integer. The same formula as simple packing applies: Y = (X * 2^E + R) * 10^(-D)

func UnpackRunLength

func UnpackRunLength(data []byte, tmpl Template5200, numValues uint32, missingValue float64) ([]float64, error)

UnpackRunLength decodes data packed with Template 5.200 (run-length packing with level values).

The algorithm follows the eccodes DataRunLengthPacking implementation:

  • Each compressed value <= maxLevelValue is a level index (0 = missing).
  • Values > maxLevelValue encode a run-length count in a variable-base representation where range = (2^bitsPerValue - 1) - maxLevelValue.

The missingValue is used for level index 0.

func UnpackSimple

func UnpackSimple(data []byte, tmpl Template50, numValues uint32) ([]float64, error)

UnpackSimple decodes data packed with Template 5.0 (simple packing).

The unpacking formula per WMO spec is:

Y = (R + X * 2^E) * 10^(-D)

Where:

R = reference value (float32)
E = binary scale factor
D = decimal scale factor
X = scaled integer value from packed bits

func WriteMessage

func WriteMessage(w io.Writer, msg *Message) error

WriteMessage writes a complete GRIB2 message to w.

func WriteSection0

func WriteSection0(w io.Writer, s Section0) error

WriteSection0 writes the 16-byte indicator section to w.

func WriteSection1

func WriteSection1(w io.Writer, s Section1) error

WriteSection1 writes the Identification Section to w.

func WriteSection2

func WriteSection2(w io.Writer, s Section2) error

WriteSection2 writes the Local Use Section.

func WriteSection3

func WriteSection3(w io.Writer, s Section3) error

WriteSection3 writes the Grid Definition Section.

func WriteSection4

func WriteSection4(w io.Writer, s Section4) error

WriteSection4 writes the Product Definition Section.

func WriteSection5

func WriteSection5(w io.Writer, s Section5) error

WriteSection5 writes the Data Representation Section.

func WriteSection6

func WriteSection6(w io.Writer, s Section6) error

WriteSection6 writes the Bit-Map Section.

func WriteSection7

func WriteSection7(w io.Writer, s Section7) error

WriteSection7 writes the Data Section.

func WriteSection8

func WriteSection8(w io.Writer) error

WriteSection8 writes the 4-byte end marker "7777".

Types

type DataRepresentationTemplate

type DataRepresentationTemplate interface {
	TemplateNumber() uint16
}

DataRepresentationTemplate is the interface for data representation templates.

type Decoder

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

Decoder reads GRIB2 messages from a stream. Use NewDecoder to create one, then call Decode repeatedly.

func NewDecoder

func NewDecoder(r io.Reader) *Decoder

NewDecoder returns a Decoder that reads from r.

func (*Decoder) Decode

func (d *Decoder) Decode() (*Message, error)

Decode reads the next GRIB2 message. Returns io.EOF when no more messages are available.

type Field

type Field struct {
	Section3 Section3
	Section4 Section4
	Section5 Section5
	Section6 Section6
	Section7 Section7
}

Field is one data field within a GRIB2 message. Each field consists of sections 3 through 7.

func (*Field) BilinearValue

func (f *Field) BilinearValue(lat, lon float64) (float64, error)

BilinearValue returns an interpolated value at the given latitude and longitude using bilinear interpolation from the 4 surrounding grid points. Only works for regular grids (Template30, Template340 regular, Template310). Returns an error for irregular grids where bilinear interpolation does not apply cleanly.

func (*Field) GridCoordinates

func (f *Field) GridCoordinates() (lats, lons []float64, err error)

GridCoordinates returns the latitude and longitude (in degrees) of every grid point in the field, in the same order as the data values returned by Field.Values(). Returns slices of length NumberOfDataPoints.

func (*Field) NearestValue

func (f *Field) NearestValue(lat, lon float64) (value float64, idx int, nearLat, nearLon float64, err error)

NearestValue returns the data value at the grid point closest to the given latitude and longitude (in degrees). Also returns the index, and the actual lat/lon of the nearest point.

For regular lat/lon grids (Template30) and regular Gaussian grids (Template340 with Ni set), a direct index computation is used. For all other grid types, a brute-force search over GridCoordinates is performed as a fallback.

func (*Field) SurfaceLevel added in v1.0.1

func (f *Field) SurfaceLevel() (float64, error)

SurfaceLevel returns the value of the first fixed surface for a field, applying the GRIB2 scaling formula: value = scaledValue * 10^(-scaleFactor).

For isobaric surfaces (typeOfFirstFixedSurface == 100), the result is in Pa. Use SurfaceLevelHPa for a convenience wrapper that returns hPa.

Some producers (notably CMC/RDPS) use non-standard scale factors. When the scale factor appears to be missing or produces an unreasonable result, this function falls back to treating the scaled value as the raw level value.

func (*Field) SurfaceLevelHPa added in v1.0.1

func (f *Field) SurfaceLevelHPa() (float64, error)

SurfaceLevelHPa returns the first fixed surface level in hectopascals (hPa/mbar) for isobaric surfaces (typeOfFirstFixedSurface == 100). For non-isobaric surfaces, returns the raw surface value.

func (*Field) SurfaceType added in v1.0.1

func (f *Field) SurfaceType() (uint8, error)

SurfaceType returns the type code of the first fixed surface (Table 4.5).

func (*Field) Values

func (f *Field) Values() ([]float64, error)

Values unpacks the data in this field and returns the final grid of values.

It performs three steps:

  1. Dispatch to the correct Unpack* function based on Section 5 TemplateNumber
  2. Apply the Section 6 bitmap (if indicator == 0), expanding the packed values into a full grid with NaN for missing positions
  3. Apply scanning mode reordering (if Section 3 Template 3.0 ScanningMode != 0)

type GridDefinitionTemplate

type GridDefinitionTemplate interface {
	TemplateNumber() uint16
}

GridDefinitionTemplate is the interface for grid definition templates.

type Message

type Message struct {
	Section0 Section0
	Section1 Section1
	Section2 *Section2 // optional, may be nil
	Fields   []Field   // one or more data fields
}

Message represents a complete GRIB2 message. A single GRIB2 message can contain multiple data fields (repeated sections 3-7).

func ReadMessage

func ReadMessage(r io.Reader) (*Message, error)

ReadMessage reads a single GRIB2 message from r. For reading multiple messages, use a Decoder instead.

type ProductDefinitionTemplate

type ProductDefinitionTemplate interface {
	TemplateNumber() uint16
}

ProductDefinitionTemplate is the interface for product definition templates.

type RawDataRepTemplate

type RawDataRepTemplate struct {
	Number uint16
	Data   []byte
}

RawDataRepTemplate stores an unparsed data representation template.

func (*RawDataRepTemplate) TemplateNumber

func (t *RawDataRepTemplate) TemplateNumber() uint16

type RawGridTemplate

type RawGridTemplate struct {
	Number uint16
	Data   []byte
}

RawGridTemplate stores an unparsed grid definition template.

func (*RawGridTemplate) TemplateNumber

func (t *RawGridTemplate) TemplateNumber() uint16

type RawProductTemplate

type RawProductTemplate struct {
	Number uint16
	Data   []byte
}

RawProductTemplate stores an unparsed product definition template.

func (*RawProductTemplate) TemplateNumber

func (t *RawProductTemplate) TemplateNumber() uint16

type Section0

type Section0 struct {
	Reserved    [2]byte // Octets 5-6 (reserved by WMO, typically 0xFF 0xFF)
	Discipline  uint8   // WMO Table 0.0
	Edition     uint8   // Must be 2
	TotalLength uint64  // Total message length in bytes
}

Section0 is the Indicator Section of a GRIB2 message. It is always exactly 16 bytes and identifies the start of a GRIB message.

Octet layout (1-indexed per WMO spec):

1-4    "GRIB" (ASCII)
5-6    Reserved
7      Discipline (Table 0.0)
8      GRIB Edition Number (2)
9-16   Total length of GRIB message in octets

func ReadSection0

func ReadSection0(r io.Reader) (Section0, error)

ReadSection0 reads the 16-byte indicator section from r. It validates the GRIB magic number and edition.

func (Section0) String

func (s Section0) String() string

String returns a human-readable description of Section0.

type Section1

type Section1 struct {
	Length                      uint32
	Centre                      uint16
	SubCentre                   uint16
	MasterTablesVersion         uint8
	LocalTablesVersion          uint8
	SignificanceOfReferenceTime uint8 // Table 1.2
	Year                        uint16
	Month                       uint8
	Day                         uint8
	Hour                        uint8
	Minute                      uint8
	Second                      uint8
	ProductionStatus            uint8 // Table 1.3
	TypeOfData                  uint8 // Table 1.4
}

Section1 is the Identification Section of a GRIB2 message.

Octet layout (1-indexed, relative to section start):

1-4    Section length
5      Number of section (1)
6-7    Identification of originating/generating centre (Table 0)
8-9    Identification of originating/generating sub-centre (Table C)
10     GRIB master tables version number (Table 1.0)
11     Version number of GRIB local tables (Table 1.1)
12     Significance of reference time (Table 1.2)
13-14  Year
15     Month
16     Day
17     Hour
18     Minute
19     Second
20     Production status of processed data (Table 1.3)
21     Type of processed data (Table 1.4)
22-N   Reserved (optional, for future use)

func ReadSection1

func ReadSection1(r io.Reader) (Section1, error)

ReadSection1 reads the Identification Section from r. The section header (5 bytes) is read first, then the body is parsed.

func (*Section1) ReferenceTime

func (s *Section1) ReferenceTime() time.Time

ReferenceTime returns the reference time as a Go time.Time.

func (Section1) String

func (s Section1) String() string

String returns a human-readable description of Section1.

type Section2

type Section2 struct {
	Length uint32
	Data   []byte // raw local-use bytes (may be empty)
}

Section2 is the Local Use Section. It contains optional data defined by the originating centre.

Octet layout:

1-4    Section length
5      Number of section (2)
6-N    Local use data

func ReadSection2

func ReadSection2(r io.Reader) (Section2, error)

ReadSection2 reads the Local Use Section. Section 2 is optional — the caller should check the section number to determine whether to call this or skip to Section 3.

type Section3

type Section3 struct {
	Length                  uint32
	Source                  uint8 // Table 3.0
	NumberOfDataPoints      uint32
	OctetsForNumberOfPoints uint8
	InterpretationOfPoints  uint8  // Table 3.11
	TemplateNumber          uint16 // Table 3.1
	Template                GridDefinitionTemplate
	OptionalPointNumbers    []byte // optional list appended after template
}

Section3 is the Grid Definition Section.

Common header (octets 1-14):

1-4    Section length
5      Number of section (3)
6      Source of grid definition (Table 3.0)
7-10   Number of data points
11     Number of octets for optional list of numbers
12     Interpretation of list of numbers (Table 3.11)
13-14  Grid definition template number (Table 3.1)
15-N   Grid definition template (varies by template number)

func ReadSection3

func ReadSection3(r io.Reader) (Section3, error)

ReadSection3 reads the Grid Definition Section.

func (Section3) String

func (s Section3) String() string

String returns a human-readable description of Section3.

type Section4

type Section4 struct {
	Length           uint32
	NV               uint16 // number of coordinate values
	TemplateNumber   uint16 // Table 4.0
	Template         ProductDefinitionTemplate
	CoordinateValues []byte // NV coordinate values (if any)
}

Section4 is the Product Definition Section.

Common header:

1-4    Section length
5      Number of section (4)
6-7    Number of coordinate values after template (NV)
8-9    Product definition template number (Table 4.0)
10-N   Product definition template

func ReadSection4

func ReadSection4(r io.Reader) (Section4, error)

ReadSection4 reads the Product Definition Section.

func (Section4) String

func (s Section4) String() string

String returns a human-readable description of Section4.

type Section5

type Section5 struct {
	Length         uint32
	NumberOfValues uint32
	TemplateNumber uint16 // Table 5.0
	Template       DataRepresentationTemplate
}

Section5 is the Data Representation Section.

1-4    Section length
5      Number of section (5)
6-9    Number of data points where one or more values are
       specified in Section 7 when a bit map is present;
       total number of data points when a bit map is absent.
10-11  Data representation template number (Table 5.0)
12-N   Data representation template

func ReadSection5

func ReadSection5(r io.Reader) (Section5, error)

ReadSection5 reads the Data Representation Section.

func (Section5) String

func (s Section5) String() string

String returns a human-readable description of Section5.

type Section6

type Section6 struct {
	Length    uint32
	Indicator uint8
	Bitmap    []byte // raw bitmap bytes (if indicator == 0)
}

Section6 is the Bit-Map Section.

1-4    Section length
5      Number of section (6)
6      Bit-map indicator (Table 6.0)
         255 = A bit map does not apply to this product
         0   = A bit map applies to this product and is specified in this section
         1-254 = A bit map previously defined applies to this product
7-N    Bit-map (if indicator = 0)

func ReadSection6

func ReadSection6(r io.Reader) (Section6, error)

ReadSection6 reads the Bit-Map Section.

func (*Section6) HasBitmap

func (s *Section6) HasBitmap() bool

HasBitmap returns true if this section contains an actual bitmap.

type Section7

type Section7 struct {
	Length uint32
	Data   []byte // raw packed data bytes
}

Section7 is the Data Section.

1-4    Section length
5      Number of section (7)
6-N    Data in a format described by Data Template in Section 5

func ReadSection7

func ReadSection7(r io.Reader) (Section7, error)

ReadSection7 reads the Data Section. The raw data is stored as-is; unpacking requires the Data Representation Template from Section 5.

type Template30

type Template30 struct {
	ShapeOfEarth                        uint8 // Table 3.2
	ScaleFactorOfRadiusOfSphericalEarth uint8
	ScaledValueOfRadiusOfSphericalEarth uint32
	ScaleFactorOfEarthMajorAxis         uint8
	ScaledValueOfEarthMajorAxis         uint32
	ScaleFactorOfEarthMinorAxis         uint8
	ScaledValueOfEarthMinorAxis         uint32
	Ni                                  uint32 // number of points along a parallel
	Nj                                  uint32 // number of points along a meridian
	BasicAngle                          uint32
	SubdivisionsOfBasicAngle            uint32
	LatitudeOfFirstGridPoint            int32  // microdegrees
	LongitudeOfFirstGridPoint           int32  // microdegrees
	ResolutionAndComponentFlags         uint8  // Flag table 3.3
	LatitudeOfLastGridPoint             int32  // microdegrees
	LongitudeOfLastGridPoint            int32  // microdegrees
	IDirectionIncrement                 uint32 // microdegrees
	JDirectionIncrement                 uint32 // microdegrees
	ScanningMode                        uint8  // Flag table 3.4
}

Template30 is Grid Definition Template 3.0: Latitude/Longitude (equidistant cylindrical, or Plate Carree).

All latitudes/longitudes are in units of 10^-6 degrees.

func (Template30) TemplateNumber

func (Template30) TemplateNumber() uint16

type Template31

type Template31 struct {
	ShapeOfEarth                        uint8 // Table 3.2
	ScaleFactorOfRadiusOfSphericalEarth uint8
	ScaledValueOfRadiusOfSphericalEarth uint32
	ScaleFactorOfEarthMajorAxis         uint8
	ScaledValueOfEarthMajorAxis         uint32
	ScaleFactorOfEarthMinorAxis         uint8
	ScaledValueOfEarthMinorAxis         uint32
	Ni                                  uint32 // number of points along a parallel
	Nj                                  uint32 // number of points along a meridian
	BasicAngle                          uint32
	SubdivisionsOfBasicAngle            uint32
	LatitudeOfFirstGridPoint            int32  // microdegrees (sign-magnitude)
	LongitudeOfFirstGridPoint           int32  // microdegrees (sign-magnitude)
	ResolutionAndComponentFlags         uint8  // Flag table 3.3
	LatitudeOfLastGridPoint             int32  // microdegrees (sign-magnitude)
	LongitudeOfLastGridPoint            int32  // microdegrees (sign-magnitude)
	IDirectionIncrement                 uint32 // microdegrees
	JDirectionIncrement                 uint32 // microdegrees
	ScanningMode                        uint8  // Flag table 3.4
	LatitudeOfSouthernPole              int32  // microdegrees (sign-magnitude)
	LongitudeOfSouthernPole             int32  // microdegrees (sign-magnitude)
	AngleOfRotation                     uint32 // angle of rotation in microdegrees
}

Template31 is Grid Definition Template 3.1: Rotated Latitude/Longitude (rotated equidistant cylindrical, or rotated Plate Carree).

Identical to Template 3.0 for octets 15-72, with three additional fields (octets 73-84) describing the rotation. All latitudes/longitudes are in units of 10^-6 degrees (sign-magnitude encoding).

func (Template31) TemplateNumber

func (Template31) TemplateNumber() uint16

type Template40

type Template40 struct {
	ParameterCategory          uint8 // Table 4.1
	ParameterNumber            uint8 // Table 4.2
	TypeOfGeneratingProcess    uint8 // Table 4.3
	BackgroundProcess          uint8
	GeneratingProcessID        uint8
	HoursAfterCutoff           uint16
	MinutesAfterCutoff         uint8
	IndicatorOfUnitOfTimeRange uint8 // Table 4.4
	ForecastTime               int32
	TypeOfFirstFixedSurface    uint8 // Table 4.5
	ScaleFactorOfFirstSurface  int8
	ScaledValueOfFirstSurface  uint32
	TypeOfSecondFixedSurface   uint8 // Table 4.5
	ScaleFactorOfSecondSurface int8
	ScaledValueOfSecondSurface uint32
}

Template40 is Product Definition Template 4.0: Analysis or forecast at a horizontal level or in a horizontal layer at a point in time.

Octets 10-34 (relative to section start).

func (Template40) TemplateNumber

func (Template40) TemplateNumber() uint16

type Template41

type Template41 struct {
	Template40
	TypeOfEnsembleForecast      uint8 // Table 4.6
	PerturbationNumber          uint8
	NumberOfForecastsInEnsemble uint8
}

Template41 is Product Definition Template 4.1: Individual ensemble forecast, control and perturbed, at a horizontal level or in a horizontal layer at a point in time. It extends Template 4.0 with 3 ensemble fields.

func (Template41) TemplateNumber

func (Template41) TemplateNumber() uint16

type Template42

type Template42 struct {
	Template40
	DerivedForecast             uint8 // Table 4.7 — 0=unweighted mean, 1=weighted mean, 2=std dev, etc.
	NumberOfForecastsInEnsemble uint8
}

Template42 is Product Definition Template 4.2: Derived forecasts based on all ensemble members at a horizontal level or in a horizontal layer at a point in time. It extends Template 4.0 with 2 derived-forecast fields.

func (Template42) TemplateNumber

func (Template42) TemplateNumber() uint16

type Template48

type Template48 struct {
	Template40
	YearOfEndOfInterval                 uint16
	MonthOfEndOfInterval                uint8
	DayOfEndOfInterval                  uint8
	HourOfEndOfInterval                 uint8
	MinuteOfEndOfInterval               uint8
	SecondOfEndOfInterval               uint8
	NumberOfTimeRangeSpecs              uint8
	NumberOfMissingInStatisticalProcess uint32
	TimeRangeSpecs                      []TimeRangeSpec
}

Template48 is Product Definition Template 4.8: Average, accumulation, extreme values or other statistically processed values at a horizontal level or in a horizontal layer in a continuous or non-continuous time interval.

Extends Template 4.0 with end-of-interval time and time range specifications.

Octets 10-34 are Template 4.0, then:

35-36  Year of end of overall time interval
37     Month of end of overall time interval
38     Day of end of overall time interval
39     Hour of end of overall time interval
40     Minute of end of overall time interval
41     Second of end of overall time interval
42     Number of time range specifications (n)
43-46  Total number of data values missing in statistical process
47-58  First time range spec (12 bytes each)
...    Additional time range specs

func (Template48) TemplateNumber

func (Template48) TemplateNumber() uint16

type Template50

type Template50 struct {
	ReferenceValue            float32
	BinaryScaleFactor         int16
	DecimalScaleFactor        int16
	BitsPerValue              uint8
	TypeOfOriginalFieldValues uint8 // Table 5.1
}

Template50 is Data Representation Template 5.0: Grid point data — simple packing.

12-15  Reference value (R) (IEEE 32-bit floating-point)
16-17  Binary scale factor (E) (signed)
18-19  Decimal scale factor (D) (signed)
20     Number of bits used for each packed value
21     Type of original field values (Table 5.1)

func PackPNG

func PackPNG(values []float64, bitsPerValue uint8, width, height int) ([]byte, Template50, error)

PackPNG encodes data using Template 5.41 (PNG packing). It packs the values into a grayscale PNG image.

func PackSimple

func PackSimple(values []float64, bitsPerValue uint8) ([]byte, Template50, error)

PackSimple encodes data using Template 5.0 (simple packing). Returns the packed data bytes and the Template50 with computed parameters.

func (Template50) TemplateNumber

func (Template50) TemplateNumber() uint16

type Template52

type Template52 struct {
	Template50                               // octets 12-21
	GroupSplittingMethod              uint8  // octet 22 (Table 5.4)
	MissingValueManagement            uint8  // octet 23 (Table 5.5)
	PrimaryMissingValueSubstitute     uint32 // octets 24-27
	SecondaryMissingValueSubstitute   uint32 // octets 28-31
	NumberOfGroups                    uint32 // octets 32-35
	ReferenceForGroupWidths           uint8  // octet 36
	NumberOfBitsForGroupWidths        uint8  // octet 37
	ReferenceForGroupLengths          uint32 // octets 38-41
	LengthIncrementForGroupLengths    uint8  // octet 42
	TrueLengthOfLastGroup             uint32 // octets 43-46
	NumberOfBitsForScaledGroupLengths uint8  // octet 47
}

Template52 is Data Representation Template 5.2: Grid point data — complex packing. Extends Template 5.0 with group splitting parameters.

func PackComplex

func PackComplex(values []float64, bitsPerValue uint8) ([]byte, Template52, error)

PackComplex encodes values using Template 5.2 (complex packing). Returns packed data bytes and the completed Template52.

func (Template52) TemplateNumber

func (Template52) TemplateNumber() uint16

type Template53

type Template53 struct {
	Template52                           // octets 12-47
	OrderOfSpatialDifferencing     uint8 // octet 48 (Table 5.6)
	NumberOfOctetsExtraDescriptors uint8 // octet 49
}

Template53 is Data Representation Template 5.3: Grid point data — complex packing and spatial differencing. Extends Template 5.2 with spatial differencing parameters.

func PackComplexSpatialDiff

func PackComplexSpatialDiff(values []float64, bitsPerValue uint8, order uint8) ([]byte, Template53, error)

PackComplexSpatialDiff encodes values using Template 5.3 (complex packing with spatial differencing). order must be 1 or 2. Returns packed data bytes and the completed Template53.

func (Template53) TemplateNumber

func (Template53) TemplateNumber() uint16

type Template54

type Template54 struct {
	Precision uint8 // Table 5.7
}

Template54 is Data Representation Template 5.4: Grid point data — IEEE floating point.

12     Precision (Table 5.7):
         1 = IEEE 32-bit (4 bytes per value)
         2 = IEEE 64-bit (8 bytes per value)

func PackIEEE

func PackIEEE(values []float64, precision uint8) ([]byte, Template54, error)

PackIEEE encodes data using Template 5.4 (IEEE floating point).

func (Template54) TemplateNumber

func (Template54) TemplateNumber() uint16

type Template310

type Template310 struct {
	ShapeOfEarth                        uint8 // Table 3.2
	ScaleFactorOfRadiusOfSphericalEarth uint8
	ScaledValueOfRadiusOfSphericalEarth uint32
	ScaleFactorOfEarthMajorAxis         uint8
	ScaledValueOfEarthMajorAxis         uint32
	ScaleFactorOfEarthMinorAxis         uint8
	ScaledValueOfEarthMinorAxis         uint32
	Ni                                  uint32 // number of points along a parallel
	Nj                                  uint32 // number of points along a meridian
	LatitudeOfFirstGridPoint            int32  // microdegrees (sign-magnitude)
	LongitudeOfFirstGridPoint           int32  // microdegrees (sign-magnitude)
	ResolutionAndComponentFlags         uint8  // Flag table 3.3
	LaD                                 int32  // latitude where Dx and Dy are specified (sign-magnitude)
	LatitudeOfLastGridPoint             int32  // microdegrees (sign-magnitude)
	LongitudeOfLastGridPoint            int32  // microdegrees (sign-magnitude)
	ScanningMode                        uint8  // Flag table 3.4
	OrientationOfTheGrid                uint32 // orientation angle in microdegrees
	Di                                  uint32 // longitudinal direction grid length in millimetres
	Dj                                  uint32 // latitudinal direction grid length in millimetres
}

Template310 is Grid Definition Template 3.10: Mercator.

All latitudes/longitudes are in units of 10^-6 degrees (sign-magnitude encoding). Di and Dj are in units of 10^-3 metres (millimetres).

func (Template310) TemplateNumber

func (Template310) TemplateNumber() uint16

type Template320

type Template320 struct {
	ShapeOfEarth                        uint8 // Table 3.2
	ScaleFactorOfRadiusOfSphericalEarth uint8
	ScaledValueOfRadiusOfSphericalEarth uint32
	ScaleFactorOfEarthMajorAxis         uint8
	ScaledValueOfEarthMajorAxis         uint32
	ScaleFactorOfEarthMinorAxis         uint8
	ScaledValueOfEarthMinorAxis         uint32
	Nx                                  uint32 // number of points along the x-axis
	Ny                                  uint32 // number of points along the y-axis
	LatitudeOfFirstGridPoint            int32  // microdegrees (sign-magnitude)
	LongitudeOfFirstGridPoint           int32  // microdegrees (sign-magnitude)
	ResolutionAndComponentFlags         uint8  // Flag table 3.3
	LaD                                 int32  // latitude where Dx and Dy are specified (sign-magnitude)
	OrientationOfTheGrid                int32  // orientation of the grid, microdegrees (sign-magnitude)
	Dx                                  uint32 // x-direction grid length in millimetres
	Dy                                  uint32 // y-direction grid length in millimetres
	ProjectionCentreFlag                uint8  // Flag table 3.5
	ScanningMode                        uint8  // Flag table 3.4
}

Template320 is Grid Definition Template 3.20: Polar Stereographic.

All latitudes/longitudes are in units of 10^-6 degrees (sign-magnitude encoding). Per the WMO GRIB2 specification, all lat/lon fields use sign-magnitude encoding (MSB=1 means negative). This matches eccodes' unsigned[4] declaration — eccodes handles the sign-magnitude conversion internally. Longitudes can range from -180 to +360 depending on convention. Dx and Dy are in units of 10^-3 metres (millimetres).

func (Template320) TemplateNumber

func (Template320) TemplateNumber() uint16

type Template330

type Template330 struct {
	ShapeOfEarth                        uint8 // Table 3.2
	ScaleFactorOfRadiusOfSphericalEarth uint8
	ScaledValueOfRadiusOfSphericalEarth uint32
	ScaleFactorOfEarthMajorAxis         uint8
	ScaledValueOfEarthMajorAxis         uint32
	ScaleFactorOfEarthMinorAxis         uint8
	ScaledValueOfEarthMinorAxis         uint32
	Nx                                  uint32 // number of points along the X-axis
	Ny                                  uint32 // number of points along the Y-axis
	LatitudeOfFirstGridPoint            int32  // microdegrees
	LongitudeOfFirstGridPoint           int32  // microdegrees (sign-magnitude)
	ResolutionAndComponentFlags         uint8  // Flag table 3.3
	LaD                                 int32  // latitude where Dx and Dy are specified, microdegrees
	LoV                                 int32  // longitude of meridian parallel to Y-axis, microdegrees (sign-magnitude)
	Dx                                  uint32 // X-direction grid length in millimetres
	Dy                                  uint32 // Y-direction grid length in millimetres
	ProjectionCentreFlag                uint8  // Flag table 3.5
	ScanningMode                        uint8  // Flag table 3.4
	Latin1                              int32  // first standard parallel, microdegrees
	Latin2                              int32  // second standard parallel, microdegrees
	LatitudeOfSouthernPole              int32  // microdegrees
	LongitudeOfSouthernPole             int32  // microdegrees (sign-magnitude)
}

Template330 is Grid Definition Template 3.30: Lambert Conformal (can be secant or tangent, conical or bipolar).

All latitudes/longitudes are in units of 10^-6 degrees. Per the WMO GRIB2 specification, all lat/lon fields use sign-magnitude encoding (MSB=1 means negative). This matches eccodes' unsigned[4] declaration — eccodes handles the sign-magnitude conversion internally. Longitudes can range from -180 to +360 depending on convention. Dx and Dy are in units of 10^-3 metres (millimetres).

func (Template330) TemplateNumber

func (Template330) TemplateNumber() uint16

type Template340

type Template340 struct {
	ShapeOfEarth                        uint8 // Table 3.2
	ScaleFactorOfRadiusOfSphericalEarth uint8
	ScaledValueOfRadiusOfSphericalEarth uint32
	ScaleFactorOfEarthMajorAxis         uint8
	ScaledValueOfEarthMajorAxis         uint32
	ScaleFactorOfEarthMinorAxis         uint8
	ScaledValueOfEarthMinorAxis         uint32
	Ni                                  uint32 // number of points along a parallel (MISSING for reduced)
	Nj                                  uint32 // number of points along a meridian
	BasicAngle                          uint32
	SubdivisionsOfBasicAngle            uint32
	LatitudeOfFirstGridPoint            int32  // microdegrees
	LongitudeOfFirstGridPoint           int32  // microdegrees
	ResolutionAndComponentFlags         uint8  // Flag table 3.3
	LatitudeOfLastGridPoint             int32  // microdegrees
	LongitudeOfLastGridPoint            int32  // microdegrees
	IDirectionIncrement                 uint32 // microdegrees (may be MISSING for reduced)
	N                                   uint32 // number of parallels between pole and equator
	ScanningMode                        uint8  // Flag table 3.4
}

Template340 is Grid Definition Template 3.40: Gaussian Latitude/Longitude.

Identical layout to Template 3.0 except octets 68-71 hold N (number of parallels between a pole and the equator) instead of jDirectionIncrement.

For reduced Gaussian grids, Ni is set to 0xFFFFFFFF (MISSING) and an optional PL array (number of points per latitude row) is appended after the template in Section3.OptionalPointNumbers.

func (Template340) TemplateNumber

func (Template340) TemplateNumber() uint16

type Template390

type Template390 struct {
	ShapeOfEarth                        uint8 // Table 3.2
	ScaleFactorOfRadiusOfSphericalEarth uint8
	ScaledValueOfRadiusOfSphericalEarth uint32
	ScaleFactorOfEarthMajorAxis         uint8
	ScaledValueOfEarthMajorAxis         uint32
	ScaleFactorOfEarthMinorAxis         uint8
	ScaledValueOfEarthMinorAxis         uint32
	Nx                                  uint32 // number of points along X-axis
	Ny                                  uint32 // number of points along Y-axis
	LatitudeOfSubSatellitePoint         int32  // microdegrees (sign-magnitude)
	LongitudeOfSubSatellitePoint        int32  // microdegrees (sign-magnitude)
	ResolutionAndComponentFlags         uint8  // Flag table 3.3
	Dx                                  uint32 // apparent diameter of Earth in grid lengths, X-direction
	Dy                                  uint32 // apparent diameter of Earth in grid lengths, Y-direction
	Xp                                  uint32 // X-coordinate of sub-satellite point (10^-3 grid lengths)
	Yp                                  uint32 // Y-coordinate of sub-satellite point (10^-3 grid lengths)
	ScanningMode                        uint8  // Flag table 3.4
	OrientationOfTheGrid                int32  // angle in microdegrees (sign-magnitude)
	Nr                                  uint32 // altitude of camera from Earth centre (10^-6 Earth radii)
	Xo                                  uint32 // X-coordinate of origin of sector image
	Yo                                  uint32 // Y-coordinate of origin of sector image
}

Template390 is Grid Definition Template 3.90: Space view perspective or orthographic. Used by geostationary satellites (GOES-R, Himawari, MSG).

All latitudes/longitudes are in units of 10^-6 degrees (sign-magnitude encoding). Xp, Yp are in units of 10^-3 grid lengths. Nr is in units of 10^-6 of the Earth's equatorial radius.

func (Template390) TemplateNumber

func (Template390) TemplateNumber() uint16

type Template411

type Template411 struct {
	Template40
	TypeOfEnsembleForecast              uint8 // Table 4.6
	PerturbationNumber                  uint8
	NumberOfForecastsInEnsemble         uint8
	YearOfEndOfInterval                 uint16
	MonthOfEndOfInterval                uint8
	DayOfEndOfInterval                  uint8
	HourOfEndOfInterval                 uint8
	MinuteOfEndOfInterval               uint8
	SecondOfEndOfInterval               uint8
	NumberOfTimeRangeSpecs              uint8
	NumberOfMissingInStatisticalProcess uint32
	TimeRangeSpecs                      []TimeRangeSpec
}

Template411 is Product Definition Template 4.11: Individual ensemble forecast, control and perturbed, at a horizontal level or in a horizontal layer in a continuous or non-continuous time interval. Combines Template 4.1 (ensemble member info) + Template 4.8 (time interval).

Octets 10-34 are Template 4.0, then:

35     Type of ensemble forecast (Table 4.6)
36     Perturbation number
37     Number of forecasts in ensemble
38-39  Year of end of overall time interval
40     Month of end of overall time interval
41     Day of end of overall time interval
42     Hour of end of overall time interval
43     Minute of end of overall time interval
44     Second of end of overall time interval
45     Number of time range specifications (n)
46-49  Total number of data values missing in statistical process
50-61  First time range spec (12 bytes each)
...    Additional time range specs

func (Template411) TemplateNumber

func (Template411) TemplateNumber() uint16

type Template412

type Template412 struct {
	Template40
	DerivedForecast                     uint8 // Table 4.7
	NumberOfForecastsInEnsemble         uint8
	YearOfEndOfInterval                 uint16
	MonthOfEndOfInterval                uint8
	DayOfEndOfInterval                  uint8
	HourOfEndOfInterval                 uint8
	MinuteOfEndOfInterval               uint8
	SecondOfEndOfInterval               uint8
	NumberOfTimeRangeSpecs              uint8
	NumberOfMissingInStatisticalProcess uint32
	TimeRangeSpecs                      []TimeRangeSpec
}

Template412 is Product Definition Template 4.12: Derived forecasts based on all ensemble members at a horizontal level or in a horizontal layer in a continuous or non-continuous time interval. Combines Template 4.2 (derived ensemble) + Template 4.8 (time interval).

Octets 10-34 are Template 4.0, then:

35     Derived forecast type (Table 4.7)
36     Number of forecasts in ensemble
37-38  Year of end of overall time interval
39     Month of end of overall time interval
40     Day of end of overall time interval
41     Hour of end of overall time interval
42     Minute of end of overall time interval
43     Second of end of overall time interval
44     Number of time range specifications (n)
45-48  Total number of data values missing in statistical process
49-60  First time range spec (12 bytes each)
...    Additional time range specs

func (Template412) TemplateNumber

func (Template412) TemplateNumber() uint16

type Template540

type Template540 struct {
	Template50
	TypeOfCompression      uint8 // octet 22 (Table 5.40): 0=lossless, 1=lossy
	TargetCompressionRatio uint8 // octet 23: 255=missing (lossless), or ratio for lossy
}

Template540 is Data Representation Template 5.40: Grid point data — JPEG 2000 code stream format. Extends Template 5.0 with compression parameters.

func PackJPEG2000

func PackJPEG2000(values []float64, bitsPerValue uint8) ([]byte, Template540, error)

PackJPEG2000 encodes values using Template 5.40 (JPEG2000 lossless).

The scaling formula is the same as simple packing:

X = (Y * 2^E + R) * 10^(-D)

where X is the original value, Y is the packed pixel value, E is the binary scale factor, R is the reference value, and D is the decimal scale factor.

PackJPEG2000 chooses R as the minimum value, D=0, and E computed so that the quantized values fit in bitsPerValue bits. The quantized values are then encoded as a JPEG 2000 lossless codestream.

func (Template540) TemplateNumber

func (Template540) TemplateNumber() uint16

type Template542

type Template542 struct {
	Template50
	CcsdsFlags     uint8  // octet 22: CCSDS compression options mask
	CcsdsBlockSize uint8  // octet 23: block size
	CcsdsRsi       uint16 // octets 24-25: reference sample interval
}

Template542 is Data Representation Template 5.42: Grid point data — CCSDS recommended lossless compression. Extends Template 5.0 with CCSDS/AEC compression parameters.

12-21  Same as Template 5.0 (ref value, binary/decimal scale, bpv, type)
22     CCSDS compression options mask (ccsdsFlags)
23     Block size for CCSDS (ccsdsBlockSize)
24-25  Reference sample interval for CCSDS (ccsdsRsi)

func PackCCSDS

func PackCCSDS(values []float64, bitsPerValue uint8, blockSize uint8, rsi uint16) ([]byte, Template542, error)

PackCCSDS encodes values using Template 5.42 (CCSDS/AEC) compression.

It quantises the float64 values into unsigned integers using simple packing parameters (reference value, binary scale, decimal scale) and then compresses the integer stream with the AEC encoder (CCSDS 121.0-B-3).

Returns the compressed byte stream and the populated Template542.

func (Template542) TemplateNumber

func (Template542) TemplateNumber() uint16

type Template5200

type Template5200 struct {
	BitsPerValue        uint8
	MaxLevelValue       uint16
	NumberOfLevelValues uint16
	DecimalScaleFactor  uint8
	LevelValues         []uint16
}

Template5200 is Data Representation Template 5.200: Grid point data -- run-length packing with level values.

Octet 12:      Number of bits used for each packed value (bitsPerValue)
Octets 13-14:  Maximum level value (maxLevelValue)
Octets 15-16:  Number of level values (numberOfLevelValues)
Octet 17:      Decimal scale factor
Octets 18-...: Level values (each 2 bytes, numberOfLevelValues entries)

func (Template5200) TemplateNumber

func (Template5200) TemplateNumber() uint16

type TimeRangeSpec

type TimeRangeSpec struct {
	TypeOfStatisticalProcessing     uint8 // Table 4.10
	TypeOfTimeIncrement             uint8 // Table 4.11
	IndicatorOfUnitForTimeRange     uint8 // Table 4.4
	LengthOfTimeRange               uint32
	IndicatorOfUnitForTimeIncrement uint8 // Table 4.4
	TimeIncrement                   uint32
}

TimeRangeSpec describes one statistical processing time range within Template 4.8.

Directories

Path Synopsis
internal
aec
Package aec implements the Adaptive Entropy Coding (AEC) decoder per CCSDS 121.0-B-3 recommended standard for lossless data compression.
Package aec implements the Adaptive Entropy Coding (AEC) decoder per CCSDS 121.0-B-3 recommended standard for lossless data compression.
j2k
Package j2k provides a pure-Go JPEG 2000 decoder for use in GRIB2.
Package j2k provides a pure-Go JPEG 2000 decoder for use in GRIB2.

Jump to

Keyboard shortcuts

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