-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathread_npy.R
More file actions
255 lines (235 loc) · 6.78 KB
/
Copy pathread_npy.R
File metadata and controls
255 lines (235 loc) · 6.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
#' Read a .npy file
#'
#' @param file Path to the .npy file
#'
#' @returns An array containing the data from the .npy file
#'
#' @export
#'
#' @examples
#' read_npy(
#' system.file("extdata", "test.npy", package = "grumpy")
#' )
read_npy <- function(file) {
if (is.character(file)) {
if (!file.exists(file)) {
stop("File does not exist: ", file, call. = FALSE)
}
con <- file(file, "rb")
on.exit(close(con))
} else if (inherits(file, "connection")) {
con <- file
} else {
stop(
"Invalid bytes: file must be a character string or a connection.",
call. = FALSE
)
}
# Read the header
magic_string <- readBin(con, "raw", n = 6L)
if (!identical(magic_string, charToRaw("\x93NUMPY"))) {
stop("Not a valid .npy file: ", file, call. = FALSE)
}
format_version <- readBin(
con,
"integer",
n = 2L,
size = 1L,
endian = "little"
)
header_len <- if (format_version[1L] == 1L) {
readBin(con, "integer", n = 1L, size = 2L, endian = "little")
} else if (format_version[1L] %in% c(2L, 3L)) {
readBin(con, "integer", n = 1L, size = 4L, endian = "little")
} else {
stop("Unsupported .npy version: ", format_version[1L], call. = FALSE)
}
header <- parse_npy_descr(readBin(con, "raw", n = header_len))
# TODO: improve int64 support
if (any(header$base_type %in% c("uint", "int") & header$nbytes == 8L)) {
warning(
"64-bit integers may overflow when converted to R integers.",
call. = FALSE
)
}
# Read the data
num_elements <- prod(header$shape)
bytes <- readBin(con, "raw", n = sum(num_elements * header$nbytes))
convert_bytes_to_array(
bytes,
what = header$base_type,
shape = header$shape,
size = header$nbytes,
endian = header$endian
)
}
parse_npy_descr <- function(bytes) {
# TODO: If I understand correctly, fortranarray in python are still displayed
# the same way as regular arrays, but with a different order in memory.
# It is not related to the way the data is stored in the file, nor the way
# it appears to the user.
# We just ignore it, at least for now.
header <- bytes |>
rawToChar() |>
convert_py_dict_to_json() |>
jsonlite::fromJSON(simplifyMatrix = FALSE)
parsed_descr <- parse_npy_datatype(header$descr)
return(list(
endian = parsed_descr$endian,
base_type = parsed_descr$base_type,
nbytes = parsed_descr$nbytes,
fortran_order = header$fortran_order,
shape = header$shape
))
}
#' Parse a NumPy Array-protocol type strings
#'
#' @param descr A NumPy dtype description string, or a list of such strings fo
#' structured dtypes
#'
#' @returns A list containing the parsed data type information, including the base
#' type, the number of bytes, and the endianness
#'
#' @export
#'
#' @examples
#' parse_npy_datatype(">i8")
#' parse_npy_datatype("|b1")
#' parse_npy_datatype(list(c("r", "<i8"), c("g", "<i8"), c("b", "<i8")))
#'
parse_npy_datatype <- function(descr) {
if (is.list(descr)) {
# structured data type
types <- lapply(descr, function(field) {
parse_npy_datatype(field[[2]])
})
return(
list(
types,
nbytes = vapply(types, function(x) x$nbytes, integer(1L)),
base_type = vapply(types, function(x) x$base_type, character(1L)),
endian = vapply(types, function(x) x$endian, character(1L))
)
)
}
if (startsWith(descr, "|S")) {
return(
list(
endian = NA_character_,
base_type = "string",
nbytes = as.integer(sub("|S", "", descr, fixed = TRUE))
)
)
}
if (startsWith(descr, "<U") || startsWith(descr, ">U")) {
charlen <- as.integer(sub("^[<>]U", "", descr))
return(
list(
endian = if (startsWith(descr, "<")) "little" else "big",
base_type = "unicode",
nbytes = charlen * 4L
)
)
}
entry <- supported_types[[descr]]
if (is.null(entry)) {
stop("Unsupported data type: ", descr, call. = FALSE)
}
return(list(
endian = entry$endian,
base_type = entry$base_type,
nbytes = entry$nbytes
))
}
#' Convert raw bytes to an R array based on the specified data type information
#'
#' This is a replacement for [readBin()] that can handle the various data types
#' and endianness specified in the .npy file header.
#'
#' @param bytes A raw vector containing the bytes to convert
#' @param what A character specifying the base type to convert to (e.g., `"float"`,
#' `"int"`, `"string"`, etc.)
#' @param shape A numeric vector with desired shape of the output array
#' @param size A numeric value with the number of bytes per element for the
#' specified type
#' @param endian The endianness of the data (`"little"`, `"big"`, or `NA` for
#' single-byte types)
#'
#' @returns An R array containing the converted data, with the specified shape and
#' data type.
#'
#' @export
#'
#' @examples
#' x <- matrix(c(3L, 6L, 2L, 1L, 12L, 0L), nrow = 2, ncol = 3)
#' x
#'
#' y <- writeBin(c(x), raw()) |>
#' convert_bytes_to_array("int", shape = c(2L, 3L), size = 4L, endian = "little")
#' y
#' dim(y)
#' is.array(y)
#' storage.mode(y)
#'
convert_bytes_to_array <- function(bytes, what, shape, size, endian) {
if (length(what) > 1L) {
# structured datatype
record_size <- sum(size)
n_records <- prod(shape)
# Byte offset of each field within one record
field_start <- c(0L, cumsum(size)[-length(size)])
# Convert each field via strided index extraction
res_fields <- vector("list", length(what))
for (i in seq_along(what)) {
starts <- seq(
field_start[[i]] + 1L,
by = record_size,
length.out = n_records
)
idx <- rep(starts, each = size[[i]]) + seq_len(size[[i]]) - 1
res_fields[[i]] <- convert_bytes_to_array(
bytes[idx],
what = what[[i]],
shape = NULL,
size = size[[i]],
endian = endian[[i]]
)
}
# Final list-transpose
res <- vector("list", n_records)
for (j in seq_len(n_records)) {
res[[j]] <- lapply(res_fields, `[[`, j)
}
dim(res) <- shape
return(res)
}
if (is.na(endian)) {
endian <- .Platform$endian
}
# FIXME: optimize this
if (what != "unicode" && endian != .Platform$endian) {
ind <- rep_len(rev(seq_len(size)), length(bytes)) +
(seq_along(bytes) - 1L) %/% size * size
bytes <- bytes[ind]
}
res <- .Call(
C_type_convert,
bytes,
what,
size,
shape,
endian,
PACKAGE = "grumpy"
)
return(res)
}
convert_py_dict_to_json <- function(dict_str) {
dict_str |>
gsub("'", '"', x = _, fixed = TRUE) |>
gsub("None", "null", x = _, fixed = TRUE) |>
gsub("True", "true", x = _, fixed = TRUE) |>
gsub("False", "false", x = _, fixed = TRUE) |>
gsub("(", "[", x = _, fixed = TRUE) |>
gsub(")", "]", x = _, fixed = TRUE) |>
gsub(",\\s*(}|\\])", "\\1", x = _) # trailing commas
}