Eclipse SUMO - Simulation of Urban MObility
Loading...
Searching...
No Matches
NBNodeCont.cpp
Go to the documentation of this file.
1/****************************************************************************/
2// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3// Copyright (C) 2001-2026 German Aerospace Center (DLR) and others.
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// https://www.eclipse.org/legal/epl-2.0/
7// This Source Code may also be made available under the following Secondary
8// Licenses when the conditions for such availability set forth in the Eclipse
9// Public License 2.0 are satisfied: GNU General Public License, version 2
10// or later which is available at
11// https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html
12// SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later
13/****************************************************************************/
24// Container for nodes during the netbuilding process
25/****************************************************************************/
26#include <config.h>
27
28#include <string>
29#include <map>
30#include <algorithm>
31#include <cmath>
33#include <utils/geom/Boundary.h>
46#include "NBHelpers.h"
47#include "NBAlgorithms.h"
48#include "NBDistrict.h"
49#include "NBEdgeCont.h"
51#include "NBOwnTLDef.h"
52#include "NBPTStop.h"
53#include "NBNodeCont.h"
54#include "NBPTStopCont.h"
55#include "NBPTLineCont.h"
56#include "NBParking.h"
57
58// ===========================================================================
59// Algorithm constants
60// ===========================================================================
61#define MAX_SLIPLANE_LENGTH 1000
62
63// ===========================================================================
64// Debug Flags
65// ===========================================================================
66
67//#define DEBUG_JOINJUNCTIONS
68//#define DEBUG_REDUCE
69//#define DEBUG_JOINJUNCTIONS_CONNECTIONS
70//#define DEBUG_GUESSSIGNALS
71#define DEBUGNODEID ""
72#define DEBUGNODEID2 ""
73//#define DEBUGNODEID "5548037023"
74#define DEBUGCOND(obj) ((obj) != 0 && ((obj)->getID() == DEBUGNODEID || (obj)->getID() == DEBUGNODEID2))
75//#define DEBUGCOND(obj) (true)
76
77
78// ===========================================================================
79// method definitions
80// ===========================================================================
84
85
86// ----------- Insertion/removal/retrieval of nodes
87bool
88NBNodeCont::insert(const std::string& id, const Position& position,
89 NBDistrict* district) {
90 NodeCont::iterator i = myNodes.find(id);
91 if (i != myNodes.end()) {
92 return false;
93 }
94 NBNode* node = new NBNode(id, position, district);
95 myNodes[id] = node;
96 const float pos[2] = {(float)position.x(), (float)position.y()};
97 myRTree.Insert(pos, pos, node);
98 return true;
99}
100
101
102bool
104 std::string id = node->getID();
105 NodeCont::iterator i = myNodes.find(id);
106 if (i != myNodes.end()) {
107 return false;
108 }
109 myNodes[id] = node;
110 const float pos[2] = {(float)node->getPosition().x(), (float)node->getPosition().y()};
111 myRTree.Insert(pos, pos, node);
112 return true;
113}
114
115
116NBNode*
117NBNodeCont::retrieve(const std::string& id) const {
118 NodeCont::const_iterator i = myNodes.find(id);
119 if (i == myNodes.end()) {
120 return nullptr;
121 }
122 return (*i).second;
123}
124
125
126std::vector<NBNode*>
127NBNodeCont::retrieveByPos(const Position& position, const double offset) const {
128 std::vector<NBNode*> result;
129 const double extOffset = offset + POSITION_EPS;
130 const float cmin[2] = {(float)(position.x() - extOffset), (float)(position.y() - extOffset)};
131 const float cmax[2] = {(float)(position.x() + extOffset), (float)(position.y() + extOffset)};
132 std::set<const Named*> into;
133 Named::StoringVisitor sv(into);
134 myRTree.Search(cmin, cmax, sv);
135 for (const Named* namedNode : into) {
136 NBNode* node = const_cast<NBNode*>(dynamic_cast<const NBNode*>(namedNode));
137 if (fabs(node->getPosition().x() - position.x()) <= offset
138 &&
139 fabs(node->getPosition().y() - position.y()) <= offset) {
140 result.push_back(node);
141 }
142 }
143 return result;
144}
145
146
147bool
149 if (extract(node)) {
150 delete node;
151 return true;
152 } else {
153 return false;
154 }
155}
156
157
158bool
160 NodeCont::iterator i = myNodes.find(node->getID());
161 if (i == myNodes.end()) {
162 return false;
163 }
164 myNodes.erase(i);
165 const float pos[2] = {(float)node->getPosition().x(), (float)node->getPosition().y()};
166 myRTree.Remove(pos, pos, node);
167 node->removeTrafficLights();
168 if (remember) {
169 myExtractedNodes[node->getID()] = node;
170 }
171 return true;
172}
173
174
175// ----------- Adapting the input
176int
178 int no = 0;
179 for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) {
180 no += (*i).second->removeSelfLoops(dc, ec, tc);
181 }
182 if (no != 0) {
183 WRITE_WARNING(toString(no) + " self-looping edge(s) removed.");
184 }
185 return no;
186}
187
188
189void
191 // magic values
192 const double distanceThreshold = 7.; // don't merge edges further apart
193 const double lengthThreshold = 0.10; // don't merge edges with higher relative length-difference
194
195 for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) {
196 // count the edges to other nodes outgoing from the current node
197 std::map<NBNode*, EdgeVector> connectionCount;
198 const EdgeVector& outgoing = (*i).second->getOutgoingEdges();
199 for (EdgeVector::const_iterator j = outgoing.begin(); j != outgoing.end(); j++) {
200 connectionCount[(*j)->getToNode()].push_back(*j);
201 }
202 // check whether more than a single edge connect another node and join them
203 std::map<NBNode*, EdgeVector>::iterator k;
204 for (k = connectionCount.begin(); k != connectionCount.end(); k++) {
205 // possibly we do not have anything to join...
206 if ((*k).second.size() < 2) {
207 continue;
208 }
209 // for the edges that seem to be a single street,
210 // check whether the geometry is similar
211 const EdgeVector& ev = (*k).second;
212 const NBEdge* const first = ev.front();
213 EdgeVector::const_iterator jci; // join candidate iterator
214 for (jci = ev.begin() + 1; jci != ev.end(); ++jci) {
215 const double relativeLengthDifference = fabs(first->getLoadedLength() - (*jci)->getLoadedLength()) / first->getLoadedLength();
216 if ((!first->isNearEnough2BeJoined2(*jci, distanceThreshold)) ||
217 (relativeLengthDifference > lengthThreshold) ||
218 (fabs(first->getSpeed() - (*jci)->getSpeed()) >= 0.01) || // output accuracy
219 (first->getPermissions() != (*jci)->getPermissions())
220 ) {
221 break;
222 }
223 }
224 // @bug If there are 3 edges of which 2 can be joined, no joining will
225 // take place with the current implementation
226 if (jci == ev.end()) {
227 if (removeDuplicates) {
228 for (int ei = 1; ei < (int)ev.size(); ei++) {
229 ec.extract(dc, ev[ei], true);
230 }
231 } else {
232 ec.joinSameNodeConnectingEdges(dc, tlc, ev);
233 }
234 }
235 }
236 }
237}
238
239
240int
242 int numRemovedEdges = 0;
243 // Warn of isolated edges, i.e. a single edge with no connection to another edge
244 const std::vector<std::string>& edgeNames = ec.getAllNames();
245 for (std::vector<std::string>::const_iterator it = edgeNames.begin(); it != edgeNames.end(); ++it) {
246 // Test whether this node starts at a dead end, i.e. it has only one adjacent node
247 // to which an edge exists and from which an edge may come.
248 NBEdge* e = ec.retrieve(*it);
249 if (e == nullptr) {
250 continue;
251 }
252 NBNode* from = e->getFromNode();
253 const EdgeVector& outgoingEdges = from->getOutgoingEdges();
254 if (outgoingEdges.size() != 1) {
255 // At this node, several edges or no edge start; so, this node is no dead end.
256 continue;
257 }
258 const EdgeVector& incomingEdges = from->getIncomingEdges();
259 if (incomingEdges.size() > 1) {
260 // At this node, several edges end; so, this node is no dead end.
261 continue;
262 } else if (incomingEdges.size() == 1) {
263 NBNode* fromNodeOfIncomingEdge = incomingEdges[0]->getFromNode();
264 NBNode* toNodeOfOutgoingEdge = outgoingEdges[0]->getToNode();
265 if (fromNodeOfIncomingEdge != toNodeOfOutgoingEdge) {
266 // At this node, an edge ends which is not the inverse direction of
267 // the starting node.
268 continue;
269 }
270 }
271 // Now we know that the edge e starts a dead end.
272 // Next we test if the dead end is isolated, i.e. does not lead to a junction
273 bool hasJunction = false;
274 EdgeVector road;
275 NBEdge* eOld = nullptr;
276 NBNode* to;
277 NodeSet adjacentNodes;
278 do {
279 road.push_back(e);
280 eOld = e;
281 from = e->getFromNode();
282 to = e->getToNode();
283 const EdgeVector& outgoingEdgesOfToNode = to->getOutgoingEdges();
284 const EdgeVector& incomingEdgesOfToNode = to->getIncomingEdges();
285 adjacentNodes.clear();
286 for (EdgeVector::const_iterator itOfOutgoings = outgoingEdgesOfToNode.begin(); itOfOutgoings != outgoingEdgesOfToNode.end(); ++itOfOutgoings) {
287 if ((*itOfOutgoings)->getToNode() != from // The back path
288 && (*itOfOutgoings)->getToNode() != to // A loop / dummy edge
289 ) {
290 e = *itOfOutgoings; // Probably the next edge
291 }
292 adjacentNodes.insert((*itOfOutgoings)->getToNode());
293 }
294 for (EdgeVector::const_iterator itOfIncomings = incomingEdgesOfToNode.begin(); itOfIncomings != incomingEdgesOfToNode.end(); ++itOfIncomings) {
295 adjacentNodes.insert((*itOfIncomings)->getFromNode());
296 }
297 adjacentNodes.erase(to); // Omit loops
298 if (adjacentNodes.size() > 2) {
299 hasJunction = true;
300 }
301 } while (!hasJunction && eOld != e);
302 if (!hasJunction) {
303 std::string warningString;
304 for (EdgeVector::iterator roadIt = road.begin(); roadIt != road.end(); ++roadIt) {
305 if (roadIt == road.begin()) {
306 warningString += (*roadIt)->getID();
307 } else {
308 warningString += "," + (*roadIt)->getID();
309 }
310
311 NBNode* fromNode = (*roadIt)->getFromNode();
312 NBNode* toNode = (*roadIt)->getToNode();
313 ec.erase(dc, *roadIt);
314 numRemovedEdges++;
315 if (fromNode->getIncomingEdges().size() == 0 && fromNode->getOutgoingEdges().size() == 0) {
316 // Node is empty; can be removed
317 erase(fromNode);
318 }
319 if (toNode->getIncomingEdges().size() == 0 && toNode->getOutgoingEdges().size() == 0) {
320 // Node is empty; can be removed
321 erase(toNode);
322 }
323 }
324 WRITE_WARNINGF(TL("Removed a road without junctions: %."), warningString);
325 }
326 }
327 return numRemovedEdges;
328}
329
330
331int
332NBNodeCont::removeComponents(NBDistrictCont& dc, NBEdgeCont& ec, const int numKeep, bool hasPTStops) {
333 myRailComponents.clear();
334 std::vector<std::set<NBEdge*> > components;
335 // need to use ids here to have the same ordering on all platforms
336 std::set<std::string> edgesLeft;
337 for (std::map<std::string, NBEdge*>::const_iterator edgeIt = ec.begin(); edgeIt != ec.end(); ++edgeIt) {
338 edgesLeft.insert(edgeIt->first);
339 }
340 EdgeVector queue;
341 std::set<NBEdge*> toRemove;
342 int foundComponents = 0;
343 int numRemoved = 0;
344 while (!edgesLeft.empty()) {
345 queue.push_back(ec.getByID(*edgesLeft.begin()));
346 std::set<NBEdge*> component;
347 while (!queue.empty()) {
348 NBEdge* const e = queue.back();
349 queue.pop_back();
350 component.insert(e);
351 std::vector<EdgeVector> edgeLists;
352 edgeLists.push_back(e->getFromNode()->getOutgoingEdges());
353 edgeLists.push_back(e->getFromNode()->getIncomingEdges());
354 edgeLists.push_back(e->getToNode()->getOutgoingEdges());
355 edgeLists.push_back(e->getToNode()->getIncomingEdges());
356 for (std::vector<EdgeVector>::const_iterator listIt = edgeLists.begin(); listIt != edgeLists.end(); ++listIt) {
357 for (EdgeVector::const_iterator edgeIt = listIt->begin(); edgeIt != listIt->end(); ++edgeIt) {
358 std::set<std::string>::iterator leftIt = edgesLeft.find((*edgeIt)->getID());
359 if (leftIt != edgesLeft.end()) {
360 queue.push_back(*edgeIt);
361 edgesLeft.erase(leftIt);
362 }
363 }
364 }
365 }
366 foundComponents++;
367 std::vector<std::set<NBEdge*> >::iterator cIt;
368 for (cIt = components.begin(); cIt != components.end(); ++cIt) {
369 if (cIt->size() < component.size()) {
370 break;
371 }
372 }
373 components.insert(cIt, component);
374 if ((int)components.size() > numKeep) {
375 bool recheck = false;
376 if (hasPTStops) {
377 for (NBEdge* e : components.back()) {
378 SVCPermissions permissions = e->getPermissions();
379 if (isRailway(permissions) || isWaterway(permissions)) {
380 // recheck for connection to other components via access definitions
381 recheck = true;
382 break;
383 }
384 }
385 }
386 if (!recheck) {
387 toRemove.insert(components.back().begin(), components.back().end());
388 numRemoved++;
389 } else {
390 std::vector<std::string> edgeIDs;
391 for (NBEdge* e : components.back()) {
392 edgeIDs.push_back(e->getID());
393 }
394 myRailComponents.push_back(edgeIDs);
395 }
396 components.pop_back();
397 }
398 }
399 ec.removeRoundaboutEdges(toRemove);
400 for (NBEdge* e : toRemove) {
401 NBNode* const fromNode = e->getFromNode();
402 NBNode* const toNode = e->getToNode();
403 ec.erase(dc, e);
404 if (fromNode->getIncomingEdges().size() == 0 && fromNode->getOutgoingEdges().size() == 0) {
405 erase(fromNode);
406 }
407 if (toNode->getIncomingEdges().size() == 0 && toNode->getOutgoingEdges().size() == 0) {
408 erase(toNode);
409 }
410 }
411 if (foundComponents > 1) {
412 WRITE_MESSAGEF(TL("Found % components and removed % (% edges)."), toString(foundComponents), toString(numRemoved), toString(toRemove.size()));
413 }
414 return (int)toRemove.size();
415}
416
417
418int
420 std::set<std::string> stopEdges;
421 for (const auto& item : sc.getStops()) {
422 stopEdges.insert(item.second->getEdgeId());
423 }
424 int numRemoved = 0;
425 EdgeSet toRemove;
426 for (auto& component : myRailComponents) {
427 bool keep = false;
428 for (const std::string& edgeID : component) {
429 if (stopEdges.count(edgeID) != 0) {
430 keep = true;
431 break;
432 }
433 }
434 if (!keep) {
435 numRemoved++;
436 for (const std::string& edgeID : component) {
437 NBEdge* e = ec.retrieve(edgeID);
438 if (e != nullptr) {
439 toRemove.insert(e);
440 }
441 }
442 }
443 }
444 ec.removeRoundaboutEdges(toRemove);
445 for (NBEdge* e : toRemove) {
446 NBNode* const fromNode = e->getFromNode();
447 NBNode* const toNode = e->getToNode();
448 ec.erase(dc, e);
449 if (fromNode->getIncomingEdges().size() == 0 && fromNode->getOutgoingEdges().size() == 0) {
450 erase(fromNode);
451 }
452 if (toNode->getIncomingEdges().size() == 0 && toNode->getOutgoingEdges().size() == 0) {
453 erase(toNode);
454 }
455 }
456 myRailComponents.clear();
457 if (numRemoved > 0) {
458 WRITE_MESSAGEF(TL("Removed % railway components (% edges)."), toString(numRemoved), toString(toRemove.size()));
459 }
460 return (int)toRemove.size();
461}
462
463
464int
467 NBPTLineCont& lc,
468 NBParkingCont& pc,
469 bool removeGeometryNodes) {
471 // load edges that shall not be modified
472 std::set<std::string> edges2keep;
473 if (removeGeometryNodes) {
474 if (oc.isSet("geometry.remove.keep-edges.input-file")) {
475 NBHelpers::loadEdgesFromFile(oc.getString("geometry.remove.keep-edges.input-file"), edges2keep);
476 }
477 if (oc.isSet("geometry.remove.keep-edges.explicit")) {
478 const std::vector<std::string> edges = oc.getStringVector("geometry.remove.keep-edges.explicit");
479 edges2keep.insert(edges.begin(), edges.end());
480 }
481 // no need to keep pt stop edges, they are remapped later
482 // no need to keep all pt route edges. They are validated again before writing
483 pc.addEdges2Keep(oc, edges2keep);
484 if (oc.exists("geometry.remove.keep-ptstops") && oc.getBool("geometry.remove.keep-ptstops")) {
485 sc.addEdges2Keep(oc, edges2keep);
486 }
487 }
488
489 std::map<NBEdge*, std::set<NBTrafficLightDefinition*> > tlsLookup;
490 for (auto it = ec.begin(); it != ec.end(); it++) {
491 NBEdge* e = it->second;
492 NBNode* to = e->getToNode();
493 if (to->isTLControlled()) {
494 tlsLookup[e] = to->getControllingTLS();
495 }
496 }
497 const bool outputRemoved = oc.getBool("output.removed-nodes");
498 std::vector<NBNode*> toRemove;
499 for (const auto& i : myNodes) {
500 NBNode* const current = i.second;
501 bool remove = false;
502 // check for completely empty nodes and check for nodes which are only geometry nodes and ask the node whether to join
503 if (current->getEdges().empty() || (removeGeometryNodes && mySplit.count(current) == 0 && current->checkIsRemovable())) {
504 remove = true;
505 // check whether any of the edges must be kept
506 for (NBEdge* const it_edge : current->getEdges()) {
507 if (edges2keep.find(it_edge->getID()) != edges2keep.end()) {
508 remove = false;
509 break;
510 }
511 }
512 }
513 // remove the node and join the geometries when wished
514 if (!remove) {
515 continue;
516 }
517 for (const std::pair<NBEdge*, NBEdge*>& j : current->getEdgesToJoin()) {
518 NBEdge* const begin = j.first;
519 NBEdge* const continuation = j.second;
520 begin->append(continuation);
521 continuation->getToNode()->replaceIncoming(continuation, begin, 0);
522 auto itTL = tlsLookup.find(continuation);
523 if (itTL != tlsLookup.end()) {
524 for (NBTrafficLightDefinition* tls : itTL->second) {
525 tls->replaceRemoved(continuation, -1, begin, -1, true);
526 }
527 tlsLookup[begin] = itTL->second;
528 }
529 sc.replaceEdge(continuation->getID(), { begin });
530 lc.replaceEdge(continuation->getID(), { begin });
531 ec.extract(dc, continuation, true);
532 if (outputRemoved) {
533 begin->updateRemovedNodes(current->getID());
534 }
535 }
536 toRemove.push_back(current);
537 }
538 // erase all
539 for (NBNode* n : toRemove) {
540 extract(n, true);
541 }
542 return (int)toRemove.size();
543}
544
545
546void
548 for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) {
549 (*i).second->avoidOverlap();
550 }
551}
552
553
554// ----------- (Helper) methods for joining nodes
555void
556NBNodeCont::generateNodeClusters(double maxDist, NodeClusters& into) const {
557 std::set<NBNode*> visited;
558 for (const auto& i : myNodes) {
559 if (visited.count(i.second) > 0) {
560 continue;
561 }
562 std::vector<NodeAndDist> toProc;
563 toProc.emplace_back(i.second, 0.);
564 NodeSet c;
565 while (!toProc.empty()) {
566 NBNode* const n = toProc.back().first;
567 const double dist = toProc.back().second;
568 toProc.pop_back();
569 if (visited.count(n) > 0) {
570 continue;
571 }
572 visited.insert(n);
573 bool pureRail = true;
574 bool railAndPeds = true;
575 for (NBEdge* e : n->getEdges()) {
576 if ((e->getPermissions() & ~(SVC_RAIL_CLASSES | SVC_PEDESTRIAN)) != 0) {
577 railAndPeds = false;
578 pureRail = false;
579 break;
580 }
581 if ((e->getPermissions() & ~(SVC_RAIL_CLASSES)) != 0) {
582 pureRail = false;
583 }
584 }
585 if (pureRail) {
586 // do not join pure rail nodes
587 continue;
588 }
589 c.insert(n);
590 for (NBEdge* e : n->getEdges()) {
591 NBNode* s = n->hasIncoming(e) ? e->getFromNode() : e->getToNode();
592 const double length = e->getLoadedLength();
593#ifdef DEBUG_JOINJUNCTIONS
594 if (DEBUGCOND(s)) {
595 std::cout << "generateNodeClusters: consider s=" << s->getID()
596 << " clusterNode=" << n->getID() << " edge=" << e->getID() << " dist=" << dist << " length=" << length << " with cluster " << joinNamedToString(c, ' ') << "\n";
597 }
598#endif
599 if (railAndPeds && n->getType() != SumoXMLNodeType::RAIL_CROSSING) {
600 bool railAndPeds2 = true;
601 for (NBEdge* e2 : n->getEdges()) {
602 if ((e2->getPermissions() & ~(SVC_RAIL_CLASSES | SVC_PEDESTRIAN)) != 0) {
603 railAndPeds2 = false;
604 break;
605 }
606 }
607 if (railAndPeds2 && s->getType() != SumoXMLNodeType::RAIL_CROSSING) {
608 // do not join rail/ped nodes unless at a rail crossing
609 // (neither nodes nor the traffic lights)
610 continue;
611 }
612 }
613 const bool bothCrossing = n->getType() == SumoXMLNodeType::RAIL_CROSSING && s->getType() == SumoXMLNodeType::RAIL_CROSSING;
614 const bool joinPedCrossings = bothCrossing && e->getPermissions() == SVC_PEDESTRIAN;
615 if ( // never join pedestrian stuff (unless at a rail crossing
616 !joinPedCrossings && (
617 e->getPermissions() == SVC_PEDESTRIAN
618 // only join edges for regular passenger traffic or edges that are extremely short
619 || (length > 3 * POSITION_EPS
620 && (e->getPermissions() & (SVC_PASSENGER | SVC_TRAM)) == 0
622#ifdef DEBUG_JOINJUNCTIONS
623 if (DEBUGCOND(s)) {
624 std::cout << " ignored s=" << s->getID() << " pedestrian edge=" << e->getID() << " cd=" << n->getPosition().distanceTo2D(s->getPosition()) << "\n";
625 }
626#endif
627 continue;
628 }
629 // never join rail_crossings with other node types unless the crossing is only for tram
632 const SVCPermissions railNoTram = (SVC_RAIL_CLASSES & ~SVC_TRAM);
633 bool foundRail = false;
634 NBNode* crossingNode = n->getType() == SumoXMLNodeType::RAIL_CROSSING ? n : s;
635 for (NBEdge* e2 : crossingNode->getIncomingEdges()) {
636 if ((e2->getPermissions() & railNoTram) != 0) {
637 foundRail = true;
638 break;
639 }
640 }
641 if (foundRail) {
642 continue;
643 }
644 }
645 // never join rail_crossings via a rail edge
646 if (bothCrossing && (e->getPermissions() & ~SVC_RAIL_CLASSES) == 0) {
647 continue;
648 }
649 if (visited.find(s) != visited.end()) {
650 continue;
651 }
652 if (length + dist < maxDist) {
653 // don't add long "boring" appendages but always join the whole rail crossing or tls
654 const bool trueGeomLike = s->geometryLike();
655 if (trueGeomLike || geometryLikeForClass(s, SVC_VULNERABLE | SVC_DELIVERY)) {
656 const bool hasTLS = n->isTrafficLight() || s->isTrafficLight();
657 const double fullLength = e->getGeometry().length2D();
658 const double length2 = bothCrossing || hasTLS || trueGeomLike ? length : fullLength;
659 toProc.emplace_back(s, dist + length2);
660 } else {
661 toProc.emplace_back(s, 0.);
662 }
663 }
664 }
665 }
666 if (c.size() < 2) {
667 continue;
668 }
669#ifdef DEBUG_JOINJUNCTIONS
670 std::cout << " DEBUG: consider cluster " << joinNamedToString(c, ' ') << "\n";
671#endif
672 into.push_back(c);
673 }
674}
675
676
677bool
679 EdgeVector allowedIn;
680 EdgeVector allowedOut;
681 for (NBEdge* e : n->getIncomingEdges()) {
682 if ((e->getPermissions() & ~ignored) != 0) {
683 allowedIn.push_back(e);
684 }
685 }
686 for (NBEdge* e : n->getOutgoingEdges()) {
687 if ((e->getPermissions() & ~ignored) != 0) {
688 allowedOut.push_back(e);
689 }
690 }
691 if (allowedIn.size() > 0 && allowedOut.size() > 0) {
692 //std::cout << n->getID() << " geometryLikeForClass=" << n->geometryLike(allowedIn, allowedOut) << " in=" << toString(allowedIn) << " out=" << toString(allowedOut) << "\n";
693 return n->geometryLike(allowedIn, allowedOut);
694 }
695 return true;
696}
697
698
699void
700NBNodeCont::addJoinExclusion(const std::vector<std::string>& ids) {
701 for (const std::string& nodeID : ids) {
702 // error handling has to take place here since joinExclusions could be
703 // loaded from multiple files / command line
704 if (myJoined.count(nodeID) > 0) {
705 WRITE_WARNINGF(TL("Ignoring join exclusion for junction '%' since it already occurred in a list of nodes to be joined."), nodeID);
706 } else {
707 myJoinExclusions.insert(nodeID);
708 }
709 }
710}
711
712
713std::string
714NBNodeCont::createUnusedID(const std::string& base, const std::string& sep) {
715 std::string result = base;
716 int i = 0;
717 while (myNodes.find(result) != myNodes.end()) {
718 result = base + sep + toString(i++);
719 }
720 return result;
721}
722
723
724std::string
725NBNodeCont::createClusterId(const std::set<std::string>& cluster, const std::string& prefix) {
726 int maxIds = OptionsCont::getOptions().getInt("max-join-ids");
727 if (maxIds <= 0) {
728 maxIds = (int)cluster.size();
729 }
730 if ((int)cluster.size() > maxIds) {
731 auto clusterIt = cluster.begin();
732 std::string result = prefix + *clusterIt;
733 for (int i = 1; i < maxIds; i++) {
734 ++clusterIt;
735 result += "_" + *clusterIt;
736 }
737 return result + "_#" + toString((int)cluster.size() - maxIds) + "more";
738 }
739 return prefix + joinToString(cluster, "_");
740}
741
742
743void
744NBNodeCont::addCluster2Join(const std::set<std::string>& cluster, NBNode* node, const bool resetConnections) {
745 // error handling has to take place here since joins could be loaded from multiple files
746 JoinCluster join{{}, node, resetConnections};
747 for (std::string nodeID : cluster) {
748 if (myJoinExclusions.count(nodeID) > 0) {
749 WRITE_WARNINGF(TL("Ignoring join-cluster because junction '%' was already excluded from joining."), nodeID);
750 return;
751 } else if (myJoined.count(nodeID) > 0) {
752 WRITE_WARNINGF(TL("Ignoring join-cluster because junction '%' already occurred in another join-cluster."), nodeID);
753 return;
754 } else {
755 if (retrieve(nodeID) != nullptr) {
756 join.cluster.insert(nodeID);
757 } else {
758 WRITE_ERRORF(TL("Unknown junction '%' in join-cluster."), nodeID);
759 }
760 }
761 }
762 if (join.cluster.size() > 1) {
763 myJoined.insert(join.cluster.begin(), join.cluster.end());
764 myClusters2Join.emplace_back(join);
765 } else {
766 WRITE_WARNINGF(TL("Ignoring join-cluster '%' because it has size '%'."), node->getID(), join.cluster.size());
767 }
768}
769
770
771int
773 int numJoined = 0;
774 for (JoinCluster& item : myClusters2Join) {
775 // verify loaded cluster
776 NodeSet cluster;
777 for (std::string nodeID : item.cluster) {
778 NBNode* node = retrieve(nodeID);
779 if (node == nullptr) {
780 WRITE_ERRORF(TL("unknown junction '%' while joining."), nodeID);
781 } else {
782 cluster.insert(node);
783 }
784 }
785 if (cluster.size() > 1) {
786 joinNodeCluster(cluster, dc, ec, tlc, item.node, item.resetConnections);
787 numJoined++;
788 myJoinExclusions.insert(item.node->getID());
789 }
790 }
791 myClusters2Join.clear(); // make save for recompute
792 return numJoined;
793}
794
795
796int
798#ifdef DEBUG_JOINJUNCTIONS
799 std::cout << "joinJunctions...\n";
800#endif
801 NodeClusters cands;
802 NodeClusters clusters;
803 std::map<const NBNode*, std::vector<NBNode*> > ptStopEnds;
804 // check for stop edges within the cluster
805 for (const auto& stopIt : sc.getStops()) {
806 NBEdge* edge = ec.retrieve(stopIt.second->getEdgeId());
807 if (edge != nullptr) {
808 ptStopEnds[edge->getFromNode()].push_back(edge->getToNode());
809 }
810 }
811 generateNodeClusters(maxDist, cands);
812 for (NodeSet& cluster : cands) {
813#ifdef DEBUG_JOINJUNCTIONS
814 gDebugFlag1 = false;
815 for (NBNode* n : cluster) {
816 if (DEBUGCOND(n)) {
817 gDebugFlag1 = true;
818 }
819 }
820#endif
821 // remove join exclusions
822 for (NodeSet::iterator j = cluster.begin(); j != cluster.end();) {
823 NodeSet::iterator check = j;
824 ++j;
825 if (myJoinExclusions.count((*check)->getID()) > 0) {
826 cluster.erase(check);
827 }
828 }
829 std::string origCluster = joinNamedToString(cluster, ',');
830 // remove nodes that can be eliminated by geometry.remove
831 pruneClusterFringe(cluster, maxDist);
832 if (cluster.size() < 2) {
833 continue;
834 }
835 // remove nodes that are part of a bypass lane (typically for turning right without waiting at a traffic light)
836 pruneSlipLaneNodes(cluster, maxDist);
837 if (cluster.size() < 2) {
838 WRITE_WARNINGF(TL("Not joining junctions % (%)."), origCluster, "slip lane");
839 continue;
840 }
841 origCluster = joinNamedToString(cluster, ',');
842 NBNode* tryRemove = nullptr;
843 std::string reason;
844 std::string origReason;
845 // pruneLongEdges might remove too much, so we check first to have a fallback with the circles
846 bool feasible = feasibleCluster(cluster, ptStopEnds, maxDist, origReason, tryRemove);
847 if (feasible && ((int)cluster.size() - pruneLongEdges(cluster, maxDist, true) < 2)) {
848 origReason = "long edge";
849 feasible = false;
850 }
851 if (!feasible) {
852#ifdef DEBUG_JOINJUNCTIONS
853 if (gDebugFlag1) {
854 std::cout << " try to reduce to 4-circle nodes=" << joinNamedToString(cluster, ',') << "\n";
855 }
856#endif
857 if (reduceToCircle(cluster, 4, cluster, maxDist)) {
858 feasible = feasibleCluster(cluster, ptStopEnds, maxDist, reason, tryRemove);
859 if (feasible) {
860 WRITE_WARNINGF(TL("Reducing junction cluster % (%)."), origCluster, origReason);
861 }
862 }
863 }
864 if (!feasible) {
865#ifdef DEBUG_JOINJUNCTIONS
866 if (gDebugFlag1) {
867 std::cout << " try to reduce to 2-circle nodes=" << joinNamedToString(cluster, ',') << "\n";
868 }
869#endif
870 if (reduceToCircle(cluster, 2, cluster, maxDist)) {
871 feasible = feasibleCluster(cluster, ptStopEnds, maxDist, reason, tryRemove);
872 if (feasible) {
873 WRITE_WARNINGF(TL("Reducing junction cluster % (%)."), origCluster, origReason);
874 }
875 }
876 }
877 while (!feasible && tryRemove != nullptr) {
878 cluster.erase(tryRemove);
879 pruneClusterFringe(cluster, maxDist);
880 tryRemove = nullptr;
881 feasible = feasibleCluster(cluster, ptStopEnds, maxDist, reason, tryRemove);
882 if (feasible) {
883 WRITE_WARNINGF(TL("Reducing junction cluster % (%)."), origCluster, origReason);
884 }
885 }
886 if (cluster.size() < 2) {
887 WRITE_WARNINGF(TL("Not joining junctions % (%)."), origCluster, "after reduction");
888 continue;
889 }
890 // avoid removal of long edges (must have been added via an alternative path).
891 const int numPruned = pruneLongEdges(cluster, maxDist);
892 if (cluster.size() < 2) {
893 WRITE_WARNINGF(TL("Not joining junctions % (%)."), origCluster, "long edge");
894 continue;
895 }
896 // after pruning long edges we have to recheck
897 if (numPruned > 0) {
898 pruneClusterFringe(cluster, maxDist);
899 if (cluster.size() < 2) {
900 WRITE_WARNINGF(TL("Not joining junctions % (%)."), origCluster, "long edge");
901 continue;
902 }
903 pruneSlipLaneNodes(cluster, maxDist);
904 if (cluster.size() < 2) {
905 WRITE_WARNINGF(TL("Not joining junctions % (%)."), origCluster, "slip lane");
906 continue;
907 }
908 }
909 feasible = feasibleCluster(cluster, ptStopEnds, maxDist, origReason, tryRemove);
910 if (!feasible) {
911 WRITE_WARNINGF(TL("Not joining junctions % (%)."), origCluster, origReason);
912 continue;
913 }
914 // compute all connected components of this cluster
915 // (may be more than 1 if intermediate nodes were removed)
916 NodeClusters components;
917 for (NBNode* current : cluster) {
918 // merge all connected components into newComp
919 NodeSet newComp;
920 //std::cout << "checking connectivity for " << current->getID() << "\n";
921 newComp.insert(current);
922 for (NodeClusters::iterator it_comp = components.begin(); it_comp != components.end();) {
923 NodeClusters::iterator check = it_comp;
924 //std::cout << " connected with " << toString(*check) << "?\n";
925 bool connected = false;
926 for (NBNode* k : *check) {
927 if (current->getConnectionTo(k) != nullptr || k->getConnectionTo(current) != nullptr) {
928 //std::cout << "joining with connected component " << toString(*check) << "\n";
929 newComp.insert((*check).begin(), (*check).end());
930 it_comp = components.erase(check);
931 connected = true;
932 break;
933 }
934 }
935 if (!connected) {
936 it_comp++;
937 }
938 }
939 //std::cout << "adding new component " << toString(newComp) << "\n";
940 components.push_back(newComp);
941 }
942 for (NodeClusters::iterator it_comp = components.begin(); it_comp != components.end(); ++it_comp) {
943 if ((*it_comp).size() > 1) {
944 //std::cout << "adding cluster " << toString(*it_comp) << "\n";
945 clusters.push_back(*it_comp);
946 }
947 }
948#ifdef DEBUG_JOINJUNCTIONS
949 gDebugFlag1 = false;
950#endif
951 }
952 joinNodeClusters(clusters, dc, ec, tlc);
953 return (int)clusters.size();
954}
955
956
957int
959#ifdef DEBUG_JOINJUNCTIONS
960 std::cout << "joinSameJunctions...\n";
961#endif
962 std::set<NBNode*> checked;
963 NodeClusters clusters;
964 for (auto& item : myNodes) {
965 NBNode* n = item.second;
966 if (myJoinExclusions.count(item.first) > 0) {
967 continue;
968 }
969 std::vector<NBNode*> nearby = retrieveByPos(n->getPosition(), maxDist);
970 NodeSet cluster;
971 for (NBNode* n2 : nearby) {
972 if (myJoinExclusions.count(n2->getID()) == 0 && checked.count(n2) == 0) {
973 cluster.insert(n2);
974 }
975 }
976 if (cluster.size() > 1) {
977 checked.insert(cluster.begin(), cluster.end());
978 clusters.push_back(cluster);
979 }
980 }
981 joinNodeClusters(clusters, dc, ec, tlc, true);
982 return (int)clusters.size();
983}
984
985void
986NBNodeCont::pruneClusterFringe(NodeSet& cluster, double maxDist, bool remove2TLS) const {
987#ifdef DEBUG_JOINJUNCTIONS
988 if (gDebugFlag1) {
989 std::cout << "pruning cluster=" << joinNamedToString(cluster, ' ') << "\n";
990 }
991#endif
992 // iteratively remove the fringe
993 NodeSet geometryLikeTLS;
994 bool pruneFringe = true;
995 bool pruneNoisyFringe = false;
996 // collect nodes that shall be joined due to distance but are not connected
997 // to the cluster for passenger traffic
998 while (pruneFringe) {
999 pruneFringe = false;
1000 for (NodeSet::iterator j = cluster.begin(); j != cluster.end();) {
1001 NodeSet::iterator check = j;
1002 NBNode* n = *check;
1003 ++j;
1004
1005 // compute clusterDist for node (length of shortest edge which connects this node to the cluster)
1006 double clusterDist = std::numeric_limits<double>::max();
1007 bool touchingCluster = false;
1008 for (EdgeVector::const_iterator it_edge = n->getOutgoingEdges().begin(); it_edge != n->getOutgoingEdges().end(); ++it_edge) {
1009 NBNode* neighbor = (*it_edge)->getToNode();
1010 if (cluster.count(neighbor) != 0) {
1011 clusterDist = MIN2(clusterDist, (*it_edge)->getLoadedLength());
1012 touchingCluster |= n->getPosition().distanceTo2D(neighbor->getPosition()) <= SUMO_const_laneWidth;
1013 }
1014 }
1015 for (EdgeVector::const_iterator it_edge = n->getIncomingEdges().begin(); it_edge != n->getIncomingEdges().end(); ++it_edge) {
1016 NBNode* neighbor = (*it_edge)->getFromNode();
1017 if (cluster.count(neighbor) != 0) {
1018 clusterDist = MIN2(clusterDist, (*it_edge)->getLoadedLength());
1019 touchingCluster |= n->getPosition().distanceTo2D(neighbor->getPosition()) <= SUMO_const_laneWidth;
1020 }
1021 }
1022 // remove geometry-like nodes at fringe of the cluster
1023 // (they have 1 neighbor in the cluster and at most 1 neighbor outside the cluster)
1024 std::set<NBNode*> outsideNeighbors;
1025 std::set<NBNode*> clusterNeighbors;
1026 const double pedestrianFringeThreshold = 0.3;
1027 for (NBEdge* e : n->getEdges()) {
1028 NBNode* neighbor = e->getFromNode() == n ? e->getToNode() : e->getFromNode();
1029 if (cluster.count(neighbor) == 0) {
1030 if ((e->getPermissions() & SVC_PASSENGER) != 0
1031 || isRailway(e->getPermissions()) // join railway crossings
1032 || (clusterDist <= pedestrianFringeThreshold
1033 && (!pruneNoisyFringe
1034 || isForVulnerableModes(e->getPermissions())
1035 // permit joining small opposite merges
1036 || getDiameter(cluster) < maxDist
1037 || cluster.size() == 2))
1038 || touchingCluster) {
1039 outsideNeighbors.insert(neighbor);
1040 }
1041 } else {
1042 clusterNeighbors.insert(neighbor);
1043 }
1044 }
1045#ifdef DEBUG_JOINJUNCTIONS
1046 if (gDebugFlag1) std::cout << " check n=" << n->getID()
1047 << " clusterDist=" << clusterDist
1048 << " cd<th=" << (clusterDist <= pedestrianFringeThreshold)
1049 << " touching=" << touchingCluster
1050 << " out=" << joinNamedToString(outsideNeighbors, ',')
1051 << " in=" << joinNamedToString(clusterNeighbors, ',')
1052 << " dia=" << getDiameter(cluster)
1053 << "\n";
1054#endif
1055 if (clusterNeighbors.size() == 0
1056 || (outsideNeighbors.size() <= 1
1057 && clusterNeighbors.size() == 1
1058 && !(n->isTLControlled() /*|| n->hadSignal()*/))) {
1059 cluster.erase(check);
1060 pruneFringe = true; // other nodes could belong to the fringe now
1061#ifdef DEBUG_JOINJUNCTIONS
1062 if (gDebugFlag1) {
1063 std::cout << " pruned n=" << n->getID() << "\n";
1064 }
1065#endif
1066 } else if (outsideNeighbors.size() <= 1 && clusterNeighbors.size() == 1) {
1067 geometryLikeTLS.insert(n);
1068 }
1069 }
1070 if (!pruneFringe && !pruneNoisyFringe) {
1071 // run once more and prune more things (with a look at cluster size)
1072 pruneFringe = true;
1073 pruneNoisyFringe = true;
1074
1075 }
1076 }
1077 if (remove2TLS && geometryLikeTLS.size() == cluster.size()) {
1078 cluster.clear();
1079 }
1080}
1081
1082double
1084 double result = 0;
1085 for (const NBNode* n1 : cluster) {
1086 for (const NBNode* n2 : cluster) {
1087 result = MAX2(result, n1->getPosition().distanceTo2D(n2->getPosition()));
1088 }
1089 }
1090 return result;
1091}
1092
1093int
1094NBNodeCont::pruneLongEdges(NodeSet& cluster, double maxDist, const bool dryRun) {
1095 std::set<NBNode*> toRemove;
1096 int maxPassengerLanes = 0;
1097 for (NBNode* n : cluster) {
1098 for (NBEdge* edge : n->getEdges()) {
1099 maxPassengerLanes = MAX2(maxPassengerLanes, edge->getNumLanesThatAllow(SVC_PASSENGER));
1100 }
1101 }
1102 for (NBNode* n : cluster) {
1103 for (NBEdge* edge : n->getOutgoingEdges()) {
1104 // we must track the edge length across geometry like nodes
1105 // Also, intersections that are geometry-like
1106 // from the perspective of passenger traffic should be tracked across
1107 std::vector<NBNode*> passed;
1108 double length = 0;
1109 NBEdge* cur = edge;
1110 NBNode* to = edge->getToNode();
1111 while (cluster.count(to) != 0) {
1112 length += cur->getLoadedLength();
1113 bool goStraight = (std::find(passed.begin(), passed.end(), to) == passed.end()
1114 && (edge->getPermissions() & SVC_PASSENGER) != 0
1115 && to->geometryLike(
1118 passed.push_back(to);
1119 if (goStraight) {
1121 if (cur != nullptr) {
1122 to = cur->getToNode();
1123 } else {
1124 break;
1125 }
1126 } else {
1127 break;
1128 }
1129 }
1130 // allow higher threshold at larger junctions
1131 double longThreshold = maxDist + SUMO_const_laneWidth * MAX2(0, maxPassengerLanes - 1);
1132#ifdef DEBUG_JOINJUNCTIONS
1133 if (gDebugFlag1) {
1134 std::cout << "check edge length " << edge->getID() << " (" << length << ", passed=" << passed.size() << ", max=" << longThreshold << ")\n";
1135 }
1136#endif
1137 if (length > longThreshold) {
1138 // we found an edge that should not be removed. Maybe we can
1139 // still keep the start or end in the cluster
1140 // (keep the start if the end can be removed and vice versa)
1141 const bool keepStart = getClusterNeighbors(passed.back(), longThreshold, cluster).size() == 1;
1142 const bool keepEnd = !keepStart && getClusterNeighbors(n, longThreshold, cluster).size() == 1;
1143#ifdef DEBUG_JOINJUNCTIONS
1144 if (gDebugFlag1) {
1145 std::cout << "node=" << n->getID() << " long edge " << edge->getID() << " (" << length << ", passed=" << toString(passed) << ", max=" << longThreshold << ") keepStart=" << keepStart << " keepEnd=" << keepEnd << "\n";
1146 }
1147#endif
1148 if (!keepStart) {
1149 toRemove.insert(n);
1150 }
1151 toRemove.insert(passed.begin(), passed.end() - 1);
1152 if (!keepEnd) {
1153 toRemove.insert(passed.back());
1154 }
1155
1156 }
1157 }
1158 }
1159 if (!dryRun) {
1160 for (std::set<NBNode*>::iterator j = toRemove.begin(); j != toRemove.end(); ++j) {
1161 cluster.erase(*j);
1162 }
1163 }
1164 return (int)toRemove.size();
1165}
1166
1167
1168NodeSet
1169NBNodeCont::getClusterNeighbors(const NBNode* n, double longThreshold, NodeSet& cluster) {
1170 NodeSet result;
1171 for (NBEdge* e : n->getEdges()) {
1172 if (e->getLength() > longThreshold) {
1173 continue;
1174 }
1175 NBNode* neighbor = e->getFromNode() == n ? e->getToNode() : e->getFromNode();
1176 if (cluster.count(neighbor) != 0) {
1177 result.insert(neighbor);
1178 }
1179 }
1180 return result;
1181}
1182
1183
1184void
1185NBNodeCont::pruneSlipLaneNodes(NodeSet& cluster, double maxDist) const {
1186#ifdef DEBUG_JOINJUNCTIONS
1187 if (gDebugFlag1) {
1188 std::cout << "pruning slip-lanes at cluster=" << joinNamedToString(cluster, ' ') << "\n";
1189 }
1190#endif
1191 // fringe has already been removed
1192 if (cluster.size() <= 2) {
1193 return;
1194 }
1195 NodeSet toRemove;
1196 for (NBNode* n : cluster) {
1197 EdgeVector outgoing;
1198 double inAngle;
1199 // find slip lanes where the start is part of the cluster
1200 if (maybeSlipLaneStart(n, outgoing, inAngle)) {
1201 // potential slip lane start but we don't know which of the outgoing edges it is
1202#ifdef DEBUG_JOINJUNCTIONS
1203 if (gDebugFlag1) {
1204 std::cout << " candidate slip-lane start=" << n->getID() << " outgoing=" << toString(outgoing) << "\n";
1205 }
1206#endif
1207 for (NBEdge* contEdge : outgoing) {
1208 if ((contEdge->getPermissions() & SVC_PASSENGER) == 0) {
1209 continue;
1210 }
1211 double slipLength = contEdge->getLength();
1212 NBNode* cont = contEdge->getToNode();
1213 NodeSet cands;
1214 cands.insert(n);
1215 while (isSlipLaneContinuation(cont) && slipLength < MAX_SLIPLANE_LENGTH) {
1216 if (cands.count(cont) != 0) {
1217 break; // circle, should not happen
1218 }
1219 cands.insert(cont);
1220#ifdef DEBUG_JOINJUNCTIONS
1221 if (gDebugFlag1) {
1222 std::cout << " candidate slip-lane cont=" << cont->getID() << "\n";
1223 }
1224#endif
1225 NBEdge* next = cont->getOutgoingEdges().front();
1226 slipLength += next->getLength();
1227 cont = next->getToNode();
1228 }
1229#ifdef DEBUG_JOINJUNCTIONS
1230 if (gDebugFlag1) {
1231 std::cout << " candidate slip-lane end=" << cont->getID() << " slipLength=" << slipLength << "\n";
1232 }
1233#endif
1234 if (cont->getIncomingEdges().size() >= 2 && cont->getOutgoingEdges().size() == 1 &&
1235 // slip lanes are for turning so there needs to be a sufficient angle
1236 abs(NBHelpers::relAngle(inAngle, cont->getOutgoingEdges().front()->getAngleAtNode(cont))) > 45) {
1237 // check whether the other continuation at n is also connected to the sliplane end
1238 const NBEdge* const otherEdge = (contEdge == outgoing.front() ? outgoing.back() : outgoing.front());
1239 NodeSet visited;
1240 visited.insert(n);
1241 std::vector<NodeAndDist> toProc;
1242 toProc.push_back(std::make_pair(otherEdge->getToNode(), otherEdge->getLength()));
1243 bool found = false;
1244 while (!toProc.empty()) {
1245 NodeAndDist nodeAndDist = toProc.back();
1246 NBNode* cont2 = nodeAndDist.first;
1247 double dist = nodeAndDist.second;
1248#ifdef DEBUG_JOINJUNCTIONS
1249 if (gDebugFlag1) {
1250 std::cout << " search alternative cont2=" << cont2->getID() << " dist=" << dist << "\n";
1251 }
1252#endif
1253 toProc.pop_back();
1254 if (visited.find(cont2) != visited.end()) {
1255 continue;
1256 }
1257 visited.insert(cont2);
1258 if (cont2 == cont) {
1259 found = true;
1260 break;
1261 }
1262 for (NBEdge* e : cont2->getOutgoingEdges()) {
1263 const double dist2 = dist + e->getLength();
1264 if (dist2 < slipLength * 2 && (e->getPermissions() & SVC_PASSENGER) != 0) {
1265 toProc.push_back(std::make_pair(e->getToNode(), dist2));
1266 }
1267 }
1268 }
1269 if (found) {
1270 // found slip lane
1271 cands.insert(cont);
1272 toRemove.insert(cands.begin(), cands.end());
1273#ifdef DEBUG_JOINJUNCTIONS
1274 if (gDebugFlag1) {
1275 std::cout << " found slip-lane with nodes=" << joinNamedToString(cands, ' ') << "\n";
1276 }
1277#endif
1278 }
1279 }
1280 }
1281 }
1282
1283 EdgeVector incoming;
1284 double outAngle;
1285 // find slip lanes where the end is part of the cluster
1286 if (maybeSlipLaneEnd(n, incoming, outAngle)) {
1287 // potential slip lane end but we don't know which of the incoming edges it is
1288#ifdef DEBUG_JOINJUNCTIONS
1289 if (gDebugFlag1) {
1290 std::cout << " candidate slip-lane end=" << n->getID() << " incoming=" << toString(incoming) << "\n";
1291 }
1292#endif
1293 for (NBEdge* contEdge : incoming) {
1294 if ((contEdge->getPermissions() & SVC_PASSENGER) == 0) {
1295 continue;
1296 }
1297 double slipLength = contEdge->getLength();
1298 NBNode* cont = contEdge->getFromNode();
1299 NodeSet cands;
1300 cands.insert(n);
1301 while (isSlipLaneContinuation(cont) && slipLength < MAX_SLIPLANE_LENGTH) {
1302 if (cands.count(cont) != 0) {
1303 break; // circle, should not happen
1304 }
1305 cands.insert(cont);
1306#ifdef DEBUG_JOINJUNCTIONS
1307 if (gDebugFlag1) {
1308 std::cout << " candidate slip-lane cont=" << cont->getID() << "\n";
1309 }
1310#endif
1311 NBEdge* next = cont->getIncomingEdges().front();
1312 slipLength += next->getLength();
1313 cont = next->getFromNode();
1314 }
1315#ifdef DEBUG_JOINJUNCTIONS
1316 if (gDebugFlag1) {
1317 std::cout << " candidate slip-lane start=" << cont->getID() << " slipLength=" << slipLength << "\n";
1318 }
1319#endif
1320 if (cont->getOutgoingEdges().size() >= 2 && cont->getIncomingEdges().size() == 1 &&
1321 // slip lanes are for turning so there needs to be a sufficient angle
1322 abs(NBHelpers::relAngle(outAngle, cont->getIncomingEdges().front()->getAngleAtNode(cont))) > 45) {
1323 // check whether the other continuation at n is also connected to the sliplane end
1324 const NBEdge* const otherEdge = (contEdge == incoming.front() ? incoming.back() : incoming.front());
1325 NodeSet visited;
1326 visited.insert(n);
1327 std::vector<NodeAndDist> toProc;
1328 toProc.push_back(std::make_pair(otherEdge->getFromNode(), otherEdge->getLength()));
1329 bool found = false;
1330 while (!toProc.empty()) {
1331 NodeAndDist nodeAndDist = toProc.back();
1332 NBNode* cont2 = nodeAndDist.first;
1333 double dist = nodeAndDist.second;
1334#ifdef DEBUG_JOINJUNCTIONS
1335 if (gDebugFlag1) {
1336 std::cout << " search alternative cont2=" << cont2->getID() << " dist=" << dist << "\n";
1337 }
1338#endif
1339 toProc.pop_back();
1340 if (visited.find(cont2) != visited.end()) {
1341 continue;
1342 }
1343 visited.insert(cont2);
1344 if (cont2 == cont) {
1345 found = true;
1346 break;
1347 }
1348 for (NBEdge* e : cont2->getIncomingEdges()) {
1349 const double dist2 = dist + e->getLength();
1350 if (dist2 < slipLength * 2 && (e->getPermissions() & SVC_PASSENGER) != 0) {
1351 toProc.push_back(std::make_pair(e->getFromNode(), dist2));
1352 }
1353 }
1354 }
1355 if (found) {
1356 // found slip lane
1357 cands.insert(cont);
1358 toRemove.insert(cands.begin(), cands.end());
1359#ifdef DEBUG_JOINJUNCTIONS
1360 if (gDebugFlag1) {
1361 std::cout << " found slip-lane start with nodes=" << joinNamedToString(cands, ' ') << "\n";
1362 }
1363#endif
1364 }
1365 }
1366 }
1367 }
1368
1369
1370
1371 }
1372 int numRemoved = 0;
1373 for (NBNode* n : toRemove) {
1374 numRemoved += (int)cluster.erase(n);
1375 }
1376 if (numRemoved > 0) {
1377#ifdef DEBUG_JOINJUNCTIONS
1378 if (gDebugFlag1) {
1379 std::cout << " removed " << numRemoved << " nodes from cluster: " << joinNamedToString(toRemove, ' ') << "\n";
1380 }
1381#endif
1382 pruneClusterFringe(cluster, maxDist);
1383 }
1384}
1385
1386
1387bool
1389 return cont->getPassengerEdges(true).size() == 1 && cont->getPassengerEdges(false).size() == 1;
1390}
1391
1392
1393bool
1394NBNodeCont::maybeSlipLaneStart(const NBNode* n, EdgeVector& outgoing, double& inAngle) const {
1395 EdgeVector inPE = n->getPassengerEdges(true);
1396 EdgeVector outPE = n->getPassengerEdges(false);
1397 if (inPE.size() == 1 && outPE.size() == 2) {
1398 outgoing.insert(outgoing.begin(), outPE.begin(), outPE.end());
1399 inAngle = inPE.front()->getAngleAtNode(n);
1400 return true;
1401 } else if (inPE.size() >= 2 && outPE.size() == 3) {
1402 // check if the incoming edges are going in opposite directions and then
1403 // use the incoming edge that has 2 almost-straight outgoing edges
1404 const double inRelAngle = fabs(NBHelpers::relAngle(inPE.front()->getAngleAtNode(n), inPE.back()->getAngleAtNode(n)));
1405 //std::cout << "n=" << n->getID() << " inRelAngle=" << inRelAngle << "\n";
1406 if (inRelAngle < 135) {
1407 return false; // not opposite incoming
1408 }
1409 for (NBEdge* in : inPE) {
1410 EdgeVector straight;
1411 int numReverse = 0;
1412 for (NBEdge* out : outPE) {
1413 const double outRelAngle = fabs(NBHelpers::relAngle(in->getAngleAtNode(n), out->getAngleAtNode(n)));
1414 if (outRelAngle <= 45) {
1415 straight.push_back(out);
1416 } else if (outRelAngle >= 135) {
1417 numReverse++;
1418 }
1419 }
1420 if (straight.size() == 2 && numReverse == 1) {
1421 outgoing.insert(outgoing.begin(), straight.begin(), straight.end());
1422 inAngle = in->getAngleAtNode(n);
1423 return true;
1424 }
1425 }
1426 }
1427 return false;
1428}
1429
1430
1431bool
1432NBNodeCont::maybeSlipLaneEnd(const NBNode* n, EdgeVector& incoming, double& outAngle) const {
1433 EdgeVector inPE = n->getPassengerEdges(true);
1434 EdgeVector outPE = n->getPassengerEdges(false);
1435 if (inPE.size() == 2 && outPE.size() == 1) {
1436 incoming.insert(incoming.begin(), inPE.begin(), inPE.end());
1437 outAngle = outPE.front()->getAngleAtNode(n);
1438 return true;
1439 } else if (inPE.size() == 3 && outPE.size() >= 2) {
1440 // check if the outgoing edges are going in opposite directions and then
1441 // use the outgoing edge that has 2 almost-straight incoming edges
1442 const double outRelAngle = fabs(NBHelpers::relAngle(outPE.front()->getAngleAtNode(n), outPE.back()->getAngleAtNode(n)));
1443 //std::cout << "n=" << n->getID() << " outRelAngle=" << outRelAngle << "\n";
1444 if (outRelAngle < 135) {
1445 return false; // not opposite outgoing
1446 }
1447 for (NBEdge* out : outPE) {
1448 EdgeVector straight;
1449 int numReverse = 0;
1450 for (NBEdge* in : inPE) {
1451 const double inRelAngle = fabs(NBHelpers::relAngle(in->getAngleAtNode(n), out->getAngleAtNode(n)));
1452 if (inRelAngle <= 45) {
1453 straight.push_back(in);
1454 } else if (inRelAngle >= 135) {
1455 numReverse++;
1456 }
1457 }
1458 if (straight.size() == 2 && numReverse == 1) {
1459 incoming.insert(incoming.begin(), straight.begin(), straight.end());
1460 outAngle = out->getAngleAtNode(n);
1461 return true;
1462 }
1463 }
1464 }
1465 return false;
1466}
1467
1468bool
1469NBNodeCont::feasibleCluster(const NodeSet& cluster, const std::map<const NBNode*, std::vector<NBNode*> >& ptStopEnds,
1470 double maxDist, std::string& reason, NBNode*& tryRemove) const {
1471 // check for clusters which are to complex and probably won't work very well
1472 // we count the incoming edges of the final junction
1473 std::map<NBEdge*, double, ComparatorIdLess> finalIncomingAngles;
1474 std::map<NBEdge*, double, ComparatorIdLess> finalOutgoingAngles;
1475 for (NBNode* n : cluster) {
1476 for (EdgeVector::const_iterator it_edge = n->getIncomingEdges().begin(); it_edge != n->getIncomingEdges().end(); ++it_edge) {
1477 NBEdge* edge = *it_edge;
1478 if (cluster.count(edge->getFromNode()) == 0 && (edge->getPermissions() & SVC_PASSENGER) != 0) {
1479 // incoming edge, does not originate in the cluster
1480 finalIncomingAngles[edge] = edge->getAngleAtNode(edge->getToNode());
1481 }
1482 }
1483 for (EdgeVector::const_iterator it_edge = n->getOutgoingEdges().begin(); it_edge != n->getOutgoingEdges().end(); ++it_edge) {
1484 NBEdge* edge = *it_edge;
1485 if (cluster.count(edge->getToNode()) == 0 && (edge->getPermissions() & SVC_PASSENGER) != 0) {
1486 // outgoing edge, does not end in the cluster
1487 finalOutgoingAngles[edge] = edge->getAngleAtNode(edge->getFromNode());
1488 }
1489 }
1490
1491 }
1492#ifdef DEBUG_JOINJUNCTIONS
1493 for (NBNode* n : cluster) {
1494 if (DEBUGCOND(n)) {
1495 std::cout << "feasibleCluster c=" << joinNamedToString(cluster, ',')
1496 << "\n inAngles=" << joinNamedToString(finalIncomingAngles, ' ', ':')
1497 << "\n outAngles=" << joinNamedToString(finalOutgoingAngles, ' ', ':')
1498 << "\n";
1499 }
1500 }
1501#endif
1502 if (finalIncomingAngles.size() > 5) {
1503 reason = toString(finalIncomingAngles.size()) + " incoming edges";
1504 return false;
1505 }
1506 // check for incoming parallel edges
1507 const double PARALLEL_THRESHOLD_DIFF_NODE = OptionsCont::getOptions().getFloat("junctions.join.parallel-threshold");
1508 const double PARALLEL_THRESHOLD_SAME_NODE = PARALLEL_THRESHOLD_DIFF_NODE / 3;
1509 bool foundParallel = false;
1510 for (auto j = finalIncomingAngles.begin(); j != finalIncomingAngles.end() && !foundParallel; ++j) {
1511 auto k = j;
1512 for (++k; k != finalIncomingAngles.end() && !foundParallel; ++k) {
1513 const double angleDiff = fabs(j->second - k->second);
1514 if (angleDiff < PARALLEL_THRESHOLD_DIFF_NODE) {
1515 NBEdge* e1 = j->first;
1516 NBEdge* e2 = k->first;
1517 // for edge targeting the same node, permit a narrower angle
1518 const double edgeDist = e1->getLaneShape(0).back().distanceTo2D(e2->getLaneShape(0).back());
1519#ifdef DEBUG_JOINJUNCTIONS
1520 if (DEBUGCOND(e1->getToNode())) {
1521 std::cout << " angleDiff=" << angleDiff << " shapeDist=" << edgeDist << "\n";
1522 }
1523#endif
1524 if (angleDiff >= PARALLEL_THRESHOLD_SAME_NODE && (
1525 (e1->getToNode() == e2->getToNode()
1526 || (edgeDist < maxDist)))) {
1527 continue;
1528 }
1529 reason = "parallel incoming " + e1->getID() + "," + e2->getID();
1530 if (e1->getToNode() != e2->getToNode() && (int)cluster.size() > 2) {
1531 // removing one of the nodes and try again
1532 if (e1->getPriority() > e2->getPriority()
1534 tryRemove = e2->getToNode();
1535 } else {
1536 tryRemove = e1->getToNode();
1537 }
1538 }
1539 return false;
1540 }
1541 }
1542 }
1543 // check for outgoing parallel edges
1544 for (auto j = finalOutgoingAngles.begin(); j != finalOutgoingAngles.end() && !foundParallel; ++j) {
1545 auto k = j;
1546 for (++k; k != finalOutgoingAngles.end() && !foundParallel; ++k) {
1547 const double angleDiff = fabs(j->second - k->second);
1548 if (angleDiff < PARALLEL_THRESHOLD_DIFF_NODE) {
1549 NBEdge* e1 = j->first;
1550 NBEdge* e2 = k->first;
1551 // for edge leaving the same node, permit a narrower angle
1552 const double edgeDist = e1->getLaneShape(0).front().distanceTo2D(e2->getLaneShape(0).front());
1553#ifdef DEBUG_JOINJUNCTIONS
1554 if (DEBUGCOND(e1->getFromNode())) {
1555 std::cout << " angleDiff=" << angleDiff << " shapeDist=" << edgeDist << "\n";
1556 }
1557#endif
1558 if (angleDiff >= PARALLEL_THRESHOLD_SAME_NODE && (
1559 (e1->getFromNode() == e2->getFromNode()
1560 || (edgeDist < maxDist)))) {
1561 continue;
1562 }
1563 reason = "parallel outgoing " + e1->getID() + "," + e2->getID();
1564 if (e1->getFromNode() != e2->getFromNode() && (int)cluster.size() > 2) {
1565 // removing one of the nodes and try again
1566 if (e1->getPriority() > e2->getPriority()
1568 tryRemove = e2->getFromNode();
1569 } else {
1570 tryRemove = e1->getFromNode();
1571 }
1572 }
1573 return false;
1574 }
1575 }
1576 }
1577 // check for stop edges and tls within the cluster
1578 bool hasTLS = false;
1579 for (NBNode* n : cluster) {
1580 if (n->isTLControlled() || n->hadSignal()) {
1581 hasTLS = true;
1582 }
1583 const auto& stopEnds = ptStopEnds.find(n);
1584 if (stopEnds != ptStopEnds.end()) {
1585 for (NBNode* const to : stopEnds->second) {
1586 if (cluster.count(to) != 0) {
1587 reason = "it contains a pt stop edge";
1588 return false;
1589 }
1590 }
1591 }
1592 }
1593 // prevent removal of long edges unless there is weak circle or a traffic light
1594 if (cluster.size() > 2) {
1595 // find the nodes with the biggests physical distance between them
1596 double maxLength = -1;
1597 NBEdge* maxEdge = nullptr;
1598 for (NBNode* n1 : cluster) {
1599 for (NBNode* n2 : cluster) {
1600 NBEdge* e1 = n1->getConnectionTo(n2);
1601 NBEdge* e2 = n2->getConnectionTo(n1);
1602 if (e1 != nullptr && e1->getLoadedLength() > maxLength) {
1603 maxLength = e1->getLoadedLength();
1604 maxEdge = e1;
1605 }
1606 if (e2 != nullptr && e2->getLoadedLength() > maxLength) {
1607 maxLength = e2->getLoadedLength();
1608 maxEdge = e2;
1609 }
1610 }
1611 }
1612#ifdef DEBUG_JOINJUNCTIONS
1613 for (NBNode* n : cluster) {
1614 if (DEBUGCOND(n)) {
1615 std::cout << "feasible hasTLS=" << hasTLS << " maxLength=" << maxLength << " maxEdge=" << maxEdge->getID() << "\n";
1616 }
1617 }
1618#endif
1619 if (!hasTLS && maxLength > 5) {
1620 // find a weak circle within cluster that does not use maxEdge
1621 std::vector<NBNode*> toCheck;
1622 std::set<NBNode*> visited;
1623 toCheck.push_back(maxEdge->getToNode());
1624 bool foundCircle = false;
1625 while (!toCheck.empty()) {
1626 NBNode* n = toCheck.back();
1627 if (n == maxEdge->getFromNode()) {
1628 foundCircle = true;
1629 break;
1630 }
1631 toCheck.pop_back();
1632 visited.insert(n);
1633 for (NBEdge* e : n->getEdges()) {
1634 if (e != maxEdge) {
1635 NBNode* cand = e->getFromNode() == n ? e->getToNode() : e->getFromNode();
1636 if (visited.count(cand) == 0 && cluster.count(cand) != 0) {
1637 toCheck.push_back(cand);
1638 }
1639 }
1640 }
1641 }
1642 if (!foundCircle) {
1643 reason = "not compact (maxEdge=" + maxEdge->getID() + " length=" + toString(maxLength) + ")";
1644 return false;
1645 }
1646 }
1647 }
1648 // prevent joining of simple merging/spreading structures
1649 if (cluster.size() >= 2) {
1650 int entryNodes = 0;
1651 int exitNodes = 0;
1652 EdgeVector outsideIncoming;
1653 EdgeVector outsideOutgoing;
1654 int edgesWithin = 0;
1655 for (NBNode* n : cluster) {
1656 bool foundOutsideIncoming = false;
1657 for (NBEdge* e : n->getIncomingEdges()) {
1658 if (cluster.count(e->getFromNode()) == 0) {
1659 // edge entering from outside the cluster
1660 outsideIncoming.push_back(e);
1661 foundOutsideIncoming = true;
1662 } else {
1663 edgesWithin++;
1664 }
1665 }
1666 if (foundOutsideIncoming) {
1667 entryNodes++;
1668 }
1669 bool foundOutsideOutgoing = false;
1670 for (NBEdge* e : n->getOutgoingEdges()) {
1671 if (cluster.count(e->getToNode()) == 0) {
1672 // edge leaving cluster
1673 outsideOutgoing.push_back(e);
1674 foundOutsideOutgoing = true;
1675 }
1676 }
1677 if (foundOutsideOutgoing) {
1678 exitNodes++;
1679 }
1680 }
1681 if (!hasTLS) {
1682 if (entryNodes < 2) {
1683 reason = "only 1 entry node";
1684 return false;
1685 }
1686 if (exitNodes < 2) {
1687 reason = "only 1 exit node";
1688 return false;
1689 }
1690 if (cluster.size() == 2) {
1691 if (edgesWithin == 1 && outsideIncoming.size() < 3 && outsideOutgoing.size() < 3) {
1692 reason = "only 1 edge within and no cross-traffic";
1693 return false;
1694 }
1695 }
1696 }
1697 /*
1698 if (NBNode::geometryLike(outsideIncoming, outsideOutgoing) && hasTLS && OptionsCont::getOptions().getBool("tls.discard-simple")) {
1699 reason = "geometry-like simple tls";
1700 return false;
1701 }
1702 */
1703 }
1704 return true;
1705}
1706
1707
1708bool
1709NBNodeCont::reduceToCircle(NodeSet& cluster, int circleSize, NodeSet startNodes, double maxDist, std::vector<NBNode*> cands) const {
1710#ifdef DEBUG_REDUCE
1711 std::cout << "reduceToCircle cs=" << circleSize << " cands=" << toString(cands, ',') << " startNodes=" << joinNamedToString(startNodes, ',') << "\n";
1712#endif
1713 assert(circleSize >= 2);
1714 if ((int)cands.size() == circleSize) {
1715 if (cands.back()->getConnectionTo(cands.front()) != nullptr) {
1716 // cluster found
1717 NodeSet candCluster;
1718 candCluster.insert(cands.begin(), cands.end());
1719 pruneClusterFringe(candCluster, maxDist, true);
1720 bool feasible = (int)candCluster.size() == circleSize;
1721 if (feasible) {
1722 cluster.clear();
1723 cluster.insert(cands.begin(), cands.end());
1724 }
1725 return feasible;
1726 } else {
1727 return false;
1728 }
1729 }
1730 if ((int)cluster.size() <= circleSize || startNodes.size() == 0) {
1731 // no reduction possible
1732#ifdef DEBUG_REDUCE
1733 std::cout << " abort\n";
1734#endif
1735 return false;
1736 }
1737 if (cands.size() == 0) {
1738 // try to find a circle starting from another start node
1739 NBEdge* e = shortestEdge(cluster, startNodes, cands);
1740 if (e != nullptr) {
1741 cands.push_back(e->getFromNode());
1742 startNodes.erase(e->getFromNode());
1743 if (reduceToCircle(cluster, circleSize, startNodes, maxDist, cands)) {
1744 return true;
1745 } else {
1746 // try another start node
1747 return reduceToCircle(cluster, circleSize, startNodes, maxDist);
1748 }
1749 }
1750 } else {
1751 NodeSet singleStart;
1752 singleStart.insert(cands.back());
1753 NBEdge* e = shortestEdge(cluster, singleStart, cands);
1754 if (e != nullptr) {
1755 std::vector<NBNode*> cands2(cands);
1756 cands2.push_back(e->getToNode());
1757 if (reduceToCircle(cluster, circleSize, startNodes, maxDist, cands2)) {
1758 return true;
1759 }
1760 }
1761 }
1762#ifdef DEBUG_REDUCE
1763 std::cout << " abort2\n";
1764#endif
1765 return false;
1766}
1767
1768
1769NBEdge*
1770NBNodeCont::shortestEdge(const NodeSet& cluster, const NodeSet& startNodes, const std::vector<NBNode*>& exclude) const {
1771 double minDist = std::numeric_limits<double>::max();
1772 NBEdge* result = nullptr;
1773 for (NBNode* n : startNodes) {
1774 for (NBEdge* e : n->getOutgoingEdges()) {
1775 NBNode* neigh = e->getToNode();
1776 if (cluster.count(neigh) != 0 && std::find(exclude.begin(), exclude.end(), neigh) == exclude.end()) {
1777 const double dist = n->getPosition().distanceTo2D(neigh->getPosition());
1778 //std::cout << " e=" << e->getID() << " dist=" << dist << " minD=" << minDist << "\n";
1779 if (dist < minDist) {
1780 minDist = dist;
1781 result = e;
1782 }
1783 }
1784 }
1785 }
1786 //std::cout << "closestNeighbor startNodes=" << toString(startNodes) << " result=" << Named::getIDSecure(result) << "\n";
1787 return result;
1788}
1789
1790void
1792 NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc, bool resetConnections) {
1793 for (NodeSet cluster : clusters) {
1794 joinNodeCluster(cluster, dc, ec, tlc, nullptr, resetConnections);
1795 }
1796}
1797
1798
1799void
1800NBNodeCont::joinNodeCluster(NodeSet cluster, NBDistrictCont& dc, NBEdgeCont& ec, NBTrafficLightLogicCont& tlc, NBNode* predefined, bool resetConnections) {
1801 const bool origNames = OptionsCont::getOptions().getBool("output.original-names");
1802 assert(cluster.size() > 1);
1803 std::string id = "cluster_";
1804 Position pos;
1805 bool setTL = false;
1808 // collect edges
1809 std::set<NBEdge*, ComparatorIdLess> allEdges;
1810 for (NBNode* n : cluster) {
1811 const EdgeVector& edges = n->getEdges();
1812 allEdges.insert(edges.begin(), edges.end());
1813 }
1814 // determine edges with are incoming or fully inside
1815 std::set<NBEdge*, ComparatorIdLess> clusterIncoming;
1816 std::set<NBEdge*, ComparatorIdLess> inside;
1817 for (NBEdge* e : allEdges) {
1818 if (cluster.count(e->getToNode()) > 0) {
1819 if (cluster.count(e->getFromNode()) > 0) {
1820 inside.insert(e);
1821 if (e->getSignalPosition() != Position::INVALID) {
1822 setTL = true;
1824 }
1825 } else {
1826 clusterIncoming.insert(e);
1827 }
1828 }
1829 }
1830#ifdef DEBUG_JOINJUNCTIONS_CONNECTIONS
1831 std::cout << "joining cluster " << joinNamedToString(cluster, ' ')
1832 << " resetConnections=" << resetConnections << "\n"
1833 << " incoming=" << joinNamedToString(clusterIncoming, ' ') << "\n"
1834 << " inside=" << joinNamedToString(inside, ' ') << "\n";
1835#endif
1836 analyzeCluster(cluster, id, pos, setTL, type, nodeType);
1837 NBNode* newNode = nullptr;
1838 if (predefined != nullptr) {
1839 newNode = predefined;
1840 } else {
1841 if (!insert(id, pos)) {
1842 // should not fail
1843 WRITE_WARNINGF(TL("Could not join junctions %."), id);
1844 return;
1845 }
1846 newNode = retrieve(id);
1847 }
1848 std::string tlID = id;
1849 if (predefined != nullptr) {
1850 if (predefined->getType() != SumoXMLNodeType::UNKNOWN) {
1851 nodeType = predefined->getType();
1852 setTL = predefined->isTLControlled();
1853 }
1854 Position ppos = predefined->getPosition();
1855 if (ppos.x() != Position::INVALID.x()) {
1856 pos.setx(ppos.x());
1857 }
1858 if (ppos.y() != Position::INVALID.y()) {
1859 pos.sety(ppos.y());
1860 }
1861 if (ppos.z() != Position::INVALID.z()) {
1862 pos.setz(ppos.z());
1863 }
1864 }
1865 newNode->reinit(pos, nodeType);
1866 if (origNames) {
1867 newNode->setParameter(SUMO_PARAM_ORIGID, joinNamedToString(cluster, ' '));
1868 }
1869 if (setTL && !newNode->isTLControlled()) {
1870 NBTrafficLightDefinition* tlDef = new NBOwnTLDef(tlID, newNode, 0, type);
1871 if (!tlc.insert(tlDef)) {
1872 // actually, nothing should fail here
1873 delete tlDef;
1874 throw ProcessError(TLF("Could not allocate tls '%'.", id));
1875 }
1876 }
1877
1878 // determine possible connectivity from outside edges
1879 std::map<NBEdge*, EdgeSet> reachable;
1880 std::map<std::pair<NBEdge*, NBEdge*>, SVCPermissions> conPermissions;
1881 EdgeSet specialPermissions;
1882 for (NBEdge* const e : clusterIncoming) {
1883 EdgeVector open;
1884 EdgeSet seen;
1885 open.push_back(e);
1886 while (open.size() > 0) {
1887 NBEdge* const cur = open.back();
1888 const SVCPermissions pCur = conPermissions.count({e, cur}) == 0 ? cur->getPermissions() : conPermissions[ {e, cur}];
1889#ifdef DEBUG_JOINJUNCTIONS_CONNECTIONS
1890 std::cout << "e=" << e->getID() << " cur=" << cur->getID() << " open=" << toString(open) << "\n";
1891 std::cout << "e=" << e->getID() << " cur=" << cur->getID() << " open=" << toString(open) << "\n";
1892#endif
1893 seen.insert(cur);
1894 open.pop_back();
1895 if (cluster.count(cur->getToNode()) == 0) {
1896 //std::cout << " continue\n";
1897 continue;
1898 }
1899 const auto& cons = cur->getConnections();
1900 if (cons.size() == 0 || ec.hasPostProcessConnection(cur->getID()) || cur->getStep() == NBEdge::EdgeBuildingStep::INIT) {
1901 // check permissions to determine reachability
1902 for (NBEdge* out : cur->getToNode()->getOutgoingEdges()) {
1903 if (allEdges.count(out) != 0) {
1904 const SVCPermissions p = pCur & out->getPermissions();
1905 if (seen.count(out) == 0 || (~conPermissions[ {e, out}] & p) != 0) {
1906 if ((p & ~SVC_PEDESTRIAN) != 0) {
1907 open.push_back(out);
1908 conPermissions[ {e, out}] |= p;
1909#ifdef DEBUG_JOINJUNCTIONS_CONNECTIONS
1910 std::cout << " e=" << e->getID() << " out=" << out->getID() << " pOut=" << getVehicleClassNames(out->getPermissions()) << "\n p=" << getVehicleClassNames(p) << "\n q=" << getVehicleClassNames(conPermissions[ {e, out}]) << "\n";
1911#endif
1912 }
1913 }
1914 }
1915 }
1916 } else {
1917 // check existing connections
1918 for (const auto& con : cons) {
1919 if (con.toEdge != nullptr && allEdges.count(con.toEdge) != 0) {
1920 SVCPermissions p = pCur & con.toEdge->getPermissions();
1921 if (con.permissions != SVC_UNSPECIFIED) {
1922 p &= con.permissions;
1923 }
1924 if (seen.count(con.toEdge) == 0 || (~conPermissions[ {e, con.toEdge}] & p) != 0) {
1925 open.push_back(con.toEdge);
1926 conPermissions[ {e, con.toEdge}] |= p;
1927 //std::cout << " e=" << e->getID() << " con.toEdge=" << con.toEdge->getID() << " pSpecial=" << toString(con.permissions) << " pOut=" << getVehicleClassNames(con.toEdge->getPermissions()) << "\n p=" << getVehicleClassNames(p) << "\n q=" << getVehicleClassNames(conPermissions[{e, con.toEdge}]) << "\n";
1928 }
1929 }
1930 }
1931 }
1932 }
1933 seen.erase(e);
1934 for (NBEdge* reached : seen) {
1935 // filter out inside edges from reached
1936 if (inside.count(reached) == 0) {
1937 if (e->getStep() > NBEdge::EdgeBuildingStep::INIT && reached->getFromNode() == e->getToNode() && !e->isConnectedTo(reached)) {
1938 // also filter out edges that are outgoing of the to-node of edge but aren't currently connected
1939 continue;
1940 }
1941 reachable[e].insert(reached);
1942 const SVCPermissions pDefault = e->getPermissions() & reached->getPermissions();
1943 if (conPermissions[ {e, reached}] != pDefault) {
1944 specialPermissions.insert(e);
1945#ifdef DEBUG_JOINJUNCTIONS_CONNECTIONS
1946 std::cout << "e=" << e->getID() << " out=" << reached->getID() << " special=" << getVehicleClassNames(conPermissions[ {e, reached}]) << "\n";
1947#endif
1948 }
1949 }
1950 }
1951#ifdef DEBUG_JOINJUNCTIONS_CONNECTIONS
1952 std::cout << " reachable e=" << e->getID() << " seen=" << toString(seen) << " reachable=" << toString(reachable[e]) << "\n";
1953#endif
1954 }
1955
1956 // remap and remove edges which are completely within the new intersection
1957 if (origNames) {
1958 newNode->setParameter("origEdgeIds", joinNamedToString(inside, ' '));
1959 }
1960 for (NBEdge* e : inside) {
1961 for (NBEdge* e2 : allEdges) {
1962 if (e != e2) {
1963 e2->replaceInConnections(e, e->getConnections());
1964 }
1965 }
1966 ec.extract(dc, e, true);
1967 allEdges.erase(e);
1968 }
1969
1970 // remap edges which are incoming / outgoing
1971 for (NBEdge* e : allEdges) {
1972 const bool outgoing = cluster.count(e->getFromNode()) > 0;
1973 NBNode* from = outgoing ? newNode : e->getFromNode();
1974 NBNode* to = outgoing ? e->getToNode() : newNode;
1975 if (origNames) {
1976 if (outgoing) {
1977 e->setParameter("origFrom", e->getFromNode()->getID());
1978 } else {
1979 e->setParameter("origTo", e->getToNode()->getID());
1980 }
1981 }
1982 if (e->getTurnSignTarget() != "") {
1983 for (NBNode* n : cluster) {
1984 if (e->getTurnSignTarget() == n->getID()) {
1985 e->setTurnSignTarget(to->getID());
1986 break;
1987 }
1988 }
1989 }
1990 e->reinitNodes(from, to);
1991 // re-add connections which previously existed and may still valid.
1992 // connections to removed edges will be ignored
1993 std::vector<NBEdge::Connection> conns = e->getConnections();
1994 for (std::vector<NBEdge::Connection>::iterator k = conns.begin(); k != conns.end(); ++k) {
1995 if ((*k).toEdge == nullptr) {
1996 // edge explicitly set to have no connections
1997 continue;
1998 }
1999 e->addLane2LaneConnection((*k).fromLane, (*k).toEdge, (*k).toLane, NBEdge::Lane2LaneInfoType::USER, false, (*k).mayDefinitelyPass);
2000 if ((*k).fromLane >= 0 && (*k).fromLane < e->getNumLanes() && e->getLaneStruct((*k).fromLane).connectionsDone) {
2001 // @note (see NIImporter_DlrNavteq::ConnectedLanesHandler)
2002 e->declareConnectionsAsLoaded(NBEdge::EdgeBuildingStep::INIT);
2003#ifdef DEBUG_JOINJUNCTIONS_CONNECTIONS
2004 std::cout << " e=" << e->getID() << " declareConnectionsAsLoaded\n";
2005#endif
2006 }
2007 }
2008 }
2009 if (!resetConnections) {
2010 // disable connections that were impossible with the old topology
2011 // if connectivity has special permissions, set edge to edge connections explicitly
2012 for (NBEdge* in : newNode->getIncomingEdges()) {
2013 for (NBEdge* out : newNode->getOutgoingEdges()) {
2014 if (reachable[in].count(out) == 0) {
2015 if (!ec.hasPostProcessConnection(in->getID(), out->getID())) {
2016 //std::cout << " removeUnreachable in=" << in->getID() << " out=" << out->getID() << "\n";
2017 in->removeFromConnections(out, -1, -1, true, false, true);
2018 } else {
2019 //std::cout << " hasPostProcessConnection in=" << in->getID() << " out=" << out->getID() << "\n";
2020 }
2021 } else if (specialPermissions.count(in) != 0) {
2022 SVCPermissions pDefault = in->getPermissions() & out->getPermissions();
2023 SVCPermissions p = conPermissions[ {in, out}] == 0 ? pDefault : conPermissions[ {in, out}];
2024 in->addEdge2EdgeConnection(out, true, p == pDefault ? SVC_UNSPECIFIED : p);
2025 //std::cout << " addEdge2Edge in=" << in->getID() << " out=" << out->getID() << "\n";
2026 }
2027 }
2028 }
2029 } else {
2030 for (NBEdge* in : newNode->getIncomingEdges()) {
2031 in->invalidateConnections(true);
2032 }
2033 }
2034
2035 // remove original nodes
2036 registerJoinedCluster(cluster);
2037 for (NBNode* n : cluster) {
2038 erase(n);
2039 }
2040}
2041
2042
2043void
2045 std::set<std::string> ids;
2046 for (NBNode* n : cluster) {
2047 ids.insert(n->getID());
2048 }
2049 myJoinedClusters.push_back(ids);
2050}
2051
2052void
2053NBNodeCont::registerJoinedCluster(const std::set<std::string>& cluster) {
2054 myJoinedClusters.push_back(cluster);
2055}
2056
2057void
2058NBNodeCont::unregisterJoinedCluster(const std::set<std::string>& cluster) {
2059 auto it = std::find(myJoinedClusters.begin(), myJoinedClusters.end(), cluster);
2060 if (it != myJoinedClusters.end()) {
2061 myJoinedClusters.erase(it);
2062 }
2063}
2064
2065
2066void
2067NBNodeCont::analyzeCluster(NodeSet cluster, std::string& id, Position& pos,
2068 bool& hasTLS, TrafficLightType& type, SumoXMLNodeType& nodeType) {
2069 id = createClusterId(cluster, id);
2070 bool ambiguousType = false;
2071 for (NBNode* j : cluster) {
2072 pos.add(j->getPosition());
2073 // add a traffic light if any of the cluster members was controlled
2074 if (j->isTLControlled()) {
2075 if (!hasTLS) {
2076 // init type
2077 type = (*j->getControllingTLS().begin())->getType();
2078 } else if (type != (*j->getControllingTLS().begin())->getType()) {
2079 ambiguousType = true;
2080 }
2081 hasTLS = true;
2082 }
2083 SumoXMLNodeType otherType = j->getType();
2084 if (nodeType == SumoXMLNodeType::UNKNOWN) {
2085 nodeType = otherType;
2086 } else if (nodeType != otherType) {
2087 if (hasTLS) {
2089 } else if (otherType != SumoXMLNodeType::UNKNOWN) {
2090 if ((nodeType != SumoXMLNodeType::PRIORITY && (nodeType != SumoXMLNodeType::NOJUNCTION || otherType != SumoXMLNodeType::PRIORITY))
2091 || (otherType != SumoXMLNodeType::NOJUNCTION && otherType != SumoXMLNodeType::UNKNOWN && otherType != SumoXMLNodeType::PRIORITY)) {
2092 WRITE_WARNINGF("Ambiguous node type for node cluster '%' (%,%), setting to '" + toString(SumoXMLNodeType::PRIORITY) + "'.", id, toString(nodeType), toString(otherType));
2093 }
2094 nodeType = SumoXMLNodeType::PRIORITY;
2095 }
2096 }
2097 }
2098 pos.mul(1. / (double)cluster.size());
2099 if (ambiguousType) {
2100 type = SUMOXMLDefinitions::TrafficLightTypes.get(OptionsCont::getOptions().getString("tls.default-type"));
2101 WRITE_WARNINGF(TL("Ambiguous traffic light type for node cluster '%', setting to '%'."), id, toString(type));
2102 }
2103}
2104
2105
2106// ----------- (Helper) methods for guessing/computing traffic lights
2107bool
2108NBNodeCont::shouldBeTLSControlled(const NodeSet& c, double laneSpeedThreshold, bool recheck) const {
2109 bool tooFast = false;
2110 double laneSpeedSum = 0;
2111 std::set<NBEdge*> seen;
2112 for (NBNode* j : c) {
2113 for (const NBEdge* e : j->getEdges()) {
2114 if (c.find(e->getFromNode()) != c.end() && c.find(e->getToNode()) != c.end()) {
2115 // edges fully within the cluster do not count
2116 continue;
2117 }
2118 if (j->hasIncoming(e)) {
2119 if (recheck && !j->hasConflict(e)) {
2120 // edges without conflict do not count
2121 // we can only check this after connections have been computed
2122 continue;
2123 }
2124 laneSpeedSum += (double)e->getNumLanes() * e->getLaneSpeed(0);
2125 }
2126 if (e->getLaneSpeed(0) * 3.6 > 79) {
2127 tooFast = true;
2128 }
2129 }
2130 }
2131 //std::cout << " c=" << joinNamedToString(c, ' ') << " size=" << c.size() << " laneSpeedSum=" << laneSpeedSum << " thresh=" << laneSpeedThreshold << " tooFast=" << tooFast << "\n";
2132 return !tooFast && laneSpeedSum >= laneSpeedThreshold && c.size() != 0;
2133}
2134
2135bool
2137 // check whether all component nodes are solely pedestrian crossings
2138 // (these work fine without joining)
2139 for (NBNode* node : c) {
2140 EdgeVector nonPedIncoming;
2141 EdgeVector nonPedOutgoing;
2142 for (NBEdge* e : node->getIncomingEdges()) {
2143 if (e->getPermissions() != SVC_PEDESTRIAN) {
2144 nonPedIncoming.push_back(e);
2145 }
2146 }
2147 for (NBEdge* e : node->getOutgoingEdges()) {
2148 if (e->getPermissions() != SVC_PEDESTRIAN) {
2149 nonPedOutgoing.push_back(e);
2150 }
2151 }
2152 if (!node->geometryLike(nonPedIncoming, nonPedOutgoing)) {
2153 //for (NBNode* node : c) {
2154 // if (node->getID() == "2480337678") {
2155 // std::cout << " node=" << node->getID() << " nonPedIncoming=" << toString(nonPedIncoming) << " nonPedOutgoing=" << toString(nonPedOutgoing) << "\n";
2156 // }
2157 //}
2158 return false;
2159 }
2160 }
2161 return true;
2162}
2163
2164
2165bool
2167 for (NBNode* node : c) {
2168 if (node->isTLControlled()) {
2169 NBTrafficLightDefinition* tl = (*node->getControllingTLS().begin());
2170 if (tl->getNodes().size() > 1) {
2171 // joined tls also imply a customID
2172 return true;
2173 }
2174 const std::string tlID = tl->getID();
2175 if (tlID != node->getID()
2176 && !StringUtils::startsWith(tlID, "joinedS_")
2177 && !StringUtils::startsWith(tlID, "joinedG_")
2178 && !StringUtils::startsWith(tlID, "GS")) {
2179 return true;
2180 }
2181 }
2182 }
2183 return false;
2184}
2185
2186
2187void
2189 myGuessedTLS.clear();
2190 // build list of definitely not tls-controlled junctions
2191 const double laneSpeedThreshold = oc.getFloat("tls.guess.threshold");
2192 if (oc.isSet("tls.unset")) {
2193 std::vector<std::string> notTLControlledNodes = oc.getStringVector("tls.unset");
2194 for (std::vector<std::string>::const_iterator i = notTLControlledNodes.begin(); i != notTLControlledNodes.end(); ++i) {
2196 if (n == nullptr) {
2197 throw ProcessError(TLF(" The junction '%' to set as not-controlled is not known.", *i));
2198 }
2199 std::set<NBTrafficLightDefinition*> tls = n->getControllingTLS();
2200 for (std::set<NBTrafficLightDefinition*>::const_iterator j = tls.begin(); j != tls.end(); ++j) {
2201 (*j)->removeNode(n);
2202 }
2204 myUnsetTLS.insert(n);
2205 }
2206 }
2207
2209 // loop#1 checking whether the node shall be tls controlled,
2210 // because it is assigned to a district
2211 if (oc.exists("tls.taz-nodes") && oc.getBool("tls.taz-nodes")) {
2212 for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) {
2213 NBNode* cur = (*i).second;
2214 if (cur->isNearDistrict() && myUnsetTLS.count(cur) == 0) {
2215 setAsTLControlled(cur, tlc, type);
2216 }
2217 }
2218 }
2219
2220 // figure out which nodes mark the locations of TLS signals
2221 // This assumes nodes are already joined
2222 if (oc.exists("tls.guess-signals") && oc.getBool("tls.guess-signals")) {
2223 // prepare candidate edges
2224 const double signalDist = oc.getFloat("tls.guess-signals.dist");
2225 for (const auto& item : myNodes) {
2226 const NBNode* node = item.second;
2227 if (node->isTLControlled() && (node->getIncomingEdges().size() == 1 || node->geometryLike())) {
2228#ifdef DEBUG_GUESSSIGNALS
2229 if (DEBUGCOND(node) || true) {
2230 std::cout << " propagate TLS from " << node->getID() << " downstream\n";
2231 }
2232#endif
2233 for (NBEdge* edge : node->getOutgoingEdges()) {
2234 // do not overwrite closer signals
2235 if (edge->getSignalOffset() == NBEdge::UNSPECIFIED_SIGNAL_OFFSET) {
2236 edge->setSignalPosition(node->getPosition(), node);
2237 }
2238 }
2239 }
2240 }
2241 std::set<NBEdge*> seen;
2242 std::set<NBEdge*> check;
2243 for (const auto& item : myNodes) {
2244 for (NBEdge* edge : item.second->getOutgoingEdges()) {
2245 if (edge->getSignalPosition() != Position::INVALID) {
2246 check.insert(edge);
2247 seen.insert(edge);
2248#ifdef DEBUG_GUESSSIGNALS
2249 if (DEBUGCOND(edge->getSignalNode()) || true) {
2250 std::cout << " primary signalPosition edge=" << edge->getID() << " pos=" << edge->getSignalPosition() << "\n";
2251 }
2252#endif
2253 }
2254 }
2255 }
2256 // propagate signal position until the next real intersection
2257 while (check.size() > 0) {
2258 NBEdge* const edge = *check.begin();
2259 check.erase(check.begin());
2260 seen.insert(edge);
2261 NBNode* const nextNode = edge->getToNode();
2262 if (nextNode->geometryLike() && !nextNode->isTLControlled()) {
2263 for (NBEdge* const outEdge : nextNode->getOutgoingEdges()) {
2264 if (seen.count(outEdge) == 0) {
2265 outEdge->setSignalPosition(edge->getSignalPosition(), edge->getSignalNode());
2266#ifdef DEBUG_GUESSSIGNALS
2267 if (DEBUGCOND(edge->getSignalNode()) || true) {
2268 std::cout << " setSignalPosition edge=" << outEdge->getID() << " pos=" << edge->getSignalPosition() << "\n";
2269 }
2270#endif
2271 check.insert(outEdge);
2272 }
2273 }
2274 }
2275 }
2276
2277 // check which nodes should be controlled
2278 const int slack = oc.getInt("tls.guess-signals.slack");
2279 for (std::map<std::string, NBNode*>::const_iterator i = myNodes.begin(); i != myNodes.end(); ++i) {
2280 NBNode* node = i->second;
2281 if (myUnsetTLS.count(node) != 0) {
2282 continue;
2283 }
2284 const EdgeVector& incoming = node->getIncomingEdges();
2285 const EdgeVector& outgoing = node->getOutgoingEdges();
2286 if (!node->isTLControlled() && incoming.size() > 1 && !node->geometryLike()
2288 && node->getType() != SumoXMLNodeType::RAIL_CROSSING) {
2289 std::vector<const NBNode*> signals;
2290 int foundSignals = 0;
2291 int missingSignals = 0;
2292 // check if there is a signal at every incoming edge
2293 for (EdgeVector::const_iterator it_i = incoming.begin(); it_i != incoming.end(); ++it_i) {
2294 const NBEdge* inEdge = *it_i;
2296 if ((inEdge->getPermissions() & SVC_PASSENGER) != 0) {
2297#ifdef DEBUG_GUESSSIGNALS
2298 if (DEBUGCOND(node)) {
2299 std::cout << " noTLS, edge=" << inEdge->getID() << "\n";
2300 }
2301#endif
2302 missingSignals++;
2303 if (missingSignals > slack) {
2304 break;
2305 }
2306 }
2307 } else {
2308 foundSignals++;
2309 }
2310 }
2311 missingSignals = 0;
2312 int foundSignalsAtDist = 0;
2313 if (foundSignals > 1 && missingSignals <= slack && missingSignals < foundSignals) {
2314 node->updateSurroundingGeometry();
2315 // check if all signals are within the required distance
2316 // (requires detailed geometry computation)
2317 for (EdgeVector::const_iterator it_i = incoming.begin(); it_i != incoming.end(); ++it_i) {
2318 const NBEdge* inEdge = *it_i;
2319 if (inEdge->getSignalOffset() == NBEdge::UNSPECIFIED_SIGNAL_OFFSET || inEdge->getSignalOffset() > signalDist) {
2320 if ((inEdge->getPermissions() & SVC_PASSENGER) != 0) {
2321#ifdef DEBUG_GUESSSIGNALS
2322 if (DEBUGCOND(node)) {
2323 std::cout << " noTLS, edge=" << inEdge->getID() << " offset=" << inEdge->getSignalOffset() << " tlsPos=" << inEdge->getSignalPosition() << "\n";
2324 }
2325#endif
2326 missingSignals++;
2327 if (missingSignals > slack) {
2328 break;
2329 }
2330 }
2331 } else {
2332 foundSignalsAtDist++;
2333 }
2334 const NBNode* signal = inEdge->getSignalNode();
2335 if (signal != nullptr) {
2336 signals.push_back(signal);
2337 }
2338 }
2339 // outgoing edges may be tagged with pedestrian crossings. These
2340 // should also be merged into the main TLS
2341 for (const NBEdge* outEdge : outgoing) {
2342 NBNode* cand = outEdge->getToNode();
2343 if (cand->isTLControlled() && cand->geometryLike() && outEdge->getLength() <= signalDist) {
2344#ifdef DEBUG_GUESSSIGNALS
2345 if (DEBUGCOND(node)) {
2346 std::cout << " node=" << node->getID() << " outEdge=" << outEdge->getID() << " signalNode=" << cand->getID() << " len=" << outEdge->getLength() << "\n";
2347 }
2348#endif
2349 signals.push_back(cand);
2350 }
2351 }
2352 }
2353 if (foundSignalsAtDist > 1 && missingSignals <= slack && missingSignals < foundSignalsAtDist) {
2354 for (const NBNode* s : signals) {
2355 std::set<NBTrafficLightDefinition*> tls = s->getControllingTLS();
2356 const_cast<NBNode*>(s)->reinit(s->getPosition(), SumoXMLNodeType::PRIORITY);
2357 for (std::set<NBTrafficLightDefinition*>::iterator k = tls.begin(); k != tls.end(); ++k) {
2358 tlc.removeFully(s->getID());
2359 }
2360 }
2361 //if (true) std::cout << " node=" << node->getID() << " signals=" << toString(signals) << "\n";
2362 NBTrafficLightDefinition* tlDef = new NBOwnTLDef("GS_" + node->getID(), node, 0, type);
2363 // @todo patch endOffset for all incoming lanes according to the signal positions
2364 if (!tlc.insert(tlDef)) {
2365 // actually, nothing should fail here
2366 WRITE_WARNINGF(TL("Could not build joined tls '%'."), node->getID());
2367 delete tlDef;
2368 return;
2369 }
2370 }
2371 }
2372 }
2373 }
2374
2375 // guess joined tls first, if wished
2376 if (oc.getBool("tls.guess.joining")) {
2377 // get node clusters
2378 NodeClusters cands;
2379 generateNodeClusters(oc.getFloat("tls.join-dist"), cands);
2380 // check these candidates (clusters) whether they should be controlled by a tls
2381 for (NodeClusters::iterator i = cands.begin(); i != cands.end();) {
2382 NodeSet& c = (*i);
2383 // regard only junctions which are not yet controlled and are not
2384 // forbidden to be controlled
2385 for (NodeSet::iterator j = c.begin(); j != c.end();) {
2386 if ((*j)->isTLControlled() || myUnsetTLS.count(*j) != 0) {
2387 c.erase(j++);
2388 } else {
2389 ++j;
2390 }
2391 }
2392 // check whether the cluster should be controlled
2393 // to avoid gigantic clusters, assume that at most 4 nodes should be needed for a guessed-joined-tls
2394 if (c.size() == 0 || !shouldBeTLSControlled(c, laneSpeedThreshold * (double)c.size() / MIN2((double)c.size(), 4.))) {
2395 i = cands.erase(i);
2396 } else {
2397 ++i;
2398 }
2399 }
2400 // cands now only contain sets of junctions that shall be joined into being tls-controlled
2401 for (auto nodeSet : cands) {
2402 std::vector<NBNode*> nodes;
2403 for (NBNode* node : nodeSet) {
2404 nodes.push_back(node);
2405 myGuessedTLS.insert(node);
2406 }
2407 const std::string& id = createClusterId(nodeSet, "joinedG_");
2408 NBTrafficLightDefinition* tlDef = new NBOwnTLDef(id, nodes, 0, type);
2409 if (!tlc.insert(tlDef)) {
2410 // actually, nothing should fail here
2411 WRITE_WARNING(TL("Could not build guessed, joined tls."));
2412 delete tlDef;
2413 return;
2414 }
2415 }
2416 }
2417
2418 // guess single tls
2419 if (oc.getBool("tls.guess")) {
2420 for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) {
2421 NBNode* cur = (*i).second;
2422 // do nothing if already is tl-controlled
2423 if (cur->isTLControlled()) {
2424 continue;
2425 }
2426 // do nothing if in the list of explicit non-controlled junctions
2427 if (myUnsetTLS.count(cur) != 0) {
2428 continue;
2429 }
2430 NodeSet c;
2431 c.insert(cur);
2432 if (!shouldBeTLSControlled(c, laneSpeedThreshold) || cur->geometryLike()) {
2433 continue;
2434 }
2435 setAsTLControlled(cur, tlc, type);
2436 myGuessedTLS.insert(cur);
2437 }
2438 }
2439}
2440
2441
2442void
2444 std::set<NBTrafficLightDefinition*> recompute;
2445 for (NBNode* node : myGuessedTLS) {
2446 if (!node->hasConflict() || !recheckTLSThreshold(node)) {
2447 const std::set<NBTrafficLightDefinition*>& tlDefs = node->getControllingTLS();
2448 recompute.insert(tlDefs.begin(), tlDefs.end());
2449 node->removeTrafficLights(true);
2450 for (NBEdge* edge : node->getIncomingEdges()) {
2451 edge->clearControllingTLInformation();
2452 }
2453 }
2454 }
2455 for (NBTrafficLightDefinition* def : recompute) {
2456 if (def->getNodes().size() == 0) {
2457 tlc.removeFully(def->getID());
2458 } else {
2459 def->setParticipantsInformation();
2460 def->setTLControllingInformation();
2462 }
2463 }
2464}
2465
2466
2467bool
2469 if (!node->isTLControlled()) {
2470 return false;
2471 }
2472 if ((*node->getControllingTLS().begin())->getNodes().size() != 1) {
2473 // unable to perform check for a joined tls
2474 return true;
2475 }
2476 NodeSet c;
2477 c.insert(node);
2478 const double laneSpeedThreshold = OptionsCont::getOptions().getFloat("tls.guess.threshold");
2479 return shouldBeTLSControlled(c, laneSpeedThreshold, true);
2480}
2481
2482
2483void
2485 for (const auto& item : myNodes) {
2486 item.second->computeKeepClear();
2487 }
2488}
2489
2490
2491void
2493 const std::vector<std::string> excludeList = OptionsCont::getOptions().getStringVector("tls.join-exclude");
2494 for (const std::string& tlsID : excludeList) {
2495 if (!tlc.exist(tlsID, false)) {
2496 WRITE_WARNINGF("Unknown tls ID '%' in option tls.join-exclude", tlsID);
2497 }
2498 }
2499 std::set<std::string> exclude(excludeList.begin(), excludeList.end());
2500 NodeClusters cands;
2501 generateNodeClusters(maxdist, cands);
2502 for (NodeSet& c : cands) {
2503 for (NodeSet::iterator j = c.begin(); j != c.end();) {
2504 if (!(*j)->isTLControlled() || exclude.count((*(*j)->getControllingTLS().begin())->getID()) != 0) {
2505 c.erase(j++);
2506 } else {
2507 ++j;
2508 }
2509 }
2510 if (c.size() < 2 || onlyCrossings(c) || customTLID(c)) {
2511 continue;
2512 }
2513 // figure out type of the joined TLS
2514 Position dummyPos;
2515 bool dummySetTL = false;
2516 std::string id = "joinedS_"; // prefix (see #3871)
2517 TrafficLightType type;
2519 analyzeCluster(c, id, dummyPos, dummySetTL, type, nodeType);
2520 for (NBNode* j : c) {
2521 std::set<NBTrafficLightDefinition*> tls = j->getControllingTLS();
2522 j->removeTrafficLights();
2523 for (NBTrafficLightDefinition* k : tls) {
2524 tlc.removeFully(k->getID());
2525 }
2526 }
2527 std::vector<NBNode*> nodes;
2528 for (NBNode* j : c) {
2529 nodes.push_back(j);
2530 }
2531 NBTrafficLightDefinition* tlDef = new NBOwnTLDef(id, nodes, 0, type);
2532 if (!tlc.insert(tlDef)) {
2533 // actually, nothing should fail here
2534 WRITE_WARNING(TL("Could not build a joined tls."));
2535 delete tlDef;
2536 return;
2537 }
2538 }
2539}
2540
2541
2542void
2544 TrafficLightType type, std::string id) {
2545 if (id == "") {
2546 id = node->getID();
2547 }
2548 NBTrafficLightDefinition* tlDef = new NBOwnTLDef(id, node, 0, type);
2549 if (!tlc.insert(tlDef)) {
2550 // actually, nothing should fail here
2551 WRITE_WARNINGF(TL("Building a tl-logic for junction '%' twice is not possible."), id);
2552 delete tlDef;
2553 return;
2554 }
2555}
2556
2557
2558// -----------
2559void
2561 for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) {
2562 (*i).second->computeLanes2Lanes();
2563 }
2564}
2565
2566
2567// computes the "wheel" of incoming and outgoing edges for every node
2568void
2570 for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) {
2571 (*i).second->computeLogic(ec);
2572 }
2573}
2574
2575
2576void
2578 std::set<NBNode*> roundaboutNodes;
2579 const bool checkLaneFoesAll = oc.getBool("check-lane-foes.all");
2580 const bool checkLaneFoesRoundabout = !checkLaneFoesAll && oc.getBool("check-lane-foes.roundabout");
2581 if (checkLaneFoesRoundabout) {
2582 const std::set<EdgeSet>& roundabouts = ec.getRoundabouts();
2583 for (std::set<EdgeSet>::const_iterator i = roundabouts.begin(); i != roundabouts.end(); ++i) {
2584 for (EdgeSet::const_iterator j = (*i).begin(); j != (*i).end(); ++j) {
2585 roundaboutNodes.insert((*j)->getToNode());
2586 }
2587 }
2588 }
2589 for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) {
2590 const bool checkLaneFoes = checkLaneFoesAll || (checkLaneFoesRoundabout && roundaboutNodes.count((*i).second) > 0);
2591 (*i).second->computeLogic2(checkLaneFoes);
2592 }
2593}
2594
2595
2596void
2598 for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) {
2599 delete ((*i).second);
2600 }
2601 myNodes.clear();
2602 for (auto& item : myExtractedNodes) {
2603 delete item.second;
2604 }
2605 myExtractedNodes.clear();
2606}
2607
2608
2609std::string
2611 int counter = 0;
2612 std::string freeID = "SUMOGenerated" + toString<int>(counter);
2613 // While there is a node with id equal to freeID
2614 while (retrieve(freeID) != nullptr) {
2615 // update counter and generate a new freeID
2616 counter++;
2617 freeID = "SUMOGenerated" + toString<int>(counter);
2618 }
2619 return freeID;
2620}
2621
2622
2623void
2624NBNodeCont::computeNodeShapes(double mismatchThreshold) {
2625 for (NodeCont::iterator i = myNodes.begin(); i != myNodes.end(); i++) {
2626 (*i).second->computeNodeShape(mismatchThreshold);
2627 }
2628}
2629
2630
2631void
2633 WRITE_MESSAGE(TL("-----------------------------------------------------"));
2634 WRITE_MESSAGE(TL("Summary:"));
2635
2636 int numUnregulatedJunctions = 0;
2637 int numDeadEndJunctions = 0;
2638 int numTrafficLightJunctions = 0;
2639 int numPriorityJunctions = 0;
2640 int numRightBeforeLeftJunctions = 0;
2641 int numLeftBeforeRightJunctions = 0;
2642 int numAllWayStopJunctions = 0;
2643 int numZipperJunctions = 0;
2644 int numDistrictJunctions = 0;
2645 int numRailCrossing = 0;
2646 int numRailSignals = 0;
2647 for (NodeCont::const_iterator i = myNodes.begin(); i != myNodes.end(); i++) {
2648 switch ((*i).second->getType()) {
2650 ++numUnregulatedJunctions;
2651 break;
2653 ++numDeadEndJunctions;
2654 break;
2658 ++numTrafficLightJunctions;
2659 break;
2662 ++numPriorityJunctions;
2663 break;
2665 ++numRightBeforeLeftJunctions;
2666 break;
2668 ++numLeftBeforeRightJunctions;
2669 break;
2671 ++numAllWayStopJunctions;
2672 break;
2674 ++numZipperJunctions;
2675 break;
2677 ++numDistrictJunctions;
2678 break;
2680 ++numRailCrossing;
2681 break;
2683 ++numRailSignals;
2684 break;
2686 // should not happen
2687 break;
2688 default:
2689 break;
2690 }
2691 }
2692 WRITE_MESSAGE(TL(" Node type statistics:"));
2693 WRITE_MESSAGE(" Unregulated junctions : " + toString(numUnregulatedJunctions));
2694 if (numDeadEndJunctions > 0) {
2695 WRITE_MESSAGE(" Dead-end junctions : " + toString(numDeadEndJunctions));
2696 }
2697 WRITE_MESSAGE(" Priority junctions : " + toString(numPriorityJunctions));
2698 WRITE_MESSAGE(" Right-before-left junctions : " + toString(numRightBeforeLeftJunctions));
2699 if (numLeftBeforeRightJunctions > 0) {
2700 WRITE_MESSAGE(" Left-before-right junctions : " + toString(numLeftBeforeRightJunctions));
2701 }
2702 if (numTrafficLightJunctions > 0) {
2703 WRITE_MESSAGE(" Traffic light junctions : " + toString(numTrafficLightJunctions));
2704 }
2705 if (numAllWayStopJunctions > 0) {
2706 WRITE_MESSAGE(" All-way stop junctions : " + toString(numAllWayStopJunctions));
2707 }
2708 if (numZipperJunctions > 0) {
2709 WRITE_MESSAGE(" Zipper-merge junctions : " + toString(numZipperJunctions));
2710 }
2711 if (numRailCrossing > 0) {
2712 WRITE_MESSAGE(" Rail crossing junctions : " + toString(numRailCrossing));
2713 }
2714 if (numRailSignals > 0) {
2715 WRITE_MESSAGE(" Rail signal junctions : " + toString(numRailSignals));
2716 }
2717 if (numDistrictJunctions > 0) {
2718 WRITE_MESSAGE(" District junctions : " + toString(numDistrictJunctions));
2719 }
2720 const GeoConvHelper& geoConvHelper = GeoConvHelper::getProcessing();
2721 WRITE_MESSAGE(TL(" Network boundaries:"));
2722 WRITE_MESSAGE(" Original boundary : " + toString(geoConvHelper.getOrigBoundary()));
2723 WRITE_MESSAGE(" Applied offset : " + toString(geoConvHelper.getOffsetBase()));
2724 WRITE_MESSAGE(" Converted boundary : " + toString(geoConvHelper.getConvBoundary()));
2725 WRITE_MESSAGE(TL("-----------------------------------------------------"));
2726}
2727
2728
2729std::vector<std::string>
2731 std::vector<std::string> ret;
2732 for (NodeCont::const_iterator i = myNodes.begin(); i != myNodes.end(); ++i) {
2733 ret.push_back((*i).first);
2734 }
2735 return ret;
2736}
2737
2738
2739void
2740NBNodeCont::addPrefix(const std::string& prefix) {
2741 // make a copy of node containers
2742 const auto nodeContainerCopy = myNodes;
2743 myNodes.clear();
2744 for (const auto& node : nodeContainerCopy) {
2745 node.second->setID(prefix + node.second->getID());
2746 myNodes[node.second->getID()] = node.second;
2747 }
2748}
2749
2750
2751void
2752NBNodeCont::rename(NBNode* node, const std::string& newID) {
2753 if (myNodes.count(newID) != 0) {
2754 throw ProcessError(TLF("Attempt to rename node using existing id '%'", newID));
2755 }
2756 myNodes.erase(node->getID());
2757 node->setID(newID);
2758 myNodes[newID] = node;
2759}
2760
2761
2762void
2764 for (NodeCont::const_iterator i = myNodes.begin(); i != myNodes.end(); ++i) {
2765 NBNode* node = i->second;
2766 if (node->isTLControlled() && (!geometryLike || node->geometryLike())) {
2767 // make a copy of tldefs
2768 const std::set<NBTrafficLightDefinition*> tldefs = node->getControllingTLS();
2769 if (geometryLike && (*tldefs.begin())->getNodes().size() > 1) {
2770 // do not remove joined tls when only removing geometry-like tls
2771 continue;
2772 }
2773 if (node->getCrossings().size() > 0) {
2774 // keep controlled pedestrian crossings
2775 continue;
2776 }
2777 // record signal location
2778 for (NBEdge* edge : node->getOutgoingEdges()) {
2779 edge->setSignalPosition(node->getPosition(), nullptr);
2780#ifdef DEBUG_GUESSSIGNALS
2781 std::cout << " discard-simple " << node->getID() << " edge=" << edge->getID() << " pos=" << edge->getSignalPosition() << "\n";
2782#endif
2783 }
2784 for (std::set<NBTrafficLightDefinition*>::const_iterator it = tldefs.begin(); it != tldefs.end(); ++it) {
2785 NBTrafficLightDefinition* tlDef = *it;
2786 node->removeTrafficLight(tlDef);
2787 tlc.extract(tlDef);
2788 }
2790 node->reinit(node->getPosition(), newType);
2791 }
2792 }
2793}
2794
2795
2796void
2798 for (auto& item : myNodes) {
2799 NBNode* node = item.second;
2800 if (node->getType() == SumoXMLNodeType::RAIL_SIGNAL) {
2801 node->reinit(node->getPosition(), SumoXMLNodeType::PRIORITY);
2802 }
2803 }
2804}
2805
2806
2807int
2808NBNodeCont::remapIDs(bool numericaIDs, bool reservedIDs, bool keptIDs, const std::string& prefix, NBTrafficLightLogicCont& tlc) {
2809 bool startGiven = !OptionsCont::getOptions().isDefault("numerical-ids.node-start");
2810 if (!numericaIDs && !reservedIDs && prefix == "" && !startGiven) {
2811 return 0;
2812 }
2813 std::vector<std::string> avoid;
2814 if (startGiven) {
2815 avoid.push_back(toString(OptionsCont::getOptions().getInt("numerical-ids.node-start") - 1));
2816 } else {
2817 avoid = getAllNames();
2818 }
2819 std::set<std::string> reserve;
2820 if (reservedIDs) {
2821 NBHelpers::loadPrefixedIDsFomFile(OptionsCont::getOptions().getString("reserved-ids"), "node:", reserve); // backward compatibility
2822 NBHelpers::loadPrefixedIDsFomFile(OptionsCont::getOptions().getString("reserved-ids"), "junction:", reserve); // selection format
2823 avoid.insert(avoid.end(), reserve.begin(), reserve.end());
2824 }
2825 IDSupplier idSupplier("", avoid);
2826 NodeSet toChange;
2827 for (NodeCont::iterator it = myNodes.begin(); it != myNodes.end(); it++) {
2828 if (startGiven) {
2829 toChange.insert(it->second);
2830 continue;
2831 }
2832 if (numericaIDs) {
2833 try {
2834 StringUtils::toLong(it->first);
2835 } catch (NumberFormatException&) {
2836 toChange.insert(it->second);
2837 }
2838 }
2839 if (reservedIDs && reserve.count(it->first) > 0) {
2840 toChange.insert(it->second);
2841 }
2842 }
2843 std::set<std::string> keep;
2844 if (keptIDs) {
2845 NBHelpers::loadPrefixedIDsFomFile(OptionsCont::getOptions().getString("kept-ids"), "node:", keep); // backward compatibility
2846 NBHelpers::loadPrefixedIDsFomFile(OptionsCont::getOptions().getString("kept-ids"), "junction:", keep); // selection format
2847 for (auto it = toChange.begin(); it != toChange.end();) {
2848 if (keep.count((*it)->getID()) != 0) {
2849 it = toChange.erase(it++);
2850 } else {
2851 it++;
2852 }
2853 }
2854 }
2855 const bool origNames = OptionsCont::getOptions().getBool("output.original-names");
2856 for (NBNode* node : toChange) {
2857 myNodes.erase(node->getID());
2858 }
2859 for (NBNode* node : toChange) {
2860 if (origNames && node->getParameter(SUMO_PARAM_ORIGID) == "") {
2861 node->setParameter(SUMO_PARAM_ORIGID, node->getID());
2862 }
2863 node->setID(idSupplier.getNext());
2864 for (NBTrafficLightDefinition* tlDef : node->getControllingTLS()) {
2865 tlc.rename(tlDef, node->getID());
2866 }
2867 myNodes[node->getID()] = node;
2868 }
2869 if (prefix.empty()) {
2870 return (int)toChange.size();
2871 } else {
2872 int renamed = 0;
2873 // make a copy because we will modify the map
2874 auto oldNodes = myNodes;
2875 for (auto item : oldNodes) {
2876 if (!StringUtils::startsWith(item.first, prefix) && keep.count(item.first) == 0) {
2877 rename(item.second, prefix + item.first);
2878 for (NBTrafficLightDefinition* tlDef : item.second->getControllingTLS()) {
2879 if (!StringUtils::startsWith(tlDef->getID(), prefix)) {
2880 tlc.rename(tlDef, prefix + tlDef->getID());
2881 }
2882 }
2883 renamed++;
2884 }
2885 }
2886 return renamed;
2887 }
2888}
2889
2890
2891int
2893 // guess outer fringe by topology and being on the pareto-boundary
2894 NodeSet topRightFront;
2895 NodeSet topLeftFront;
2896 NodeSet bottomRightFront;
2897 NodeSet bottomLeftFront;
2898 for (const auto& item : myNodes) {
2899 paretoCheck(item.second, topRightFront, 1, 1);
2900 paretoCheck(item.second, topLeftFront, -1, 1);
2901 paretoCheck(item.second, bottomRightFront, 1, -1);
2902 paretoCheck(item.second, bottomLeftFront, -1, -1);
2903 }
2904 NodeSet front;
2905 front.insert(topRightFront.begin(), topRightFront.end());
2906 front.insert(topLeftFront.begin(), topLeftFront.end());
2907 front.insert(bottomRightFront.begin(), bottomRightFront.end());
2908 front.insert(bottomLeftFront.begin(), bottomLeftFront.end());
2909 int numFringe = 0;
2910 for (NBNode* n : front) {
2911 const int in = (int)n->getIncomingEdges().size();
2912 const int out = (int)n->getOutgoingEdges().size();
2913 if ((in <= 1 && out <= 1) &&
2914 (in == 0 || out == 0
2915 || n->getIncomingEdges().front()->isTurningDirectionAt(n->getOutgoingEdges().front()))) {
2916 n->setFringeType(FringeType::OUTER);
2917 numFringe++;
2918 }
2919 }
2920 // guess outer fringe by topology and speed
2921 const double speedThreshold = OptionsCont::getOptions().getFloat("fringe.guess.speed-threshold");
2922 for (const auto& item : myNodes) {
2923 NBNode* n = item.second;
2924 if (front.count(n) != 0) {
2925 continue;
2926 }
2927 if (n->getEdges().size() == 1 && n->getEdges().front()->getSpeed() > speedThreshold) {
2929 numFringe++;
2930 }
2931 }
2932 return numFringe;
2933}
2934
2935
2936void
2937NBNodeCont::paretoCheck(NBNode* node, NodeSet& frontier, int xSign, int ySign) {
2938 const double x = node->getPosition().x() * xSign;
2939 const double y = node->getPosition().y() * ySign;
2940 std::vector<NBNode*> dominated;
2941 for (NBNode* fn : frontier) {
2942 const double x2 = fn->getPosition().x() * xSign;
2943 const double y2 = fn->getPosition().y() * ySign;
2944 if (x2 >= x && y2 >= y) {
2945 return;
2946 } else if (x2 <= x && y2 <= y) {
2947 dominated.push_back(fn);
2948 }
2949 }
2950 frontier.insert(node);
2951 for (NBNode* r : dominated) {
2952 frontier.erase(r);
2953 }
2954}
2955
2956
2957void
2959 for (const auto& item : myNodes) {
2960 NBNode* n = item.second;
2961 if (n->isTLControlled() && n->getRightOfWay() == RightOfWay::DEFAULT) {
2962 bool hasNEMA = false;
2964 if (tl->getType() == TrafficLightType::NEMA) {
2965 hasNEMA = true;
2966 break;
2967 }
2968 }
2969 if (hasNEMA) {
2970 // NEMA controller defaults to allway_stop behavior when switched off
2972 }
2973 }
2974 }
2975}
2976
2977
2978bool
2980 bool hadShapes = false;
2981 for (const auto& item : myNodes) {
2982 if (item.second->getShape().size() > 0 && !item.second->hasCustomShape()) {
2983 hadShapes = true;
2984 item.second->resetShape();
2985 }
2986 }
2987 return hadShapes;
2988}
2989/****************************************************************************/
#define DEBUGCOND(PED)
#define WRITE_WARNINGF(...)
Definition MsgHandler.h:299
#define WRITE_MESSAGEF(...)
Definition MsgHandler.h:301
#define WRITE_ERRORF(...)
Definition MsgHandler.h:308
#define WRITE_MESSAGE(msg)
Definition MsgHandler.h:300
#define WRITE_WARNING(msg)
Definition MsgHandler.h:298
#define TL(string)
Definition MsgHandler.h:316
#define TLF(string,...)
Definition MsgHandler.h:318
std::set< NBNode *, ComparatorIdLess > NodeSet
Definition NBCont.h:52
std::set< NBEdge * > EdgeSet
container for unique edges
Definition NBCont.h:50
std::vector< NBEdge * > EdgeVector
container for (sorted) edges
Definition NBCont.h:42
#define MAX_SLIPLANE_LENGTH
bool isForVulnerableModes(SVCPermissions permissions)
Returns whether an edge with the given permissions allows only vulnerable road users.
bool isRailway(SVCPermissions permissions)
Returns whether an edge with the given permissions is a (exclusive) railway edge.
const SVCPermissions SVC_UNSPECIFIED
permissions not specified
bool isWaterway(SVCPermissions permissions)
Returns whether an edge with the given permissions is a waterway edge.
const std::string & getVehicleClassNames(SVCPermissions permissions, bool expand)
Returns the ids of the given classes, divided using a ' '.
long long int SVCPermissions
bitset where each bit declares whether a certain SVC may use this edge/lane
@ SVC_RAIL_CLASSES
classes which drive on tracks
@ SVC_PASSENGER
vehicle is a passenger car (a "normal" car)
@ SVC_DELIVERY
vehicle is a small delivery vehicle
@ SVC_VULNERABLE
@ SVC_TRAM
vehicle is a light rail
@ SVC_PEDESTRIAN
pedestrian
const std::string SUMO_PARAM_ORIGID
SumoXMLNodeType
Numbers representing special SUMO-XML-attribute values for representing node- (junction-) types used ...
bool gDebugFlag1
global utility flags for debugging
Definition StdDefs.cpp:44
const double SUMO_const_laneWidth
Definition StdDefs.h:52
T MIN2(T a, T b)
Definition StdDefs.h:80
T MAX2(T a, T b)
Definition StdDefs.h:86
std::string joinNamedToString(const std::set< T *, C > &ns, const T_BETWEEN &between)
Definition ToString.h:374
std::string joinToString(const std::vector< T > &v, const T_BETWEEN &between, std::streamsize accuracy=gPrecision)
Definition ToString.h:322
std::string toString(const T &t, std::streamsize accuracy=gPrecision)
Definition ToString.h:57
static methods for processing the coordinates conversion for the current net
const Boundary & getOrigBoundary() const
Returns the original boundary.
static GeoConvHelper & getProcessing()
the coordinate transformation to use for input conversion and processing
const Position getOffsetBase() const
Returns the network base.
const Boundary & getConvBoundary() const
Returns the converted boundary.
std::string getNext()
Returns the next id.
A container for districts.
A class representing a single district.
Definition NBDistrict.h:62
Storage for edges, including some functionality operating on multiple edges.
Definition NBEdgeCont.h:59
NBEdge * getByID(const std::string &edgeID) const
Returns the edge with id if it exists.
const std::set< EdgeSet > getRoundabouts() const
Returns the determined roundabouts.
std::map< std::string, NBEdge * >::const_iterator begin() const
Returns the pointer to the begin of the stored edges.
Definition NBEdgeCont.h:171
void extract(NBDistrictCont &dc, NBEdge *edge, bool remember=false)
Removes the given edge from the container like erase but does not delete it.
void erase(NBDistrictCont &dc, NBEdge *edge)
Removes the given edge from the container (deleting it)
NBEdge * retrieve(const std::string &id, bool retrieveExtracted=false) const
Returns the edge that has the given id.
std::map< std::string, NBEdge * >::const_iterator end() const
Returns the pointer to the end of the stored edges.
Definition NBEdgeCont.h:178
bool hasPostProcessConnection(const std::string &from, const std::string &to="")
add post process connections
void removeRoundaboutEdges(const EdgeSet &toRemove)
remove edges from all stored roundabouts
void joinSameNodeConnectingEdges(NBDistrictCont &dc, NBTrafficLightLogicCont &tlc, EdgeVector edges)
Joins the given edges because they connect the same nodes.
std::vector< std::string > getAllNames() const
Returns all ids of known edges.
The representation of a single edge during network building.
Definition NBEdge.h:92
double getLength() const
Returns the computed length of the edge.
Definition NBEdge.h:599
SVCPermissions getPermissions(int lane=-1) const
get the union of allowed classes over all lanes or for a specific lane
Definition NBEdge.cpp:4545
const std::vector< Connection > & getConnections() const
Returns the connections.
Definition NBEdge.h:1047
const Position & getSignalPosition() const
Returns the position of a traffic signal on this edge.
Definition NBEdge.h:718
double getLoadedLength() const
Returns the length was set explicitly or the computed length if it wasn't set.
Definition NBEdge.h:608
NBNode * getToNode() const
Returns the destination node of the edge.
Definition NBEdge.h:552
static EdgeVector filterByPermissions(const EdgeVector &edges, SVCPermissions permissions)
return only those edges that permit at least one of the give permissions
Definition NBEdge.cpp:5028
EdgeBuildingStep getStep() const
The building step of this edge.
Definition NBEdge.h:641
NBEdge * getStraightContinuation(SVCPermissions permissions) const
return the straightest follower edge for the given permissions or nullptr (never returns turn-arounds...
Definition NBEdge.cpp:5039
bool isNearEnough2BeJoined2(NBEdge *e, double threshold) const
Check if edge is near enough to be joined to another edge.
Definition NBEdge.cpp:4189
@ INIT
The edge has been loaded, nothing is computed yet.
double getSpeed() const
Returns the speed allowed on this edge.
Definition NBEdge.h:625
const std::string & getID() const
Definition NBEdge.h:1559
static const double UNSPECIFIED_SIGNAL_OFFSET
unspecified signal offset
Definition NBEdge.h:367
const NBNode * getSignalNode() const
Returns the node that (possibly) represents a traffic signal controlling at the end of this edge.
Definition NBEdge.h:723
int getNumLanesThatAllow(SVCPermissions permissions, bool allPermissions=true) const
Definition NBEdge.cpp:4674
@ USER
The connection was given by the user.
NBNode * getFromNode() const
Returns the origin node of the edge.
Definition NBEdge.h:545
double getAngleAtNode(const NBNode *const node) const
Returns the angle of the edge's geometry at the given node.
Definition NBEdge.cpp:2187
double getSignalOffset() const
Returns the offset of a traffic signal from the end of this edge.
Definition NBEdge.cpp:4592
int getPriority() const
Returns the priority of the edge.
Definition NBEdge.h:533
const PositionVector & getLaneShape(int i) const
Returns the shape of the nth lane.
Definition NBEdge.cpp:1010
void append(NBEdge *continuation)
append another edge
Definition NBEdge.cpp:4097
static void loadPrefixedIDsFomFile(const std::string &file, const std::string prefix, std::set< std::string > &into)
Add prefixed ids defined in file.
static double relAngle(double angle1, double angle2)
computes the relative angle between the two angles
Definition NBHelpers.cpp:45
static void loadEdgesFromFile(const std::string &file, std::set< std::string > &into)
Add edge ids defined in file (either ID or edge:ID per line) into the given set.
Definition NBHelpers.cpp:86
void clear()
deletes all nodes
std::set< std::string > myJoinExclusions
set of node ids which should not be joined
Definition NBNodeCont.h:460
std::vector< std::vector< std::string > > myRailComponents
network components that must be removed if not connected to the road network via stop access
Definition NBNodeCont.h:484
static double getDiameter(const NodeSet &cluster)
compute the maximum distance between any two cluster nodes
NamedRTree myRTree
node positions for faster lookup
Definition NBNodeCont.h:481
void avoidOverlap()
fix overlap
int removeRailComponents(NBDistrictCont &dc, NBEdgeCont &ec, NBPTStopCont &sc)
bool onlyCrossings(const NodeSet &c) const
check whether the set of nodes only contains pedestrian crossings
std::string createClusterId(const NodeSet &cluster, const std::string &prefix="cluster_")
generate id from cluster node ids
Definition NBNodeCont.h:144
std::map< std::string, NBNode * >::const_iterator begin() const
Returns the pointer to the begin of the stored nodes.
Definition NBNodeCont.h:118
void recheckGuessedTLS(NBTrafficLightLogicCont &tlc)
recheck myGuessedTLS after node logics are computed
std::vector< NodeSet > NodeClusters
Definition of a node cluster container.
Definition NBNodeCont.h:61
void computeKeepClear()
compute keepClear status for all connections
std::vector< NBNode * > retrieveByPos(const Position &position, const double offset=0.) const
Returns the node with the given coordinates.
NodeCont myNodes
The map of names to nodes.
Definition NBNodeCont.h:454
bool reduceToCircle(NodeSet &cluster, int circleSize, NodeSet startNodes, double maxDist, std::vector< NBNode * > cands=std::vector< NBNode * >()) const
try to find a joinable subset (recursively)
void registerJoinedCluster(const NodeSet &cluster)
gets all joined clusters (see doc for myClusters2Join)
std::string getFreeID()
generates a new node ID
int removeSelfLoops(NBDistrictCont &dc, NBEdgeCont &ec, NBTrafficLightLogicCont &tc)
Removes self-loop edges (edges where the source and the destination node are the same)
bool recheckTLSThreshold(NBNode *node)
check whether a specific guessed tls should keep its type
void paretoCheck(NBNode *node, NodeSet &frontier, int xSign, int ySign)
update pareto frontier with the given node
bool maybeSlipLaneStart(const NBNode *n, EdgeVector &outgoing, double &inAngle) const
check whether the given node maybe the start of a slip lane
void addJoinExclusion(const std::vector< std::string > &ids)
bool erase(NBNode *node)
Removes the given node, deleting it.
int joinLoadedClusters(NBDistrictCont &dc, NBEdgeCont &ec, NBTrafficLightLogicCont &tlc)
Joins loaded junction clusters (see NIXMLNodesHandler)
static bool geometryLikeForClass(const NBNode *n, SVCPermissions permissions)
check whether the node is geometryLike when only considering edges that support the given permissions
void applyConditionalDefaults()
apply default values after loading
void pruneSlipLaneNodes(NodeSet &cluster, double maxDist) const
remove nodes that form a slip lane from cluster
int remapIDs(bool numericaIDs, bool reservedIDs, bool keptIDs, const std::string &prefix, NBTrafficLightLogicCont &tlc)
remap node IDs according to options –numerical-ids and –reserved-ids
bool insert(const std::string &id, const Position &position, NBDistrict *district=0)
Inserts a node into the map.
std::set< const NBNode * > myUnsetTLS
nodes that are excluded from tls-guessing
Definition NBNodeCont.h:478
NBNode * retrieve(const std::string &id) const
Returns the node with the given name.
NodeCont myExtractedNodes
The extracted nodes which are kept for reference.
Definition NBNodeCont.h:457
void joinTLS(NBTrafficLightLogicCont &tlc, double maxdist)
Builds clusters of tls-controlled junctions and joins the control if possible.
int removeUnwishedNodes(NBDistrictCont &dc, NBEdgeCont &ec, NBTrafficLightLogicCont &tlc, NBPTStopCont &sc, NBPTLineCont &lc, NBParkingCont &pc, bool removeGeometryNodes)
Removes "unwished" nodes.
~NBNodeCont()
Destructor.
std::vector< JoinCluster > myClusters2Join
loaded sets of node ids to join (cleared after use)
Definition NBNodeCont.h:463
bool extract(NBNode *node, bool remember=false)
Removes the given node but does not delete it.
void pruneClusterFringe(NodeSet &cluster, double maxDist, bool remove2TLS=false) const
remove geometry-like fringe nodes from cluster
int removeComponents(NBDistrictCont &dc, NBEdgeCont &ec, const int numKeep, bool hasPTStops)
Checks the network for weak connectivity and removes all but the largest components....
std::vector< std::string > getAllNames() const
get all node names
void computeLogics2(const NBEdgeCont &ec, OptionsCont &oc)
compute right-of-way logic for all lane-to-lane connections
bool shouldBeTLSControlled(const NodeSet &c, double laneSpeedThreshold, bool recheck=false) const
Returns whether the given node cluster should be controlled by a tls.
void rename(NBNode *node, const std::string &newID)
Renames the node. Throws exception if newID already exists.
void joinSimilarEdges(NBDistrictCont &dc, NBEdgeCont &ec, NBTrafficLightLogicCont &tlc, bool removeDuplicates)
Joins edges connecting the same nodes.
int removeIsolatedRoads(NBDistrictCont &dc, NBEdgeCont &ec)
Removes sequences of edges that are not connected with a junction. Simple roads without junctions som...
void joinNodeClusters(NodeClusters clusters, NBDistrictCont &dc, NBEdgeCont &ec, NBTrafficLightLogicCont &tlc, bool resetConnections=false)
joins the given node clusters
void discardRailSignals()
discards rail signals
void addPrefix(const std::string &prefix)
add prefix to all nodes
void printBuiltNodesStatistics() const
Prints statistics about built nodes.
void setAsTLControlled(NBNode *node, NBTrafficLightLogicCont &tlc, TrafficLightType type, std::string id="")
Sets the given node as being controlled by a tls.
std::set< const NBNode * > mySplit
nodes that were created when splitting an edge
Definition NBNodeCont.h:472
static NodeSet getClusterNeighbors(const NBNode *n, double longThreshold, NodeSet &cluster)
return all cluster neighbors for the given node
void computeLogics(const NBEdgeCont &ec)
build the list of outgoing edges and lanes
void joinNodeCluster(NodeSet clusters, NBDistrictCont &dc, NBEdgeCont &ec, NBTrafficLightLogicCont &tlc, NBNode *predefined=nullptr, bool resetConnections=false)
void unregisterJoinedCluster(const std::set< std::string > &cluster)
remove cluster from list (on netedit-undo)
void generateNodeClusters(double maxDist, NodeClusters &into) const
Builds node clusters.
static bool isSlipLaneContinuation(const NBNode *cont)
whether the given node may continue a slip lane
void computeNodeShapes(double mismatchThreshold=-1)
Compute the junction shape for this node.
std::vector< std::set< std::string > > myJoinedClusters
sets of node ids which were joined
Definition NBNodeCont.h:466
NBEdge * shortestEdge(const NodeSet &cluster, const NodeSet &startNodes, const std::vector< NBNode * > &exclude) const
find closest neighbor for building circle
std::pair< NBNode *, double > NodeAndDist
Definition NBNodeCont.h:62
void guessTLs(OptionsCont &oc, NBTrafficLightLogicCont &tlc)
Guesses which junctions or junction clusters shall be controlled by tls.
bool feasibleCluster(const NodeSet &cluster, const std::map< const NBNode *, std::vector< NBNode * > > &ptStopEnds, double maxDist, std::string &reason, NBNode *&tryRemove) const
determine whether the cluster is not too complex for joining
int joinSameJunctions(NBDistrictCont &dc, NBEdgeCont &ec, NBTrafficLightLogicCont &tlc, double maxDist)
Joins junctions with similar coordinates regardless of topology.
int guessFringe()
guess and mark fringe nodes
int joinJunctions(double maxDist, NBDistrictCont &dc, NBEdgeCont &ec, NBTrafficLightLogicCont &tlc, NBPTStopCont &sc)
Joins junctions that are very close together.
void computeLanes2Lanes()
divides the incoming lanes on outgoing lanes
void addCluster2Join(const std::set< std::string > &cluster, NBNode *node, const bool resetConnections=false)
add ids of nodes which shall be joined into a single node
void discardTrafficLights(NBTrafficLightLogicCont &tlc, bool geometryLike)
std::set< NBNode *, ComparatorIdLess > myGuessedTLS
nodes that received a traffic light due to guessing (–tls.guess)
Definition NBNodeCont.h:475
std::set< std::string > myJoined
ids found in loaded join clusters used for error checking
Definition NBNodeCont.h:469
void analyzeCluster(NodeSet cluster, std::string &id, Position &pos, bool &hasTLS, TrafficLightType &type, SumoXMLNodeType &nodeType)
std::string createUnusedID(const std::string &base, const std::string &sep)
if base is an existing node id, find a unused id of the form base + sep + INT
bool customTLID(const NodeSet &c) const
check whether the set of nodes contains traffic lights with custom id
bool resetNodeShapes()
reset all node shapes
static int pruneLongEdges(NodeSet &cluster, double maxDist, const bool dryRun=false)
avoid removal of long edges when joining junction clusters
bool maybeSlipLaneEnd(const NBNode *n, EdgeVector &incoming, double &outAngle) const
check whether the given node maybe the end of a slip lane
Represents a single node (junction) during network building.
Definition NBNode.h:66
bool hasIncoming(const NBEdge *const e) const
Returns whether the given edge ends at this node.
Definition NBNode.cpp:2003
RightOfWay getRightOfWay() const
Returns hint on how to compute right of way.
Definition NBNode.h:302
const std::set< NBTrafficLightDefinition * > & getControllingTLS() const
Returns the traffic lights that were assigned to this node (The set of tls that control this node)
Definition NBNode.h:347
void reinit(const Position &position, SumoXMLNodeType type, bool updateEdgeGeometries=false)
Resets initial values.
Definition NBNode.cpp:361
SumoXMLNodeType getType() const
Returns the type of this node.
Definition NBNode.h:287
void setRightOfWay(RightOfWay rightOfWay)
set method for computing right-of-way
Definition NBNode.h:583
static bool isTrafficLight(SumoXMLNodeType type)
return whether the given type is a traffic light
Definition NBNode.cpp:4276
const EdgeVector & getIncomingEdges() const
Returns this node's incoming edges (The edges which yield in this node)
Definition NBNode.h:270
std::vector< std::pair< NBEdge *, NBEdge * > > getEdgesToJoin() const
get edges to join
Definition NBNode.cpp:2756
const EdgeVector & getOutgoingEdges() const
Returns this node's outgoing edges (The edges which start at this node)
Definition NBNode.h:275
void removeTrafficLights(bool setAsPriority=false)
Removes all references to traffic lights that control this tls.
Definition NBNode.cpp:454
void replaceIncoming(NBEdge *which, NBEdge *by, int laneOff)
Replaces occurrences of the first edge within the list of incoming by the second Connections are rema...
Definition NBNode.cpp:1897
EdgeVector getPassengerEdges(bool incoming) const
return edges that permit passengers (either incoming or outgoing)
Definition NBNode.cpp:2496
const Position & getPosition() const
Definition NBNode.h:262
const EdgeVector & getEdges() const
Returns all edges which participate in this node (Edges that start or end at this node)
Definition NBNode.h:280
bool checkIsRemovable() const
check if node is removable
Definition NBNode.cpp:2673
void setFringeType(FringeType fringeType)
set fringe type
Definition NBNode.h:588
bool geometryLike() const
whether this is structurally similar to a geometry node
Definition NBNode.cpp:4033
bool isNearDistrict() const
@chech if node is near district
Definition NBNode.cpp:2821
bool isTLControlled() const
Returns whether this node is controlled by any tls.
Definition NBNode.h:338
static bool isRailwayNode(const NBNode *n)
whether the given node only has rail edges
A traffic light logics which must be computed (only nodes/edges are given)
Definition NBOwnTLDef.h:44
void replaceEdge(const std::string &edgeID, const EdgeVector &replacement)
replace the edge with the given edge list in all lines
Container for public transport stops during the net building process.
void replaceEdge(const std::string &edgeID, const std::vector< NBEdge * > &replacement)
replace the edge with the closes edge on the given edge list in all stops
const std::map< std::string, std::shared_ptr< NBPTStop > > & getStops() const
Returns an unmodifiable reference to the stored pt stops.
void addEdges2Keep(const OptionsCont &oc, std::set< std::string > &into)
add edges that must be kept
void addEdges2Keep(const OptionsCont &oc, std::set< std::string > &into)
add edges that must be kept
Definition NBParking.cpp:78
The base class for traffic light logic definitions.
const std::vector< NBNode * > & getNodes() const
Returns the list of controlled nodes.
A container for traffic light definitions and built programs.
bool exist(const std::string &newID, bool requireComputed=true) const
check if exists a definition with the given ID
void rename(NBTrafficLightDefinition *tlDef, const std::string &newID)
rename traffic light
bool computeSingleLogic(OptionsCont &oc, NBTrafficLightDefinition *def)
Computes a specific traffic light logic (using by netedit)
bool removeFully(const std::string id)
Removes a logic definition (and all programs) from the dictionary.
bool insert(NBTrafficLightDefinition *logic, bool forceInsert=false)
Adds a logic definition to the dictionary.
void extract(NBTrafficLightDefinition *definition)
Extracts a traffic light definition from myDefinitions but keeps it in myExtracted for eventual * del...
Allows to store the object; used as context while traveling the rtree in TraCI.
Definition Named.h:89
Base class for objects which have an id.
Definition Named.h:53
const std::string & getID() const
Returns the id.
Definition Named.h:73
void Remove(const float a_min[2], const float a_max[2], Named *const &a_data)
Remove entry.
Definition NamedRTree.h:90
void Insert(const float a_min[2], const float a_max[2], Named *const &a_data)
Insert entry.
Definition NamedRTree.h:79
int Search(const float a_min[2], const float a_max[2], const Named::StoringVisitor &c) const
Find all within search rectangle.
Definition NamedRTree.h:112
A storage for options typed value containers)
Definition OptionsCont.h:92
bool isSet(const std::string &name, bool failOnNonExistant=true) const
Returns the information whether the named option is set.
double getFloat(const std::string &name) const
Returns the double-value of the named option (only for Option_Float)
int getInt(const std::string &name) const
Returns the int-value of the named option (only for Option_Integer)
std::string getString(const std::string &name) const
Returns the string-value of the named option (only for Option_String)
bool isDefault(const std::string &name) const
Returns the information whether the named option has still the default value.
bool exists(const std::string &name) const
Returns the information whether the named option is known.
bool getBool(const std::string &name) const
Returns the boolean-value of the named option (only for Option_Bool)
const StringVector & getStringVector(const std::string &name) const
Returns the list of string-value of the named option (only for Option_StringVector)
static OptionsCont & getOptions()
Retrieves the options.
virtual void setParameter(const std::string &key, const std::string &value)
Sets a parameter.
A point in 2D or 3D with translation and scaling methods.
Definition Position.h:37
void setx(double x)
set position x
Definition Position.h:67
static const Position INVALID
used to indicate that a position is valid
Definition Position.h:323
double distanceTo2D(const Position &p2) const
returns the euclidean distance in the x-y-plane
Definition Position.h:273
double x() const
Returns the x-position.
Definition Position.h:52
void add(const Position &pos)
Adds the given position to this one.
Definition Position.h:129
void setz(double z)
set position z
Definition Position.h:77
void mul(double val)
Multiplies position with the given value.
Definition Position.h:102
double z() const
Returns the z-position.
Definition Position.h:62
void sety(double y)
set position y
Definition Position.h:72
double y() const
Returns the y-position.
Definition Position.h:57
static StringBijection< TrafficLightType > TrafficLightTypes
traffic light types
T get(const std::string &str) const
get key
static long long int toLong(const std::string &sData)
converts a string into the long value described by it by calling the char-type converter,...
static bool startsWith(const std::string &str, const std::string prefix)
Checks whether a given string starts with the prefix.
unsigned node
static double fn[10]
Definition odrSpiral.cpp:87