Source file npy.ml
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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
exception Cannot_write
exception Read_error of string
let read_error fmt = Printf.ksprintf (fun s -> raise (Read_error s)) fmt
let magic_string = "\147NUMPY"
let magic_string_len = String.length magic_string
type packed_kind = P : (_, _) Bigarray.kind -> packed_kind
let dtype ~packed_kind =
let endianness =
match packed_kind with
| P Bigarray.Char -> "|"
| P _ -> if Sys.big_endian then ">" else "<"
in
let kind =
match packed_kind with
| P Bigarray.Int32 -> "i4"
| P Bigarray.Int64 -> "i8"
| P Bigarray.Float16 -> "f2"
| P Bigarray.Float32 -> "f4"
| P Bigarray.Float64 -> "f8"
| P Bigarray.Int8_unsigned -> "u1"
| P Bigarray.Int8_signed -> "i1"
| P Bigarray.Int16_unsigned -> "u2"
| P Bigarray.Int16_signed -> "i2"
| P Bigarray.Char -> "S1"
| P Bigarray.Complex32 -> "c8"
| P Bigarray.Complex64 -> "c16"
| P Bigarray.Int -> failwith "Int is not supported"
| P Bigarray.Nativeint -> failwith "Nativeint is not supported."
in
endianness ^ kind
let map_file file_descr ~pos kind layout shared shape =
let is_scalar = Array.length shape = 0 in
let array =
Unix.map_file
file_descr
~pos
kind
layout
shared
(if is_scalar then [| 1 |] else shape)
in
if is_scalar then Bigarray.reshape array [||] else array
let fortran_order (type a) ~(layout : a Bigarray.layout) =
match layout with
| Bigarray.C_layout -> "False"
| Bigarray.Fortran_layout -> "True"
let shape ~dims =
match dims with
| [| dim1 |] -> Printf.sprintf "%d," dim1
| dims -> Array.to_list dims |> List.map string_of_int |> String.concat ", "
let ? ~layout ~packed_kind ~dims () =
let =
Printf.sprintf
"{'descr': '%s', 'fortran_order': %s, 'shape': (%s), }"
(dtype ~packed_kind)
(fortran_order ~layout)
(shape ~dims)
in
let padding_len =
let total_len = String.length header + magic_string_len + 4 + 1 in
match header_len with
| None -> if total_len mod 16 = 0 then 0 else 16 - (total_len mod 16)
| Some ->
if header_len mod 16 <> 0 then failwith "header_len has to be divisible by 16";
if header_len < total_len then failwith "header_len is smaller than total_len";
header_len - total_len
in
let = String.length header + padding_len + 1 in
Printf.sprintf
"%s\001\000%c%c%s%s\n"
magic_string
(total_header_len mod 256 |> Char.chr)
(total_header_len / 256 |> Char.chr)
header
(String.make padding_len ' ')
let with_file filename flags mask ~f =
let file_descr = Unix.openfile filename flags mask in
try
let result = f file_descr in
Unix.close file_descr;
result
with
| exn ->
Unix.close file_descr;
raise exn
let write ? bigarray filename =
with_file filename [ O_CREAT; O_TRUNC; O_RDWR ] 0o640 ~f:(fun file_descr ->
let =
full_header
()
?header_len
~layout:(Bigarray.Genarray.layout bigarray)
~packed_kind:(P (Bigarray.Genarray.kind bigarray))
~dims:(Bigarray.Genarray.dims bigarray)
in
let = String.length full_header in
if Unix.write_substring file_descr full_header 0 full_header_len <> full_header_len
then raise Cannot_write;
let file_array =
map_file
~pos:(Int64.of_int full_header_len)
file_descr
(Bigarray.Genarray.kind bigarray)
(Bigarray.Genarray.layout bigarray)
true
(Bigarray.Genarray.dims bigarray)
in
Bigarray.Genarray.blit bigarray file_array)
let write1 array1 filename = write (Bigarray.genarray_of_array1 array1) filename
let write2 array2 filename = write (Bigarray.genarray_of_array2 array2) filename
let write3 array3 filename = write (Bigarray.genarray_of_array3 array3) filename
module Batch_writer = struct
let = 128
type t =
{ file_descr : Unix.file_descr
; mutable bytes_written_so_far : int
; mutable dims_and_packed_kind : (int array * packed_kind) option
}
let append t bigarray =
let file_array =
map_file
~pos:(Int64.of_int t.bytes_written_so_far)
t.file_descr
(Bigarray.Genarray.kind bigarray)
(Bigarray.Genarray.layout bigarray)
true
(Bigarray.Genarray.dims bigarray)
in
Bigarray.Genarray.blit bigarray file_array;
let size_in_bytes = Bigarray.Genarray.size_in_bytes bigarray in
t.bytes_written_so_far <- t.bytes_written_so_far + size_in_bytes;
match t.dims_and_packed_kind with
| None ->
let dims = Bigarray.Genarray.dims bigarray in
let kind = Bigarray.Genarray.kind bigarray in
t.dims_and_packed_kind <- Some (dims, P kind)
| Some (dims, _kind) ->
let dims' = Bigarray.Genarray.dims bigarray in
let incorrect_dimensions =
match Array.to_list dims, Array.to_list dims' with
| [], _ | _, [] -> true
| _ :: d, _ :: d' -> d <> d'
in
if incorrect_dimensions
then
Printf.sprintf "Incorrect dimensions %s vs %s." (shape ~dims) (shape ~dims:dims')
|> failwith;
dims.(0) <- dims.(0) + dims'.(0)
let create filename =
let file_descr = Unix.openfile filename [ O_CREAT; O_TRUNC; O_RDWR ] 0o640 in
{ file_descr; bytes_written_so_far = header_len; dims_and_packed_kind = None }
let close t =
assert (Unix.lseek t.file_descr 0 SEEK_SET = 0);
let =
match t.dims_and_packed_kind with
| None -> failwith "Nothing to write"
| Some (dims, packed_kind) ->
full_header ~header_len ~layout:C_layout ~dims ~packed_kind ()
in
if Unix.write_substring t.file_descr header 0 header_len <> header_len
then raise Cannot_write;
Unix.close t.file_descr
end
let really_read fd len =
let buffer = Bytes.create len in
let rec loop offset =
let read = Unix.read fd buffer offset (len - offset) in
if read + offset < len
then loop (read + offset)
else if read = 0
then read_error "unexpected eof"
in
loop 0;
Bytes.to_string buffer
type packed_array = P : (_, _, _) Bigarray.Genarray.t -> packed_array
type packed_array1 = P1 : (_, _, _) Bigarray.Array1.t -> packed_array1
type packed_array2 = P2 : (_, _, _) Bigarray.Array2.t -> packed_array2
type packed_array3 = P3 : (_, _, _) Bigarray.Array3.t -> packed_array3
let read_mmap filename ~shared =
let access = if shared then Unix.O_RDWR else O_RDONLY in
let file_descr = Unix.openfile filename [ access ] 0 in
let pos, =
try
let magic_string' = really_read file_descr magic_string_len in
if magic_string <> magic_string' then read_error "magic string mismatch";
let version = really_read file_descr 2 |> fun v -> v.[0] |> Char.code in
let =
match version with
| 1 -> 2
| 2 -> 4
| _ -> read_error "unsupported version %d" version
in
let , =
really_read file_descr header_len_len
|> fun str ->
let = ref 0 in
for i = String.length str - 1 downto 0 do
header_len := (256 * !header_len) + Char.code str.[i]
done;
really_read file_descr !header_len, !header_len
in
let = Header.parse header in
Int64.of_int (header_len + header_len_len + magic_string_len + 2), header
with
| exn ->
Unix.close file_descr;
raise exn
in
let (Header.P kind) = header.kind in
let build layout =
let array = map_file file_descr ~pos kind layout shared header.shape in
Gc.finalise (fun _ -> Unix.close file_descr) array;
P array
in
if header.fortran_order then build Fortran_layout else build C_layout
let read_mmap1 filename ~shared =
let (P array) = read_mmap filename ~shared in
P1 (Bigarray.array1_of_genarray array)
let read_mmap2 filename ~shared =
let (P array) = read_mmap filename ~shared in
P2 (Bigarray.array2_of_genarray array)
let read_mmap3 filename ~shared =
let (P array) = read_mmap filename ~shared in
P3 (Bigarray.array3_of_genarray array)
let read_copy filename =
let (P array) = read_mmap filename ~shared:false in
let result =
Bigarray.Genarray.create
(Bigarray.Genarray.kind array)
(Bigarray.Genarray.layout array)
(Bigarray.Genarray.dims array)
in
Bigarray.Genarray.blit array result;
P result
let read_copy1 filename =
let (P array) = read_copy filename in
P1 (Bigarray.array1_of_genarray array)
let read_copy2 filename =
let (P array) = read_copy filename in
P2 (Bigarray.array2_of_genarray array)
let read_copy3 filename =
let (P array) = read_copy filename in
P3 (Bigarray.array3_of_genarray array)
module Npz = struct
let npy_suffix = ".npy"
let maybe_add_suffix array_name ~suffix =
let suffix =
match suffix with
| None -> npy_suffix
| Some suffix -> suffix
in
array_name ^ suffix
type in_file = Zip.in_file
let open_in = Zip.open_in
let entries t =
Zip.entries t
|> List.map (fun entry ->
let filename = entry.Zip.filename in
if String.length filename < String.length npy_suffix
then filename
else (
let start_pos = String.length filename - String.length npy_suffix in
if String.sub filename start_pos (String.length npy_suffix) = npy_suffix
then String.sub filename 0 start_pos
else filename))
let close_in = Zip.close_in
let read ?suffix t array_name =
let array_name = maybe_add_suffix array_name ~suffix in
let entry =
try Zip.find_entry t array_name with
| Not_found -> raise (Invalid_argument ("unable to find " ^ array_name))
in
let tmp_file = Filename.temp_file "ocaml-npz" ".tmp" in
Zip.copy_entry_to_file t entry tmp_file;
let data = read_copy tmp_file in
Sys.remove tmp_file;
data
type out_file = Zip.out_file
let open_out filename = Zip.open_out filename
let close_out = Zip.close_out
let write ?suffix t array_name array =
let array_name = maybe_add_suffix array_name ~suffix in
let tmp_file = Filename.temp_file "ocaml-npz" ".tmp" in
write array tmp_file;
Zip.copy_file_to_entry tmp_file t array_name;
Sys.remove tmp_file
end
(** Type equalities module, used in conversion function *)
module Eq = struct
(** An equality type to extract type equalities *)
type ('a, 'b) t = W : ('a, 'a) t
open Bigarray
(** Type equalities for bigarray kinds *)
module Kind = struct
let ( === )
: type a b c d. (a, b) kind -> (c, d) kind -> ((a, b) kind, (c, d) kind) t option
=
fun x y ->
match x, y with
| Float32, Float32 -> Some W
| Float64, Float64 -> Some W
| Int8_signed, Int8_signed -> Some W
| Int8_unsigned, Int8_unsigned -> Some W
| Int16_signed, Int16_signed -> Some W
| Int16_unsigned, Int16_unsigned -> Some W
| Int32, Int32 -> Some W
| Int64, Int64 -> Some W
| Int, Int -> Some W
| Nativeint, Nativeint -> Some W
| Complex32, Complex32 -> Some W
| Complex64, Complex64 -> Some W
| Char, Char -> Some W
| _ -> None
end
(** Type equalities for layout *)
module Layout = struct
let ( === ) : type a b. a layout -> b layout -> (a layout, b layout) t option =
fun x y ->
match x, y with
| Fortran_layout, Fortran_layout -> Some W
| C_layout, C_layout -> Some W
| _, _ -> None
end
end
(** Conversion functions from packed arrays to bigarrays *)
let to_bigarray
(type a b c)
(layout : c Bigarray.layout)
(kind : (a, b) Bigarray.kind)
(P x)
=
match Eq.Layout.(Bigarray.Genarray.layout x === layout) with
| None -> None
| Some Eq.W ->
(match Eq.Kind.(Bigarray.Genarray.kind x === kind) with
| None -> None
| Some Eq.W -> Some (x : (a, b, c) Bigarray.Genarray.t))
let to_bigarray1
(type a b c)
(layout : c Bigarray.layout)
(kind : (a, b) Bigarray.kind)
(P1 x)
=
match Eq.Layout.(Bigarray.Array1.layout x === layout) with
| None -> None
| Some Eq.W ->
(match Eq.Kind.(Bigarray.Array1.kind x === kind) with
| None -> None
| Some Eq.W -> Some (x : (a, b, c) Bigarray.Array1.t))
let to_bigarray2
(type a b c)
(layout : c Bigarray.layout)
(kind : (a, b) Bigarray.kind)
(P2 x)
=
match Eq.Layout.(Bigarray.Array2.layout x === layout) with
| None -> None
| Some Eq.W ->
(match Eq.Kind.(Bigarray.Array2.kind x === kind) with
| None -> None
| Some Eq.W -> Some (x : (a, b, c) Bigarray.Array2.t))
let to_bigarray3
(type a b c)
(layout : c Bigarray.layout)
(kind : (a, b) Bigarray.kind)
(P3 x)
=
match Eq.Layout.(Bigarray.Array3.layout x === layout) with
| None -> None
| Some Eq.W ->
(match Eq.Kind.(Bigarray.Array3.kind x === kind) with
| None -> None
| Some Eq.W -> Some (x : (a, b, c) Bigarray.Array3.t))