aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/tensor/functions/Generate.java
blob: 52620814ecddd515ba09f5a1532c856f3364ce77 (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.tensor.functions;

import com.yahoo.tensor.DimensionSizes;
import com.yahoo.tensor.IndexedTensor;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.evaluation.EvaluationContext;
import com.yahoo.tensor.evaluation.TypeContext;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;

/**
 * An indexed tensor whose values are generated by a function
 *
 * @author bratseth
 */
public class Generate extends PrimitiveTensorFunction {

    private final TensorType type;

    // One of these are null
    private final Function<List<Long>, Double> freeGenerator;
    private final ScalarFunction boundGenerator;

    /** The same as Generate.free */
    public Generate(TensorType type, Function<List<Long>, Double> generator) {
        this(type, Objects.requireNonNull(generator), null);
    }

    /**
     * Creates a generated tensor from a free function
     *
     * @param type the type of the tensor
     * @param generator the function generating values from a list of numbers specifying the indexes of the
     *                  tensor cell which will receive the value
     * @throws IllegalArgumentException if any of the tensor dimensions are not indexed bound
     */
    public static Generate free(TensorType type, Function<List<Long>, Double> generator) {
        return new Generate(type, Objects.requireNonNull(generator), null);
    }

    /**
     * Creates a generated tensor from a bound function
     *
     * @param type the type of the tensor
     * @param generator the function generating values from a list of numbers specifying the indexes of the
     *                  tensor cell which will receive the value
     * @throws IllegalArgumentException if any of the tensor dimensions are not indexed bound
     */
    public static Generate bound(TensorType type, ScalarFunction generator) {
        return new Generate(type, null, Objects.requireNonNull(generator));
    }

    private Generate(TensorType type, Function<List<Long>, Double> freeGenerator, ScalarFunction boundGenerator) {
        Objects.requireNonNull(type, "The argument tensor type cannot be null");
        validateType(type);
        this.type = type;
        this.freeGenerator = freeGenerator;
        this.boundGenerator = boundGenerator;
    }

    private void validateType(TensorType type) {
        for (TensorType.Dimension dimension : type.dimensions())
            if (dimension.type() != TensorType.Dimension.Type.indexedBound)
                throw new IllegalArgumentException("A generated tensor can only have indexed bound dimensions");
    }

    @Override
    public List<TensorFunction> arguments() { return Collections.emptyList(); }

    @Override
    public TensorFunction withArguments(List<TensorFunction> arguments) {
        if ( arguments.size() != 0)
            throw new IllegalArgumentException("Generate must have 0 arguments, got " + arguments.size());
        return this;
    }

    @Override
    public PrimitiveTensorFunction toPrimitive() { return this; }

    @Override
    public <NAMETYPE extends TypeContext.Name> TensorType type(TypeContext<NAMETYPE> context) { return type; }

    @Override
    public <NAMETYPE extends TypeContext.Name> Tensor evaluate(EvaluationContext<NAMETYPE> context) {
        Tensor.Builder builder = Tensor.Builder.of(type);
        IndexedTensor.Indexes indexes = IndexedTensor.Indexes.of(dimensionSizes(type));
        GenerateContext<NAMETYPE> generateContext = new GenerateContext<>(type, context);
        for (int i = 0; i < indexes.size(); i++) {
            indexes.next();
            builder.cell(generateContext.apply(indexes), indexes.indexesForReading());
        }
        return builder.build();
    }

    private DimensionSizes dimensionSizes(TensorType type) {
        DimensionSizes.Builder b = new DimensionSizes.Builder(type.dimensions().size());
        for (int i = 0; i < b.dimensions(); i++)
            b.set(i, type.dimensions().get(i).size().get());
        return b.build();
    }

    @Override
    public String toString(ToStringContext context) { return type + "(" + generatorToString(context) + ")"; }

    private String generatorToString(ToStringContext context) {
        if (freeGenerator != null)
            return freeGenerator.toString();
        else
            return boundGenerator.toString(context);
    }

    /**
     * A context for generating all the values of a tensor produced by evaluating Generate.
     * This returns all the current index values as variables and falls back to delivering from the given
     * evaluation context.
     */
    private class GenerateContext<NAMETYPE extends TypeContext.Name> implements EvaluationContext<NAMETYPE> {

        private final TensorType type;
        private final EvaluationContext<NAMETYPE> context;

        private IndexedTensor.Indexes indexes;

        GenerateContext(TensorType type, EvaluationContext<NAMETYPE> context) {
            this.type = type;
            this.context = context;
        }

        @SuppressWarnings("unchecked")
        double apply(IndexedTensor.Indexes indexes) {
            if (freeGenerator != null) {
                return freeGenerator.apply(indexes.toList());
            }
            else {
                this.indexes = indexes;
                return boundGenerator.apply(this);
            }
        }

        @Override
        public Tensor getTensor(String name) {
            Optional<Integer> index = type.indexOfDimension(name);
            if (index.isPresent()) // this is the name of a dimension
                return Tensor.from(indexes.indexesForReading()[index.get()]);
            else
                return context.getTensor(name);
        }

        @Override
        public TensorType getType(NAMETYPE name) {
            Optional<Integer> index = type.indexOfDimension(name.name());
            if (index.isPresent()) // this is the name of a dimension
                return TensorType.empty;
            else
                return context.getType(name);
        }

        @Override
        public TensorType getType(String name) {
            Optional<Integer> index = type.indexOfDimension(name);
            if (index.isPresent()) // this is the name of a dimension
                return TensorType.empty;
            else
                return context.getType(name);
        }

    }

}