I am parsing a large ASCII sparse matrix, output of PETSc, but my current implementation is impossibly slow. I don't know how I could speed that up.
The ASCII file of a sparse PETSc aij
matrix is as follows (with col
being an integer index, and val being a floating point, e.g., 1.372e-1
):
row0: (col, val) (col, val) ...
row1: (col, val) (col, val) ...
row2: (col, val) (col, val) ...
...
What I did right now is simple: with a text editor I remove the rowX:
part and then use the following code:
(* Open and split into lines *)
Ktxt = StringSplit[Import["K.txt"], "\n"]
(* convert ASCII exponents *)
convert[s_] := ToExpression /@ StringReplace[StringSplit@s, "e" | "E" :> "*^"]
l = {}
(* For each row, convert and append element *)
For[r = 1, r <= Length[Ktxt], r++,
t = StringSplit[Ktxt[[r]]];
For[i = 1, i <= Length[t], i += 2,
s1 = (convert[StringReplace[t[[i]], {"(" -> "", "," -> ""}]])[[1]];
s2 = (convert[StringReplace[t[[i + 1]], ")" -> ""]])[[1]];
AppendTo[l, {r, s1 + 1} -> s2]
];
If[Mod[r, 100] == 0, Print["row ", r]]
]
(* Make the sparse matrix *)
MM = SparseArray[l]
Is there a way to make this faster? For a 15,000 x 15,000
matrix with 800,000
non-zero elements it takes hours.
Thank you!
Import[]
, like *.mtx? $\endgroup$aij
matrix file (or code that generates its content) -- it is much more likely to get responses to your question. $\endgroup$Import[..,"Table"]
do with that? $\endgroup$