netcdf

package module
v0.0.0-...-5be112a Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 10 Imported by: ? modules, 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.

README

netcdf

CI Go Reference codecov

Pure Go reader and writer for NetCDF files — classic CDF-1, CDF-2, CDF-5 and NetCDF-4 — with no cgo and no C dependencies. It is part of the scigolib ecosystem and builds NetCDF-4 on top of scigolib/hdf5.

Status: early development. The classic formats (CDF-1, CDF-2, CDF-5) are read and written: headers, attributes, metadata and data, whole variables and hyperslabs. NetCDF-4 support is next. The API is not stable before v1.0.

Install

go get github.com/scigolib/netcdf

Requires Go 1.27 or newer. We support only Go releases that still receive security fixes (1.26 and 1.27 today). The floor also matches scigolib/hdf5, the foundation NetCDF-4 builds on: a module's go line must be at least its dependencies'. Go 1.27 additionally enables generic methods, which let one type-safe method replace a family of per-type methods; this library keeps its typed helpers as generic functions and does not adopt them, though a generic method would be added where it collapses a real family.

Quick start

package main

import (
	"fmt"
	"log"

	"github.com/scigolib/netcdf"
)

func main() {
	f, err := netcdf.Open("data.nc")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()

	// Dimensions, attributes and variables are parsed when the file opens;
	// data is read on demand.
	for _, v := range f.Variables() {
		fmt.Println(v.Name(), v.Type(), v.Shape())
	}

	temp, ok := f.Variable("temp")
	if !ok {
		log.Fatal("no variable temp")
	}
	values := make([]float64, temp.Len())
	if err := temp.Read(&values); err != nil {
		log.Fatal(err)
	}
	fmt.Println(values)

	// A hyperslab: the first two records of the first column.
	part := make([]float64, 2)
	if err := temp.ReadSlice(&part, []int64{0, 0}, []int64{2, 1}); err != nil {
		log.Fatal(err)
	}
	fmt.Println(part)
}

Read and ReadSlice take a pointer to a slice whose element type matches the variable's netCDF type: []int8 for byte, []byte for char and ubyte, []int16, []uint16, []int32, []uint32, []float32, []float64, []int64, []uint64. A mismatched slice is reported with ErrTypeMismatch, never silently converted.

Writing a file

schema := netcdf.NewSchema(netcdf.FormatClassic) // CDF-1; FormatClassic64 is CDF-2, FormatClassic64Data is CDF-5
time := schema.AddDimension("time", 0)           // length 0 = unlimited
x := schema.AddDimension("x", 3)
temp := schema.AddVariable("temp", netcdf.TypeFloat, time, x)
if err := temp.SetAttr("units", "K"); err != nil {
	log.Fatal(err)
}

w, err := netcdf.Create("out.nc", schema)
if err != nil {
	log.Fatal(err)
}
v, _ := w.Variable("temp")
// Two records of three values; writing past the current count appends and
// fills the records in between with the fill value.
if err := v.WriteSlice([]float32{1, 2, 3, 4, 5, 6}, []int64{0, 0}, []int64{2, 3}); err != nil {
	log.Fatal(err)
}
if err := w.Close(); err != nil { // writes the record count; the file is consistent
	log.Fatal(err)
}

Attribute values are Go slices whose netCDF type is inferred (string/[]byte are char, []int8 byte, []int32 int, []float64 double, …); SetAttrTyped states the type explicitly for the ambiguous cases (ubyte vs char, uint vs int). Create validates the whole schema before touching the file; a schema error is reported before anything is written. The output is byte-identical to netCDF-C's ncgen for the same model and format (the fixtures in testdata/ are the proof). ncdump and nccopy read it too — checked by hand against netCDF-C 4.10.1 on 2026-11-14; automated differential runs against the C tools are planned.

Formats

Format Starts with Read Write
CDF-1 (classic) CDF + version 1 yes yes
CDF-2 (64-bit offset) CDF + version 2 yes yes
CDF-5 (64-bit data) CDF + version 5 yes yes
NetCDF-4 (HDF5) the eight-byte HDF5 signature planned planned

