001package org.clafer.ontology;
002
003import java.util.ArrayList;
004import java.util.Collection;
005import java.util.List;
006import java.util.Map;
007import java.util.Map.Entry;
008import java.util.Set;
009import java.util.stream.Collectors;
010import org.clafer.domain.Domain;
011import org.clafer.math.SetEnvironment;
012import org.clafer.math.SetTheory;
013
014/**
015 * An oracle for answering queries of is-a and has-a relationships.
016 *
017 * @author jimmy
018 */
019public class Oracle {
020
021    private final Relation<Concept> isA;
022    private final Relation<Concept> hasA;
023    private final Relation<Concept> aHas;
024
025    private final IdMap<Path> idMap = new IdMap<>();
026    private final SetTheory theory = new SetTheory();
027    private int tempId = -1;
028
029    public Oracle(
030            Relation<Concept> isA,
031            Relation<Concept> hasA,
032            ConstraintDatabase constraints,
033            List<ConstraintDatabase[]> disjunctions) {
034        this.isA = isA.transitiveClosureWithoutCycles();
035        this.hasA = this.isA.compose(hasA);
036        this.aHas = this.isA.compose(this.hasA.inverse());
037
038        compile(constraints, theory);
039        for (ConstraintDatabase[] disjunction : disjunctions) {
040            SetEnvironment[] ors = new SetEnvironment[disjunction.length];
041            for (int i = 0; i < disjunction.length; i++) {
042                ors[i] = SetTheory.or();
043                compile(disjunction[i], ors[i]);
044            }
045            theory.constructiveDisjunction(ors);
046        }
047
048        new ArrayList<>(idMap.keySet()).forEach(this::addPathConstraints);
049    }
050
051    private void compile(ConstraintDatabase database, SetEnvironment theory) {
052        for (Entry<Path, Domain> assignment : database.assignments.entrySet()) {
053            Path path = assignment.getKey();
054            Domain value = assignment.getValue();
055            for (Path groundPath : groundPaths(path)) {
056                theory.subset(idMap.getId(groundPath), value);
057            }
058        }
059
060        for (Entry<Path, Set<Path>> equality1 : database.equalities.entrySet()) {
061            Path path1 = equality1.getKey();
062            List<Path> groundPaths1 = groundPaths(path1);
063            int[] groundPaths1Id = idMap.getIds(groundPaths1);
064            for (Path path2 : equality1.getValue()) {
065                int[] groundPaths2Id = idMap.getIds(groundPaths(path2));
066                unionEqual(theory, groundPaths1Id, groundPaths2Id);
067            }
068        }
069
070        for (Entry<Path, Set<Path>> equality1 : database.localEqualities.entrySet()) {
071            Path path1 = equality1.getKey();
072            List<Path> groundPaths1 = groundPaths(path1);
073            Map<Concept, List<Path>> groundPathsMap1
074                    = groundPaths1.stream().collect(Collectors.groupingBy(Path::getContext));
075            for (Path path2 : equality1.getValue()) {
076                Map<Concept, List<Path>> groundPathsMap2
077                        = groundPaths(path2).stream().collect(Collectors.groupingBy(Path::getContext));
078                for (Concept concept : groundPathsMap1.keySet()) {
079                    List<Path> groundPaths2 = groundPathsMap2.get(concept);
080                    if (groundPaths2 == null) {
081                        // Nothing to equate in this context.
082                        continue;
083                    }
084                    int[] groundPaths1Id = idMap.getIds(groundPathsMap1.get(concept));
085                    int[] groundPaths2Id = idMap.getIds(groundPaths2);
086                    unionEqual(theory, groundPaths1Id, groundPaths2Id);
087                }
088            }
089        }
090
091    }
092
093    private void unionEqual(SetEnvironment theory, int[] union1, int[] union2) {
094        if (union1.length == 1) {
095            theory.union(union1[0], union2);
096        } else if (union2.length == 1) {
097            theory.union(union2[0], union1);
098        } else {
099            theory.union(tempId, union1);
100            theory.union(tempId, union2);
101            tempId--;
102        }
103    }
104
105    private void addPathConstraints(Path path) {
106        groundPaths(path).forEach(this::addGroundPathConstraints);
107    }
108
109    private void addGroundPathConstraints(Path groundPath) {
110        Path cur = groundPath;
111        while (cur.length() > 1) {
112            Path next = cur.dropPrefix(1);
113            theory.
114                    union(idMap.getId(next),
115                            aHas.from(next.getContext()).stream()
116                            .filter(x -> isGround(x, isA))
117                            .map(next::prepend).mapToInt(idMap::getId).toArray());
118            cur = next;
119        }
120    }
121
122    public boolean isA(Concept sub, Concept sup) {
123        return isA.has(sub, sup);
124    }
125
126    public boolean hasA(Concept parent, Concept child) {
127        return hasA.has(parent, child);
128    }
129
130    public Domain getAssignment(Concept... steps) {
131        return getAssignment(new Path(steps));
132    }
133
134    /**
135     * Returns the envelope of values the path must take.
136     *
137     * @param path
138     * @return the envelope of values the path must take, or null if unbounded
139     */
140    public Domain getAssignment(Path path) {
141        addPathConstraints(path);
142        theory.union(idMap.getId(path), idMap.getIds(groundPaths(path)));
143        theory.propagate();
144        return theory.getEnv(idMap.getId(path));
145    }
146
147    public void newAssignment(Path path, Domain value) {
148        theory.subset(idMap.getId(path), value);
149    }
150
151    public boolean propagate() {
152        return theory.propagate();
153    }
154
155    private ArrayList<Path> groundPaths(Path path) {
156        ArrayList<Path> out = new ArrayList<>();
157        groundPaths(path.getSteps(), 0, out);
158        return out;
159    }
160
161    private void groundPaths(Concept[] steps, int index, List<Path> out) {
162        if (index == steps.length) {
163            out.add(new Path(steps));
164        } else {
165            Collection<Concept> subs = isA.to(steps[index]);
166            for (Concept sub : subs) {
167                if (isGround(sub, isA)) {
168                    Concept[] alter = steps.clone();
169                    alter[index] = sub;
170                    groundPaths(alter, index + 1, out);
171                }
172            }
173        }
174    }
175
176    private static boolean isGround(Concept concept, Relation<Concept> isA) {
177        Set<Concept> subs = isA.to(concept);
178        return subs.size() == 1 && subs.contains(concept);
179    }
180}