刘光辉
6 小时以前 06f314545ac3514d7ce28939920866ae8188d31c
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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package jnpf.elnFormula;
 
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
public final class FormulaLatexRenderer {
 
    private final FormulaFunctionRegistry functions = new FormulaFunctionRegistry();
 
    public String render(FormulaAst.Node node, Map<String, String> parameterDisplayNames) {
        if (node == null || parameterDisplayNames == null) {
            throw new IllegalArgumentException("node and parameterDisplayNames must not be null");
        }
        return renderNode(node, parameterDisplayNames, 0, false);
    }
 
    private String renderNode(FormulaAst.Node node, Map<String, String> names,
                              int parentPrecedence, boolean rightChild) {
        int precedence = precedence(node);
        String rendered;
        if (node instanceof FormulaAst.Literal) {
            rendered = literal((FormulaAst.Literal) node);
        } else if (node instanceof FormulaAst.Parameter) {
            FormulaAst.Parameter parameter = (FormulaAst.Parameter) node;
            String displayName = names.get(parameter.getCode());
            rendered = "\\text{" + escapeText(displayName == null ? parameter.getCode() : displayName) + "}";
        } else if (node instanceof FormulaAst.Unary) {
            FormulaAst.Unary unary = (FormulaAst.Unary) node;
            String operator = unaryOperator(unary.getOperator());
            rendered = operator + renderNode(unary.getOperand(), names, precedence, true);
        } else if (node instanceof FormulaAst.Binary) {
            rendered = binary((FormulaAst.Binary) node, names);
        } else if (node instanceof FormulaAst.FunctionCall) {
            rendered = function((FormulaAst.FunctionCall) node, names);
        } else {
            throw new IllegalArgumentException("unsupported formula node");
        }
 
        boolean parentheses = precedence < parentPrecedence
                || (rightChild && precedence == parentPrecedence
                && node instanceof FormulaAst.Binary);
        return parentheses ? "\\left(" + rendered + "\\right)" : rendered;
    }
 
    private String binary(FormulaAst.Binary binary, Map<String, String> names) {
        String operator = binary.getOperator();
        int precedence = precedence(binary);
        if ("/".equals(operator)) {
            return "\\frac{" + renderNode(binary.getLeft(), names, 0, false) + "}{"
                    + renderNode(binary.getRight(), names, 0, false) + "}";
        }
        if ("^".equals(operator)) {
            String left = renderNode(binary.getLeft(), names, precedence, false);
            if (binary.getLeft() instanceof FormulaAst.Binary
                    && "^".equals(((FormulaAst.Binary) binary.getLeft()).getOperator())) {
                left = "\\left(" + left + "\\right)";
            }
            return left + "^{" + renderNode(binary.getRight(), names, 0, false) + "}";
        }
        String left = renderNode(binary.getLeft(), names, precedence, false);
        if (precedence == 3 && binary.getLeft() instanceof FormulaAst.Binary
                && precedence(binary.getLeft()) == precedence) {
            left = "\\left(" + left + "\\right)";
        }
        return left + latexOperator(operator)
                + renderNode(binary.getRight(), names, precedence, true);
    }
 
    private String function(FormulaAst.FunctionCall call, Map<String, String> names) {
        if (!functions.contains(call.getName())) {
            throw new IllegalArgumentException("unsupported formula function");
        }
        List<String> arguments = new ArrayList<>();
        for (FormulaAst.Node argument : call.getArguments()) {
            arguments.add(renderNode(argument, names, 0, false));
        }
        String name = call.getName();
        if ("ABS".equals(name)) {
            return "\\left|" + arguments.get(0) + "\\right|";
        }
        if ("SQRT".equals(name)) {
            return "\\sqrt{" + arguments.get(0) + "}";
        }
        if ("POW".equals(name)) {
            return powerBase(call.getArguments().get(0), arguments.get(0))
                    + "^{" + arguments.get(1) + "}";
        }
        if ("NTH_ROOT".equals(name)) {
            return "\\sqrt[" + arguments.get(1) + "]{" + arguments.get(0) + "}";
        }
        if ("LN".equals(name)) {
            return "\\ln\\left(" + arguments.get(0) + "\\right)";
        }
        if ("LOG10".equals(name)) {
            return "\\log_{10}\\left(" + arguments.get(0) + "\\right)";
        }
        if ("LOG".equals(name)) {
            return "\\log_{" + arguments.get(1) + "}\\left("
                    + arguments.get(0) + "\\right)";
        }
        if ("EXP".equals(name)) {
            return "e^{" + arguments.get(0) + "}";
        }
        if ("MIN".equals(name) || "MAX".equals(name)) {
            return "\\" + name.toLowerCase() + "\\left(" + join(arguments) + "\\right)";
        }
        if ("SUM".equals(name)) {
            return "\\sum\\left(" + arguments.get(0) + "\\right)";
        }
        if ("MEAN".equals(name)) {
            return "\\overline{" + arguments.get(0) + "}";
        }
        if ("STDDEV_S".equals(name)) {
            return "s\\left(" + arguments.get(0) + "\\right)";
        }
        if ("STDDEV_P".equals(name)) {
            return "\\sigma\\left(" + arguments.get(0) + "\\right)";
        }
        if ("VAR_S".equals(name)) {
            return "s^{2}\\left(" + arguments.get(0) + "\\right)";
        }
        if ("VAR_P".equals(name)) {
            return "\\sigma^{2}\\left(" + arguments.get(0) + "\\right)";
        }
        return "\\operatorname{" + escapeFunctionName(name) + "}\\left("
                + join(arguments) + "\\right)";
    }
 