Why another NetCDF library

  • Pure Go, zero cgo. Cross-compiles to every platform Go supports, no C toolchain.
  • One ecosystem. NetCDF-4 will sit on scigolib/hdf5, our own HDF5 engine; the classic formats implemented today need no other library.
  • Checked against the C implementation. We read files that ncgen writes, and the files we write have been read back by ncdump and nccopy by hand (netCDF-C 4.10.1, 2026-11-14).

Documentation

License

MIT — see LICENSE.

Documentation

Overview

Package netcdf reads and writes NetCDF files.

The classic formats — CDF-1, CDF-2 (64-bit offset) and CDF-5 (64-bit data) — are read and written today. NetCDF-4 stores its data in an HDF5 file and is planned on top of github.com/scigolib/hdf5. The classic formats are defined by the NetCDF Classic Format Specification (https://docs.unidata.ucar.edu/netcdf-c/current/file_format_specifications.html); the reference implementation is netCDF-C (https://github.com/Unidata/netcdf-c).

The classic formats are big-endian: every value is stored in network byte order, whatever the host order. The package spells that out at each decode site and never assumes the native order.

Data access is typed. Variable.Read, Variable.ReadSlice, VarWriter.Write and VarWriter.WriteSlice are generic over the element type, which is inferred from the argument ([]int8 for byte, []byte for char and ubyte, and the matching slice type for the rest), so the element type is checked at compile time. A file's type is known only after opening it, so the variable's type is also checked at run time; a mismatch is ErrTypeMismatch, never a silent conversion. When the type is discovered at run time, switch on Variable.Type and call the typed method per arm (see ExampleVariable_Read_dynamic).

The generic methods live on the concrete Variable and VarWriter types: Go does not allow generic interface methods, so an interface-based abstraction over them would need its own non-generic contract.

Status: early development. The classic formats are read and written — header, dimensions, attributes, variables and data (whole variables and hyperslabs). NetCDF-4 is not implemented yet, and the API is not stable before v1.0.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotNetCDF reports input that is not a NetCDF file.
	ErrNotNetCDF = errors.New("not a NetCDF file")

	// ErrCorrupt reports a file whose header or data violates the format.
	ErrCorrupt = errors.New("corrupt NetCDF file")

	// ErrOutOfRange reports an index or selection outside the variable, or a
	// destination slice whose length does not match the selection.
	ErrOutOfRange = errors.New("selection outside the variable")

	// ErrUnsupportedFormat reports a NetCDF format this package does not read
	// yet: a NetCDF-4 file (HDF5-backed) is detected and reported with it.
	ErrUnsupportedFormat = errors.New("unsupported netCDF format")

	// ErrTypeMismatch reports a destination slice whose element type does not
	// match the variable's netCDF type.
	ErrTypeMismatch = errors.New("destination type does not match the data type")

	// ErrClosed reports use of a File after Close.
	ErrClosed = errors.New("netCDF file is closed")

	// ErrInvalidSchema reports a schema Create cannot write: an unknown format,
	// an illegal or duplicated name, a type the format does not have, a
	// variable whose dimensions are not the schema's, more than one unlimited
	// dimension, an invalid _FillValue, or a layout the format cannot address.
	ErrInvalidSchema = errors.New("invalid netCDF schema")
)

Errors reported by the package; all are matchable with errors.Is.

Functions

This section is empty.

Types

type Attribute

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

Attribute is one attribute, global or attached to a variable.

The values are kept in their external big-endian representation; Value decodes them into a typed Go slice, Bytes returns the raw bytes.

func (*Attribute) Bytes

func (a *Attribute) Bytes() []byte

Bytes returns the values' external (big-endian) representation, without header padding. The result is a copy the caller may modify.

func (*Attribute) Len

func (a *Attribute) Len() int

Len returns the number of values the attribute holds.

func (*Attribute) Name

func (a *Attribute) Name() string

Name returns the attribute's name.

func (*Attribute) String

