summaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/tensor/TensorParser.java
blob: 4d9bb25842382e96a047b4f5081dd8d1647aa06b (plain) (blame)
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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.tensor;

import java.util.Optional;

/**
 * @author bratseth
 */
class TensorParser {

    static Tensor tensorFrom(String tensorString, Optional<TensorType> explicitType) {
        Optional<TensorType> type;
        String valueString;

        tensorString = tensorString.trim();
        if (tensorString.startsWith("tensor")) {
            int colonIndex = tensorString.indexOf(':');
            String typeString = tensorString.substring(0, colonIndex);
            TensorType typeFromString = TensorTypeParser.fromSpec(typeString);
            if (explicitType.isPresent() && ! explicitType.get().equals(typeFromString))
                throw new IllegalArgumentException("Got tensor with type string '" + typeString + "', but was " +
                                                   "passed type " + explicitType.get());
            type = Optional.of(typeFromString);
            valueString = tensorString.substring(colonIndex + 1);
        }
        else {
            type = explicitType;
            valueString = tensorString;
        }

        valueString = valueString.trim();
        if (valueString.startsWith("{")) {
            return tensorFromSparseValueString(valueString, type);
        }
        else if (valueString.startsWith("[")) {
            return tensorFromDenseValueString(valueString, type);
        }
        else {
            if (explicitType.isPresent() && ! explicitType.get().equals(TensorType.empty))
                throw new IllegalArgumentException("Got a zero-dimensional tensor value ('" + tensorString +
                                                   "') where type " + explicitType.get() + " is required");
            try {
                return Tensor.Builder.of(TensorType.empty).cell(Double.parseDouble(tensorString)).build();
            }
            catch (NumberFormatException e) {
                throw new IllegalArgumentException("Excepted a number or a string starting by {, [ or tensor(...):, got '" +
                                                   tensorString + "'");
            }
        }
    }

    /** Derives the tensor type from the first address string in the given tensor string */
    private static TensorType typeFromSparseValueString(String valueString) {
        String s = valueString.substring(1).trim(); // remove tensor start
        int firstKeyOrTensorEnd = s.indexOf('}');
        if (firstKeyOrTensorEnd < 0)
            throw new IllegalArgumentException("Excepted a number or a string starting by {, [ or tensor(...):, got '" +
                                               valueString + "'");
        String addressBody = s.substring(0, firstKeyOrTensorEnd).trim();
        if (addressBody.isEmpty()) return TensorType.empty; // Empty tensor
        if ( ! addressBody.startsWith("{")) return TensorType.empty; // Single value tensor

        addressBody = addressBody.substring(1, addressBody.length()); // remove key start
        if (addressBody.isEmpty()) return TensorType.empty; // Empty key

        TensorType.Builder builder = new TensorType.Builder(TensorType.Value.DOUBLE);
        for (String elementString : addressBody.split(",")) {
            String[] pair = elementString.split(":");
            if (pair.length != 2)
                throw new IllegalArgumentException("Expecting argument elements to be on the form dimension:label, " +
                                                   "got '" + elementString + "'");
            builder.mapped(pair[0].trim());
        }

        return builder.build();
    }

    private static Tensor tensorFromSparseValueString(String valueString, Optional<TensorType> type) {
        try {
            valueString = valueString.trim();
            Tensor.Builder builder = Tensor.Builder.of(type.orElse(typeFromSparseValueString(valueString)));
            return fromCellString(builder, valueString);
        }
        catch (NumberFormatException e) {
            throw new IllegalArgumentException("Excepted a number or a string starting by { or tensor(, got '" +
                                               valueString + "'");
        }
    }

    private static Tensor tensorFromDenseValueString(String valueString, Optional<TensorType> type) {
        if (type.isEmpty())
            throw new IllegalArgumentException("The dense tensor form requires an explicit tensor type " +
                                               "on the form 'tensor(dimensions):...");
        if (type.get().dimensions().stream().anyMatch(d -> ( d.size().isEmpty())))
            throw new IllegalArgumentException("The dense tensor form requires a tensor type containing " +
                                               "only dense dimensions with a given size");
        IndexedTensor.BoundBuilder builder = (IndexedTensor.BoundBuilder)IndexedTensor.Builder.of(type.get());

        // Since we know the dimensions the brackets are just syntactic sugar
        long[] indexes = new long[builder.type().rank()];
        int currentChar;
        int nextNumberEnd = 0;
        while ((currentChar = nextStartCharIndex(nextNumberEnd + 1, valueString)) < valueString.length()) {
            nextNumberEnd   = nextStopCharIndex(currentChar, valueString);
            if (currentChar == nextNumberEnd) return builder.build();

            if (builder.type().valueType() == TensorType.Value.DOUBLE)
                builder.cellByDirectIndex(nextCellIndex(indexes, builder), Double.parseDouble(valueString.substring(currentChar, nextNumberEnd)));
            else if (builder.type().valueType() == TensorType.Value.FLOAT)
                builder.cellByDirectIndex(nextCellIndex(indexes, builder), Float.parseFloat(valueString.substring(currentChar, nextNumberEnd)));
            else
                throw new IllegalArgumentException(builder.type().valueType() + " is not supported");
        }
        return builder.build();
    }

