001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.validation.tests; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005import static org.openstreetmap.josm.tools.I18n.trc; 006 007import java.util.ArrayDeque; 008import java.util.ArrayList; 009import java.util.Arrays; 010import java.util.Collection; 011import java.util.HashSet; 012import java.util.List; 013import java.util.Map; 014import java.util.Queue; 015import java.util.Set; 016import java.util.stream.Collectors; 017 018import org.openstreetmap.josm.data.algorithms.Tarjan; 019import org.openstreetmap.josm.data.osm.BBox; 020import org.openstreetmap.josm.data.osm.Node; 021import org.openstreetmap.josm.data.osm.NodeGraph; 022import org.openstreetmap.josm.data.osm.OsmPrimitive; 023import org.openstreetmap.josm.data.osm.QuadBuckets; 024import org.openstreetmap.josm.data.osm.Way; 025import org.openstreetmap.josm.data.osm.WaySegment; 026import org.openstreetmap.josm.data.preferences.sources.ValidatorPrefHelper; 027import org.openstreetmap.josm.data.validation.Severity; 028import org.openstreetmap.josm.data.validation.Test; 029import org.openstreetmap.josm.data.validation.TestError; 030import org.openstreetmap.josm.gui.progress.ProgressMonitor; 031import org.openstreetmap.josm.spi.preferences.Config; 032import org.openstreetmap.josm.tools.Pair; 033 034/** 035 * Test for detecting <a href="https://en.wikipedia.org/wiki/Cycle_(graph_theory)">cycles</a> in a directed graph, 036 * currently used for waterways only. The processed graph consists of ways labeled as waterway. 037 * 038 * @author gaben 039 * @since 19062 040 */ 041public class CycleDetector extends Test { 042 protected static final int CYCLE_DETECTED = 4200; 043 044 /** All waterways for cycle detection */ 045 private final Set<Way> usableWaterways = new HashSet<>(); 046 047 /** Already visited primitive unique IDs */ 048 private final Set<Long> visitedWays = new HashSet<>(); 049 050 /** Currently used directional waterways from the OSM wiki */ 051 private List<String> directionalWaterways; 052 053 protected static final String PREFIX = ValidatorPrefHelper.PREFIX + "." + CycleDetector.class.getSimpleName(); 054 055 /** 056 * Constructor 057 */ 058 public CycleDetector() { 059 super(tr("Cycle detector"), tr("Detects cycles in drainage systems.")); 060 } 061 062 @Override 063 public boolean isPrimitiveUsable(OsmPrimitive p) { 064 return p.isUsable() && (p instanceof Way) && (((Way) p).getNodesCount() > 1) && p.hasTag("waterway", directionalWaterways); 065 } 066 067 @Override 068 public void visit(Way w) { 069 if (isPrimitiveUsable(w)) 070 usableWaterways.add(w); 071 } 072 073 @Override 074 public void startTest(ProgressMonitor progressMonitor) { 075 super.startTest(progressMonitor); 076 directionalWaterways = Config.getPref().getList(PREFIX + ".directionalWaterways", 077 Arrays.asList("river", "stream", "tidal_channel", "drain", "ditch", "fish_pass")); 078 } 079 080 @Override 081 public void endTest() { 082 final QuadBuckets<Way> quadBuckets = new QuadBuckets<>(); 083 quadBuckets.addAll(usableWaterways); 084 085 for (Collection<Way> graph : getGraphs()) { 086 NodeGraph nodeGraph = NodeGraph.createDirectedGraphFromWays(graph); 087 Tarjan tarjan = new Tarjan(nodeGraph); 088 Collection<List<Node>> scc = tarjan.getSCC(); 089 090 // for partial selection, we need to manually add the rest of graph members to the lookup object 091 if (partialSelection) { 092 quadBuckets.addAll(graph); 093 } 094 095 for (List<Node> possibleCycle : scc) { 096 // there is a cycle in the graph if a strongly connected component has more than one node 097 if (possibleCycle.size() > 1) { 098 // build bbox to locate the issue 099 BBox bBox = new BBox(); 100 possibleCycle.forEach(node -> bBox.addPrimitive(node, 0)); 101 // find ways within this bbox 102 List<Way> waysWithinErrorBbox = quadBuckets.search(bBox); 103 List<Way> toReport = waysWithinErrorBbox.stream() 104 .filter(w -> possibleCycle.stream().filter(w.getNodes()::contains).count() > 1) 105 .collect(Collectors.toList()); 106 107 Map<Node, List<Node>> graphMap = tarjan.getGraphMap(); 108 errors.add( 109 TestError.builder(this, Severity.ERROR, CYCLE_DETECTED) 110 .message(trc("graph theory", "Cycle in directional waterway network")) 111 .primitives(toReport) 112 .highlightWaySegments(createSegments(graphMap, possibleCycle)) 113 .build() 114 ); 115 } 116 } 117 } 118 119 usableWaterways.clear(); 120 visitedWays.clear(); 121 super.endTest(); 122 } 123 124 /** 125 * Creates WaySegments from Nodes for the error highlight function. 126 * 127 * @param graphMap the complete graph data 128 * @param nodes nodes to build the way segments from 129 * @return WaySegments from the Nodes 130 */ 131 private static Collection<WaySegment> createSegments(Map<Node, List<Node>> graphMap, Collection<Node> nodes) { 132 List<Pair<Node, Node>> pairs = new ArrayList<>(); 133 134 // build new graph exclusively from SCC nodes 135 for (Node node : nodes) { 136 for (Node successor : graphMap.get(node)) { 137 // check for outbound nodes 138 if (nodes.contains(successor)) { 139 pairs.add(new Pair<>(node, successor)); 140 } 141 } 142 } 143 144 Collection<WaySegment> segments = new ArrayList<>(); 145 146 for (Pair<Node, Node> pair : pairs) { 147 final Node n = pair.a; 148 final Node m = pair.b; 149 150 if (n != null && m != null && !n.equals(m)) { 151 List<Way> intersect = new ArrayList<>(n.getParentWays()); 152 List<Way> mWays = m.getParentWays(); 153 intersect.retainAll(mWays); 154 155 for (Way w : intersect) { 156 if (isConsecutive(w, n, m)) { 157 segments.add(WaySegment.forNodePair(w, n, m)); 158 } 159 } 160 } 161 } 162 163 return segments; 164 } 165 166 /** 167 * Determines if the given nodes are consecutive part of the parent way. 168 * 169 * @param w parent way 170 * @param n the first node to look up in the way direction 171 * @param m the second, possibly consecutive node 172 * @return {@code true} if the nodes are consecutive order in the way direction 173 */ 174 private static boolean isConsecutive(Way w, Node n, Node m) { 175 for (int i = 0; i < w.getNodesCount() - 1; i++) { 176 if (w.getNode(i).equals(n) && w.getNode(i + 1).equals(m)) { 177 return true; 178 } 179 } 180 181 return false; 182 } 183 184 /** 185 * Returns all directional waterways which connect to at least one other usable way. 186 * 187 * @return all directional waterways which connect to at least one other usable way 188 */ 189 private Collection<Collection<Way>> getGraphs() { 190 // HashSet doesn't make a difference here 191 Collection<Collection<Way>> graphs = new ArrayList<>(); 192 193 for (Way waterway : usableWaterways) { 194 if (visitedWays.contains(waterway.getUniqueId())) { 195 continue; 196 } 197 Collection<Way> graph = buildGraph(waterway); 198 199 if (!graph.isEmpty()) { 200 graphs.add(graph); 201 } 202 } 203 204 return graphs; 205 } 206 207 /** 208 * Returns a collection of ways, which belongs to the same graph. 209 * 210 * @param way starting way to extend the graph from 211 * @return a collection of ways which belongs to the same graph 212 */ 213 private Collection<Way> buildGraph(Way way) { 214 final Set<Way> graph = new HashSet<>(); 215 Queue<Way> queue = new ArrayDeque<>(); 216 queue.offer(way); 217 218 while (!queue.isEmpty()) { 219 Way currentWay = queue.poll(); 220 visitedWays.add(currentWay.getUniqueId()); 221 222 for (Node node : currentWay.getNodes()) { 223 Collection<Way> referrers = node.referrers(Way.class) 224 .filter(this::isPrimitiveUsable) 225 .filter(candidate -> candidate != currentWay) 226 .collect(Collectors.toList()); 227 228 if (!referrers.isEmpty()) { 229 for (Way referrer : referrers) { 230 if (!visitedWays.contains(referrer.getUniqueId())) { 231 queue.offer(referrer); 232 visitedWays.add(referrer.getUniqueId()); 233 } 234 } 235 graph.addAll(referrers); 236 } 237 } 238 } 239 240 // case for single, non-connected waterways 241 if (graph.isEmpty()) { 242 graph.add(way); 243 } 244 245 return graph; 246 } 247}