This repository has been archived by the owner on Nov 10, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 104
/
LinkedSparseMatrix.java
470 lines (419 loc) · 14.4 KB
/
LinkedSparseMatrix.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
package no.uib.cipr.matrix.sparse;
import lombok.AllArgsConstructor;
import lombok.ToString;
import lombok.extern.java.Log;
import no.uib.cipr.matrix.AbstractMatrix;
import no.uib.cipr.matrix.Matrix;
import no.uib.cipr.matrix.MatrixEntry;
import no.uib.cipr.matrix.Vector;
import no.uib.cipr.matrix.io.MatrixInfo;
import no.uib.cipr.matrix.io.MatrixSize;
import no.uib.cipr.matrix.io.MatrixVectorReader;
import java.io.IOException;
import java.util.Iterator;
/**
* A Linked List (with shortcuts to important nodes) implementation of an
* {@code n x m} Matrix with {@code z} elements that has a typical
* {@code O(z / m)} insertion / lookup cost and an iterator that traverses
* columns then rows: a good fit for unstructured sparse matrices. A secondary
* link maintains fast transpose iteration.
* <p/>
* However, memory requirements (
* {@code 1 instance (8 bytes), 2 int (16 bytes), 2 ref (16 bytes), 1 double (8 bytes) = 48 bytes}
* per matrix element, plus {@code 8 x numcol + 8 x numrow bytes}s for the
* cache) are slightly higher than structured sparse matrix storage. Note that
* on 32 bit JVMs, or on 64 bit JVMs with <a
* href="https://wikis.oracle.com/display/HotSpotInternals/CompressedOops"
* >CompressedOops</a> enabled, references and ints only cost 4 bytes each,
* bringing the cost to 28 bytes per element.
*
* @author Sam Halliday
*/
@Log
public class LinkedSparseMatrix extends AbstractMatrix {
// java.util.LinkedList is doubly linked and therefore too heavyweight.
@AllArgsConstructor
@ToString(exclude = {"rowTail", "colTail"})
static class Node {
final int row, col;
double val;
Node rowTail, colTail;
}
// there is a lot of duplicated code in this class between
// row and col linkages, but subtle differences make it
// extremely difficult to factor away.
class Linked {
final Node head = new Node(0, 0, 0, null, null);
Node[] rows = new Node[numRows], cols = new Node[numColumns];
private boolean isHead(int row, int col) {
return head.row == row && head.col == col;
}
// true if node exists, it's row tail exists, and has this row/col
private boolean isNextByRow(Node node, int row, int col) {
return node != null && node.rowTail != null
&& node.rowTail.row == row && node.rowTail.col == col;
}
// true if node exists, it's col tail exists, and has this row/col
private boolean isNextByCol(Node node, int row, int col) {
return node != null && node.colTail != null
&& node.colTail.col == col && node.colTail.row == row;
}
public double get(int row, int col) {
if (isHead(row, col))
return head.val;
if (col <= row) {
Node node = findPreceedingByRow(row, col);
if (isNextByRow(node, row, col))
return node.rowTail.val;
} else {
Node node = findPreceedingByCol(row, col);
if (isNextByCol(node, row, col))
return node.colTail.val;
}
return 0;
}
public void set(int row, int col, double val) {
if (val == 0) {
delete(row, col);
return;
}
if (isHead(row, col))
head.val = val;
else {
Node prevRow = findPreceedingByRow(row, col);
if (isNextByRow(prevRow, row, col))
prevRow.rowTail.val = val;
else {
Node prevCol = findPreceedingByCol(row, col);
Node nextCol = findNextByCol(row, col);
prevRow.rowTail = new Node(row, col, val, prevRow.rowTail,
nextCol);
prevCol.colTail = prevRow.rowTail;
updateCache(prevRow.rowTail);
}
}
}
private Node findNextByCol(int row, int col) {
Node cur = cachedByCol(col - 1);
while (cur != null) {
if (row < cur.row && col <= cur.col || col < cur.col)
return cur;
cur = cur.colTail;
}
return cur;
}
private void updateCache(Node inserted) {
if (rows[inserted.row] == null
|| inserted.col > rows[inserted.row].col)
rows[inserted.row] = inserted;
if (cols[inserted.col] == null
|| inserted.row > cols[inserted.col].row)
cols[inserted.col] = inserted;
}
private void delete(int row, int col) {
if (isHead(row, col)) {
head.val = 0;
return;
}
Node precRow = findPreceedingByRow(row, col);
Node precCol = findPreceedingByCol(row, col);
if (isNextByRow(precRow, row, col)) {
if (rows[row] == precRow.rowTail)
rows[row] = precRow.row == row ? precRow : null;
precRow.rowTail = precRow.rowTail.rowTail;
}
if (isNextByCol(precCol, row, col)) {
if (cols[col] == precCol.colTail)
cols[col] = precCol.col == col ? precCol : null;
precCol.colTail = precCol.colTail.colTail;
}
}
// returns the node that either references this
// index, or should reference it if inserted.
Node findPreceedingByRow(int row, int col) {
Node last = cachedByRow(row - 1);
Node cur = last;
while (cur != null && cur.row <= row) {
if (cur.row == row && cur.col >= col)
return last;
last = cur;
cur = cur.rowTail;
}
return last;
}
// helper for findPreceeding
private Node cachedByRow(int row) {
for (int i = row; i >= 0; i--)
if (rows[i] != null)
return rows[i];
return head;
}
Node findPreceedingByCol(int row, int col) {
Node last = cachedByCol(col - 1);
Node cur = last;
while (cur != null && cur.col <= col) {
if (cur.col == col && cur.row >= row)
return last;
last = cur;
cur = cur.colTail;
}
return last;
}
private Node cachedByCol(int col) {
for (int i = col; i >= 0; i--)
if (cols[i] != null)
return cols[i];
return head;
}
Node startOfRow(int row) {
if (row == 0)
return head;
Node prec = findPreceedingByRow(row, 0);
if (prec.rowTail != null && prec.rowTail.row == row)
return prec.rowTail;
return null;
}
Node startOfCol(int col) {
if (col == 0)
return head;
Node prec = findPreceedingByCol(0, col);
if (prec != null && prec.colTail != null && prec.colTail.col == col)
return prec.colTail;
return null;
}
}
Linked links;
public LinkedSparseMatrix(int numRows, int numColumns) {
super(numRows, numColumns);
links = new Linked();
}
public LinkedSparseMatrix(Matrix A) {
super(A);
links = new Linked();
set(A);
}
public LinkedSparseMatrix(MatrixVectorReader r) throws IOException {
super(0, 0);
try {
MatrixInfo info = r.readMatrixInfo();
if (info.isComplex())
throw new IllegalArgumentException(
"complex matrices not supported");
if (!info.isCoordinate())
throw new IllegalArgumentException(
"only coordinate matrices supported");
MatrixSize size = r.readMatrixSize(info);
numRows = size.numRows();
numColumns = size.numColumns();
links = new Linked();
int nz = size.numEntries();
int[] row = new int[nz];
int[] column = new int[nz];
double[] entry = new double[nz];
r.readCoordinate(row, column, entry);
r.add(-1, row);
r.add(-1, column);
for (int i = 0; i < nz; ++i)
set(row[i], column[i], entry[i]);
} finally {
r.close();
}
}
@Override
public Matrix zero() {
links = new Linked();
return this;
}
@Override
public double get(int row, int column) {
return links.get(row, column);
}
@Override
public void set(int row, int column, double value) {
check(row, column);
links.set(row, column, value);
}
// avoids object creation
static class ReusableMatrixEntry implements MatrixEntry {
int row, col;
double val;
@Override
public int column() {
return col;
}
@Override
public int row() {
return row;
}
@Override
public double get() {
return val;
}
@Override
public void set(double value) {
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return row + "," + col + "=" + val;
}
}
@Override
public Iterator<MatrixEntry> iterator() {
return new Iterator<MatrixEntry>() {
Node cur = links.head;
ReusableMatrixEntry entry = new ReusableMatrixEntry();
@Override
public boolean hasNext() {
return cur != null;
}
@Override
public MatrixEntry next() {
entry.row = cur.row;
entry.col = cur.col;
entry.val = cur.val;
cur = cur.rowTail;
return entry;
}
@Override
public void remove() {
throw new UnsupportedOperationException("TODO");
}
};
}
@Override
public Matrix scale(double alpha) {
if (alpha == 0)
zero();
else if (alpha != 1)
for (MatrixEntry e : this)
set(e.row(), e.column(), e.get() * alpha);
return this;
}
@Override
public Matrix copy() {
return new LinkedSparseMatrix(this);
}
@Override
public Matrix transpose() {
Linked old = links;
numRows = numColumns;
numColumns = old.rows.length;
links = new Linked();
Node node = old.head;
while (node != null) {
set(node.col, node.row, node.val);
node = node.rowTail;
}
return this;
}
@Override
public Vector multAdd(double alpha, Vector x, Vector y) {
checkMultAdd(x, y);
if (alpha == 0)
return y;
Node node = links.head;
while (node != null) {
y.add(node.row, alpha * node.val * x.get(node.col));
node = node.rowTail;
}
return y;
}
@Override
public Vector transMultAdd(double alpha, Vector x, Vector y) {
checkTransMultAdd(x, y);
if (alpha == 0)
return y;
Node node = links.head;
while (node != null) {
y.add(node.col, alpha * node.val * x.get(node.row));
node = node.colTail;
}
return y;
}
// TODO: optimise matrix mults based on RHS Matrix
@Override
public Matrix multAdd(double alpha, Matrix B, Matrix C) {
checkMultAdd(B, C);
if (alpha == 0)
return C;
for (int i = 0; i < numRows; i++) {
Node row = links.startOfRow(i);
if (row != null)
for (int j = 0; j < B.numColumns(); j++) {
Node node = row;
double v = 0;
while (node != null && node.row == i) {
v += (B.get(node.col, j) * node.val);
node = node.rowTail;
}
if (v != 0)
C.add(i, j, alpha * v);
}
}
return C;
}
@Override
public Matrix transBmultAdd(double alpha, Matrix B, Matrix C) {
checkTransBmultAdd(B, C);
if (alpha == 0)
return C;
for (int i = 0; i < numRows; i++) {
Node row = links.startOfRow(i);
if (row != null)
for (int j = 0; j < B.numRows(); j++) {
Node node = row;
double v = 0;
while (node != null && node.row == i) {
v += (B.get(j, node.col) * node.val);
node = node.rowTail;
}
if (v != 0)
C.add(i, j, alpha * v);
}
}
return C;
}
@Override
public Matrix transAmultAdd(double alpha, Matrix B, Matrix C) {
checkTransAmultAdd(B, C);
if (alpha == 0)
return C;
for (int i = 0; i < numColumns; i++) {
Node row = links.startOfCol(i);
if (row != null)
for (int j = 0; j < B.numColumns(); j++) {
Node node = row;
double v = 0;
while (node != null && node.col == i) {
v += (B.get(node.row, j) * node.val);
node = node.colTail;
}
if (v != 0)
C.add(i, j, alpha * v);
}
}
return C;
}
@Override
public Matrix transABmultAdd(double alpha, Matrix B, Matrix C) {
checkTransABmultAdd(B, C);
if (alpha == 0)
return C;
for (int i = 0; i < numColumns; i++) {
Node row = links.startOfCol(i);
if (row != null)
for (int j = 0; j < B.numRows(); j++) {
Node node = row;
double v = 0;
while (node != null && node.col == i) {
v += (B.get(j, node.row) * node.val);
node = node.colTail;
}
if (v != 0)
C.add(i, j, alpha * v);
}
}
return C;
}
}