001package org.clafer.ig;
002
003import java.util.ArrayList;
004import java.util.Comparator;
005import java.util.List;
006import java.util.function.UnaryOperator;
007import org.clafer.ig.ClaferModel.Clafer;
008
009/**
010 * The views of the solutions, claferIG's {@code SolutionView.hs}: a static
011 * model has instances, and a dynamic model has traces, whose states are
012 * instances. Both are sequences of snapshots, which the full view shows one by
013 * one, and the diff view shows as the changes from the previous snapshot.
014 */
015public final class SolutionView {
016
017    private SolutionView() {
018    }
019
020    /**
021     * The full view of the n-th solution: the instance, or each state of the
022     * trace.
023     */
024    public static String showSolution(int n, Solution solution) {
025        return switch (solution) {
026            case Solution.Instance i -> "=== Instance " + n + " Begin ===\n\n" + i.model()
027                    + "\n--- Instance " + n + " End ---\n\n";
028            case Solution.Trace t -> "=== Trace " + n + " Begin ===\n\n" + solutionText(t)
029                    + "--- Trace " + n + " End ---\n\n";
030        };
031    }
032
033    /**
034     * The text of a solution, as it is saved: the instance, or the states of
035     * the trace.
036     */
037    public static String solutionText(Solution solution) {
038        return switch (solution) {
039            case Solution.Instance i -> i.text() != null ? i.text() : i.model().toString();
040            case Solution.Trace t -> {
041                StringBuilder sb = new StringBuilder();
042                for (int s = 0; s < t.states().size(); s++) {
043                    sb.append(stateHeader(s)).append(t.states().get(s)).append('\n');
044                }
045                yield sb.append(loopBack(t.loopState())).toString();
046            }
047        };
048    }
049
050    /**
051     * The diff view of the n-th solution. The first state of a trace, whose
052     * clafers all appear (+), is shown in full, and each next state as its
053     * changes: the clafers that appear (+), with their children, and that
054     * disappear (-), and the values that change (~), each at its depth in the
055     * tree and with its least-partially-qualified name, given by the UID of its
056     * clafer. The states are compared by instance, which has the same name in
057     * every state. An instance is compared with the previous instance, if any,
058     * by its structure, since the names of the instances of separate solutions
059     * are unrelated.
060     *
061     * @param previous the previous solution, or null
062     */
063    public static String showSolutionDiff(UnaryOperator<String> names, int n, Solution previous, Solution solution) {
064        return switch (solution) {
065            case Solution.Instance i -> "=== Instance " + n + " Begin ===\n\n"
066                    + (previous instanceof Solution.Instance p
067                            ? showChanges(structureDiff(names, p.model(), i.model()))
068                            : appears(i.model()))
069                    + "\n--- Instance " + n + " End ---\n\n";
070            case Solution.Trace t -> {
071                StringBuilder sb = new StringBuilder("=== Trace " + n + " Begin ===\n\n");
072                List<ClaferModel> states = t.states();
073                for (int s = 0; s < states.size(); s++) {
074                    sb.append(stateHeader(s)).append(s == 0 ? appears(states.get(0))
075                            : showChanges(instanceDiff(names, states.get(s - 1), states.get(s)))).append('\n');
076                }
077                yield sb.append(loopBack(t.loopState())).append("--- Trace " + n + " End ---\n\n").toString();
078            }
079        };
080    }
081
082    /**
083     * A snapshot without a previous one, whose clafers all appear (+),
084     * aligned with the changes.
085     */
086    static String appears(ClaferModel model) {
087        StringBuilder sb = new StringBuilder();
088        for (String line : lines(model.toString())) {
089            sb.append("+ ").append(line).append('\n');
090        }
091        return sb.toString();
092    }
093
094    /**
095     * The Graphviz graph of a solution: an instance is a single node, and a
096     * trace is a node per state with an edge to the next state, and a dashed
097     * edge from the last state back to the loop state.
098     */
099    public static String solutionDot(Solution solution) {
100        List<String> labels = new ArrayList<>();
101        solution.models().forEach(m -> labels.add(m.toString()));
102        return graphWith(labels, solution);
103    }
104
105    /**
106     * The Graphviz graph of a solution in the diff view, which keeps large
107     * traces readable: the first state in full, and each next state as its
108     * changes from the previous one.
109     */
110    public static String solutionDiffDot(UnaryOperator<String> names, Solution solution) {
111        if (solution instanceof Solution.Trace t) {
112            List<String> labels = new ArrayList<>();
113            labels.add(appears(t.states().get(0)));
114            for (int s = 1; s < t.states().size(); s++) {
115                labels.add(showChanges(instanceDiff(names, t.states().get(s - 1), t.states().get(s))));
116            }
117            return graphWith(labels, solution);
118        }
119        return solutionDot(solution);
120    }
121
122    private static String graphWith(List<String> labels, Solution solution) {
123        // no minimum size, so that a box fits its text
124        StringBuilder sb = new StringBuilder("digraph solution {\n"
125                + "    node [shape=box, fontname=\"monospace\", width=0, height=0, margin=\"0.08,0.04\"];\n");
126        switch (solution) {
127            case Solution.Instance i -> sb.append(dotNode("instance", "", String.join("", labels)));
128            case Solution.Trace t -> {
129                sb.append("    start [shape=point, width=0.05];\n");
130                for (int s = 0; s < labels.size(); s++) {
131                    // the name of a state is outside its box, and it is also the tooltip of the box
132                    sb.append(dotNode(stateNode(s), ", xlabel=\"" + stateNode(s) + "\"", labels.get(s)));
133                }
134                int last = t.states().size() - 1;
135                sb.append("    start -> ").append(stateNode(0)).append(";\n");
136                for (int s = 1; s <= last; s++) {
137                    sb.append("    ").append(stateNode(s - 1)).append(" -> ").append(stateNode(s)).append(";\n");
138                }
139                sb.append("    ").append(stateNode(last)).append(" -> ").append(stateNode(t.loopState()))
140                        .append(" [style=dashed, label=\"loop\"];\n");
141            }
142        }
143        return sb.append("}\n").toString();
144    }
145
146    private static String stateNode(int i) {
147        return "S" + i;
148    }
149
150    /**
151     * A node with left-aligned lines, which keep the indentation of the tree,
152     * and further attributes.
153     */
154    private static String dotNode(String name, String attributes, String text) {
155        StringBuilder sb = new StringBuilder("    " + name + " [label=\"");
156        for (String l : lines(text)) {
157            if (l.isEmpty()) {
158                continue;
159            }
160            for (char ch : l.toCharArray()) {
161                switch (ch) {
162                    case '"' -> sb.append("\\\"");
163                    case '\\' -> sb.append("\\\\");
164                    default -> sb.append(ch);
165                }
166            }
167            sb.append("\\l");
168        }
169        return sb.append('"').append(attributes).append("];\n").toString();
170    }
171
172    static String stateHeader(int i) {
173        return "--- State " + i + " ---\n";
174    }
175
176    static String loopBack(int loopState) {
177        return "--- Loop back to state " + loopState + " ---\n\n";
178    }
179
180    /**
181     * Haskell's {@code lines}.
182     */
183    static List<String> lines(String s) {
184        List<String> out = new ArrayList<>();
185        int start = 0;
186        while (start < s.length()) {
187            int end = s.indexOf('\n', start);
188            if (end < 0) {
189                out.add(s.substring(start));
190                break;
191            }
192            out.add(s.substring(start, end));
193            start = end + 1;
194        }
195        return out;
196    }
197
198    /**
199     * A clafer of an instance: the names on the path from a top-level clafer
200     * to it, which identify it, its name to show and its value.
201     */
202    record Entry(List<String> path, String name, String value) {
203    }
204
205    private static final Comparator<Entry> EntryOrder = (a, b) -> {
206        for (int i = 0; i < Math.min(a.path().size(), b.path().size()); i++) {
207            int c = a.path().get(i).compareTo(b.path().get(i));
208            if (c != 0) {
209                return c;
210            }
211        }
212        int c = Integer.compare(a.path().size(), b.path().size());
213        if (c != 0) {
214            return c;
215        }
216        c = a.name().compareTo(b.name());
217        return c != 0 ? c : a.value().compareTo(b.value());
218    };
219
220    private static List<Entry> entries(UnaryOperator<String> names, ClaferModel model) {
221        List<Entry> out = new ArrayList<>();
222        model.topLevel().forEach(c -> entries(names, List.of(), c, out));
223        return out;
224    }
225
226    private static void entries(UnaryOperator<String> names, List<String> path, Clafer c, List<Entry> out) {
227        List<String> path2 = new ArrayList<>(path);
228        path2.add(c.id().name());
229        out.add(new Entry(List.copyOf(path2), displayName(names, c),
230                c.value() == null ? "" : ClaferModel.showValue(c.value())));
231        c.children().forEach(x -> entries(names, path2, x, out));
232    }
233
234    // the instance's name with the least-partially-qualified name of its clafer: green$2 : Light
235    // -> normal.green$2 : Light
236    private static String displayName(UnaryOperator<String> names, Clafer c) {
237        String lpq = names.apply(c.uid());
238        String last = lpq.substring(lpq.lastIndexOf('.') + 1);
239        return c.id().name().startsWith(last) ? lpq + c.id().name().substring(last.length()) : c.id().name();
240    }
241
242    private sealed interface Change {
243
244        Entry entry();
245    }
246
247    private record Added(Entry entry) implements Change {
248    }
249
250    private record Removed(Entry entry) implements Change {
251    }
252
253    private record Changed(Entry entry) implements Change {
254    }
255
256    /**
257     * The changes, each as in the tree of the instance, after its marker.
258     */
259    private static String showChanges(List<Change> changes) {
260        if (changes.isEmpty()) {
261            return "(no changes)\n";
262        }
263        StringBuilder sb = new StringBuilder();
264        for (Change ch : changes) {
265            char marker = switch (ch) {
266                case Added a -> '+';
267                case Removed r -> '-';
268                case Changed c -> '~';
269            };
270            Entry e = ch.entry();
271            sb.append(marker).append(' ').append(" ".repeat(2 * (e.path().size() - 1))).append(e.name())
272                    .append(e.value()).append('\n');
273        }
274        return sb.toString();
275    }
276
277    /**
278     * The changes from one state to the next: an instance is the same in both
279     * if it has the same path. A removed clafer is shown without its children,
280     * which disappear with it.
281     */
282    private static List<Change> instanceDiff(UnaryOperator<String> names, ClaferModel previous, ClaferModel current) {
283        List<Entry> before = entries(names, previous);
284        List<Entry> after = entries(names, current);
285        List<List<String>> previousPaths = before.stream().map(Entry::path).toList();
286        List<List<String>> currentPaths = after.stream().map(Entry::path).toList();
287        List<List<String>> removedPaths = previousPaths.stream().filter(p -> !currentPaths.contains(p)).toList();
288        List<Change> out = new ArrayList<>();
289        for (Entry e : before) {
290            if (!currentPaths.contains(e.path())
291                    && properPrefixes(e.path()).stream().noneMatch(removedPaths::contains)) {
292                out.add(new Removed(e));
293            }
294        }
295        for (Entry e : after) {
296            for (Entry p : before) {
297                if (p.path().equals(e.path())) {
298                    if (!p.value().equals(e.value())) {
299                        out.add(new Changed(e));
300                    }
301                    break;
302                }
303            }
304        }
305        for (Entry e : after) {
306            if (!previousPaths.contains(e.path())) {
307                out.add(new Added(e));
308            }
309        }
310        return out;
311    }
312
313    /**
314     * The changes from one instance to another of a static model, by their
315     * structure: the clafers without the numbers of their instances, with their
316     * values, as multisets.
317     */
318    private static List<Change> structureDiff(UnaryOperator<String> names, ClaferModel previous,
319            ClaferModel current) {
320        List<Entry> before = entries(names, previous).stream().map(SolutionView::anonymous).toList();
321        List<Entry> after = entries(names, current).stream().map(SolutionView::anonymous).toList();
322        List<Change> out = new ArrayList<>();
323        minus(before, after).stream().sorted(EntryOrder).forEach(e -> out.add(new Removed(e)));
324        minus(after, before).stream().sorted(EntryOrder).forEach(e -> out.add(new Added(e)));
325        return out;
326    }
327
328    // Haskell's \\: the first occurrence of each element of ys is removed from xs
329    private static List<Entry> minus(List<Entry> xs, List<Entry> ys) {
330        List<Entry> out = new ArrayList<>(xs);
331        for (Entry y : ys) {
332            out.remove(y);
333        }
334        return out;
335    }
336
337    private static Entry anonymous(Entry e) {
338        return new Entry(e.path().stream().map(SolutionView::dropOrdinal).toList(), dropOrdinal(e.name()),
339                dropOrdinal(e.value()));
340    }
341
342    // name$2 : Super -> name : Super
343    private static String dropOrdinal(String name) {
344        int i = name.indexOf('$');
345        if (i < 0) {
346            return name;
347        }
348        int j = i + 1;
349        while (j < name.length() && Character.isDigit(name.charAt(j))) {
350            j++;
351        }
352        return name.substring(0, i) + name.substring(j);
353    }
354
355    /**
356     * The paths of the ancestors, the outermost first.
357     */
358    private static List<List<String>> properPrefixes(List<String> xs) {
359        List<List<String>> out = new ArrayList<>();
360        for (int i = 1; i < xs.size(); i++) {
361            out.add(xs.subList(0, i));
362        }
363        return out;
364    }
365}