summaryrefslogtreecommitdiffstats
path: root/searchlib/src/main/java/com/yahoo/searchlib/rankingexpression/rule/LambdaFunctionNode.java
blob: 3a3410aeebb03d634798dacf6d0bbf1cffc22efd (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
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchlib.rankingexpression.rule;

import com.google.common.collect.ImmutableList;
import com.yahoo.searchlib.rankingexpression.Reference;
import com.yahoo.searchlib.rankingexpression.evaluation.Context;
import com.yahoo.searchlib.rankingexpression.evaluation.MapContext;
import com.yahoo.searchlib.rankingexpression.evaluation.Value;
import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.evaluation.TypeContext;

import java.util.Collections;
import java.util.Deque;
import java.util.List;
import java.util.Optional;
import java.util.function.DoubleBinaryOperator;
import java.util.function.DoubleUnaryOperator;

/**
 * A free, parametrized function
 *
 * @author bratseth
 */
public class LambdaFunctionNode extends CompositeNode {

    private final ImmutableList<String> arguments;
    private final ExpressionNode functionExpression;

    public LambdaFunctionNode(List<String> arguments, ExpressionNode functionExpression) {
        // TODO: Verify that the function only accesses the given arguments
        this.arguments = ImmutableList.copyOf(arguments);
        this.functionExpression = functionExpression;
    }

    @Override
    public List<ExpressionNode> children() {
        return Collections.singletonList(functionExpression);
    }

    @Override
    public CompositeNode setChildren(List<ExpressionNode> children) {
        if ( children.size() != 1)
            throw new IllegalArgumentException("A lambda function must have a single child expression");
        return new LambdaFunctionNode(arguments, children.get(0));
    }

    @Override
    public StringBuilder toString(StringBuilder string, SerializationContext context, Deque<String> path, CompositeNode parent) {
        string.append("f(").append(commaSeparated(arguments)).append(")(");
        return functionExpression.toString(string, context, path, this).append(")");
    }

    private String commaSeparated(List<String> list) {
        StringBuilder b = new StringBuilder();
        for (String element : list)
            b.append(element).append(",");
        if (b.length() > 0)
            b.setLength(b.length()-1);
        return b.toString();
    }

    @Override
    public TensorType type(TypeContext<Reference> context) {
        return TensorType.empty; // by definition - no nested lambdas
    }

    /** Evaluate this in a context which must have the arguments bound */
    @Override
    public Value evaluate(Context context) {
        return functionExpression.evaluate(context);
    }

    /**
     * Returns this as a double unary operator
     *
     * @throws IllegalStateException if this has more than one argument
     */
    public DoubleUnaryOperator asDoubleUnaryOperator() {
        if (arguments.size() > 1)
            throw new IllegalStateException("Cannot apply " + this + " as a DoubleUnaryOperator: " +
                                            "Must have at most one argument " + " but has " + arguments);
        return new DoubleUnaryLambda();
    }

    /**
     * Returns this as a double binary operator
     *
     * @throws IllegalStateException if this has more than two arguments
     */
    public DoubleBinaryOperator asDoubleBinaryOperator() {
        if (arguments.size() > 2)
            throw new IllegalStateException("Cannot apply " + this + " as a DoubleBinaryOperator: " +
                                            "Must have at most two argument " + " but has " + arguments);

        // Optimization: if possible, calculate directly rather than creating a context and evaluating the expression
        return getDirectEvaluator().orElseGet(DoubleBinaryLambda::new);
    }

    private Optional<DoubleBinaryOperator> getDirectEvaluator() {
        if ( ! (functionExpression instanceof ArithmeticNode)) {
            return Optional.empty();
        }
        ArithmeticNode node = (ArithmeticNode) functionExpression;
        if ( ! (node.children().get(0) instanceof ReferenceNode) || ! (node.children().get(1) instanceof ReferenceNode)) {
            return Optional.empty();
        }
        if (node.operators().size() != 1) {
            return Optional.empty();
        }
        ArithmeticOperator operator = node.operators().get(0);
        switch (operator) {
            case OR: return asFunctionExpression((left, right) -> ((left != 0.0) || (right != 0.0)) ? 1.0 : 0.0);
            case AND: return asFunctionExpression((left, right) -> ((left != 0.0) && (right != 0.0)) ? 1.0 : 0.0);
            case PLUS: return asFunctionExpression((left, right) -> left + right);
            case MINUS: return asFunctionExpression((left, right) -> left - right);
            case MULTIPLY: return asFunctionExpression((left, right) -> left * right);
            case DIVIDE: return asFunctionExpression((left, right) -> left / right);
            case MODULO: return asFunctionExpression((left, right) -> left % right);
            case POWER: return asFunctionExpression(Math::pow);
        }
        return Optional.empty();
    }

    private Optional<DoubleBinaryOperator> asFunctionExpression(DoubleBinaryOperator operator) {
        return Optional.of(new DoubleBinaryOperator() {
            @Override
            public double applyAsDouble(double left, double right) {
                return operator.applyAsDouble(left, right);
            }
            @Override
            public String toString() {
                return LambdaFunctionNode.this.toString();
            }
        });
    }

    private class DoubleUnaryLambda implements DoubleUnaryOperator {

        @Override
        public double applyAsDouble(double operand) {
            MapContext context = new MapContext();
            if (arguments.size() > 0)
                context.put(arguments.get(0), operand);
            return evaluate(context).asDouble();
        }

        @Override
        public String toString() {
            return LambdaFunctionNode.this.toString();
        }

    }

    private class DoubleBinaryLambda implements DoubleBinaryOperator {

        @Override
        public double applyAsDouble(double left, double right) {
            MapContext context = new MapContext();
            if (arguments.size() > 0)
                context.put(arguments.get(0), left);
            if (arguments.size() > 1)
                context.put(arguments.get(1), right);
            return evaluate(context).asDouble();
        }

        @Override
        public String toString() {
            return LambdaFunctionNode.this.toString();
        }

    }

}