matrix-toolkits-java
matrix-toolkits-java copied to clipboard
Better API for Matrix Market files
Original author: [email protected] (May 16, 2009 11:22:13)
The API for reading and writing Matrix Market files is both cumbersome and confusing. A simple API would be a welcome improvement.
Original issue: http://code.google.com/p/matrix-toolkits-java/issues/detail?id=16
Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.
From [email protected] on January 17, 2013 11:20:32 maybe something along these lines ? this was a quick hack so i do to not lose too much precision... ...and it does not conform to the matrix-market format, as it lacks the MatrixInfo and MatrixSize stuff (i did not need it after all, as i had just the precision issue)
fortunately java's Double.toString() and its complement Double.parseDouble() do all the work :)
hth, rainer
// own implementation, as the matrix market stuff from mtj loses precision private static void saveMatrixSPARSE(File outputFile, Matrix M) throws FileNotFoundException { PrintWriter pwriter = new PrintWriter(new BufferedOutputStream(new FileOutputStream(outputFile)));
Matrix SM = (FlexCompRowMatrix) M;
pwriter.println(String.format("%d, %d", SM.numRows(), SM.numColumns()));
for (MatrixEntry e : SM) {
pwriter.println(String.format("%d, %d, %s", e.row(), e.column(), Double.toString(e.get())));
}
pwriter.flush();
pwriter.close();
}
// same...
private static Matrix loadMatrixFromSPARSE(File inputFile) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), MatrixOps.UTF8_ENCODING));
String line = reader.readLine();
StringTokenizer tokens = new StringTokenizer(line, MatrixOps.CSV_DELIMITERS, false);
int numRows = Integer.parseInt(tokens.nextToken());
int numColumns = Integer.parseInt(tokens.nextToken());
FlexCompRowMatrix M = new FlexCompRowMatrix(numRows, numColumns);
while ((line = reader.readLine()) != null) {
tokens = new StringTokenizer(line, MatrixOps.CSV_DELIMITERS, false);
String rawRow = tokens.nextToken();
String rawCol = tokens.nextToken();
String rawD = tokens.nextToken();
M.set(Integer.parseInt(rawRow), Integer.parseInt(rawCol), Double.parseDouble(rawD));
}
return M;
}
From [email protected] on January 17, 2013 12:09:50 Ha! Cool. It will take me some time to get around to this, but it's really excellent that you've posted some code here as it means people can C&P as a workaround.