Skip to content

Commit

Permalink
add more comments
Browse files Browse the repository at this point in the history
  • Loading branch information
Momtchil Momtchev committed Sep 1, 2023
1 parent f62a4e3 commit 441759c
Showing 1 changed file with 34 additions and 1 deletion.
35 changes: 34 additions & 1 deletion examples/numpy.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,29 +57,49 @@ const op = proxify(pymport('operator'));
const a = np.array([20, 30, 40, 50]);
const b = np.arange(4);
console.log(b.toString());

// c = a - b
const c = op.sub(a, b);

console.log(c.toString());

// print(b ** 2)
console.log(op.pow(b, 2).toString());

// print(10 * np.sin(a))
console.log(op.mul(10, np.sin(a)).toString());

// print(a < 35)
console.log(op.lt(a, 35).toString());

const A = np.array([[1, 1], [0, 1]]);
const B = np.array([[2, 0], [3, 4]]);

// print(A * B)
console.log(op.mul(A, B).toString());

// print(A @ B)
console.log(op.matmul(A, B).toString());

// print(A.dot(B))
console.log(A.dot(B).toString());
}

const rg = np.random.default_rng(1);
{
const a = np.ones([2, 3], { dtype: np.int32 });
const b = rg.random([2, 3]);

// a *= 3
op.imul(a, 3);
console.log(a.toString());

// b += a
op.iadd(b, a);
console.log(b.toString());

try {
// a += b -> it throws
op.iadd(a, b);
} catch (e) {
console.warn(e);
Expand All @@ -100,6 +120,9 @@ const rg = np.random.default_rng(1);
{
const a = rg.random([2, 3]);
console.log(a.toString());

// a.sum() is a PyObject (Python reference) that contains a float
// a.sum().toJS() is a JS number
console.log(a.sum().toJS());
console.log(a.min().toJS());
console.log(a.max().toJS());
Expand All @@ -108,8 +131,13 @@ const rg = np.random.default_rng(1);
{
const b = np.arange(12).reshape(3, 4);
console.log(b.toString());

// print(b.sum(axis=0))
console.log(b.sum({ axis: 0 }).toString());

// print(b.min(axis=1))
console.log(b.min({ axis: 1 }).toString());

console.log(b.cumsum({ axis: 1 }).toString());
}

Expand Down Expand Up @@ -137,24 +165,29 @@ console.log('Indexing, Slicing and Iterating');
a.__setitem__(PyObject.slice({ stop: 6, step: 2 }), 1000);
console.log(a.toString());

// a[::-1] # reversed a
console.log(a.__getitem__(PyObject.slice({ step: -1 })).toString());

// numpy arrays are directly iterable in JavaScript
// every element is a PyObject
for (const i of a) {
console.log(op.pow(i, 1 / 3).toString());
}
}

{
// Don't forget that this function will receive PyObject arguments
const f = (x, y) => op.add(op.mul(10, x), y);

const b = np.fromfunction(f, [5, 4], { dtype: np.int32 });
console.log(b.toString());

// b[2, 3]
// b[2, 3] -> (2, 3) is a tuple which is a single argument to operator[]
console.log(b.__getitem__(PyObject.tuple([2, 3])).toString());

// b[0:5, 1]
console.log(b.__getitem__(PyObject.tuple([PyObject.slice({ start: 0, stop: 5 }), 1])).toString());

// b[-1]
console.log(b.__getitem__(-1).toString());
}

0 comments on commit 441759c

Please sign in to comment.