func (a *Attribute) String() string

String returns a text attribute's value with trailing NUL bytes trimmed. It is meant for attributes of type TypeChar; for other types it returns "".

func (*Attribute) Type

func (a *Attribute) Type() Type

Type returns the attribute's netCDF type.

func (*Attribute) Value

func (a *Attribute) Value() any

Value returns the attribute's values as a typed slice: []int8 for TypeByte, []byte for TypeChar and TypeUByte, []int16, []uint16, []int32, []uint32, []float32, []float64, []int64 and []uint64 for the rest.

type Dimension

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

Dimension is one dimension of a NetCDF file. Dimensions are shared by every variable that uses them.

func (*Dimension) Len

func (d *Dimension) Len() int64

Len returns the dimension's current length. For the unlimited dimension that is the file's record count, not the zero the header stores.

func (*Dimension) Name

func (d *Dimension) Name() string

Name returns the dimension's name.

func (*Dimension) Unlimited

func (d *Dimension) Unlimited() bool

Unlimited reports whether the dimension is the record (unlimited) dimension.

type File

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

File is an open NetCDF file. Its metadata (dimensions, attributes, variables) is parsed once when the file is opened; data is read on demand.

A File may be read from several goroutines at once. Close must not run concurrently with reads.

func NewReader

func NewReader(r io.ReaderAt, size int64) (*File, error)

NewReader reads a NetCDF file from r, whose content is size bytes long. The caller keeps ownership of r: Close does not close it.

NewReader is what makes reading from memory, a section of a larger file, or a test fixture possible without a temporary file.

func Open

func Open(path string) (*File, error)

Open opens the NetCDF file at path for reading. It recognizes the classic formats (CDF-1, CDF-2, CDF-5) and reports ErrUnsupportedFormat for a NetCDF-4 file, whose HDF5 layer is not wired up yet.

The returned File owns the underlying file; Close releases it.

func (*File) Attribute

func (f *File) Attribute(name string) (*Attribute, bool)

Attribute returns the global attribute with the given name.

func (*File) Attributes

func (f *File) Attributes() []*Attribute

Attributes returns the global attributes in definition order.

func (*File) Close

func (f *File) Close() error

Close releases the file. It is idempotent; for a File created with NewReader it does not close the caller's reader.

func (*File) Dimension

func (f *File) Dimension(name string) (*Dimension, bool)

Dimension returns the dimension with the given name.

func (*File) Dimensions

func (f *File) Dimensions() []*Dimension

Dimensions returns the file's dimensions in definition order.

func (*File) Format

func (f *File) Format() Format

Format returns the file's format.

func (*File) Variable

func (f *File) Variable(name string) (*Variable, bool)

Variable returns the variable with the given name.

func (*File) Variables

func (f *File) Variables() []*Variable

Variables returns the file's variables in definition order.

type Format

type Format int

Format identifies a NetCDF file format.

const (
	// FormatUnknown means the header matches no NetCDF format.
	FormatUnknown Format = iota

	// FormatClassic is CDF-1, the classic format with 32-bit offsets.
	FormatClassic

	// FormatClassic64 is CDF-2, the classic format with 64-bit offsets.
	FormatClassic64

	// FormatClassic64Data is CDF-5, the classic format with 64-bit offsets
	// and 64-bit sizes.
	FormatClassic64Data

	// FormatHDF5 is NetCDF-4, which stores its data in an HDF5 file.
	FormatHDF5
)

func DetectFormat

func DetectFormat(header []byte) Format

DetectFormat reports the format of a NetCDF file from its first bytes.

header must hold at least the first eight bytes of the file. A shorter slice is not an error: it simply cannot match the HDF5 signature and yields FormatUnknown unless it carries a complete classic header.

A classic file starts with the three bytes "CDF" and a version byte: 1 is CDF-1, 2 is CDF-2 and 5 is CDF-5. Version bytes 3 and 4 were proposed and never used; they are reported as FormatUnknown. A NetCDF-4 file is an HDF5 file written by netCDF-C without a user block, so the HDF5 signature sits at offset 0.

