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.dense;
20
21 import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
22
23 import java.io.DataInput;
24 import java.io.DataOutput;
25 import java.io.IOException;
26
27 import org.apache.hadoop.io.Writable;
28
29
30
31
32
33
34
35 public class DoubleDenseVector implements Writable {
36
37 private final DoubleArrayList entries = new DoubleArrayList();
38
39 private boolean isSingleton = false;
40
41 private int singletonIndex;
42
43 private double singletonValue;
44
45
46 public DoubleDenseVector() { }
47
48
49
50
51
52
53 public DoubleDenseVector(int size) {
54 ensureCapacity(size);
55 }
56
57
58
59
60
61
62
63 public void setSingleton(int index, double value) {
64 isSingleton = true;
65 this.singletonIndex = index;
66 this.singletonValue = value;
67 }
68
69
70
71
72
73
74 public int getSingletonIndex() {
75 return singletonIndex;
76 }
77
78
79
80
81
82
83 public double getSingletonValue() {
84 return singletonValue;
85 }
86
87
88
89
90
91
92
93 public double get(int i) {
94
95 if (i >= entries.size()) {
96 return 0.0;
97 }
98 return entries.getDouble(i);
99 }
100
101
102
103
104
105
106
107 public void set(int i, double value) {
108 entries.set(i, value);
109 }
110
111
112
113
114
115
116
117 public void add(DoubleDenseVector other) {
118 if (isSingleton) {
119 throw new RuntimeException("Cannot add to singleton vector");
120 }
121 if (other.isSingleton) {
122 ensureCapacity(other.singletonIndex + 1);
123 entries.set(other.singletonIndex,
124 entries.getDouble(other.singletonIndex) + other.singletonValue);
125 } else {
126 ensureCapacity(other.entries.size());
127 for (int i = 0; i < other.entries.size(); ++i) {
128 entries.set(i, entries.getDouble(i) + other.entries.getDouble(i));
129 }
130 }
131 }
132
133
134
135
136
137
138 private void ensureCapacity(int size) {
139 if (entries.size() < size) {
140 entries.size(size);
141 }
142 }
143
144 @Override
145 public void write(DataOutput out) throws IOException {
146 out.writeBoolean(isSingleton);
147 if (isSingleton) {
148 out.writeInt(singletonIndex);
149 out.writeDouble(singletonValue);
150 } else {
151 out.writeInt(entries.size());
152 for (int i = 0; i < entries.size(); ++i) {
153 out.writeDouble(entries.getDouble(i));
154 }
155 }
156 }
157
158 @Override
159 public void readFields(DataInput in) throws IOException {
160 isSingleton = in.readBoolean();
161 if (isSingleton) {
162 singletonIndex = in.readInt();
163 singletonValue = in.readDouble();
164 } else {
165 int size = in.readInt();
166 for (int i = 0; i < size; ++i) {
167 entries.add(in.readDouble());
168 }
169 }
170 }
171 }