1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.giraph.aggregators.matrix.sparse;
20
21 import it.unimi.dsi.fastutil.ints.Int2DoubleMap;
22 import it.unimi.dsi.fastutil.ints.Int2DoubleOpenHashMap;
23 import it.unimi.dsi.fastutil.objects.ObjectIterator;
24
25 import java.io.DataInput;
26 import java.io.DataOutput;
27 import java.io.IOException;
28
29 import org.apache.hadoop.io.Writable;
30
31
32
33
34 public class DoubleSparseVector implements Writable {
35
36
37
38 private Int2DoubleOpenHashMap entries = null;
39
40
41
42
43 public DoubleSparseVector() {
44 initialize(Int2DoubleOpenHashMap.DEFAULT_INITIAL_SIZE);
45 }
46
47
48
49
50
51
52 public DoubleSparseVector(int size) {
53 initialize(size);
54 }
55
56
57
58
59
60
61 private void initialize(int size) {
62 entries = new Int2DoubleOpenHashMap(size);
63 entries.defaultReturnValue(0.0f);
64 }
65
66
67
68
69
70
71
72 public double get(int i) {
73 return entries.get(i);
74 }
75
76
77
78
79
80
81
82 public void set(int i, double value) {
83 entries.put(i, value);
84 }
85
86
87
88
89
90
91 public void add(int key, double value) {
92 entries.addTo(key, value);
93 }
94
95
96
97
98 public void clear() {
99 entries.clear();
100 }
101
102
103
104
105
106
107
108 public void add(DoubleSparseVector other) {
109 ObjectIterator<Int2DoubleMap.Entry> iter =
110 other.entries.int2DoubleEntrySet().fastIterator();
111 while (iter.hasNext()) {
112 Int2DoubleMap.Entry entry = iter.next();
113 entries.addTo(entry.getIntKey(), entry.getDoubleValue());
114 }
115 }
116
117 @Override
118 public void write(DataOutput out) throws IOException {
119 out.writeInt(entries.size());
120 ObjectIterator<Int2DoubleMap.Entry> iter =
121 entries.int2DoubleEntrySet().fastIterator();
122 while (iter.hasNext()) {
123 Int2DoubleMap.Entry entry = iter.next();
124 out.writeInt(entry.getIntKey());
125 out.writeDouble(entry.getDoubleValue());
126 }
127 }
128
129 @Override
130 public void readFields(DataInput in) throws IOException {
131 int size = in.readInt();
132 initialize(size);
133 for (int i = 0; i < size; ++i) {
134 int row = in.readInt();
135 double value = in.readDouble();
136 entries.put(row, value);
137 }
138 }
139 }