Example
package main

import (
	"fmt"

	"github.com/scigolib/netcdf"
)

func main() {
	// The first eight bytes of a file are enough to tell the formats apart.
	header := []byte("CDF\x02rest of the header")

	fmt.Println(netcdf.DetectFormat(header))

}
Output:
CDF-2

func (Format) String

func (f Format) String() string

String returns the format's name as the NetCDF documentation writes it.

type Schema

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

Schema collects the definitions of one file to create.

func NewSchema

func NewSchema(format Format) *Schema

NewSchema returns an empty schema for the given format: FormatClassic is CDF-1, FormatClassic64 is CDF-2 and FormatClassic64Data is CDF-5.

func (*Schema) AddDimension

func (s *Schema) AddDimension(name string, length int64) *SchemaDim

AddDimension adds a dimension. It returns the handle AddVariable takes; the name and the length are validated by Create.

func (*Schema) AddVariable

func (s *Schema) AddVariable(name string, typ Type, dims ...*SchemaDim) *SchemaVar

AddVariable adds a variable over the given dimensions. The dimensions must be handles this schema returned (Create reports a foreign one); the first dimension may be the unlimited one. A type the classic formats cannot hold (TypeString, user-type ids) is reported by Create as ErrInvalidSchema.

func (*Schema) Dimensions

func (s *Schema) Dimensions() []*SchemaDim

Dimensions returns the schema's dimensions in definition order.

func (*Schema) Format

func (s *Schema) Format() Format

Format returns the format the schema will be written in.

func (*Schema) SetAttr

func (s *Schema) SetAttr(name string, values any) error

SetAttr sets a global attribute, inferring the netCDF type from the Go value: string and []byte are char, []int8 byte, []int16 short, []int32 int, []float32 float, []float64 double, []uint16 ushort, []uint32 uint, []int64 int64 and []uint64 uint64. Setting an existing name replaces its value in place. The error is also recorded in the schema, so Create fails even if the caller ignores it.

func (*Schema) SetAttrTyped

func (s *Schema) SetAttrTyped(name string, typ Type, values any) error

SetAttrTyped sets a global attribute with an explicit netCDF type, for the cases inference cannot tell apart (ubyte vs char, uint vs int).

func (*Schema) Variables

func (s *Schema) Variables() []*SchemaVar

Variables returns the schema's variables in definition order.

type SchemaDim

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

SchemaDim is one dimension of a schema. A length of zero marks the unlimited (record) dimension. The classic formats allow at most one, and it must be the first dimension of every variable that uses it; Create enforces that rule per format, the enhanced model will not.

func (*SchemaDim) Len

func (d *SchemaDim) Len() int64

Len returns the dimension's defined length; the unlimited dimension is 0.

func (*SchemaDim) Name

func (d *SchemaDim) Name() string

Name returns the dimension's name.

func (*SchemaDim) Unlimited

func (d *SchemaDim) Unlimited() bool

Unlimited reports whether the dimension is the record (unlimited) one.

type SchemaVar

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

SchemaVar is one variable of a schema, with its attributes.

func (*SchemaVar) Attributes

func (v *SchemaVar) Attributes() []*Attribute

Attributes returns the variable's attributes in definition order.

func (*SchemaVar) Dims

func (v *SchemaVar) Dims() []*SchemaDim

Dims returns the variable's dimensions in order.

func (*SchemaVar) Name

func (v *SchemaVar) Name() string

Name returns the variable's name.

func (*SchemaVar) SetAttr

func (v *SchemaVar) SetAttr(name string, values any) error

SetAttr sets a variable attribute; see Schema.SetAttr.

func (*SchemaVar) SetAttrTyped

func (v *SchemaVar) SetAttrTyped(name string, typ Type, values any) error

SetAttrTyped sets a variable attribute with an explicit type; see Schema.SetAttrTyped.

func (*SchemaVar) Type

func (v *SchemaVar) Type() Type

Type returns the variable's netCDF type.

type Type

type Type int

