1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 package org.dishevelled.matrix.io.impl;
25
26 import java.io.IOException;
27
28 import org.dishevelled.functor.TernaryPredicate;
29 import org.dishevelled.functor.TernaryProcedure;
30
31 import org.dishevelled.matrix.Matrix2D;
32
33
34
35
36
37
38
39 public final class MatrixMarketWriter
40 extends AbstractMatrix2DWriter<Number>
41 {
42
43
44
45
46
47
48 private static final TernaryPredicate<Long, Long, Object> NOT_NULL = new TernaryPredicate<Long, Long, Object>()
49 {
50
51 public boolean test(final Long row, final Long column, final Object value)
52 {
53 return (value != null);
54 }
55 };
56
57
58
59 public <T extends Appendable> T append(final Matrix2D<? extends Number> matrix, final T appendable)
60 throws IOException
61 {
62 if (matrix == null)
63 {
64 throw new IllegalArgumentException("matrix must not be null");
65 }
66 if (appendable == null)
67 {
68 throw new IllegalArgumentException("appendable must not be null");
69 }
70
71 appendable.append("%%MatrixMarket matrix coordinate real general\n");
72 appendable.append("%\n% Note indices are 1-based.\n%\n");
73
74
75 appendable.append(String.valueOf(matrix.rows()));
76 appendable.append("\t");
77 appendable.append(String.valueOf(matrix.columns()));
78 appendable.append("\t");
79 appendable.append(String.valueOf(matrix.cardinality()));
80 appendable.append("\n");
81
82
83 matrix.forEach(NOT_NULL, new TernaryProcedure<Long, Long, Object>()
84 {
85
86 public void run(final Long row, final Long column, final Object value)
87 {
88
89 try
90 {
91 appendable.append(String.valueOf(row + 1L));
92 appendable.append("\t");
93 appendable.append(String.valueOf(column + 1L));
94 appendable.append("\t");
95 appendable.append(MatrixIOUtils.toCharSequence(value));
96 appendable.append("\n");
97 }
98 catch (IOException e)
99 {
100
101 }
102 }
103 });
104
105 return appendable;
106 }
107 }