View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.giraph.aggregators.matrix.sparse;
20  
21  import static org.junit.Assert.assertEquals;
22  
23  import org.apache.giraph.utils.WritableUtils;
24  import org.junit.Test;
25  
26  public class TestIntSparseMatrix {
27  
28    @Test
29    public void testVectorAdd() {
30      // The default value should be 0
31      IntSparseVector vec1 = new IntSparseVector();
32      assertEquals(0, vec1.get(0));
33  
34      // Basic get/set
35      vec1.set(0, 1);
36      vec1.set(10, 14);
37      assertEquals(1, vec1.get(0));
38      assertEquals(0, vec1.get(5));
39      assertEquals(14, vec1.get(10));
40  
41      // Add another vector
42      IntSparseVector vec2 = new IntSparseVector();
43      vec2.set(0, 5);
44      vec2.set(5, 17);
45  
46      vec1.add(vec2);
47      assertEquals(6, vec1.get(0));
48      assertEquals(17, vec1.get(5));
49      assertEquals(14, vec1.get(10));
50      assertEquals(0, vec1.get(15));
51    }
52  
53    @Test
54    public void testVectorSerialize() throws Exception {
55      int size = 100;
56  
57      // Serialize from
58      IntSparseVector from = new IntSparseVector(size);
59      from.set(0, 10);
60      from.set(10, 5);
61      from.set(12, 1);
62      byte[] data = WritableUtils.writeToByteArray(from);
63  
64      // De-serialize to
65      IntSparseVector to = new IntSparseVector();
66      WritableUtils.readFieldsFromByteArray(data, to);
67  
68      // The vectors should be equal
69      for (int i = 0; i < size; ++i) {
70        assertEquals(from.get(i), to.get(i));
71      }
72    }
73  }