24834, "ninivert", "[Feature Request]: FormattedIO: support for formatted arrays of numbers", "2024-04-12T11:28:02Z"
Summary of Feature
Description:
Format strings for numbers would able to be applied to arrays of numbers, as a "broadcast" of the scalar format string.
Is this a blocking issue with no known work-arounds?
no
Work-around is to call writef
multiple times with a for-loop.
(Or might be possible to generate one large format string, and unpack a large tuple containing the values of the array in a single writef(largeFormatString, (...arrayAsTuple))
call)
The documentation FormattedIO — Chapel Documentation 2.0 does not seem to mention array formatting.
Code Sample
use Random, OS;
config const n = 3, m = 2;
var A: [1..n, 1..m] real;
fillRandom(A, 42);
A[1,1] = 0.0;
A[3,2] = 0.0; // let's throw off alignment of default format
// default print does not align the columns nicely:
writeln("A=\n", A);
// A=
// 0.0 0.896538
// 0.347376 0.95269
// 0.903904 0.0
// custom, column-aligned print:
writeln("A=");
for (i,j) in A.domain do
writef("%6.3dr" + if j == A.domain.dim(1).last then "\n" else "", A(i,j));
// A=
// 0.000 0.897
// 0.347 0.953
// 0.904 0.000
// this feature request would allow the following syntax:
writef("A=\n %6.3dr", A);
// currently throws:
// A=
// uncaught SystemError: Invalid argument: Argument type mismatch in argument 0 (in fileWriter.writef(fmt:string) with path "/dev/pts/12" offset 50)
// formatArrays.chpl:14: thrown here
// formatArrays.chpl:14: uncaught here
Example using numpy
, where the formatter is specified on the array elements, and "broadcasted" to the entire array print:
>>> import numpy as np
>>> A = np.array([[0.0, 0.896538], [0.347376, 0.95269], [0.903904, 0.0]])
>>> with np.printoptions(formatter={'float': '{:6.3f}'.format}):
... print(A)
...
[[ 0.000 0.897]
[ 0.347 0.953]
[ 0.904 0.000]]