Module: Gsplat::IO::Npy

Defined in:
lib/gsplat/io/npy.rb

Overview

NumPy v1.0 NPY and NPZ interoperability.

Constant Summary collapse

MAGIC =

Binary prefix defined by the NumPy NPY format.

"\x93NUMPY".b
VERSION =

NPY format version emitted and accepted by this codec.

[1, 0].freeze
HEADER_ALIGNMENT =

Header byte alignment used by NPY v1.0.

64
DESCRIPTORS =

Mapping from supported Numo types to NumPy descriptors and pack formats.

{
  Numo::SFloat => ["<f4", "e*", 4],
  Numo::DFloat => ["<f8", "E*", 8],
  Numo::UInt8 => ["|u1", "C*", 1],
  Numo::UInt16 => ["<u2", "S<*", 2],
  Numo::Int32 => ["<i4", "l<*", 4],
  Numo::Int64 => ["<i8", "q<*", 8],
  Numo::Bit => ["|b1", "C*", 1]
}.freeze
TYPES =

Reverse descriptor-to-Numo type mapping.

DESCRIPTORS.to_h { |type, | [.first, type] }.freeze

Class Method Summary collapse

Class Method Details

.descriptor_for(type) ⇒ String

Returns the NumPy dtype descriptor for a Numo type.

Parameters:

  • type (Class)

Returns:

  • (String)


80
81
82
83
84
# File 'lib/gsplat/io/npy.rb', line 80

def descriptor_for(type)
  DESCRIPTORS.fetch(type) do
    raise NotSupportedError, "unsupported Numo dtype #{type}"
  end.first
end

.read(source) ⇒ Numo::NArray

Reads an NPY v1.0 array.

Parameters:

  • source (String, #read)

    path or binary IO

Returns:

  • (Numo::NArray)


37
38
39
# File 'lib/gsplat/io/npy.rb', line 37

def read(source)
  decode(read_bytes(source))
end

.read_npz(source) ⇒ Hash{String=>Numo::NArray}

Reads all arrays from an NPZ archive.

Parameters:

  • source (String, #read)

    path or binary IO

Returns:

  • (Hash{String=>Numo::NArray})


54
55
56
57
58
59
60
# File 'lib/gsplat/io/npy.rb', line 54

def read_npz(source)
  ZipArchive.decode(read_bytes(source)).each_with_object({}) do |(name, data), arrays|
    next unless name.end_with?(".npy")

    arrays[name.delete_suffix(".npy")] = decode(data)
  end
end

.write(target, array) ⇒ Integer

Writes an NPY v1.0 array in C order.

Parameters:

  • target (String, #write)

    path or binary IO

  • array (Numo::NArray)

Returns:

  • (Integer)

    bytes written



46
47
48
# File 'lib/gsplat/io/npy.rb', line 46

def write(target, array)
  write_bytes(target, encode(array))
end

.write_npz(target, arrays, compression: :deflate) ⇒ Integer

Writes arrays to an NPZ archive.

Parameters:

  • target (String, #write)

    path or binary IO

  • arrays (Hash{String, Symbol=>Numo::NArray})
  • compression (Symbol) (defaults to: :deflate)

    :deflate or :stored

Returns:

  • (Integer)

    bytes written



68
69
70
71
72
73
74
# File 'lib/gsplat/io/npy.rb', line 68

def write_npz(target, arrays, compression: :deflate)
  entries = arrays.to_h do |name, array|
    normalized = normalize_entry_name(name)
    ["#{normalized}.npy", encode(array)]
  end
  write_bytes(target, ZipArchive.encode(entries, compression: compression))
end