01: /*
02: * Created on 21-Feb-2005
03: */
04: package uk.org.ponder.matrix;
05:
06: import java.io.IOException;
07: import java.io.StringReader;
08:
09: import uk.org.ponder.conversion.LeafObjectParser;
10: import uk.org.ponder.streamutil.read.LexReader;
11: import uk.org.ponder.streamutil.read.LexUtil;
12: import uk.org.ponder.streamutil.read.PushbackRIS;
13: import uk.org.ponder.streamutil.read.StringRIS;
14: import uk.org.ponder.stringutil.CharWrap;
15: import uk.org.ponder.util.UniversalRuntimeException;
16:
17: /**
18: * @author Antranig Basman (amb26@ponder.org.uk)
19: *
20: */
21: public class MatrixParser implements LeafObjectParser {
22:
23: public Object parse(String matrixstring) {
24: PushbackRIS lr = new PushbackRIS(new StringRIS(matrixstring));
25: try {
26: return parseMatrix(lr);
27: } catch (Exception ioe) {
28: throw UniversalRuntimeException.accumulate(ioe,
29: "Error parsing matrix: " + ioe.getMessage());
30: }
31: }
32:
33: public Matrix parseMatrix(PushbackRIS lr) {
34: LexUtil.skipWhite(lr);
35: LexUtil.expect(lr, "dimensions:");
36: LexUtil.skipWhite(lr);
37: int rows = LexUtil.readInt(lr);
38: LexUtil.expect(lr, "x");
39: int cols = LexUtil.readInt(lr);
40: Matrix mat = new Matrix(rows, cols);
41: for (int row = 0; row < rows; ++row) {
42: for (int col = 0; col < cols; ++col) {
43: LexUtil.skipWhite(lr);
44: double val = LexUtil.readDouble(lr);
45: mat.setMval(row, col, val);
46: }
47: }
48: LexUtil.expectEmpty(lr);
49: return mat;
50: }
51:
52: public String render(Object torendero) {
53: Matrix torender = (Matrix) torendero;
54: int rows = torender.rows;
55: int cols = torender.cols;
56: CharWrap renderinto = new CharWrap();
57: renderinto.append("dimensions: ").append(rows).append("x")
58: .append(cols);
59: renderinto.append("\n");
60: for (int row = 0; row < rows; ++row) {
61: for (int col = 0; col < cols; ++col) {
62: renderinto.append(
63: Double.toString(torender.getMval(row, col)))
64: .append(" ");
65: }
66: renderinto.append("\n");
67: }
68: return renderinto.toString();
69: }
70:
71: public Object copy(Object tocopy) {
72: // TODO Auto-generated method stub
73: return null;
74: }
75:
76: }
|