aplbrain / npyjs

Read numpy .npy files in JavaScript
https://aplbrain.github.io/npyjs/
Apache License 2.0
77 stars 21 forks source link

Feature: Save() function for TypedArrays and regular arrays #15

Open TheNewSound opened 3 years ago

TheNewSound commented 3 years ago

Title says it all.

Would it be possible to include a save() function for TypedArrays and regular arrays? For both NodeJS filesystem as in-browser download? This way I can export my javascript arrays to python/numpy.

j6k4m8 commented 3 years ago

Any interest in submitting a PR? Would love to have this functionality!

TheNewSound commented 3 years ago

Since I am on a tight schedule, I currently solved this problem with the following (not using .npy file format):

Export in javascript:

const array = new Float32Array([1,2,3,4]);
const buffer = Buffer.from(array.buffer);
fs.writeFileSync("output/matrix.bin", buffer);

Import in python:

import math
import numpy as np
filename = '../node/output/matrix.bin'
with open(filename, 'rb') as f:
    simmatrix_flat = np.fromfile(f, dtype=np.float32)
print(f'Read file "{filename}" containing a matrix of size: {simmatrix_flat.size}')
#reshape matrix
simmatrix = np.reshape(simmatrix_flat, [math.isqrt(simmatrix_flat.size), math.isqrt(simmatrix_flat.size)])

I might implement this feature in the future, however, don't count on it.