|
| 1 | +package ai.timefold.solver.core.impl.domain.variable.declarative; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.IdentityHashMap; |
| 6 | +import java.util.LinkedHashMap; |
| 7 | +import java.util.List; |
| 8 | +import java.util.Map; |
| 9 | +import java.util.function.BiConsumer; |
| 10 | +import java.util.function.IntFunction; |
| 11 | +import java.util.stream.Collectors; |
| 12 | + |
| 13 | +import ai.timefold.solver.core.impl.util.DynamicIntArray; |
| 14 | +import ai.timefold.solver.core.preview.api.domain.metamodel.VariableMetaModel; |
| 15 | + |
| 16 | +import org.jspecify.annotations.NonNull; |
| 17 | +import org.jspecify.annotations.Nullable; |
| 18 | + |
| 19 | +public abstract sealed class AbstractVariableReferenceGraph<Solution_, ChangeSet_> implements VariableReferenceGraph |
| 20 | + permits DefaultVariableReferenceGraph, FixedVariableReferenceGraph { |
| 21 | + // These structures are immutable. |
| 22 | + protected final List<EntityVariablePair<Solution_>> instanceList; |
| 23 | + protected final Map<VariableMetaModel<?, ?, ?>, Map<Object, EntityVariablePair<Solution_>>> variableReferenceToInstanceMap; |
| 24 | + protected final Map<VariableMetaModel<?, ?, ?>, List<BiConsumer<AbstractVariableReferenceGraph<Solution_, ?>, Object>>> variableReferenceToBeforeProcessor; |
| 25 | + protected final Map<VariableMetaModel<?, ?, ?>, List<BiConsumer<AbstractVariableReferenceGraph<Solution_, ?>, Object>>> variableReferenceToAfterProcessor; |
| 26 | + |
| 27 | + // These structures are mutable. |
| 28 | + protected final DynamicIntArray[] edgeCount; |
| 29 | + protected final ChangeSet_ changeSet; |
| 30 | + protected final TopologicalOrderGraph graph; |
| 31 | + |
| 32 | + AbstractVariableReferenceGraph(VariableReferenceGraphBuilder<Solution_> outerGraph, |
| 33 | + IntFunction<TopologicalOrderGraph> graphCreator) { |
| 34 | + instanceList = List.copyOf(outerGraph.instanceList); |
| 35 | + var instanceCount = instanceList.size(); |
| 36 | + // Often the maps are a singleton; we improve performance by actually making it so. |
| 37 | + variableReferenceToInstanceMap = mapOfMapsDeepCopyOf(outerGraph.variableReferenceToInstanceMap); |
| 38 | + variableReferenceToBeforeProcessor = mapOfListsDeepCopyOf(outerGraph.variableReferenceToBeforeProcessor); |
| 39 | + variableReferenceToAfterProcessor = mapOfListsDeepCopyOf(outerGraph.variableReferenceToAfterProcessor); |
| 40 | + edgeCount = new DynamicIntArray[instanceCount]; |
| 41 | + for (int i = 0; i < instanceCount; i++) { |
| 42 | + edgeCount[i] = new DynamicIntArray(instanceCount); |
| 43 | + } |
| 44 | + graph = graphCreator.apply(instanceCount); |
| 45 | + graph.withNodeData(instanceList); |
| 46 | + |
| 47 | + var visited = Collections.newSetFromMap(new IdentityHashMap<>()); |
| 48 | + changeSet = createChangeSet(instanceCount); |
| 49 | + for (var instance : instanceList) { |
| 50 | + var entity = instance.entity(); |
| 51 | + if (visited.add(entity)) { |
| 52 | + for (var variableId : outerGraph.variableReferenceToAfterProcessor.keySet()) { |
| 53 | + afterVariableChanged(variableId, entity); |
| 54 | + } |
| 55 | + } |
| 56 | + } |
| 57 | + for (var fixedEdgeEntry : outerGraph.fixedEdges.entrySet()) { |
| 58 | + for (var toEdge : fixedEdgeEntry.getValue()) { |
| 59 | + addEdge(fixedEdgeEntry.getKey(), toEdge); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + protected abstract ChangeSet_ createChangeSet(int instanceCount); |
| 65 | + |
| 66 | + public @Nullable EntityVariablePair<Solution_> lookupOrNull(VariableMetaModel<?, ?, ?> variableId, Object entity) { |
| 67 | + var map = variableReferenceToInstanceMap.get(variableId); |
| 68 | + if (map == null) { |
| 69 | + return null; |
| 70 | + } |
| 71 | + return map.get(entity); |
| 72 | + } |
| 73 | + |
| 74 | + public void addEdge(@NonNull EntityVariablePair<Solution_> from, @NonNull EntityVariablePair<Solution_> to) { |
| 75 | + var fromNodeId = from.graphNodeId(); |
| 76 | + var toNodeId = to.graphNodeId(); |
| 77 | + if (fromNodeId == toNodeId) { |
| 78 | + return; |
| 79 | + } |
| 80 | + |
| 81 | + var count = edgeCount[fromNodeId].get(toNodeId); |
| 82 | + if (count == 0) { |
| 83 | + graph.addEdge(fromNodeId, toNodeId); |
| 84 | + } |
| 85 | + edgeCount[fromNodeId].set(toNodeId, count + 1); |
| 86 | + markChanged(to); |
| 87 | + } |
| 88 | + |
| 89 | + public void removeEdge(@NonNull EntityVariablePair<Solution_> from, @NonNull EntityVariablePair<Solution_> to) { |
| 90 | + var fromNodeId = from.graphNodeId(); |
| 91 | + var toNodeId = to.graphNodeId(); |
| 92 | + if (fromNodeId == toNodeId) { |
| 93 | + return; |
| 94 | + } |
| 95 | + |
| 96 | + var count = edgeCount[fromNodeId].get(toNodeId); |
| 97 | + if (count == 1) { |
| 98 | + graph.removeEdge(fromNodeId, toNodeId); |
| 99 | + } |
| 100 | + edgeCount[fromNodeId].set(toNodeId, count - 1); |
| 101 | + markChanged(to); |
| 102 | + } |
| 103 | + |
| 104 | + abstract void markChanged(EntityVariablePair<Solution_> changed); |
| 105 | + |
| 106 | + @Override |
| 107 | + public void beforeVariableChanged(VariableMetaModel<?, ?, ?> variableReference, Object entity) { |
| 108 | + if (variableReference.entity().type().isInstance(entity)) { |
| 109 | + processEntity(variableReferenceToBeforeProcessor.getOrDefault(variableReference, Collections.emptyList()), entity); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + @SuppressWarnings("ForLoopReplaceableByForEach") |
| 114 | + private void processEntity(List<BiConsumer<AbstractVariableReferenceGraph<Solution_, ?>, Object>> processorList, |
| 115 | + Object entity) { |
| 116 | + var processorCount = processorList.size(); |
| 117 | + // Avoid creation of iterators on the hot path. |
| 118 | + // The short-lived instances were observed to cause considerable GC pressure. |
| 119 | + for (int i = 0; i < processorCount; i++) { |
| 120 | + processorList.get(i).accept(this, entity); |
| 121 | + } |
| 122 | + } |
| 123 | + |
| 124 | + @Override |
| 125 | + public void afterVariableChanged(VariableMetaModel<?, ?, ?> variableReference, Object entity) { |
| 126 | + if (variableReference.entity().type().isInstance(entity)) { |
| 127 | + var node = lookupOrNull(variableReference, entity); |
| 128 | + if (node != null) { |
| 129 | + markChanged(node); |
| 130 | + } |
| 131 | + processEntity(variableReferenceToAfterProcessor.getOrDefault(variableReference, Collections.emptyList()), entity); |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + @Override |
| 136 | + public String toString() { |
| 137 | + var edgeList = new LinkedHashMap<EntityVariablePair<Solution_>, List<EntityVariablePair<Solution_>>>(); |
| 138 | + graph.forEachEdge((from, to) -> edgeList.computeIfAbsent(instanceList.get(from), k -> new ArrayList<>()) |
| 139 | + .add(instanceList.get(to))); |
| 140 | + return edgeList.entrySet() |
| 141 | + .stream() |
| 142 | + .map(e -> e.getKey() + "->" + e.getValue()) |
| 143 | + .collect(Collectors.joining( |
| 144 | + "," + System.lineSeparator() + " ", |
| 145 | + "{" + System.lineSeparator() + " ", |
| 146 | + "}")); |
| 147 | + |
| 148 | + } |
| 149 | + |
| 150 | + @SuppressWarnings("unchecked") |
| 151 | + static <K1, K2, V> Map<K1, Map<K2, V>> mapOfMapsDeepCopyOf(Map<K1, Map<K2, V>> map) { |
| 152 | + var entryArray = map.entrySet() |
| 153 | + .stream() |
| 154 | + .map(e -> Map.entry(e.getKey(), Map.copyOf(e.getValue()))) |
| 155 | + .toArray(Map.Entry[]::new); |
| 156 | + return Map.ofEntries(entryArray); |
| 157 | + } |
| 158 | + |
| 159 | + @SuppressWarnings("unchecked") |
| 160 | + static <K1, V> Map<K1, List<V>> mapOfListsDeepCopyOf(Map<K1, List<V>> map) { |
| 161 | + var entryArray = map.entrySet() |
| 162 | + .stream() |
| 163 | + .map(e -> Map.entry(e.getKey(), List.copyOf(e.getValue()))) |
| 164 | + .toArray(Map.Entry[]::new); |
| 165 | + return Map.ofEntries(entryArray); |
| 166 | + } |
| 167 | + |
| 168 | +} |
0 commit comments