Type identifies the netCDF external data type of a variable or attribute.

The numeric values are the nc_type values the format stores: the classic tags 1..11, TypeString (12), and, in NetCDF-4 files, user-type ids of 32 and above. A user-type id is file-scoped: the same number names different types in different files.

const (
	TypeByte   Type = 1  // NC_BYTE: 8-bit signed integer
	TypeChar   Type = 2  // NC_CHAR: text characters
	TypeShort  Type = 3  // NC_SHORT: 16-bit signed integer
	TypeInt    Type = 4  // NC_INT: 32-bit signed integer
	TypeFloat  Type = 5  // NC_FLOAT: IEEE single precision
	TypeDouble Type = 6  // NC_DOUBLE: IEEE double precision
	TypeUByte  Type = 7  // NC_UBYTE: 8-bit unsigned integer (CDF-5)
	TypeUShort Type = 8  // NC_USHORT: 16-bit unsigned integer (CDF-5)
	TypeUInt   Type = 9  // NC_UINT: 32-bit unsigned integer (CDF-5)
	TypeInt64  Type = 10 // NC_INT64: 64-bit signed integer (CDF-5)
	TypeUInt64 Type = 11 // NC_UINT64: 64-bit unsigned integer (CDF-5)
	TypeString Type = 12 // NC_STRING: reserved for the enhanced model, not writable here
)

The netCDF types. CDF-1 and CDF-2 know the first six; CDF-5 adds the unsigned and 64-bit ones. TypeString is reserved for the enhanced model; the classic formats this package reads and writes cannot hold it.

func (Type) Size

func (t Type) Size() int

Size returns the number of bytes one value occupies in the file. It returns 0 for types without a fixed element size, such as TypeString.

func (Type) String

func (t Type) String() string

String returns the type's name as CDL writes it.

type VarWriter

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

VarWriter writes one variable's values.

func (*VarWriter) Name

func (v *VarWriter) Name() string

Name returns the variable's name.

func (*VarWriter) Shape

func (v *VarWriter) Shape() []int64

Shape returns the variable's current shape; for a record variable the first entry is the current record count.

func (*VarWriter) Type

func (v *VarWriter) Type() Type

Type returns the variable's netCDF type.

func (*VarWriter) Write

func (v *VarWriter) Write[T any](values []T) error

Write writes the whole variable: from the first element to the last. For a fixed-size variable the values must fill its shape; for a record variable they are written from record 0 and extend the record dimension by as many records as they cover. The element type is inferred from values and checked against the variable's type at run time.

func (*VarWriter) WriteSlice

func (v *VarWriter) WriteSlice[T any](values []T, start, count []int64) error

WriteSlice writes a hyperslab. start and count hold one value per dimension: the zero-based first index and the number written. For a record variable the first dimension is addressed by record number; writing past the current record count fills and appends the records in between with the fill value, so a start far beyond the current count costs a fill of every record in between — the same behavior as netCDF-C's NCvnrecs. The element type is inferred from values and checked against the variable's type at run time.

type Variable

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

Variable is one variable of a NetCDF file: its metadata and its data.

Read and ReadSlice are generic over the element type, which is inferred from the destination slice: []int8 for byte, []byte for char and ubyte, []int16, []uint16, []int32, []uint32, []float32, []float64, []int64 and []uint64. The element type is checked at compile time; the variable's type is checked at run time (ErrTypeMismatch), because a file's type is discovered by opening it.

func (*Variable) Attribute

func (v *Variable) Attribute(name string) (*Attribute, bool)

Attribute returns the variable attribute with the given name.

func (*Variable) Attributes

func (v *Variable) Attributes() []*Attribute

Attributes returns the variable's attributes in definition order.

func (*Variable) Dims

func (v *Variable) Dims() []*Dimension

Dims returns the dimensions of the variable's shape, in order.

func (*Variable) Len

func (v *Variable) Len() int64

Len returns the number of values the variable holds in the current file.

func (*Variable) Name

func (v *Variable) Name() string

Name returns the variable's name.

func (*Variable) Read

