Documentation
¶
Overview ¶
Package npy reads and writes NumPy .npy files.
It is designed to be fast: when the on-disk byte order matches the host (the common little-endian case) the raw file bytes are reinterpreted directly as a Go slice with no per-element copy. For files that are large relative to available RAM it can memory-map the data instead of loading it.
There are two API tiers:
Dynamic, Python-like:
arr, err := npy.Open("data.npy") fmt.Println(arr.Shape) // shape auto-detected xs, _ := arr.Float64() // typed view of the data
Generic, fastest (no runtime type assertions):
nd, err := npy.Load[float64]("data.npy") _ = nd.Values // []float64 _ = nd.Shape // []int
Writing mirrors this:
npy.Save("out.npy", []float64{1, 2, 3, 4}, []int{2, 2})
npy.Write(w, []int32{1, 2, 3}, nil) // nil shape => 1-D
The .npy format is documented at https://numpy.org/devdocs/reference/generated/numpy.lib.format.html
Index ¶
- func AddTyped[T Element](zw *ZipWriter, name string, data []T, shape []int) error
- func Save(path string, data any, shape []int, opts ...Option) error
- func SaveZip(path string, arrays []NamedArray, opts ...Option) error
- func Values[T Element](a *Array) ([]T, error)
- func Write[T Element](w io.Writer, data []T, shape []int, opts ...Option) error
- type AccessMode
- type Archive
- type Array
- func (a *Array) AsFloat64() ([]float64, error)
- func (a *Array) Bool() ([]bool, error)
- func (a *Array) Close() error
- func (a *Array) Complex64() ([]complex64, error)
- func (a *Array) Complex128() ([]complex128, error)
- func (a *Array) Float32() ([]float32, error)
- func (a *Array) Float64() ([]float64, error)
- func (a *Array) Int8() ([]int8, error)
- func (a *Array) Int16() ([]int16, error)
- func (a *Array) Int32() ([]int32, error)
- func (a *Array) Int64() ([]int64, error)
- func (a *Array) Len() int
- func (a *Array) Uint8() ([]uint8, error)
- func (a *Array) Uint16() ([]uint16, error)
- func (a *Array) Uint32() ([]uint32, error)
- func (a *Array) Uint64() ([]uint64, error)
- type DType
- type Element
- type NDArray
- type NamedArray
- type Option
- type ZipWriter
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Save ¶
Save writes a typed slice to a .npy file. data must be one of the supported element slice types (for example []float64 or []int32). If shape is nil the array is written as 1-D with length len(data); otherwise the product of shape must equal len(data).
npy.Save("out.npy", []float64{1, 2, 3, 4}, []int{2, 2})
func SaveZip ¶
func SaveZip(path string, arrays []NamedArray, opts ...Option) error
SaveZip writes a .npz archive containing the given named arrays. By default entries are stored uncompressed (like numpy.savez); pass WithCompression(true) for DEFLATE (like numpy.savez_compressed).
npy.SaveZip("out.npz", []npy.NamedArray{
{Name: "x", Data: []float64{1, 2, 3, 4}, Shape: []int{2, 2}},
{Name: "y", Data: []int32{5, 6, 7}},
})
Types ¶
type AccessMode ¶
type AccessMode int
AccessMode controls how a file's data region is brought into the process.
const ( // Auto picks between InMemory and Mmap based on the data size relative to // available system memory. This is the default. Auto AccessMode = iota // InMemory reads the whole file into a heap buffer. InMemory // Mmap memory-maps the file (falling back to InMemory where unsupported). Mmap )
type Archive ¶
type Archive struct {
// contains filtered or unexported fields
}
Archive is a read handle for a NumPy .npz file (a ZIP archive of .npy entries). Array names are the entry names with the ".npy" suffix removed, matching numpy.load(...).files.
arc, _ := npy.OpenZip("data.npz")
defer arc.Close()
for _, name := range arc.Names() {
arr, _ := arc.Array(name)
fmt.Println(name, arr.Shape)
}
func OpenZip ¶
OpenZip opens a .npz archive from a file path. Like Open, it may memory-map the file (honouring WithMode / WithMaxRAMFraction) so that uncompressed entries can be read zero-copy. Call Close when done.
func ReadZip ¶
ReadZip reads a .npz archive from r. size is the total length of the archive. Entries are read into memory (no mmap).
func (*Archive) Array ¶
Array reads the named array into a dynamically-typed Array. For a memory-mapped archive the data may alias the mapping, so the returned Array must not be used after the Archive is closed.
type Array ¶
type Array struct {
Shape []int // dimensions, as in NumPy
Fortran bool // true if the data is in Fortran (column-major) order
Dtype DType // the on-disk element type
Data any // the typed element slice, e.g. []float64
// contains filtered or unexported fields
}
Array is the dynamically-typed result of reading a .npy file. The element type is discovered from the file and stored in Data as the matching Go slice type (for example []float64 or []int32).
func Decode ¶
Decode reads a .npy stream into a dynamically-typed Array. The whole array is read into memory.
func Open ¶
Open reads a .npy file, returning a dynamically-typed Array whose shape and element type are taken from the file. This is the most NumPy-like entry point:
arr, err := npy.Open("data.npy")
fmt.Println(arr.Shape)
For memory-mapped arrays, call Close when done.
func (*Array) AsFloat64 ¶
AsFloat64 returns a copy of the data converted to float64, regardless of the underlying numeric dtype. Boolean and complex arrays are not supported.
func (*Array) Close ¶
Close releases resources associated with the array. It is only meaningful for memory-mapped arrays; for in-memory arrays it is a no-op. After Close the Data slice of a memory-mapped array must not be used.
func (*Array) Complex128 ¶
func (a *Array) Complex128() ([]complex128, error)
type DType ¶
type DType struct {
Kind byte // 'f' float, 'i' int, 'u' uint, 'b' bool, 'c' complex
ItemSize int // bytes per element
Order binary.ByteOrder // on-disk byte order; nil for single-byte types
Descr string // the original descr string, e.g. "<f8"
}
DType describes the element type of an array, mirroring a NumPy dtype.
type Element ¶
type Element interface {
~int8 | ~int16 | ~int32 | ~int64 |
~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64 |
~complex64 | ~complex128 |
~bool
}
Element is the set of array element types this package can read and write. It mirrors the numeric (and boolean) dtypes NumPy stores in .npy files.
type NDArray ¶
type NDArray[T Element] struct { Values []T // the element data Shape []int // dimensions Fortran bool // true if the data is in Fortran (column-major) order // contains filtered or unexported fields }
NDArray is the statically-typed result of reading a .npy file with a known element type. It is the fastest API: there are no runtime type assertions.
func Load ¶
Load reads a .npy file into a statically-typed NDArray[T]. T must match the file's element kind and size (byte order is converted automatically). This is the fastest entry point. For memory-mapped arrays, call Close when done.
func ZipValues ¶
ZipValues reads the named array from the archive into a statically-typed NDArray[T]. T must match the entry's element kind and size.
type NamedArray ¶
type NamedArray struct {
Name string
Data any // a supported element slice, e.g. []float64
Shape []int // nil means a 1-D array of length len(Data)
}
NamedArray pairs an array name with its data and shape for SaveZip.
type Option ¶
type Option func(*config)
Option customises read and write behaviour.
func WithCompression ¶
WithCompression enables DEFLATE compression of .npz archive entries (like numpy.savez_compressed). It has no effect on single .npy files. The default is no compression (like numpy.savez).
func WithFortran ¶
WithFortran requests Fortran (column-major) ordering when writing.
func WithMaxRAMFraction ¶
WithMaxRAMFraction sets the fraction of system memory above which Auto mode switches from reading into memory to memory-mapping. The default is 0.5.
func WithMode ¶
func WithMode(m AccessMode) Option
WithMode selects the access mode used when reading from a file path.
type ZipWriter ¶
type ZipWriter struct {
// contains filtered or unexported fields
}
ZipWriter incrementally writes arrays to a .npz archive. This is useful when arrays are produced one at a time and need not all be held in memory.
zw, _ := npy.CreateZip("out.npz")
npy.AddTyped(zw, "a", []float64{1, 2, 3}, nil)
zw.Add("b", []int32{4, 5, 6}, []int{3})
zw.Close()