001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.data.validation.tests; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.awt.geom.Point2D; 007import java.util.ArrayList; 008import java.util.Collection; 009import java.util.EnumSet; 010import java.util.HashMap; 011import java.util.HashSet; 012import java.util.LinkedHashSet; 013import java.util.List; 014import java.util.Map; 015import java.util.Map.Entry; 016import java.util.Set; 017import java.util.stream.Collectors; 018 019import org.openstreetmap.josm.data.coor.ILatLon; 020import org.openstreetmap.josm.data.osm.Node; 021import org.openstreetmap.josm.data.osm.OsmPrimitive; 022import org.openstreetmap.josm.data.osm.Relation; 023import org.openstreetmap.josm.data.osm.RelationMember; 024import org.openstreetmap.josm.data.osm.Way; 025import org.openstreetmap.josm.data.osm.WaySegment; 026import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon; 027import org.openstreetmap.josm.data.osm.visitor.paint.relations.Multipolygon.JoinedWay; 028import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache; 029import org.openstreetmap.josm.data.preferences.sources.ValidatorPrefHelper; 030import org.openstreetmap.josm.data.validation.Severity; 031import org.openstreetmap.josm.data.validation.Test; 032import org.openstreetmap.josm.data.validation.TestError; 033import org.openstreetmap.josm.gui.progress.ProgressMonitor; 034import org.openstreetmap.josm.spi.preferences.Config; 035import org.openstreetmap.josm.tools.Geometry; 036import org.openstreetmap.josm.tools.Logging; 037import org.openstreetmap.josm.tools.Utils; 038 039/** 040 * Checks for 041 * <ul> 042 * <li>nodes in power lines/minor_lines that do not have a power=tower/pole/portal tag 043 * <li>nodes where the reference numbering not consistent 044 * <li>ways where are unusually long segments without line support feature 045 * <li>ways where the line type is possibly misused 046 * </ul> 047 * See #7812 and #20716 for discussions about this test. 048 */ 049public class PowerLines extends Test { 050 // Common strings 051 private static final String MINOR_LINE = "minor_line"; 052 private static final String BUILDING = "building"; 053 private static final String POWER = "power"; 054 055 // Test identifiers 056 protected static final int POWER_SUPPORT = 2501; 057 protected static final int POWER_CONNECTION = 2502; 058 protected static final int POWER_SEGMENT_LENGTH = 2503; 059 protected static final int POWER_LOCAL_REF_CONTINUITY = 2504; 060 protected static final int POWER_WAY_REF_CONTINUITY = 2505; 061 protected static final int POWER_LINE_TYPE = 2506; 062 063 protected static final String PREFIX = ValidatorPrefHelper.PREFIX + "." + PowerLines.class.getSimpleName(); 064 065 /** Values for {@code power} key interpreted as power lines */ 066 static final Set<String> POWER_LINE_TAGS = Set.of("line", MINOR_LINE); 067 /** Values for {@code power} key interpreted as power towers */ 068 static final Set<String> POWER_TOWER_TAGS = Set.of("catenary_mast", "pole", "portal", "tower"); 069 /** Values for {@code power} key interpreted as power stations */ 070 static final Set<String> POWER_STATION_TAGS = Set.of("generator", "plant", "substation"); 071 /** Values for {@code building} key interpreted as power stations */ 072 static final Set<String> BUILDING_STATION_TAGS = Set.of("transformer_tower"); 073 /** Values for {@code power} key interpreted as allowed power items */ 074 static final Set<String> POWER_INFRASTRUCTURE_TAGS = Set.of("compensator", "connection", "converter", 075 "generator", "insulator", "switch", "switchgear", "terminal", "transformer"); 076 077 /** Values for {@code power} key interpreted as power lines or cables */ 078 private static final Set<String> POWER_LINE_OR_CABLE_TAGS = Set.of("line", MINOR_LINE, "cable"); 079 080 private double hillyCompensation; 081 private double hillyThreshold; 082 private final Map<Node, Set<OsmPrimitive>> badConnections = new HashMap<>(); 083 private final Map<Node, Set<OsmPrimitive>> missingTags = new HashMap<>(); 084 private final Set<Way> wrongLineType = new HashSet<>(); 085 private final Set<WaySegment> missingNodes = new HashSet<>(); 086 private final Set<OsmPrimitive> refDiscontinuities = new HashSet<>(); 087 088 private final List<Set<Node>> segmentRefDiscontinuities = new ArrayList<>(); 089 private final List<OsmPrimitive> powerStations = new ArrayList<>(); 090 091 private final Collection<Way> foundPowerLines = new HashSet<>(); 092 /** All waterway segments, grouped by cells */ 093 private final Map<Point2D, List<WaySegment>> cellSegmentsWater = new HashMap<>(32); 094 095 /** 096 * Constructs a new {@code PowerLines} test. 097 */ 098 public PowerLines() { 099 super(tr("Power lines"), tr("Checks if power line missing a support node and " + 100 "for nodes in power lines that do not have a power=tower/pole tag")); 101 } 102 103 @Override 104 public void visit(Node n) { 105 if (!n.isConnectionNode() || n.referrers(Way.class).noneMatch(PowerLines::isPowerLineOrCable)) 106 return; 107 108 List<Way> unrelatedParents = n.referrers(Way.class).filter(w -> !isPowerLineOrCable(w) && !isRelatedToPower(w)) 109 .collect(Collectors.toList()); 110 if (!unrelatedParents.isEmpty()) { 111 Set<OsmPrimitive> set = badConnections.computeIfAbsent(n, k -> new HashSet<>()); 112 set.addAll(unrelatedParents); 113 } 114 } 115 116 @Override 117 public void visit(Way w) { 118 if (!isPrimitiveUsable(w)) return; 119 120 if (isPowerLine(w) && !w.hasKey("line") && !w.hasTag("location", "underground") && w.isUsable()) { 121 foundPowerLines.add(w); 122 } else if (w.isClosed() && isPowerStation(w)) { 123 powerStations.add(w); 124 } else if (concernsWaterArea(w)) { 125 this.addWaterWaySegments(w); 126 } 127 } 128 129 /** 130 * Add segments to the appropriate cells 131 * @param w The way to add segments from 132 */ 133 private void addWaterWaySegments(Way w) { 134 for (int i = 0; i < w.getNodesCount() - 1; i++) { 135 final WaySegment es1 = new WaySegment(w, i); 136 final Node first = es1.getFirstNode(); 137 final Node second = es1.getSecondNode(); 138 139 if (first.isLatLonKnown() && second.isLatLonKnown()) { 140 CrossingWays.getSegments(this.cellSegmentsWater, first, second).forEach(list -> list.add(es1)); 141 } 142 } 143 } 144 145 @Override 146 public void visit(Relation r) { 147 if (r.isMultipolygon() && isPowerStation(r)) { 148 powerStations.add(r); 149 } else if (concernsWaterArea(r)) { 150 r.getMemberPrimitives(Way.class).forEach(this::addWaterWaySegments); 151 } 152 } 153 154 @Override 155 public void startTest(ProgressMonitor progressMonitor) { 156 super.startTest(progressMonitor); 157 hillyCompensation = Config.getPref().getDouble(PREFIX + ".hilly_compensation", 0.2); 158 hillyThreshold = Config.getPref().getDouble(PREFIX + ".hilly_threshold", 4.0); 159 } 160 161 @Override 162 public void endTest() { 163 // Do the actual checks 164 for (Way w : this.foundPowerLines) { 165 powerlineChecks(w); 166 } 167 // Then return the errors 168 for (Entry<Node, Set<OsmPrimitive>> entry : missingTags.entrySet()) { 169 Node n = entry.getKey(); 170 if (!isInPowerStation(n)) { 171 errors.add(TestError.builder(this, Severity.WARNING, POWER_SUPPORT) 172 // the "missing tag" grouping can become broken if the MapCSS message get reworded 173 .message(tr("missing tag"), tr("node without power=*")) 174 .primitives(getAllPrimitives(entry)) 175 .highlight(n) 176 .build()); 177 } 178 } 179 180 for (Entry<Node, Set<OsmPrimitive>> entry : badConnections.entrySet()) { 181 errors.add(TestError.builder(this, Severity.WARNING, POWER_CONNECTION) 182 .message(tr("Node connects a power line or cable with an object " 183 + "which is not related to the power infrastructure")) 184 .primitives(getAllPrimitives(entry)) 185 .highlight(entry.getKey()) 186 .build()); 187 } 188 189 for (WaySegment s : missingNodes) { 190 errors.add(TestError.builder(this, Severity.WARNING, POWER_SEGMENT_LENGTH) 191 .message(tr("Possibly missing line support node within power line")) 192 .primitives(s.getFirstNode(), s.getSecondNode()) 193 .highlightWaySegments(Set.of(s)) 194 .build()); 195 } 196 197 for (OsmPrimitive p : refDiscontinuities) { 198 if (p instanceof Way) 199 errors.add(TestError.builder(this, Severity.WARNING, POWER_WAY_REF_CONTINUITY) 200 .message(tr("Mixed reference numbering")) 201 .primitives(p) 202 .build()); 203 } 204 205 final String discontinuityMsg = tr("Reference numbering don''t match majority of way''s nodes"); 206 207 for (OsmPrimitive p : refDiscontinuities) { 208 if (p instanceof Node) 209 errors.add(TestError.builder(this, Severity.WARNING, POWER_LOCAL_REF_CONTINUITY) 210 .message(discontinuityMsg) 211 .primitives(p) 212 .build()); 213 } 214 215 for (Set<Node> nodes : segmentRefDiscontinuities) { 216 errors.add(TestError.builder(this, Severity.WARNING, POWER_LOCAL_REF_CONTINUITY) 217 .message(discontinuityMsg) 218 .primitives(nodes) 219 .build()); 220 } 221 222 for (Way w : wrongLineType) { 223 errors.add(TestError.builder(this, Severity.WARNING, POWER_LINE_TYPE) 224 .message(tr("Possibly wrong power line type used")) 225 .primitives(w) 226 .build()); 227 } 228 229 super.endTest(); 230 } 231 232 /** 233 * Combine the node and the related objects. 234 * @param entry a map entry with a node and related objects 235 * @return set containing the node and the related objects 236 */ 237 private Collection<? extends OsmPrimitive> getAllPrimitives(Entry<Node, Set<OsmPrimitive>> entry) { 238 Set<OsmPrimitive> primitives = new LinkedHashSet<>(); 239 primitives.add(entry.getKey()); 240 primitives.addAll(entry.getValue()); 241 return primitives; 242 } 243 244 /** 245 * The base powerline checks 246 * @param w The powerline to check 247 */ 248 private void powerlineChecks(Way w) { 249 final int segmentCount = w.getNodesCount() - 1; 250 final double mean = w.getLength() / segmentCount; 251 final double stdDev = Utils.getStandardDeviation(w.getSegmentLengths(), mean); 252 final boolean isContinuesAsMinorLine = isContinuesAsMinorLine(w); 253 // the crossings only depend on the way, so look them up once instead of for every node 254 final Set<Way> crossingWaterWays = new HashSet<>(8); 255 final Set<ILatLon> crossingPositions = new HashSet<>(8); 256 findCrossings(this.cellSegmentsWater, w, crossingWaterWays, crossingPositions); 257 final boolean isCrossingWater = !crossingWaterWays.isEmpty(); 258 int poleCount = 0; 259 int towerCount = 0; 260 Node prevNode = w.firstNode(); 261 262 double baseThreshold = w.hasTag(POWER, "line") ? 1.6 : 1.8; 263 if (mean / stdDev < hillyThreshold) { 264 //compensate for possibly hilly areas where towers can't be put anywhere 265 baseThreshold += hillyCompensation; 266 } 267 268 for (Node n : w.getNodes()) { 269 270 /// handle power station line connections (e.g. power=line + line=*) 271 if (isConnectedToStationLine(n, w) || n.hasTag(POWER, "connection")) { 272 prevNode = n; 273 continue; // skip, it would be false positive 274 } 275 276 /// handle missing power line support tags (e.g. tower) 277 if (!isPowerTower(n) && !isPowerInfrastructure(n) && IN_DOWNLOADED_AREA.test(n) 278 && (!w.isFirstLastNode(n) || !isPowerStation(n))) { 279 Set<OsmPrimitive> set = missingTags.computeIfAbsent(n, k -> new HashSet<>()); 280 set.add(w); 281 } 282 283 /// handle missing nodes 284 double segmentLen = n.greatCircleDistance(prevNode); 285 if (isCrossingWater) { 286 double compensation = calculateIntersectingLen(prevNode, crossingPositions); 287 segmentLen -= compensation; 288 } 289 290 if (segmentCount > 4 291 && segmentLen > mean * baseThreshold 292 && !isPowerInfrastructure(n) 293 && IN_DOWNLOADED_AREA.test(n)) 294 missingNodes.add(WaySegment.forNodePair(w, prevNode, n)); 295 296 /// handle wrong line types 297 if (n.hasTag(POWER, "pole")) 298 poleCount++; 299 else if (n.hasTag(POWER, "tower", "portal")) 300 towerCount++; 301 302 prevNode = n; 303 } 304 305 /// handle ref=* numbering discontinuities 306 if (detectDiscontinuity(w, refDiscontinuities, segmentRefDiscontinuities)) 307 refDiscontinuities.add(w); 308 309 /// handle wrong line types 310 if (((poleCount > towerCount && w.hasTag(POWER, "line")) 311 || (poleCount < towerCount && w.hasTag(POWER, MINOR_LINE) 312 && !isCrossingWater 313 && !isContinuesAsMinorLine)) 314 && IN_DOWNLOADED_AREA.test(w)) 315 wrongLineType.add(w); 316 317 } 318 319 /** 320 * The summarized length (in metres) of a way where a power line hangs over a water area. 321 * @param ref Reference point 322 * @param crossingNodes Crossing nodes, unordered 323 * @return The summarized length (in metres) of a way where a power line hangs over a water area 324 */ 325 private static double calculateIntersectingLen(Node ref, Set<ILatLon> crossingNodes) { 326 double min = Double.POSITIVE_INFINITY; 327 double max = Double.NEGATIVE_INFINITY; 328 329 for (ILatLon coor : crossingNodes) { 330 331 if (ref != null && coor != null) { 332 double dist = ref.greatCircleDistance(coor); 333 334 if (dist < min) 335 min = dist; 336 if (dist > max) 337 max = dist; 338 } 339 } 340 return max - min; 341 } 342 343 /** 344 * Searches for way intersections, which intersect the {@code pair} attribute. 345 * @param ways collection of ways to search for crossings 346 * @param parent parent powerline way to find crossings for 347 * @param crossingWays found crossing ways 348 * @param crossingPositions collection of the crossing positions 349 * Inspired by {@code utilsplugin2/selection/NodeWayUtils.java#addWaysIntersectingWay()} 350 */ 351 private static void findCrossings(Map<Point2D, List<WaySegment>> ways, Way parent, Set<Way> crossingWays, 352 Set<ILatLon> crossingPositions) { 353 int nodesSize = parent.getNodesCount(); 354 for (int i = 0; i < nodesSize - 1; i++) { 355 final WaySegment es1 = new WaySegment(parent, i); 356 if (!es1.getFirstNode().isLatLonKnown() || !es1.getSecondNode().isLatLonKnown()) { 357 Logging.warn("PowerLines crossing ways test section skipped " + es1); 358 continue; 359 } 360 for (List<WaySegment> segments : CrossingWays.getSegments(ways, es1.getFirstNode(), es1.getSecondNode())) { 361 for (WaySegment segment : segments) { 362 if (es1.intersects(segment)) { 363 final ILatLon ll = Geometry.getSegmentSegmentIntersection(es1.getFirstNode(), es1.getSecondNode(), 364 segment.getFirstNode(), segment.getSecondNode()); 365 if (ll != null) { 366 crossingWays.add(es1.getWay()); 367 crossingPositions.add(ll); 368 } 369 } 370 } 371 } 372 } 373 } 374 375 /** Power line support features ref=* numbering direction. */ 376 private enum NumberingDirection { 377 /** No direction */ 378 NONE, 379 /** Numbering follows way direction */ 380 SAME, 381 /** Numbering goes opposite way direction */ 382 OPPOSITE 383 } 384 385 /** Helper class for reference numbering test. Used for storing continuous reference segment info. */ 386 private static class SegmentInfo { 387 /** Node index, follows way direction */ 388 private final int startIndex; 389 /** ref=* value at {@link SegmentInfo#startIndex} */ 390 private final int startRef; 391 /** Segment length */ 392 private final int length; 393 /** Segment direction */ 394 private final NumberingDirection direction; 395 396 SegmentInfo(int startIndex, int length, int ref, NumberingDirection direction) { 397 this.startIndex = startIndex; 398 this.length = length; 399 this.direction = direction; 400 401 if (direction == NumberingDirection.SAME) 402 this.startRef = ref - length; 403 else 404 this.startRef = ref + length; 405 406 if (length == 0 && direction != NumberingDirection.NONE) { 407 throw new IllegalArgumentException("When the segment length is zero, the direction should be NONE"); 408 } 409 } 410 411 @Override 412 public String toString() { 413 return String.format("SegmentInfo{startIndex=%d, startRef=%d, length=%d, direction=%s}", 414 startIndex, startRef, length, direction); 415 } 416 } 417 418 /** 419 * Detects ref=* numbering discontinuities in the given way. 420 * @param way checked way 421 * @param nRefDiscontinuities single node ref=* discontinuities 422 * @param sRefDiscontinuities continuous node ref=* discontinuities 423 * @return {@code true} if warning needs to be issued for the whole way 424 */ 425 static boolean detectDiscontinuity(Way way, Set<OsmPrimitive> nRefDiscontinuities, List<Set<Node>> sRefDiscontinuities) { 426 final RefChecker checker = new RefChecker(way); 427 final List<SegmentInfo> segments = checker.getSegments(); 428 final SegmentInfo referenceSegment = checker.getLongestSegment(); 429 430 if (referenceSegment == null) 431 return !segments.isEmpty(); 432 433 // collect disconnected ref segments which are not align up to the reference 434 for (SegmentInfo segment : segments) { 435 if (!isSegmentAlign(referenceSegment, segment)) { 436 if (referenceSegment.length == 0) 437 return true; 438 439 if (segment.length == 0) { 440 nRefDiscontinuities.add(way.getNode(segment.startIndex)); 441 } else { 442 Set<Node> nodeGroup = new HashSet<>(); 443 444 for (int i = segment.startIndex; i <= segment.startIndex + segment.length; i++) { 445 nodeGroup.add(way.getNode(i)); 446 } 447 sRefDiscontinuities.add(nodeGroup); 448 } 449 } 450 } 451 452 return false; 453 } 454 455 /** 456 * Checks if parameter segments align. The {@code reference} is expected to be at least as long as the {@code candidate}. 457 * @param reference Reference segment to check against 458 * @param candidate Candidate segment 459 * @return {@code true} if the two segments ref=* numbering align 460 */ 461 private static boolean isSegmentAlign(SegmentInfo reference, SegmentInfo candidate) { 462 if (reference.direction == NumberingDirection.NONE 463 || reference.direction == candidate.direction 464 || candidate.direction == NumberingDirection.NONE) 465 return Math.abs(candidate.startIndex - reference.startIndex) == Math.abs(candidate.startRef - reference.startRef); 466 return false; 467 } 468 469 /** 470 * Detects continuous reference numbering sequences. Ignores the first and last node because 471 * ways can be connected, and the connection nodes can have different numbering. 472 * <p> 473 * If the numbering switches in the middle of the way, this can also be seen as error, 474 * because line relations would require split ways. 475 */ 476 static class RefChecker { 477 private final List<SegmentInfo> segments = new ArrayList<>(); 478 private NumberingDirection direction = NumberingDirection.NONE; 479 private Integer startIndex; 480 private Integer previousRef; 481 482 RefChecker(final Way way) { 483 run(way); 484 } 485 486 private void run(Way way) { 487 final int wayLength = way.getNodesCount(); 488 489 // first and last node skipped 490 for (int i = 1; i < wayLength - 1; i++) { 491 Node n = way.getNode(i); 492 if (!isPowerTower(n)) { 493 continue; 494 } 495 maintain(parseRef(n.get("ref")), i); 496 } 497 498 // needed for creation of the last segment 499 maintain(null, wayLength - 1); 500 } 501 502 /** 503 * Maintains class variables and constructs a new segment when necessary. 504 * @param ref recognised ref=* number 505 * @param index node index in a {@link Way} 506 */ 507 private void maintain(Integer ref, int index) { 508 if (previousRef == null && ref != null) { 509 // ref change: null -> number 510 startIndex = index; 511 } else if (previousRef != null && ref == null) { 512 // ref change: number -> null 513 segments.add(new SegmentInfo(startIndex, index - 1 - startIndex, previousRef, direction)); 514 direction = NumberingDirection.NONE; // to fix directionality 515 } else if (previousRef != null) { 516 // ref change: number -> number 517 if (Math.abs(ref - previousRef) != 1) { 518 segments.add(new SegmentInfo(startIndex, index - 1 - startIndex, previousRef, direction)); 519 startIndex = index; 520 previousRef = ref; // to fix directionality 521 } 522 direction = detectDirection(ref, previousRef); 523 } 524 previousRef = ref; 525 } 526 527 /** 528 * Parses integer tag values. Later can be relatively easily extended or rewritten to handle 529 * complex references like 25/A, 25/B etc. 530 * @param value the value to be parsed 531 * @return parsed int or {@code null} in case of {@link NumberFormatException} 532 */ 533 private static Integer parseRef(String value) { 534 try { 535 return Integer.parseInt(value); 536 } catch (NumberFormatException ignore) { 537 Logging.trace("The " + RefChecker.class + " couldn't parse ref=" + value + ", consider rewriting the parser"); 538 return null; 539 } 540 } 541 542 /** 543 * Detects numbering direction. The parameters should follow way direction. 544 * @param ref last known reference value 545 * @param previousRef reference value before {@code ref} 546 * @return recognised direction 547 */ 548 private static NumberingDirection detectDirection(int ref, int previousRef) { 549 if (ref > previousRef) 550 return NumberingDirection.SAME; 551 else if (ref < previousRef) 552 return NumberingDirection.OPPOSITE; 553 return NumberingDirection.NONE; 554 } 555 556 /** 557 * Calculates the longest segment. 558 * @return the longest segment, or the lowest index if there are more than one with same length and direction, 559 * or {@code null} if there are more than one with same length and different direction 560 */ 561 SegmentInfo getLongestSegment() { 562 final Set<NumberingDirection> directions = EnumSet.noneOf(NumberingDirection.class); 563 int longestLength = -1; 564 int counter = 0; 565 SegmentInfo longest = null; 566 567 for (SegmentInfo segment : segments) { 568 if (segment.length > longestLength) { 569 longestLength = segment.length; 570 longest = segment; 571 counter = 0; 572 directions.clear(); 573 directions.add(segment.direction); 574 } else if (segment.length == longestLength) { 575 counter++; 576 directions.add(segment.direction); 577 } 578 } 579 580 // there are multiple segments with the same longest length and their directions don't match 581 if (counter > 0 && directions.size() > 1) 582 return null; 583 584 return longest; 585 } 586 587 /** 588 * Get the detected segments 589 * @return the detected segments 590 */ 591 List<SegmentInfo> getSegments() { 592 return segments; 593 } 594 } 595 596 private static boolean isRelatedToPower(Way way) { 597 if (way.hasTag(POWER) || way.hasTag(BUILDING)) 598 return true; 599 for (OsmPrimitive ref : way.getReferrers()) { 600 if (ref instanceof Relation) { 601 Relation r = (Relation) ref; 602 if (r.isMultipolygon() && (r.hasTag(POWER) || r.hasTag(BUILDING))) { 603 for (RelationMember rm : r.getMembers()) { 604 if (rm.getMember() == way) 605 return true; 606 } 607 } 608 } 609 } 610 return false; 611 } 612 613 /** 614 * Determines if the current node connected to a line which usually used inside power stations. 615 * @param n node to check 616 * @param w parent way of {@code n} 617 * @return {@code true} if {@code n} connected to power=line + line=* 618 */ 619 private static boolean isConnectedToStationLine(Node n, Way w) { 620 for (OsmPrimitive p : n.getReferrers()) { 621 if (p instanceof Way && !p.equals(w) && isPowerLine((Way) p) && p.hasKey("line")) 622 return true; 623 } 624 return false; 625 } 626 627 /** 628 * Checks if the way continues as a power=minor_line. 629 * @param way Way to be checked 630 * @return {@code true} if the way continues as a power=minor_line 631 */ 632 private static boolean isContinuesAsMinorLine(Way way) { 633 return way.firstNode().referrers(Way.class).filter(referrer -> !way.equals(referrer)).anyMatch(PowerLines::isMinorLine) || 634 way.lastNode().referrers(Way.class).filter(referrer -> !way.equals(referrer)).anyMatch(PowerLines::isMinorLine); 635 } 636 637 /** 638 * Checks if the given primitive denotes a power=minor_line. 639 * @param p primitive to be checked 640 * @return {@code true} if the given primitive denotes a power=minor_line 641 */ 642 private static boolean isMinorLine(OsmPrimitive p) { 643 return p.hasTag(POWER, MINOR_LINE); 644 } 645 646 /** 647 * Check if primitive has a tag that marks it as a water area or boundary of a water area. 648 * @param p the primitive 649 * @return {@code true} if primitive has a tag that marks it as a water area or boundary of a water area 650 */ 651 private static boolean concernsWaterArea(OsmPrimitive p) { 652 return p.hasTag("water", "river", "lake") || p.hasKey("waterway") || p.hasTag("natural", "coastline"); 653 } 654 655 /** 656 * Checks if the given node is inside a power station. 657 * @param n Node to be checked 658 * @return true if the given node is inside a power station 659 */ 660 protected final boolean isInPowerStation(Node n) { 661 for (OsmPrimitive station : powerStations) { 662 if (station instanceof Way) { 663 if (Geometry.nodeInsidePolygon(n, ((Way) station).getNodes())) { 664 return true; 665 } 666 } else if (station instanceof Relation) { 667 Multipolygon polygon = MultipolygonCache.getInstance().get((Relation) station); 668 if (polygon != null) { 669 for (JoinedWay outer : Multipolygon.joinWays(polygon.getOuterWays())) { 670 if (Geometry.nodeInsidePolygon(n, outer.getNodes())) { 671 return true; 672 } 673 } 674 } 675 } 676 } 677 return false; 678 } 679 680 /** 681 * Determines if the specified way denotes a power line. 682 * @param w The way to be tested 683 * @return {@code true} if power key is set and equal to line/minor_line 684 */ 685 protected static boolean isPowerLine(Way w) { 686 return isPowerIn(w, POWER_LINE_TAGS); 687 } 688 689 /** 690 * Determines if the specified way denotes a power line or cable. 691 * @param w The way to be tested 692 * @return {@code true} if power key is set and equal to line,minor_line or cable 693 */ 694 protected static boolean isPowerLineOrCable(Way w) { 695 return isPowerIn(w, POWER_LINE_OR_CABLE_TAGS); 696 } 697 698 /** 699 * Determines if the specified primitive denotes a power station. 700 * @param p The primitive to be tested 701 * @return {@code true} if power key is set and equal to generator/substation/plant 702 */ 703 protected static boolean isPowerStation(OsmPrimitive p) { 704 return isPowerIn(p, POWER_STATION_TAGS) || isBuildingIn(p, BUILDING_STATION_TAGS); 705 } 706 707 /** 708 * Determines if the specified node denotes a power support feature. 709 * @param n The node to be tested 710 * @return {@code true} if power key is set and equal to pole/tower/portal/catenary_mast 711 */ 712 protected static boolean isPowerTower(Node n) { 713 return isPowerIn(n, POWER_TOWER_TAGS); 714 } 715 716 /** 717 * Determines if the specified node denotes a power infrastructure allowed on a power line. 718 * @param n The node to be tested 719 * @return {@code true} if power key is set and equal to compensator/converter/generator/insulator 720 * /switch/switchgear/terminal/transformer 721 */ 722 protected static boolean isPowerInfrastructure(Node n) { 723 return isPowerIn(n, POWER_INFRASTRUCTURE_TAGS); 724 } 725 726 /** 727 * Helper function to check if power tag is a certain value. 728 * @param p The primitive to be tested 729 * @param values List of possible values 730 * @return {@code true} if power key is set and equal to possible values 731 */ 732 private static boolean isPowerIn(OsmPrimitive p, Collection<String> values) { 733 return p.hasTag(POWER, values); 734 } 735 736 /** 737 * Helper function to check if building tag is a certain value. 738 * @param p The primitive to be tested 739 * @param values List of possible values 740 * @return {@code true} if power key is set and equal to possible values 741 */ 742 private static boolean isBuildingIn(OsmPrimitive p, Collection<String> values) { 743 return p.hasTag(BUILDING, values); 744 } 745 746 @Override 747 public void clear() { 748 super.clear(); 749 badConnections.clear(); 750 cellSegmentsWater.clear(); 751 foundPowerLines.clear(); 752 missingNodes.clear(); 753 missingTags.clear(); 754 powerStations.clear(); 755 refDiscontinuities.clear(); 756 segmentRefDiscontinuities.clear(); 757 wrongLineType.clear(); 758 } 759}