func (v *Variable) Read[T any](dst *[]T) error

Read reads the whole variable into dst, which must hold exactly Len values of the matching Go element type. The element type is inferred from dst and checked against the variable's type at run time.

Example (Dynamic)

ExampleVariable_Read_dynamic shows the pattern for data whose element type is known only at run time: switch on Variable.Type and call the typed method per arm. The same switch is how a dynamic consumer builds its typed destination.

package main

import (
	"fmt"
	"log"

	"github.com/scigolib/netcdf"
)

func main() {
	f, err := netcdf.Open("data.nc")
	if err != nil {
		log.Fatal(err)
	}

	for _, v := range f.Variables() {
		switch v.Type() {
		case netcdf.TypeFloat:
			values := make([]float32, v.Len())
			if err := v.Read(&values); err != nil {
				log.Fatal(err)
			}
			fmt.Println(v.Name(), values)
		case netcdf.TypeDouble:
			values := make([]float64, v.Len())
			if err := v.Read(&values); err != nil {
				log.Fatal(err)
			}
			fmt.Println(v.Name(), values)
		case netcdf.TypeInt:
			values := make([]int32, v.Len())
			if err := v.Read(&values); err != nil {
				log.Fatal(err)
			}
			fmt.Println(v.Name(), values)
		default:
			log.Fatalf("%s: no example for type %s", v.Name(), v.Type())
		}
	}

	if err := f.Close(); err != nil {
		log.Fatal(err)
	}
}

func (*Variable) ReadSlice

func (v *Variable) ReadSlice[T any](dst *[]T, start, count []int64) error

ReadSlice reads a hyperslab into dst. start and count hold one value per dimension: the zero-based first index and the number of values along that dimension. The record dimension is addressed by record number.

dst must hold exactly the product of count values and an element type that matches the variable's netCDF type. A selection outside the shape or a dst of the wrong length yields ErrOutOfRange; a slice of the wrong element type yields ErrTypeMismatch; data beyond the end of the file yields ErrCorrupt.

func (*Variable) Shape

func (v *Variable) Shape() []int64

Shape returns the variable's current shape, one length per dimension. For a record variable the first entry is the file's current record count.

func (*Variable) Type

func (v *Variable) Type() Type

Type returns the variable's netCDF type.

type Writer

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

Writer writes data into a file created by Create. A Writer is not safe for concurrent use; Close must not run concurrently with writes.

The file is consistent after Close: the header's record count is written last, so a file abandoned before Close reads back as one with fewer records.

func Create

func Create(path string, schema *Schema) (*Writer, error)

Create writes a new file at path from schema. It validates the schema, lays the header out exactly as netCDF-C's NC_begins does, writes the header and fills every fixed-size variable with its fill value.

Create truncates an existing file at path, like os.Create and like netCDF-C without NC_NOCLOBBER; there is no option to refuse an existing file yet.

A schema error is reported before the file is touched; the returned Writer is usable until Close.

func (*Writer) Close

func (w *Writer) Close() error

Close writes the final record count into the header and closes the file. It is idempotent; a write after Close reports ErrClosed.

func (*Writer) Format

func (w *Writer) Format() Format

Format returns the format the file is written in.

func (*Writer) Variable

func (w *Writer) Variable(name string) (*VarWriter, bool)

Variable returns the variable with the given name.

func (*Writer) Variables

func (w *Writer) Variables() []*VarWriter

Variables returns the file's variables in definition order.

Directories

Path Synopsis
internal
cdf
Package cdf implements the byte-level reading of the classic netCDF file formats: CDF-1 (version byte 1, 32-bit offsets), CDF-2 (version 2, 64-bit offsets) and CDF-5 (version 5, 64-bit offsets and 64-bit sizes).
Package cdf implements the byte-level reading of the classic netCDF file formats: CDF-1 (version byte 1, 32-bit offsets), CDF-2 (version 2, 64-bit offsets) and CDF-5 (version 5, 64-bit offsets and 64-bit sizes).

Jump to

Keyboard shortcuts

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