    // -----

    /**
     * Advance to the next cell in left-adjac ent order.
     *
     * On rightmost vs. leftmost adjacency:
     * A dense tensor is laid out with the rightmost dimension as adjacent numbers,
     * but when we parse a dense tensor we encounter numbers in the leftmost-adjacent order, since
     * that is the most natural way to write it: tensor(x,y)[[1,2],[3,4]]
     * should mean {{x:0, y:0}:1, {x:1, y:0}:2, {x:0, y:1}:3, {x:1, y:1}:4}.
     * Therefore we need to convert the encounter order (numberIndex) from left-adjacent to right-adjacent.
     */
    private static long nextCellIndex(long[] indexes, IndexedTensor.BoundBuilder builder) {
        long cellIndex = IndexedTensor.toValueIndex(indexes, builder.sizes());

        // Find next dimension to advance
        int nextInDimension = 0;
        while (nextInDimension < indexes.length && indexes[nextInDimension] + 1 >= builder.sizes().size(nextInDimension)) {
            indexes[nextInDimension] = 0;
            nextInDimension++;
        }
        if (nextInDimension < indexes.length)
            indexes[nextInDimension]++;
        else // there is no next - become invalid
            indexes[0]++;

        return cellIndex;
    }

    /** Returns the position of the next character that should contain a number, or if none the string length */
    private static int nextStartCharIndex(int charIndex, String valueString) {
        for (; charIndex < valueString.length(); charIndex++) {
            if (valueString.charAt(charIndex) == ']') continue;
            if (valueString.charAt(charIndex) == '[') continue;
            if (valueString.charAt(charIndex) == ',') continue;
            if (valueString.charAt(charIndex) == ' ') continue;
            return charIndex;
        }
        return valueString.length();
    }

    private static int nextStopCharIndex(int charIndex, String valueString) {
        while (charIndex < valueString.length()) {
            if (valueString.charAt(charIndex) == ',') return charIndex;
            if (valueString.charAt(charIndex) == ']') return charIndex;
            charIndex++;
        }
        throw new IllegalArgumentException("Malformed tensor value '" + valueString +
                                           "': Expected a ',' or ']' after position " + charIndex);
    }

    private static Tensor fromCellString(Tensor.Builder builder, String s) {
        int index = 1;
        index = skipSpace(index, s);
        while (index + 1 < s.length()) {
            int keyOrTensorEnd = s.indexOf('}', index);
            TensorAddress.Builder addressBuilder = new TensorAddress.Builder(builder.type());
            if (keyOrTensorEnd < s.length() - 1) { // Key end: This has a key - otherwise TensorAddress is empty
                addLabels(s.substring(index, keyOrTensorEnd + 1), addressBuilder);
                index = keyOrTensorEnd + 1;
                index = skipSpace(index, s);
                if ( s.charAt(index) != ':')
                    throw new IllegalArgumentException("Expecting a ':' after " + s.substring(index) + ", got '" + s + "'");
                index++;
            }
            int valueEnd = s.indexOf(',', index);
            if (valueEnd < 0) { // last value
                valueEnd = s.indexOf('}', index);
                if (valueEnd < 0)
                    throw new IllegalArgumentException("A tensor string must end by '}'");
            }

            TensorAddress address = addressBuilder.build();
            Double value = asDouble(address, s.substring(index, valueEnd).trim());
            builder.cell(address, value);
            index = valueEnd+1;
            index = skipSpace(index, s);
        }
        return builder.build();
    }

    private static int skipSpace(int index, String s) {
        while (index < s.length() && s.charAt(index) == ' ')
            index++;
        return index;
    }

    /** Creates a tenor address from a string on the form {dimension1:label1,dimension2:label2,...} */
    private static void addLabels(String mapAddressString, TensorAddress.Builder builder) {
        mapAddressString = mapAddressString.trim();
        if ( ! (mapAddressString.startsWith("{") && mapAddressString.endsWith("}")))
            throw new IllegalArgumentException("Expecting a tensor address enclosed in {}, got '" + mapAddressString + "'");

        String addressBody = mapAddressString.substring(1, mapAddressString.length() - 1).trim();
        if (addressBody.isEmpty()) return;

        for (String elementString : addressBody.split(",")) {
            String[] pair = elementString.split(":");
            if (pair.length != 2)
                throw new IllegalArgumentException("Expecting argument elements on the form dimension:label, " +
                                                   "got '" + elementString + "'");
            String dimension = pair[0].trim();
            builder.add(dimension, pair[1].trim());
        }
    }

    private static Double asDouble(TensorAddress address, String s) {
        try {
            return Double.valueOf(s);
        }
        catch (NumberFormatException e) {
            throw new IllegalArgumentException("At " + address + ": Expected a floating point number, got '" + s + "'");
        }
    }

}