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
|
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.tensor;
import com.google.common.annotations.Beta;
import com.google.common.collect.ImmutableMap;
import java.util.Iterator;
import java.util.Map;
/**
* A sparse implementation of a tensor backed by a Map of cells to values.
*
* @author bratseth
*/
@Beta
public class MappedTensor implements Tensor {
private final TensorType type;
private final ImmutableMap<TensorAddress, Double> cells;
/** Creates a sparse tensor. The cell addresses must match the type. */
private MappedTensor(TensorType type, Map<TensorAddress, Double> cells) {
this.type = type;
this.cells = ImmutableMap.copyOf(cells);
}
@Override
public TensorType type() { return type; }
@Override
public int size() { return cells.size(); }
@Override
public double get(TensorAddress address) { return cells.getOrDefault(address, Double.NaN); }
@Override
public Iterator<Map.Entry<TensorAddress, Double>> cellIterator() { return cells.entrySet().iterator(); }
@Override
public Iterator<Double> valueIterator() { return cells.values().iterator(); }
@Override
public Map<TensorAddress, Double> cells() { return cells; }
@Override
public int hashCode() { return cells.hashCode(); }
@Override
public String toString() { return Tensor.toStandardString(this); }
@Override
public boolean equals(Object o) {
if ( ! (o instanceof Tensor)) return false;
return Tensor.equals(this, (Tensor)o);
}
public static class Builder implements Tensor.Builder {
private final TensorType type;
private final ImmutableMap.Builder<TensorAddress, Double> cells = new ImmutableMap.Builder<>();
public static Builder of(TensorType type) { return new Builder(type); }
private Builder(TensorType type) {
this.type = type;
}
public CellBuilder cell() {
return new CellBuilder(type, this);
}
@Override
public TensorType type() { return type; }
@Override
public Builder cell(TensorAddress address, double value) {
cells.put(address, value);
return this;
}
@Override
public Builder cell(double value, int... labels) {
cells.put(new TensorAddress(labels), value);
return this;
}
@Override
public MappedTensor build() {
return new MappedTensor(type, cells.build());
}
}
}
|