Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
eclipse
GitHub Repository: eclipse/sumo
Path: blob/main/src/mesosim/MESegment.cpp
169665 views
1
/****************************************************************************/
2
// Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.dev/sumo
3
// Copyright (C) 2001-2025 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
/****************************************************************************/
14
/// @file MESegment.cpp
15
/// @author Daniel Krajzewicz
16
/// @date Tue, May 2005
17
///
18
// A single mesoscopic segment (cell)
19
/****************************************************************************/
20
#include <config.h>
21
22
#include <algorithm>
23
#include <limits>
24
#include <utils/common/StdDefs.h>
25
#include <microsim/MSGlobals.h>
26
#include <microsim/MSEdge.h>
27
#include <microsim/MSJunction.h>
28
#include <microsim/MSNet.h>
29
#include <microsim/MSLane.h>
30
#include <microsim/MSLink.h>
31
#include <microsim/MSMoveReminder.h>
32
#include <microsim/traffic_lights/MSTrafficLightLogic.h>
33
#include <microsim/output/MSXMLRawOut.h>
34
#include <microsim/output/MSDetectorFileOutput.h>
35
#include <microsim/MSVehicleControl.h>
36
#include <microsim/devices/MSDevice.h>
37
#include <utils/common/FileHelpers.h>
38
#include <utils/common/MsgHandler.h>
39
#include <utils/iodevices/OutputDevice.h>
40
#include <utils/common/RandHelper.h>
41
#include "MEVehicle.h"
42
#include "MELoop.h"
43
#include "MESegment.h"
44
45
#define DEFAULT_VEH_LENGTH_WITH_GAP (SUMOVTypeParameter::getDefault().length + SUMOVTypeParameter::getDefault().minGap)
46
// avoid division by zero when driving very slowly
47
#define MESO_MIN_SPEED (0.05)
48
49
//#define DEBUG_OPENED
50
//#define DEBUG_JAMTHRESHOLD
51
//#define DEBUG_COND (getID() == "blocker")
52
//#define DEBUG_COND (true)
53
#define DEBUG_COND (myEdge.isSelected())
54
#define DEBUG_COND2(obj) ((obj != 0 && (obj)->isSelected()))
55
56
57
// ===========================================================================
58
// static member definition
59
// ===========================================================================
60
MSEdge MESegment::myDummyParent("MESegmentDummyParent", -1, SumoXMLEdgeFunc::UNKNOWN, "", "", -1, 0);
61
MESegment MESegment::myVaporizationTarget("vaporizationTarget");
62
const double MESegment::DO_NOT_PATCH_JAM_THRESHOLD(std::numeric_limits<double>::max());
63
const std::string MESegment::OVERRIDE_TLS_PENALTIES("meso.tls.control");
64
65
66
// ===========================================================================
67
// MESegment::Queue method definitions
68
// ===========================================================================
69
MEVehicle*
70
MESegment::Queue::remove(MEVehicle* v) {
71
myOccupancy -= v->getVehicleType().getLengthWithGap();
72
assert(std::find(myVehicles.begin(), myVehicles.end(), v) != myVehicles.end());
73
if (v == myVehicles.back()) {
74
myVehicles.pop_back();
75
if (myVehicles.empty()) {
76
myOccupancy = 0.;
77
} else {
78
return myVehicles.back();
79
}
80
} else {
81
myVehicles.erase(std::find(myVehicles.begin(), myVehicles.end(), v));
82
}
83
return nullptr;
84
}
85
86
void
87
MESegment::Queue::addDetector(MSMoveReminder* data) {
88
myDetectorData.push_back(data);
89
for (MEVehicle* const v : myVehicles) {
90
v->addReminder(data);
91
}
92
}
93
94
void
95
MESegment::Queue::addReminders(MEVehicle* veh) const {
96
for (MSMoveReminder* rem : myDetectorData) {
97
veh->addReminder(rem);
98
}
99
}
100
101
// ===========================================================================
102
// MESegment method definitions
103
// ===========================================================================
104
MESegment::MESegment(const std::string& id,
105
const MSEdge& parent, MESegment* next,
106
const double length, const double speed,
107
const int idx,
108
const bool multiQueue,
109
const MesoEdgeType& edgeType):
110
Named(id), myEdge(parent), myNextSegment(next),
111
myLength(length), myIndex(idx),
112
myTau_length(TIME2STEPS(1) / MAX2(MESO_MIN_SPEED, speed)),
113
myNumVehicles(0),
114
myLastHeadway(TIME2STEPS(-1)),
115
myMeanSpeed(speed),
116
myLastMeanSpeedUpdate(SUMOTime_MIN) {
117
118
const std::vector<MSLane*>& lanes = parent.getLanes();
119
int usableLanes = 0;
120
for (MSLane* const l : lanes) {
121
const SVCPermissions allow = MSEdge::getMesoPermissions(l->getPermissions());
122
if (multiQueue) {
123
myQueues.push_back(Queue(allow));
124
}
125
if (allow != 0) {
126
usableLanes++;
127
}
128
}
129
if (usableLanes == 0) {
130
// cars won't drive here. Give sensible tau values capacity for the ignored classes
131
usableLanes = 1;
132
}
133
if (multiQueue) {
134
if (next == nullptr) {
135
for (const MSEdge* const edge : parent.getSuccessors()) {
136
const std::vector<MSLane*>* const allowed = parent.allowedLanes(*edge);
137
assert(allowed != nullptr);
138
assert(allowed->size() > 0);
139
for (MSLane* const l : *allowed) {
140
std::vector<MSLane*>::const_iterator it = std::find(lanes.begin(), lanes.end(), l);
141
myFollowerMap[edge] |= (1 << distance(lanes.begin(), it));
142
}
143
}
144
}
145
myQueueCapacity = length;
146
} else {
147
myQueues.push_back(Queue(parent.getPermissions()));
148
}
149
150
initSegment(edgeType, parent, length * usableLanes);
151
}
152
153
void
154
MESegment::initSegment(const MesoEdgeType& edgeType, const MSEdge& parent, const double capacity) {
155
156
myCapacity = capacity;
157
if (myQueues.size() == 1) {
158
const double laneScale = capacity / myLength;
159
myQueueCapacity = capacity;
160
myTau_length = TIME2STEPS(1) / MAX2(MESO_MIN_SPEED, myMeanSpeed) / laneScale;
161
// Eissfeldt p. 90 and 151 ff.
162
myTau_ff = (SUMOTime)((double)edgeType.tauff / laneScale);
163
myTau_fj = (SUMOTime)((double)edgeType.taufj / laneScale);
164
myTau_jf = (SUMOTime)((double)edgeType.taujf / laneScale);
165
myTau_jj = (SUMOTime)((double)edgeType.taujj / laneScale);
166
} else {
167
myTau_ff = edgeType.tauff;
168
myTau_fj = edgeType.taufj;
169
myTau_jf = edgeType.taujf;
170
myTau_jj = edgeType.taujj;
171
}
172
173
myJunctionControl = myNextSegment == nullptr && (edgeType.junctionControl || MELoop::isEnteringRoundabout(parent));
174
myTLSPenalty = ((edgeType.tlsPenalty > 0 || edgeType.tlsFlowPenalty > 0) &&
175
// only apply to the last segment of a tls-controlled edge
176
myNextSegment == nullptr && (
177
parent.getToJunction()->getType() == SumoXMLNodeType::TRAFFIC_LIGHT ||
178
parent.getToJunction()->getType() == SumoXMLNodeType::TRAFFIC_LIGHT_NOJUNCTION ||
179
parent.getToJunction()->getType() == SumoXMLNodeType::TRAFFIC_LIGHT_RIGHT_ON_RED)
180
&& !tlsPenaltyOverride());
181
182
// only apply to the last segment of an uncontrolled edge that has at least 1 minor link
183
myCheckMinorPenalty = (edgeType.minorPenalty > 0 &&
184
myNextSegment == nullptr &&
185
parent.getToJunction()->getType() != SumoXMLNodeType::TRAFFIC_LIGHT &&
186
parent.getToJunction()->getType() != SumoXMLNodeType::TRAFFIC_LIGHT_NOJUNCTION &&
187
parent.getToJunction()->getType() != SumoXMLNodeType::TRAFFIC_LIGHT_RIGHT_ON_RED &&
188
parent.hasMinorLink());
189
myMinorPenalty = edgeType.minorPenalty;
190
myOvertaking = edgeType.overtaking && myCapacity > myLength;
191
192
//std::cout << getID() << " myMinorPenalty=" << myMinorPenalty << " myTLSPenalty=" << myTLSPenalty << " myJunctionControl=" << myJunctionControl << " myOvertaking=" << myOvertaking << "\n";
193
194
recomputeJamThreshold(edgeType.jamThreshold);
195
}
196
197
MESegment::MESegment(const std::string& id):
198
Named(id),
199
myEdge(myDummyParent), // arbitrary edge needed to supply the needed reference
200
myNextSegment(nullptr), myLength(0), myIndex(0),
201
myTau_ff(0), myTau_fj(0), myTau_jf(0), myTau_jj(0),
202
myTLSPenalty(false),
203
myCheckMinorPenalty(false),
204
myMinorPenalty(0),
205
myJunctionControl(false),
206
myOvertaking(false),
207
myTau_length(1) {
208
}
209
210
211
void
212
MESegment::updatePermissions() {
213
if (myQueues.size() > 1) {
214
for (MSLane* lane : myEdge.getLanes()) {
215
myQueues[lane->getIndex()].setPermissions(lane->getPermissions());
216
}
217
} else {
218
myQueues.back().setPermissions(myEdge.getPermissions());
219
}
220
}
221
222
223
void
224
MESegment::recomputeJamThreshold(double jamThresh) {
225
if (jamThresh == DO_NOT_PATCH_JAM_THRESHOLD) {
226
return;
227
}
228
if (jamThresh < 0) {
229
// compute based on speed
230
myJamThreshold = jamThresholdForSpeed(myEdge.getSpeedLimit(), jamThresh);
231
} else {
232
// compute based on specified percentage
233
myJamThreshold = jamThresh * myCapacity;
234
}
235
}
236
237
238
double
239
MESegment::jamThresholdForSpeed(double speed, double jamThresh) const {
240
// vehicles driving freely at maximum speed should not jam
241
// we compute how many vehicles could possible enter the segment until the first vehicle leaves
242
// and multiply by the space these vehicles would occupy
243
// the jamThresh parameter is scale the resulting value
244
if (speed == 0) {
245
return std::numeric_limits<double>::max(); // never jam. Irrelevant at speed 0 anyway
246
}
247
#ifdef DEBUG_JAMTHRESHOLD
248
if (true || DEBUG_COND) {
249
std::cout << "jamThresholdForSpeed seg=" << getID() << " speed=" << speed << " jamThresh=" << jamThresh << " ffVehs=" << std::ceil(myLength / (-jamThresh * speed * STEPS2TIME(tauWithVehLength(myTau_ff, DEFAULT_VEH_LENGTH_WITH_GAP)))) << " thresh=" << std::ceil(myLength / (-jamThresh * speed * STEPS2TIME(tauWithVehLength(myTau_ff, DEFAULT_VEH_LENGTH_WITH_GAP)))) * DEFAULT_VEH_LENGTH_WITH_GAP
250
<< "\n";
251
}
252
#endif
253
return std::ceil(myLength / (-jamThresh * speed * STEPS2TIME(tauWithVehLength(myTau_ff, DEFAULT_VEH_LENGTH_WITH_GAP, 1.)))) * DEFAULT_VEH_LENGTH_WITH_GAP;
254
}
255
256
257
void
258
MESegment::addDetector(MSMoveReminder* data, int queueIndex) {
259
if (queueIndex == -1) {
260
for (Queue& q : myQueues) {
261
q.addDetector(data);
262
}
263
} else {
264
assert(queueIndex < (int)myQueues.size());
265
myQueues[queueIndex].addDetector(data);
266
}
267
}
268
269
270
/*
271
void
272
MESegment::removeDetector(MSMoveReminder* data) {
273
std::vector<MSMoveReminder*>::iterator it = std::find(myDetectorData.begin(), myDetectorData.end(), data);
274
if (it != myDetectorData.end()) {
275
myDetectorData.erase(it);
276
}
277
for (const Queue& q : myQueues) {
278
for (MEVehicle* const v : q.getVehicles()) {
279
v->removeReminder(data);
280
}
281
}
282
}
283
*/
284
285
286
void
287
MESegment::prepareDetectorForWriting(MSMoveReminder& data, int queueIndex) {
288
const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
289
if (queueIndex == -1) {
290
for (const Queue& q : myQueues) {
291
SUMOTime earliestExitTime = currentTime;
292
for (std::vector<MEVehicle*>::const_reverse_iterator i = q.getVehicles().rbegin(); i != q.getVehicles().rend(); ++i) {
293
const SUMOTime exitTime = MAX2(earliestExitTime, (*i)->getEventTime());
294
(*i)->updateDetectorForWriting(&data, currentTime, exitTime);
295
earliestExitTime = exitTime + tauWithVehLength(myTau_ff, (*i)->getVehicleType().getLengthWithGap(), (*i)->getVehicleType().getCarFollowModel().getHeadwayTime());
296
}
297
}
298
} else {
299
SUMOTime earliestExitTime = currentTime;
300
for (std::vector<MEVehicle*>::const_reverse_iterator i = myQueues[queueIndex].getVehicles().rbegin(); i != myQueues[queueIndex].getVehicles().rend(); ++i) {
301
const SUMOTime exitTime = MAX2(earliestExitTime, (*i)->getEventTime());
302
(*i)->updateDetectorForWriting(&data, currentTime, exitTime);
303
earliestExitTime = exitTime + tauWithVehLength(myTau_ff, (*i)->getVehicleType().getLengthWithGap(), (*i)->getVehicleType().getCarFollowModel().getHeadwayTime());
304
}
305
}
306
}
307
308
309
SUMOTime
310
MESegment::hasSpaceFor(const MEVehicle* const veh, const SUMOTime entryTime, int& qIdx, const bool init) const {
311
SUMOTime earliestEntry = SUMOTime_MAX;
312
qIdx = 0;
313
if (myNumVehicles == 0 && myQueues.size() == 1) {
314
// we have always space for at least one vehicle
315
if (myQueues.front().allows(veh->getVClass())) {
316
return entryTime;
317
} else {
318
return earliestEntry;
319
}
320
}
321
const SUMOVehicleClass svc = veh->getVClass();
322
int minSize = std::numeric_limits<int>::max();
323
const MSEdge* const succ = myNextSegment == nullptr ? veh->succEdge(veh->getEdge() == &myEdge ? 1 : 2) : nullptr;
324
for (int i = 0; i < (int)myQueues.size(); i++) {
325
const Queue& q = myQueues[i];
326
const double newOccupancy = q.size() == 0 ? 0. : q.getOccupancy() + veh->getVehicleType().getLengthWithGap();
327
if (newOccupancy <= myQueueCapacity) { // we must ensure that occupancy remains below capacity
328
if (succ == nullptr || myFollowerMap.count(succ) == 0 || ((myFollowerMap.find(succ)->second & (1 << i)) != 0)) {
329
if (q.allows(svc) && q.size() < minSize) {
330
if (init) {
331
// regular insertions and initial insertions must respect different constraints:
332
// - regular insertions must respect entryBlockTime
333
// - initial insertions should not cause additional jamming
334
// - inserted vehicle should be able to continue at the current speed
335
if (veh->getInsertionChecks() == (int)InsertionCheck::NONE) {
336
qIdx = i;
337
minSize = q.size();
338
} else if (q.getOccupancy() <= myJamThreshold && !hasBlockedLeader() && !myTLSPenalty) {
339
if (newOccupancy <= myJamThreshold) {
340
qIdx = i;
341
minSize = q.size();
342
}
343
} else {
344
if (newOccupancy <= jamThresholdForSpeed(getMeanSpeed(false), -1)) {
345
qIdx = i;
346
minSize = q.size();
347
}
348
}
349
} else if (entryTime >= q.getEntryBlockTime()) {
350
qIdx = i;
351
minSize = q.size();
352
} else {
353
earliestEntry = MIN2(earliestEntry, q.getEntryBlockTime());
354
}
355
}
356
}
357
}
358
}
359
if (minSize == std::numeric_limits<int>::max()) {
360
return earliestEntry;
361
}
362
return entryTime;
363
}
364
365
366
bool
367
MESegment::initialise(MEVehicle* veh, SUMOTime time) {
368
int qIdx = 0;
369
if (hasSpaceFor(veh, time, qIdx, true) == time) {
370
receive(veh, qIdx, time, true);
371
// we can check only after insertion because insertion may change the route via devices
372
std::string msg;
373
if (MSGlobals::gCheckRoutes && !veh->hasValidRoute(msg)) {
374
throw ProcessError(TLF("Vehicle '%' has no valid route. %", veh->getID(), msg));
375
}
376
return true;
377
}
378
return false;
379
}
380
381
382
double
383
MESegment::getMeanSpeed(bool useCached) const {
384
const SUMOTime currentTime = MSNet::getInstance()->getCurrentTimeStep();
385
if (currentTime != myLastMeanSpeedUpdate || !useCached) {
386
myLastMeanSpeedUpdate = currentTime;
387
double v = 0;
388
int count = 0;
389
for (const Queue& q : myQueues) {
390
const SUMOTime tau = q.getOccupancy() < myJamThreshold ? myTau_ff : myTau_jf;
391
SUMOTime earliestExitTime = currentTime;
392
count += q.size();
393
for (std::vector<MEVehicle*>::const_reverse_iterator veh = q.getVehicles().rbegin(); veh != q.getVehicles().rend(); ++veh) {
394
v += (*veh)->getConservativeSpeed(earliestExitTime); // earliestExitTime is updated!
395
earliestExitTime += tauWithVehLength(tau, (*veh)->getVehicleType().getLengthWithGap(), (*veh)->getVehicleType().getCarFollowModel().getHeadwayTime());
396
}
397
}
398
if (count == 0) {
399
myMeanSpeed = myEdge.getSpeedLimit();
400
} else {
401
myMeanSpeed = v / (double) count;
402
}
403
}
404
return myMeanSpeed;
405
}
406
407
408
void
409
MESegment::resetCachedSpeeds() {
410
myLastMeanSpeedUpdate = SUMOTime_MIN;
411
}
412
413
void
414
MESegment::writeVehicles(OutputDevice& of) const {
415
for (const Queue& q : myQueues) {
416
for (const MEVehicle* const veh : q.getVehicles()) {
417
MSXMLRawOut::writeVehicle(of, *veh);
418
}
419
}
420
}
421
422
423
MEVehicle*
424
MESegment::removeCar(MEVehicle* v, SUMOTime leaveTime, const MSMoveReminder::Notification reason) {
425
Queue& q = myQueues[v->getQueIndex()];
426
// One could be tempted to do v->setSegment(next); here but position on lane will be invalid if next == 0
427
v->updateDetectors(leaveTime, true, reason);
428
myNumVehicles--;
429
myEdge.lock();
430
MEVehicle* nextLeader = q.remove(v);
431
myEdge.unlock();
432
return nextLeader;
433
}
434
435
436
SUMOTime
437
MESegment::getNextInsertionTime(SUMOTime earliestEntry) const {
438
// since we do not know which queue will be used we give a conservative estimate
439
SUMOTime earliestLeave = earliestEntry;
440
SUMOTime latestEntry = -1;
441
for (const Queue& q : myQueues) {
442
earliestLeave = MAX2(earliestLeave, q.getBlockTime());
443
latestEntry = MAX2(latestEntry, q.getEntryBlockTime());
444
}
445
if (myEdge.getSpeedLimit() == 0) {
446
return MAX2(earliestEntry, latestEntry); // FIXME: This line is just an adhoc-fix to avoid division by zero (Leo)
447
} else {
448
return MAX3(earliestEntry, earliestLeave - TIME2STEPS(myLength / myEdge.getSpeedLimit()), latestEntry);
449
}
450
}
451
452
453
MSLink*
454
MESegment::getLink(const MEVehicle* veh, bool penalty) const {
455
if (myJunctionControl || penalty) {
456
const MSEdge* const nextEdge = veh->succEdge(1);
457
if (nextEdge == nullptr || veh->getQueIndex() == PARKING_QUEUE) {
458
return nullptr;
459
}
460
// try to find any link leading to our next edge, start with the lane pointed to by the que index
461
const MSLane* const bestLane = myEdge.getLanes()[veh->getQueIndex()];
462
for (MSLink* const link : bestLane->getLinkCont()) {
463
if (&link->getLane()->getEdge() == nextEdge) {
464
return link;
465
}
466
}
467
// this is for the non-multique case, maybe we should use caching here !!!
468
for (const MSLane* const lane : myEdge.getLanes()) {
469
if (lane != bestLane) {
470
for (MSLink* const link : lane->getLinkCont()) {
471
if (&link->getLane()->getEdge() == nextEdge) {
472
return link;
473
}
474
}
475
}
476
}
477
}
478
return nullptr;
479
}
480
481
482
bool
483
MESegment::isOpen(const MEVehicle* veh) const {
484
#ifdef DEBUG_OPENED
485
if (DEBUG_COND || DEBUG_COND2(veh)) {
486
gDebugFlag1 = true;
487
std::cout << SIMTIME << " opened seg=" << getID() << " veh=" << Named::getIDSecure(veh)
488
<< " tlsPenalty=" << myTLSPenalty;
489
const MSLink* link = getLink(veh);
490
if (link == 0) {
491
std::cout << " link=0";
492
} else {
493
std::cout << " prio=" << link->havePriority()
494
<< " override=" << limitedControlOverride(link)
495
<< " isOpen=" << link->opened(veh->getEventTime(), veh->getSpeed(), veh->estimateLeaveSpeed(link),
496
veh->getVehicleType().getLengthWithGap(), veh->getImpatience(),
497
veh->getVehicleType().getCarFollowModel().getMaxDecel(), veh->getWaitingTime(),
498
0, nullptr, false, veh)
499
<< " et=" << veh->getEventTime()
500
<< " v=" << veh->getSpeed()
501
<< " vLeave=" << veh->estimateLeaveSpeed(link)
502
<< " impatience=" << veh->getImpatience()
503
<< " tWait=" << veh->getWaitingTime();
504
}
505
std::cout << "\n";
506
gDebugFlag1 = false;
507
}
508
#endif
509
if (myTLSPenalty) {
510
// XXX should limited control take precedence over tls penalty?
511
return true;
512
}
513
const MSLink* link = getLink(veh);
514
return (link == nullptr
515
|| link->havePriority()
516
|| limitedControlOverride(link)
517
|| link->opened(veh->getEventTime(), veh->getSpeed(), veh->estimateLeaveSpeed(link),
518
veh->getVehicleType().getLengthWithGap(), veh->getImpatience(),
519
veh->getVehicleType().getCarFollowModel().getMaxDecel(), veh->getWaitingTime(),
520
0, nullptr, false, veh));
521
}
522
523
524
bool
525
MESegment::limitedControlOverride(const MSLink* link) const {
526
assert(link != nullptr);
527
if (!MSGlobals::gMesoLimitedJunctionControl) {
528
return false;
529
}
530
// if the target segment of this link is not saturated junction control is disabled
531
const MSEdge& targetEdge = link->getLane()->getEdge();
532
const MESegment* target = MSGlobals::gMesoNet->getSegmentForEdge(targetEdge);
533
return (target->getBruttoOccupancy() * 2 < target->myJamThreshold) && !targetEdge.isRoundabout();
534
}
535
536
537
void
538
MESegment::send(MEVehicle* veh, MESegment* const next, const int nextQIdx, SUMOTime time, const MSMoveReminder::Notification reason) {
539
Queue& q = myQueues[veh->getQueIndex()];
540
assert(isInvalid(next) || time >= q.getBlockTime());
541
MSLink* const link = getLink(veh);
542
if (link != nullptr) {
543
link->removeApproaching(veh);
544
}
545
if (veh->isStopped()) {
546
veh->processStop();
547
}
548
MEVehicle* lc = removeCar(veh, time, reason); // new leaderCar
549
q.setBlockTime(time);
550
if (!isInvalid(next)) {
551
const bool nextFree = next->myQueues[nextQIdx].getOccupancy() <= next->myJamThreshold;
552
const SUMOTime tau = (q.getOccupancy() <= myJamThreshold
553
? (nextFree ? myTau_ff : myTau_fj)
554
: (nextFree ? myTau_jf : getTauJJ((double)next->myQueues[nextQIdx].size(), next->myQueueCapacity, next->myJamThreshold)));
555
assert(tau >= 0);
556
myLastHeadway = tauWithVehLength(tau, veh->getVehicleType().getLengthWithGap(), veh->getVehicleType().getCarFollowModel().getHeadwayTime());
557
if (myTLSPenalty) {
558
const MSLink* const tllink = getLink(veh, true);
559
if (tllink != nullptr && tllink->isTLSControlled()) {
560
assert(tllink->getGreenFraction() > 0);
561
myLastHeadway = (SUMOTime)((double)myLastHeadway / tllink->getGreenFraction());
562
}
563
}
564
q.setBlockTime(q.getBlockTime() + myLastHeadway);
565
}
566
if (lc != nullptr) {
567
lc->setEventTime(MAX2(lc->getEventTime(), q.getBlockTime()));
568
MSGlobals::gMesoNet->addLeaderCar(lc, getLink(lc));
569
}
570
}
571
572
SUMOTime
573
MESegment::getTauJJ(double nextQueueSize, double nextQueueCapacity, double nextJamThreshold) const {
574
// compute coefficients for the jam-jam headway function
575
// this function models the effect that "empty space" needs to move
576
// backwards through the downstream segment before the upstream segment may
577
// send annother vehicle.
578
// this allows jams to clear and move upstream.
579
// the headway function f(x) depends on the number of vehicles in the
580
// downstream segment x
581
// f is a linear function that passes through the following fixed points:
582
// f(n_jam_threshold) = tau_jf_withLength (for continuity)
583
// f(headwayCapacity) = myTau_jj * headwayCapacity
584
585
const SUMOTime tau_jf_withLength = tauWithVehLength(myTau_jf, DEFAULT_VEH_LENGTH_WITH_GAP, 1.);
586
// number of vehicles that fit into the NEXT queue (could be larger than expected with DEFAULT_VEH_LENGTH_WITH_GAP!)
587
const double headwayCapacity = MAX2(nextQueueSize, nextQueueCapacity / DEFAULT_VEH_LENGTH_WITH_GAP);
588
// number of vehicles above which the NEXT queue is jammed
589
const double n_jam_threshold = headwayCapacity * nextJamThreshold / nextQueueCapacity;
590
591
// slope a and axis offset b for the jam-jam headway function
592
// solving f(x) = a * x + b
593
const double a = (STEPS2TIME(myTau_jj) * headwayCapacity - STEPS2TIME(tau_jf_withLength)) / (headwayCapacity - n_jam_threshold);
594
const double b = headwayCapacity * (STEPS2TIME(myTau_jj) - a);
595
596
// it is only well defined for nextQueueSize >= n_jam_threshold (which may not be the case for longer vehicles), so we take the MAX
597
return TIME2STEPS(a * MAX2(nextQueueSize, n_jam_threshold) + b);
598
}
599
600
601
bool
602
MESegment::overtake() {
603
return myOvertaking && RandHelper::rand() > (getBruttoOccupancy() / myCapacity);
604
}
605
606
607
void
608
MESegment::addReminders(MEVehicle* veh) const {
609
if (veh->getQueIndex() != PARKING_QUEUE) {
610
myQueues[veh->getQueIndex()].addReminders(veh);
611
}
612
}
613
614
615
void
616
MESegment::receive(MEVehicle* veh, const int qIdx, SUMOTime time, const bool isDepart, const bool isTeleport, const bool newEdge) {
617
const double speed = isDepart ? -1 : MAX2(veh->getSpeed(), MESO_MIN_SPEED); // on the previous segment
618
veh->setSegment(this); // for arrival checking
619
veh->setLastEntryTime(time);
620
veh->setBlockTime(SUMOTime_MAX);
621
if (!isDepart && (
622
// arrival on entering a new edge
623
(newEdge && veh->moveRoutePointer())
624
// arrival on entering a new segment
625
|| veh->hasArrived())) {
626
// route has ended
627
veh->setEventTime(time + TIME2STEPS(myLength / speed)); // for correct arrival speed
628
addReminders(veh);
629
veh->activateReminders(MSMoveReminder::NOTIFICATION_JUNCTION);
630
veh->updateDetectors(time, true,
631
veh->getEdge()->isVaporizing() ? MSMoveReminder::NOTIFICATION_VAPORIZED_VAPORIZER : MSMoveReminder::NOTIFICATION_ARRIVED);
632
MSNet::getInstance()->getVehicleControl().scheduleVehicleRemoval(veh);
633
return;
634
}
635
assert(veh->getEdge() == &getEdge());
636
// route continues
637
Queue& q = myQueues[qIdx];
638
const double maxSpeedOnEdge = veh->getEdge()->getLanes()[qIdx]->getVehicleMaxSpeed(veh);
639
const double uspeed = MAX2(maxSpeedOnEdge, MESO_MIN_SPEED);
640
std::vector<MEVehicle*>& cars = q.getModifiableVehicles();
641
MEVehicle* newLeader = nullptr; // first vehicle in the current queue
642
const SUMOTime stopTime = veh->checkStop(time);
643
SUMOTime tleave = MAX2(stopTime + TIME2STEPS(myLength / uspeed) + getLinkPenalty(veh), q.getBlockTime());
644
if (veh->isStopped()) {
645
myEdge.addWaiting(veh);
646
}
647
if (veh->isParking()) {
648
// parking stops should take at least 1ms
649
veh->setEventTime(MAX2(stopTime, veh->getEventTime() + 1));
650
veh->setSegment(this, PARKING_QUEUE);
651
myEdge.getLanes()[0]->addParking(veh); // TODO for GUI only
652
} else {
653
myEdge.lock();
654
if (cars.empty()) {
655
cars.push_back(veh);
656
newLeader = veh;
657
} else {
658
SUMOTime leaderOut = cars[0]->getEventTime();
659
if (!isDepart && leaderOut > tleave && overtake()) {
660
if (cars.size() == 1) {
661
MSGlobals::gMesoNet->removeLeaderCar(cars[0]);
662
newLeader = veh;
663
}
664
cars.insert(cars.begin() + 1, veh);
665
} else {
666
tleave = MAX2(leaderOut + tauWithVehLength(myTau_ff, cars[0]->getVehicleType().getLengthWithGap(), cars[0]->getVehicleType().getCarFollowModel().getHeadwayTime()), tleave);
667
cars.insert(cars.begin(), veh);
668
}
669
}
670
myEdge.unlock();
671
myNumVehicles++;
672
if (!isDepart && !isTeleport) {
673
// departs and teleports could take place anywhere on the edge so they should not block regular flow
674
// the -1 facilitates interleaving of multiple streams
675
q.setEntryBlockTime(time + tauWithVehLength(myTau_ff, veh->getVehicleType().getLengthWithGap(), veh->getVehicleType().getCarFollowModel().getHeadwayTime()) - 1);
676
}
677
q.setOccupancy(MIN2(myQueueCapacity, q.getOccupancy() + veh->getVehicleType().getLengthWithGap()));
678
veh->setEventTime(tleave);
679
veh->setSegment(this, qIdx);
680
}
681
addReminders(veh);
682
if (isDepart) {
683
veh->onDepart();
684
veh->activateReminders(MSMoveReminder::NOTIFICATION_DEPARTED);
685
} else if (newEdge) {
686
veh->activateReminders(MSMoveReminder::NOTIFICATION_JUNCTION);
687
} else {
688
veh->activateReminders(MSMoveReminder::NOTIFICATION_SEGMENT);
689
}
690
if (veh->isParking()) {
691
MSGlobals::gMesoNet->addLeaderCar(veh, nullptr);
692
} else {
693
if (newLeader != nullptr) {
694
MSGlobals::gMesoNet->addLeaderCar(newLeader, getLink(newLeader));
695
}
696
}
697
}
698
699
700
bool
701
MESegment::vaporizeAnyCar(SUMOTime currentTime, const MSDetectorFileOutput* filter) {
702
for (const Queue& q : myQueues) {
703
if (q.size() > 0) {
704
for (MEVehicle* const veh : q.getVehicles()) {
705
if (filter->vehicleApplies(*veh)) {
706
MSGlobals::gMesoNet->removeLeaderCar(veh);
707
MSGlobals::gMesoNet->changeSegment(veh, currentTime + 1, &myVaporizationTarget, MSMoveReminder::NOTIFICATION_VAPORIZED_CALIBRATOR);
708
return true;
709
}
710
}
711
}
712
}
713
return false;
714
}
715
716
717
void
718
MESegment::setSpeedForQueue(double newSpeed, SUMOTime currentTime, SUMOTime blockTime, const std::vector<MEVehicle*>& vehs) {
719
MEVehicle* v = vehs.back();
720
v->updateDetectors(currentTime, false);
721
SUMOTime newEvent = MAX2(newArrival(v, newSpeed, currentTime), blockTime);
722
if (v->getEventTime() != newEvent) {
723
MSGlobals::gMesoNet->removeLeaderCar(v);
724
v->setEventTime(newEvent);
725
MSGlobals::gMesoNet->addLeaderCar(v, getLink(v));
726
}
727
for (std::vector<MEVehicle*>::const_reverse_iterator i = vehs.rbegin() + 1; i != vehs.rend(); ++i) {
728
(*i)->updateDetectors(currentTime, false);
729
newEvent = MAX2(newArrival(*i, newSpeed, currentTime), newEvent + myTau_ff);
730
//newEvent = MAX2(newArrival(*i, newSpeed, currentTime), newEvent + myTau_ff + (SUMOTime)((*(i - 1))->getVehicleType().getLength() / myTau_length));
731
(*i)->setEventTime(newEvent);
732
}
733
}
734
735
736
SUMOTime
737
MESegment::newArrival(const MEVehicle* const v, double newSpeed, SUMOTime currentTime) {
738
// since speed is only an upper bound pos may be to optimistic
739
const double pos = MIN2(myLength, STEPS2TIME(currentTime - v->getLastEntryTime()) * v->getSpeed());
740
// traveltime may not be 0
741
double tt = (myLength - pos) / MAX2(newSpeed, MESO_MIN_SPEED);
742
return currentTime + MAX2(TIME2STEPS(tt), SUMOTime(1));
743
}
744
745
746
void
747
MESegment::setSpeed(double newSpeed, SUMOTime currentTime, double jamThresh, int qIdx) {
748
recomputeJamThreshold(jamThresh);
749
//myTau_length = MAX2(MESO_MIN_SPEED, newSpeed) * myEdge.getLanes().size() / TIME2STEPS(1);
750
int i = 0;
751
for (const Queue& q : myQueues) {
752
if (q.size() != 0) {
753
if (qIdx == -1 || qIdx == i) {
754
setSpeedForQueue(newSpeed, currentTime, q.getBlockTime(), q.getVehicles());
755
}
756
}
757
i++;
758
}
759
}
760
761
762
SUMOTime
763
MESegment::getEventTime() const {
764
SUMOTime result = SUMOTime_MAX;
765
for (const Queue& q : myQueues) {
766
if (q.size() != 0 && q.getVehicles().back()->getEventTime() < result) {
767
result = q.getVehicles().back()->getEventTime();
768
}
769
}
770
if (result < SUMOTime_MAX) {
771
return result;
772
}
773
return -1;
774
}
775
776
777
void
778
MESegment::saveState(OutputDevice& out) const {
779
bool write = false;
780
for (const Queue& q : myQueues) {
781
if (q.getBlockTime() != -1 || !q.getVehicles().empty()) {
782
write = true;
783
break;
784
}
785
}
786
if (write) {
787
out.openTag(SUMO_TAG_SEGMENT).writeAttr(SUMO_ATTR_ID, getID());
788
for (const Queue& q : myQueues) {
789
out.openTag(SUMO_TAG_VIEWSETTINGS_VEHICLES);
790
out.writeAttr(SUMO_ATTR_TIME, toString<SUMOTime>(q.getBlockTime()));
791
out.writeAttr(SUMO_ATTR_BLOCKTIME, toString<SUMOTime>(q.getEntryBlockTime()));
792
out.writeAttr(SUMO_ATTR_VALUE, q.getVehicles());
793
out.closeTag();
794
}
795
out.closeTag();
796
}
797
}
798
799
800
void
801
MESegment::clearState() {
802
for (Queue& q : myQueues) {
803
q.getModifiableVehicles().clear();
804
}
805
}
806
807
void
808
MESegment::loadState(const std::vector<SUMOVehicle*>& vehs, const SUMOTime blockTime, const SUMOTime entryBlockTime, const int queIdx) {
809
Queue& q = myQueues[queIdx];
810
for (SUMOVehicle* veh : vehs) {
811
MEVehicle* v = static_cast<MEVehicle*>(veh);
812
assert(v->getSegment() == this);
813
q.getModifiableVehicles().push_back(v);
814
myNumVehicles++;
815
q.setOccupancy(q.getOccupancy() + v->getVehicleType().getLengthWithGap());
816
addReminders(v);
817
}
818
if (q.size() != 0) {
819
// add the last vehicle of this queue
820
// !!! one question - what about the previously added vehicle? Is it stored twice?
821
MEVehicle* veh = q.getVehicles().back();
822
MSGlobals::gMesoNet->addLeaderCar(veh, getLink(veh));
823
}
824
q.setBlockTime(blockTime);
825
q.setEntryBlockTime(entryBlockTime);
826
q.setOccupancy(MIN2(q.getOccupancy(), myQueueCapacity));
827
}
828
829
830
std::vector<const MEVehicle*>
831
MESegment::getVehicles() const {
832
std::vector<const MEVehicle*> result;
833
for (const Queue& q : myQueues) {
834
result.insert(result.end(), q.getVehicles().begin(), q.getVehicles().end());
835
}
836
return result;
837
}
838
839
840
bool
841
MESegment::hasBlockedLeader() const {
842
for (const Queue& q : myQueues) {
843
if (q.size() > 0 && q.getVehicles().back()->getWaitingTime() > 0) {
844
return true;
845
}
846
}
847
return false;
848
}
849
850
851
double
852
MESegment::getFlow() const {
853
return 3600 * getCarNumber() * getMeanSpeed() / myLength;
854
}
855
856
857
SUMOTime
858
MESegment::getLinkPenalty(const MEVehicle* veh) const {
859
const MSLink* link = getLink(veh, myTLSPenalty || myCheckMinorPenalty);
860
if (link != nullptr) {
861
SUMOTime result = 0;
862
if (link->isTLSControlled() && myTLSPenalty) {
863
result += link->getMesoTLSPenalty();
864
}
865
// minor tls links may get an additional penalty
866
if (!link->havePriority() &&
867
// do not apply penalty on top of tLSPenalty
868
!myTLSPenalty &&
869
// do not apply penalty if limited control is active
870
(!MSGlobals::gMesoLimitedJunctionControl || limitedControlOverride(link))) {
871
result += myMinorPenalty;
872
}
873
return result;
874
} else {
875
return 0;
876
}
877
}
878
879
880
bool
881
MESegment::tlsPenaltyOverride() const {
882
for (const MSLane* lane : myEdge.getLanes()) {
883
for (const MSLink* link : lane->getLinkCont()) {
884
if (link->isTLSControlled() && StringUtils::toBool(link->getTLLogic()->getParameter(OVERRIDE_TLS_PENALTIES, "0"))) {
885
return true;
886
}
887
}
888
}
889
return false;
890
}
891
892
893
double
894
MESegment::getWaitingSeconds() const {
895
double result = 0;
896
for (const Queue& q : myQueues) {
897
// @note: only the leader currently accumulates waitingTime but this might change in the future
898
for (const MEVehicle* veh : q.getVehicles()) {
899
result += veh->getWaitingSeconds();
900
}
901
}
902
return result;
903
}
904
905
906
/****************************************************************************/
907
908