-
Notifications
You must be signed in to change notification settings - Fork 186
/
np.load.cs
548 lines (467 loc) · 16.5 KB
/
np.load.cs
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using NumSharp.Utilities;
namespace NumSharp
{
public static partial class np
{
#region NpyFormat
//Signature from numpy doc:
// numpy.load(file, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding='ASCII')[source]
public static NDArray load(string path)
{
using (var stream = new FileStream(path, FileMode.Open))
return load(stream);
}
public static NDArray load(Stream stream)
{
using (var reader = new BinaryReader(stream, System.Text.Encoding.ASCII
#if !NET35 && !NET40
, leaveOpen: true
#endif
))
{
int bytes;
Type type;
int[] shape;
if (!parseReader(reader, out bytes, out type, out shape))
throw new FormatException();
Array array = Arrays.Create(type, shape.Aggregate((dims, dim) => dims * dim));
var result = new NDArray(readValueMatrix(reader, array, bytes, type, shape));
return result.reshape(shape);
}
}
public static T Load<T>(byte[] bytes)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable
#if !NET35
, IStructuralComparable, IStructuralEquatable
#endif
{
if (typeof(T).IsArray && (typeof(T).GetElementType().IsArray || typeof(T).GetElementType() == typeof(string)))
return LoadJagged(bytes) as T;
return LoadMatrix(bytes) as T;
}
public static T Load<T>(byte[] bytes, out T value)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable
#if !NET35
, IStructuralComparable, IStructuralEquatable
#endif
{
return value = Load<T>(bytes);
}
public static T Load<T>(string path, out T value)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable
#if !NET35
, IStructuralComparable, IStructuralEquatable
#endif
{
return value = Load<T>(path);
}
public static T Load<T>(Stream stream, out T value)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable
#if !NET35
, IStructuralComparable, IStructuralEquatable
#endif
{
return value = Load<T>(stream);
}
public static T Load<T>(string path)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable
#if !NET35
, IStructuralComparable, IStructuralEquatable
#endif
{
using (var stream = new FileStream(path, FileMode.Open))
return Load<T>(stream);
}
public static T Load<T>(Stream stream)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable
#if !NET35
, IStructuralComparable, IStructuralEquatable
#endif
{
if (typeof(T).IsArray && (typeof(T).GetElementType().IsArray || typeof(T).GetElementType() == typeof(string)))
return LoadJagged(stream) as T;
return LoadMatrix(stream) as T;
}
public static Array LoadMatrix(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
return LoadMatrix(stream);
}
public static Array LoadMatrix(string path)
{
using (var stream = new FileStream(path, FileMode.Open))
return LoadMatrix(stream);
}
public static Array LoadJagged(byte[] bytes)
{
using (var stream = new MemoryStream(bytes))
return LoadJagged(stream);
}
public static Array LoadJagged(string path)
{
using (var stream = new FileStream(path, FileMode.Open))
return LoadJagged(stream);
}
public static Array LoadMatrix(Stream stream)
{
using (var reader = new BinaryReader(stream, System.Text.Encoding.ASCII
#if !NET35 && !NET40
, leaveOpen: true
#endif
))
{
int bytes;
Type type;
int[] shape;
if (!parseReader(reader, out bytes, out type, out shape))
throw new FormatException();
Array matrix = Arrays.Create(type, shape);
if (type == typeof(String))
return readStringMatrix(reader, matrix, bytes, type, shape);
return readValueMatrix(reader, matrix, bytes, type, shape);
}
}
public static Array LoadJagged(Stream stream, bool trim = true)
{
using (var reader = new BinaryReader(stream, System.Text.Encoding.ASCII
#if !NET35 && !NET40
, leaveOpen: true
#endif
))
{
int bytes;
Type type;
int[] shape;
if (!parseReader(reader, out bytes, out type, out shape))
throw new FormatException();
Array matrix = Arrays.Create(type, shape);
if (type == typeof(String))
{
Array result = readStringMatrix(reader, matrix, bytes, type, shape);
//if (trim)
// return result.Trim();
return result;
}
return readValueJagged(reader, matrix, bytes, type, shape);
}
}
private static Array readValueMatrix(BinaryReader reader, Array matrix, int bytes, Type type, int[] shape)
{
int total = 1;
for (int i = 0; i < shape.Length; i++)
total *= shape[i];
var buffer = new byte[bytes * total];
reader.Read(buffer, 0, buffer.Length);
Buffer.BlockCopy(buffer, 0, matrix, 0, buffer.Length);
return matrix;
}
static IEnumerable<int[]> GetIndices(Array array, int[] current, int pos)
{
if (pos == current.Length)
yield return current;
else
{
for (int i = 0; i < array.GetLength(pos); i++)
{
current[pos] = i;
foreach (var ind in GetIndices(array, current, pos + 1))
yield return ind;
current[pos] = 0;
}
}
}
static IEnumerable<int[]> GetIndices(Array array)
{
return GetIndices(array, new int[array.Rank], 0);
}
private static Array readValueJagged(BinaryReader reader, Array matrix, int bytes, Type type, int[] shape)
{
int last = shape[shape.Length - 1];
byte[] buffer = new byte[bytes * last];
int[] firsts = new int[shape.Length - 1];
for (int i = 0; i < firsts.Length; i++)
firsts[i] = -1;
foreach (var p in GetIndices(matrix))
{
bool changed = false;
for (int i = 0; i < firsts.Length; i++)
{
if (firsts[i] != p[i])
{
firsts[i] = p[i];
changed = true;
}
}
if (!changed)
continue;
Array arr = (Array)matrix.GetValue(indices: firsts);
reader.Read(buffer, 0, buffer.Length);
Buffer.BlockCopy(buffer, 0, arr, 0, buffer.Length);
}
return matrix;
}
private static Array readStringMatrix(BinaryReader reader, Array matrix, int bytes, Type type, int[] shape)
{
var buffer = new byte[bytes];
unsafe
{
fixed (byte* b = buffer)
{
foreach (var p in GetIndices(matrix))
{
reader.Read(buffer, 0, bytes);
if (buffer[0] == byte.MinValue)
{
bool isNull = true;
for (int i = 1; i < buffer.Length; i++)
{
if (buffer[i] != byte.MaxValue)
{
isNull = false;
break;
}
}
if (isNull)
{
matrix.SetValue(value: null, indices: p);
continue;
}
}
#if NETSTANDARD1_4
String s = new String((char*)b);
#else
String s = new String((sbyte*)b);
#endif
matrix.SetValue(value: s, indices: p);
}
}
}
return matrix;
}
private static bool parseReader(BinaryReader reader, out int bytes, out Type t, out int[] shape)
{
bytes = 0;
t = null;
shape = null;
// The first 6 bytes are a magic string: exactly "x93NUMPY"
if (reader.ReadChar() != 63) return false;
if (reader.ReadChar() != 'N') return false;
if (reader.ReadChar() != 'U') return false;
if (reader.ReadChar() != 'M') return false;
if (reader.ReadChar() != 'P') return false;
if (reader.ReadChar() != 'Y') return false;
byte major = reader.ReadByte(); // 1
byte minor = reader.ReadByte(); // 0
if (major != 1 || minor != 0)
throw new NotSupportedException();
ushort len = reader.ReadUInt16();
string header = new String(reader.ReadChars(len));
string mark = "'descr': '";
int s = header.IndexOf(mark) + mark.Length;
int e = header.IndexOf("'", s + 1);
string type = header.Substring(s, e - s);
bool? isLittleEndian;
t = GetType(type, out bytes, out isLittleEndian);
if (isLittleEndian.HasValue && isLittleEndian.Value == false)
throw new Exception();
mark = "'fortran_order': ";
s = header.IndexOf(mark) + mark.Length;
e = header.IndexOf(",", s + 1);
bool fortran = bool.Parse(header.Substring(s, e - s));
if (fortran)
throw new Exception();
mark = "'shape': (";
s = header.IndexOf(mark) + mark.Length;
e = header.IndexOf(")", s + 1);
shape = header.Substring(s, e - s).Split(',').Where(v => !String.IsNullOrEmpty(v)).Select(Int32.Parse).ToArray();
return true;
}
private static Type GetType(string dtype, out int bytes, out bool? isLittleEndian)
{
isLittleEndian = IsLittleEndian(dtype);
bytes = Int32.Parse(dtype.Substring(2));
string typeCode = dtype.Substring(1);
if (typeCode == "b1")
return typeof(bool);
if (typeCode == "i1")
return typeof(Byte);
if (typeCode == "i2")
return typeof(Int16);
if (typeCode == "i4")
return typeof(Int32);
if (typeCode == "i8")
return typeof(Int64);
if (typeCode == "u1")
return typeof(Byte);
if (typeCode == "u2")
return typeof(UInt16);
if (typeCode == "u4")
return typeof(UInt32);
if (typeCode == "u8")
return typeof(UInt64);
if (typeCode == "f4")
return typeof(Single);
if (typeCode == "f8")
return typeof(Double);
if (typeCode.StartsWith("S"))
return typeof(String);
throw new NotSupportedException();
}
private static bool? IsLittleEndian(string type)
{
bool? littleEndian = null;
switch (type[0])
{
case '<':
littleEndian = true;
break;
case '>':
littleEndian = false;
break;
case '|':
littleEndian = null;
break;
default:
throw new Exception();
}
return littleEndian;
}
#endregion
#region NpzFormat
public static void Load_Npz<T>(byte[] bytes, out T value)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
{
using (var dict = Load_Npz<T>(bytes))
{
value = dict.Values.First();
}
}
public static void Load_Npz<T>(string path, out T value)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
{
using (var dict = Load_Npz<T>(path))
{
value = dict.Values.First();
}
}
public static void Load_Npz<T>(Stream stream, out T value)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
{
using (var dict = Load_Npz<T>(stream))
{
value = dict.Values.First();
}
}
public static NpzDictionary<T> Load_Npz<T>(byte[] bytes)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
{
return Load_Npz<T>(new MemoryStream(bytes));
}
public static NpzDictionary<T> Load_Npz<T>(string path, out NpzDictionary<T> value)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
{
return value = Load_Npz<T>(new FileStream(path, FileMode.Open));
}
public static NpzDictionary<T> Load_Npz<T>(Stream stream, out NpzDictionary<T> value)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
{
return value = Load_Npz<T>(stream);
}
public static NpzDictionary<T> Load_Npz<T>(string path)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
{
return Load_Npz<T>(new FileStream(path, FileMode.Open));
}
public static NpzDictionary<T> Load_Npz<T>(Stream stream)
where T : class,
#if !NETSTANDARD1_4
ICloneable,
#endif
IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
{
return new NpzDictionary<T>(stream);
}
public static NpzDictionary<Array> LoadMatrix_Npz(byte[] bytes)
{
return LoadMatrix_Npz(new MemoryStream(bytes));
}
public static NpzDictionary<Array> LoadMatrix_Npz(string path)
{
return LoadMatrix_Npz(new FileStream(path, FileMode.Open));
}
public static NpzDictionary<Array> LoadMatrix_Npz(Stream stream)
{
return new NpzDictionary(stream, jagged: false);
}
public static NpzDictionary<Array> LoadJagged_Npz(byte[] bytes)
{
return LoadJagged_Npz(new MemoryStream(bytes));
}
public static NpzDictionary<Array> LoadJagged_Npz(string path)
{
return LoadJagged_Npz(new FileStream(path, FileMode.Open));
}
public static NpzDictionary<Array> LoadJagged_Npz(Stream stream, bool trim = true)
{
return new NpzDictionary(stream, jagged: true);
}
#endregion
}
}