Mojo-Numerics-and-Algorithms-group / NuMojo

NuMojo is a library for numerical computing in Mojo 🔥 similar to numpy in Python.
Apache License 2.0
86 stars 15 forks source link

[lib+test] NDArray initialization from string representation of an ndarray #81

Closed forFudan closed 1 month ago

forFudan commented 1 month ago

Englighted by #80, I have implemented a new initialization of the NDArray directly from a string representation, which I found quite useful.

NDArray initialization from string representation of an ndarray. The shape can be inferred from the string representation. The literals will be casted to the dtype of the NDArray.

Note: StringLiteral is also allowed as input as it is coerced to String type before it is passed into the function.

Example:

import numojo as nm

fn main() raises:
    var A = nm.NDArray[DType.int8]("[[[1,2],[3,4]],[[5,6],[7,8]]]")
    var B = nm.NDArray[DType.float16]("[[1,2,3,4],[5,6,7,8]]")
    var C = nm.NDArray("[0.1, -2.3, 41.5, 19.29145, -199]")
    var D = nm.NDArray[DType.int32]("[0.1, -2.3, 41.5, 19.29145, -199]")

    print(A)
    print(B)
    print(C)
    print(D)

The output goes as follows. Note that the numbers are automatically casted to the dtype of the NDArray.

[[[     1       2       ]
  [     3       4       ]]
 [[     5       6       ]
  [     7       8       ]]]
3-D array  Shape: [2, 2, 2]  DType: int8

[[      1.0     2.0     3.0     4.0     ]
 [      5.0     6.0     7.0     8.0     ]]
2-D array  Shape: [2, 4]  DType: float16

[       0.10000000149011612     2.2999999523162842      41.5    19.291450500488281      199.0   ]
1-D array  Shape: [5]  DType: float32

[       0       2       41      19      199     ]
1-D array  Shape: [5]  DType: int32