    private static String powerBase(FormulaAst.Node node, String rendered) {
        return precedence(node) < 9 ? "\\left(" + rendered + "\\right)" : rendered;
    }
 
    private static String escapeFunctionName(String name) {
        return name.replace("_", "\\_");
    }
 
    private static String literal(FormulaAst.Literal literal) {
        switch (literal.getKind()) {
            case DECIMAL:
                return ((BigDecimal) literal.getValue()).toPlainString();
            case TEXT:
                return "\\text{\"" + escapeText((String) literal.getValue()) + "\"}";
            case BOOLEAN:
                return "\\mathrm{" + literal.getValue().toString() + "}";
            case NULL:
                return "\\mathrm{null}";
            default:
                throw new IllegalArgumentException("unsupported literal kind");
        }
    }
 
    private static String latexOperator(String operator) {
        if ("+".equals(operator) || "-".equals(operator)
                || ">".equals(operator) || "<".equals(operator)) {
            return " " + operator + " ";
        }
        if ("*".equals(operator)) {
            return " \\cdot ";
        }
        if ("%".equals(operator)) {
            return " \\bmod ";
        }
        if (">=".equals(operator)) {
            return " \\ge ";
        }
        if ("<=".equals(operator)) {
            return " \\le ";
        }
        if ("!=".equals(operator)) {
            return " \\ne ";
        }
        if ("==".equals(operator)) {
            return " = ";
        }
        if ("&&".equals(operator)) {
            return " \\land ";
        }
        if ("||".equals(operator)) {
            return " \\lor ";
        }
        throw new IllegalArgumentException("unsupported binary operator");
    }
 
    private static String unaryOperator(String operator) {
        if ("+".equals(operator) || "-".equals(operator)) {
            return operator;
        }
        if ("!".equals(operator)) {
            return "\\lnot ";
        }
        throw new IllegalArgumentException("unsupported unary operator");
    }
 
    private static int precedence(FormulaAst.Node node) {
        if (node instanceof FormulaAst.Binary) {
            String operator = ((FormulaAst.Binary) node).getOperator();
            if ("||".equals(operator)) {
                return 1;
            }
            if ("&&".equals(operator)) {
                return 2;
            }
            if ("==".equals(operator) || "!=".equals(operator)) {
                return 3;
            }
            if (">".equals(operator) || ">=".equals(operator)
                    || "<".equals(operator) || "<=".equals(operator)) {
                return 4;
            }
            if ("+".equals(operator) || "-".equals(operator)) {
                return 5;
            }
            if ("*".equals(operator) || "/".equals(operator) || "%".equals(operator)) {
                return 6;
            }
            if ("^".equals(operator)) {
                return 8;
            }
            throw new IllegalArgumentException("unsupported binary operator");
        }
        if (node instanceof FormulaAst.Unary) {
            return 7;
        }
        return 9;
    }
 
    private static String escapeText(String value) {
        StringBuilder escaped = new StringBuilder(value.length() + 16);
        for (int i = 0; i < value.length(); i++) {
            char current = value.charAt(i);
            switch (current) {
                case '\\':
                    escaped.append("\\textbackslash{}");
                    break;
                case '{':
                    escaped.append("\\{");
                    break;
                case '}':
                    escaped.append("\\}");
                    break;
                case '_':
                case '%':
                case '#':
                case '&':
                case '$':
                    escaped.append('\\').append(current);
                    break;
                case '<':
                    escaped.append("\\textless{}");
                    break;
                case '>':
                    escaped.append("\\textgreater{}");
                    break;
                case '^':
                    escaped.append("\\textasciicircum{}");
                    break;
                case '~':
                    escaped.append("\\textasciitilde{}");
                    break;
                case '\n':
                case '\r':
                case '\t':
                    escaped.append(' ');
                    break;
                default:
                    escaped.append(current);
            }
        }
        return escaped.toString();
    }
 
    private static String join(List<String> values) {
        StringBuilder joined = new StringBuilder();
        for (int i = 0; i < values.size(); i++) {
            if (i > 0) {
                joined.append(", ");
            }
            joined.append(values.get(i));
        }
        return joined.toString();
    }
}