Documentation
¶
Overview ¶
Package npyio provides read/write access to files following the NumPy data file format:
https://numpy.org/neps/nep-0001-npy-format.html
Supported types ¶
npyio supports r/w of scalars, arrays, slices and gonum/mat.Dense. Supported scalars are:
- bool,
- (u)int{8,16,32,64},
- float{32,64},
- complex{64,128}
Reading ¶
Reading from a NumPy data file can be performed like so:
f, err := os.Open("data.npy")
var m mat.Dense
err = npyio.Read(f, &m)
fmt.Printf("data = %v\n", mat.Formatted(&m, mat.Prefix(" "))))
npyio can also read data directly into slices, arrays or scalars, provided the on-disk data type and the provided one match.
Example:
var data []float64 err = npyio.Read(f, &data) var data uint64 err = npyio.Read(f, &data)
Writing ¶
Writing into a NumPy data file can be done like so:
f, err := os.Create("data.npy")
var m mat.Dense = ...
err = npyio.Write(f, m)
Scalars, arrays and slices are also supported:
var data []float64 = ... err = npyio.Write(f, data) var data int64 = 42 err = npyio.Write(f, data) var data [42]complex128 = ... err = npyio.Write(f, data)
Example (PartialRead) ¶
package main
import (
"fmt"
"log"
"os"
"codeberg.org/sbinet/npyio"
)
func main() {
out, err := os.Create("data.npy")
if err != nil {
log.Fatal(err)
}
defer out.Close()
f := []float64{0, 1, 2, 3, 4, 5}
fmt.Printf("-- original data --\n")
fmt.Printf("data = %v\n", f)
err = npyio.Write(out, f)
if err != nil {
log.Fatalf("error writing data: %v\n", err)
}
err = out.Close()
if err != nil {
log.Fatal(err)
}
in, err := os.Open("data.npy")
if err != nil {
log.Fatal(err)
}
defer in.Close()
r, err := npyio.NewReader(in)
if err != nil {
log.Fatal(err)
}
data := make([]float64, 3)
err = r.Read(&data)
if err != nil {
log.Fatalf("error reading data: %v\n", err)
}
fmt.Printf("-- partial data read back --\n")
fmt.Printf("data = %v\n", data)
err = r.Read(&data)
if err != nil {
log.Fatalf("error reading data: %v\n", err)
}
fmt.Printf("-- rest of data read back --\n")
fmt.Printf("data = %v\n", data)
}
Output: -- original data -- data = [0 1 2 3 4 5] -- partial data read back -- data = [0 1 2] -- rest of data read back -- data = [3 4 5]
Example (ReadIntoUserStruct) ¶
package main
import (
"bytes"
"fmt"
"log"
"os"
"codeberg.org/sbinet/npyio"
)
func main() {
raw, err := os.ReadFile("testdata/nested-subarr-struct-aligned-0_corder.npy")
if err != nil {
log.Fatal(err)
}
fmt.Printf("-- input data --\n")
err = npyio.Dump(os.Stdout, bytes.NewReader(raw))
if err != nil {
log.Fatal(err)
}
type U struct {
F1 uint16 `npy:"F11, descr='|u2'"` // take byte-order from the one specified on-disk
F2 string `npy:"F12, descr='|S1'"`
F3 []float32 `npy:"F13, descr=('f4', (2,3))"`
}
type T struct {
F1 uint32 `npy:"F01, descr='<u4'"` // explicit byte-order. /!\ better match the one on-disk /!\
F2 [2]U `npy:"F02"`
F3 float32 `npy:"F03"` // no descr. take byte-order from the one specified on-disk
}
var usr []T
err = npyio.Read(bytes.NewReader(raw), &usr)
if err != nil {
log.Fatalf("could not read npy data file into user data slice: %v", err)
}
fmt.Printf("\n-- read into user type --\n")
fmt.Printf("data = %v\n", usr)
}
Output: -- input data -- ================================================================================ file: input.npy npy-header: Header{Major:1, Minor:0, Descr:{Type:[('F01', '<u4'), ('F02', [('F11', '<u2'), ('F12', '|S1'), ('F13', '<f4', (2, 3))], (2, 1)), ('F03', '<f4')], Fortran:false, Shape:[2]}} data = [{1 [{2 a [1 2 3 4 5 6]} {3 b [2 3 4 5 6 7]}] 3.1} {2 [{3 z [2 4 6 8 10 12]} {4 y [3 4 5 6 7 8]}] 4.1}] -- read into user type -- data = [{1 [{2 a [1 2 3 4 5 6]} {3 b [2 3 4 5 6 7]}] 3.1} {2 [{3 z [2 4 6 8 10 12]} {4 y [3 4 5 6 7 8]}] 4.1}]
Example (WriteUserStruct) ¶
package main
import (
"bytes"
"fmt"
"log"
"codeberg.org/sbinet/npyio"
)
func main() {
type U struct {
Name string `npy:"usr"`
}
type T struct {
A uint8 `npy:"a"`
B string `npy:"name"`
C []float64 `npy:"t"`
D []U `npy:"ds"`
}
vs := []T{
{A: 1, B: "áà", C: []float64{1, 2, 3}, D: []U{{Name: "n1"}, {Name: "n2"}}},
{A: 2, B: "éèï", C: []float64{4, 5, 6}, D: []U{{Name: "n2"}, {Name: "n3"}}},
}
fmt.Printf("-- original data --\n")
fmt.Printf("%+v\n", vs)
buf := new(bytes.Buffer)
err := npyio.Write(buf, vs)
if err != nil {
log.Fatalf("error writing data: %v\n", err)
}
var data []T
err = npyio.Read(buf, &data)
if err != nil {
log.Fatalf("error reading data: %v\n", err)
}
fmt.Printf("-- data read back --\n")
fmt.Printf("%+v\n", data)
}
Output: -- original data -- [{A:1 B:áà C:[1 2 3] D:[{Name:n1} {Name:n2}]} {A:2 B:éèï C:[4 5 6] D:[{Name:n2} {Name:n3}]}] -- data read back -- [{A:1 B:áà C:[1 2 3] D:[{Name:n1} {Name:n2}]} {A:2 B:éèï C:[4 5 6] D:[{Name:n2} {Name:n3}]}]
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidNumPyFormat is the error returned by NewReader when // the underlying io.Reader is not a valid or recognized NumPy data // file format. ErrInvalidNumPyFormat = npy.ErrInvalidNumPyFormat // ErrTypeMismatch is the error returned by Reader when the on-disk // data type and the user provided one do NOT match. ErrTypeMismatch = npy.ErrTypeMismatch // ErrInvalidType is the error returned by Reader and Writer when // confronted with a type that is not supported or can not be // reliably (de)serialized. ErrInvalidType = npy.ErrInvalidType // Magic header present at the start of a NumPy data file format. // See https://numpy.org/neps/nep-0001-npy-format.html Magic = npy.Magic )
Functions ¶
func Dump ¶ added in v0.8.1
Dump dumps the content of the provided reader to the writer, in a human readable format
func Read ¶
Read reads the data from the r NumPy data file io.Reader, into the provided pointed at value ptr. Read returns an error if the on-disk data type and the one provided don't match.
If a *mat.Dense matrix is passed to Read, the numpy-array data is loaded into the Dense matrix, honouring Fortran/C-order and dimensions/shape parameters.
Only numpy-arrays with up to 2 dimensions are supported. Only numpy-arrays with elements convertible to float64 are supported.
Example ¶
package main
import (
"bytes"
"fmt"
"log"
"gonum.org/v1/gonum/mat"
"codeberg.org/sbinet/npyio"
)
func main() {
m := mat.NewDense(2, 3, []float64{0, 1, 2, 3, 4, 5})
fmt.Printf("-- original data --\n")
fmt.Printf("data = %v\n", mat.Formatted(m, mat.Prefix(" ")))
buf := new(bytes.Buffer)
err := npyio.Write(buf, m)
if err != nil {
log.Fatalf("error writing data: %v\n", err)
}
// modify original data
m.Set(0, 0, 6)
var data mat.Dense
err = npyio.Read(buf, &data)
if err != nil {
log.Fatalf("error reading data: %v\n", err)
}
fmt.Printf("-- data read back --\n")
fmt.Printf("data = %v\n", mat.Formatted(&data, mat.Prefix(" ")))
fmt.Printf("-- modified original data --\n")
fmt.Printf("data = %v\n", mat.Formatted(m, mat.Prefix(" ")))
}
Output: -- original data -- data = ⎡0 1 2⎤ ⎣3 4 5⎦ -- data read back -- data = ⎡0 1 2⎤ ⎣3 4 5⎦ -- modified original data -- data = ⎡6 1 2⎤ ⎣3 4 5⎦
func Write ¶
Write writes 'val' into 'w' in the NumPy data format.
- if val is a scalar, it must be of a supported type (bools, (u)ints, floats and complexes)
- if val is a slice or array, it must be a slice/array of a supported type. the shape (len,) will be written out.
- if val is a mat.Dense, the correct shape will be transmitted. (ie: (nrows, ncols))
The data-array will always be written out in C-order (row-major).
Example ¶
package main
import (
"bytes"
"fmt"
"log"
"gonum.org/v1/gonum/mat"
"codeberg.org/sbinet/npyio"
)
func main() {
m := mat.NewDense(2, 3, []float64{0, 1, 2, 3, 4, 5})
fmt.Printf("-- original data --\n")
fmt.Printf("data = %v\n", mat.Formatted(m, mat.Prefix(" ")))
buf := new(bytes.Buffer)
err := npyio.Write(buf, m)
if err != nil {
log.Fatalf("error writing data: %v\n", err)
}
// modify original data
m.Set(0, 0, 6)
var data mat.Dense
err = npyio.Read(buf, &data)
if err != nil {
log.Fatalf("error reading data: %v\n", err)
}
fmt.Printf("-- data read back --\n")
fmt.Printf("data = %v\n", mat.Formatted(&data, mat.Prefix(" ")))
fmt.Printf("-- modified original data --\n")
fmt.Printf("data = %v\n", mat.Formatted(m, mat.Prefix(" ")))
}
Output: -- original data -- data = ⎡0 1 2⎤ ⎣3 4 5⎦ -- data read back -- data = ⎡0 1 2⎤ ⎣3 4 5⎦ -- modified original data -- data = ⎡6 1 2⎤ ⎣3 4 5⎦
Types ¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
npyio-ls
command
|
|
|
internal
|
|
|
dtp
Package dtp provides tools to parse dtype strings specifications.
|
Package dtp provides tools to parse dtype strings specifications. |
|
dtp/ast
Package ast declares the types used to represent syntax trees for dtype descr.
|
Package ast declares the types used to represent syntax trees for dtype descr. |
|
dtp/token
Package token defines constants representing the lexical tokens of dtype descr strings.
|
Package token defines constants representing the lexical tokens of dtype descr strings. |
|
Package npy provides read/write access to files following the NumPy data file format:
|
Package npy provides read/write access to files following the NumPy data file format: |
|
Package npz provides read/write access to files with compressed NumPy data file format:
|
Package npz provides read/write access to files with compressed NumPy data file format: |