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 ¶
- Variables
- type Attribute
- type Dimension
- type File
- func (f *File) Attribute(name string) (*Attribute, bool)
- func (f *File) Attributes() []*Attribute
- func (f *File) Close() error
- func (f *File) Dimension(name string) (*Dimension, bool)
- func (f *File) Dimensions() []*Dimension
- func (f *File) Format() Format
- func (f *File) Variable(name string) (*Variable, bool)
- func (f *File) Variables() []*Variable
- type Format
- type Schema
- func (s *Schema) AddDimension(name string, length int64) *SchemaDim
- func (s *Schema) AddVariable(name string, typ Type, dims ...*SchemaDim) *SchemaVar
- func (s *Schema) Dimensions() []*SchemaDim
- func (s *Schema) Format() Format
- func (s *Schema) SetAttr(name string, values any) error
- func (s *Schema) SetAttrTyped(name string, typ Type, values any) error
- func (s *Schema) Variables() []*SchemaVar
- type SchemaDim
- type SchemaVar
- type Type
- type VarWriter
- type Variable
- func (v *Variable) Attribute(name string) (*Attribute, bool)
- func (v *Variable) Attributes() []*Attribute
- func (v *Variable) Dims() []*Dimension
- func (v *Variable) Len() int64
- func (v *Variable) Name() string
- func (v *Variable) Read[T any](dst *[]T) error
- func (v *Variable) ReadSlice[T any](dst *[]T, start, count []int64) error
- func (v *Variable) Shape() []int64
- func (v *Variable) Type() Type
- type Writer
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
Bytes returns the values' external (big-endian) representation, without header padding. The result is a copy the caller may modify.
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.
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 ¶
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 ¶
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) Attributes ¶
Attributes returns the global attributes in definition order.
func (*File) Close ¶
Close releases the file. It is idempotent; for a File created with NewReader it does not close the caller's reader.
func (*File) Dimensions ¶
Dimensions returns the file's dimensions 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 ¶
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
type Schema ¶
type Schema struct {
// contains filtered or unexported fields
}
Schema collects the definitions of one file to create.
func NewSchema ¶
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 ¶
AddDimension adds a dimension. It returns the handle AddVariable takes; the name and the length are validated by Create.
func (*Schema) AddVariable ¶
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 ¶
Dimensions returns the schema's dimensions in definition order.
func (*Schema) SetAttr ¶
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 ¶
SetAttrTyped sets a global attribute with an explicit netCDF type, for the cases inference cannot tell apart (ubyte vs char, uint vs int).
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.
type SchemaVar ¶
type SchemaVar struct {
// contains filtered or unexported fields
}
SchemaVar is one variable of a schema, with its attributes.
func (*SchemaVar) Attributes ¶
Attributes returns the variable's attributes in definition order.
func (*SchemaVar) SetAttrTyped ¶
SetAttrTyped sets a variable attribute with an explicit type; see Schema.SetAttrTyped.
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.
type VarWriter ¶
type VarWriter struct {
// contains filtered or unexported fields
}
VarWriter writes one variable's values.
func (*VarWriter) Shape ¶
Shape returns the variable's current shape; for a record variable the first entry is the current record count.
func (*VarWriter) Write ¶
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 ¶
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) Attributes ¶
Attributes returns the variable's attributes in definition order.
func (*Variable) Read ¶
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)
}
}
Output:
func (*Variable) ReadSlice ¶
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.
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 ¶
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 ¶
Close writes the final record count into the header and closes the file. It is idempotent; a write after Close reports ErrClosed.
Source Files
¶
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). |