void
MSTLLogicControl::WAUTSwitchProcedure_Stretch::stretchLogic(SUMOTime step, SUMOTime startPos, SUMOTime allStretchTime) {
    unsigned int currStep = myTo->getIndexFromOffset(startPos);
    SUMOTime durOfPhase = myTo->getPhase(currStep).duration;
    SUMOTime remainingStretchTime = allStretchTime;
    SUMOTime StretchTimeOfPhase = 0;
    unsigned int stretchUmlaufAnz = (unsigned int) TplConvert::_2SUMOReal(myTo->getParameterValue("StretchUmlaufAnz").c_str());
    SUMOReal facSum = 0;
    int areasNo = getStretchAreaNo(myTo);
    for (int x = 0; x < areasNo; x++) {
        StretchBereichDef def = getStretchBereichDef(myTo, x + 1);
        facSum += def.fac;
    }
    facSum *= stretchUmlaufAnz;

    //switch to startPos and stretch this phase, if there is a end of "bereich" between startpos and end of phase
    SUMOTime diffToStart = getDiffToStartOfPhase(*myTo, startPos);
    for (int x = 0; x < areasNo; x++) {
        StretchBereichDef def = getStretchBereichDef(myTo, x + 1);
        SUMOTime end = TIME2STEPS(def.end);
        SUMOTime endOfPhase = (startPos + durOfPhase - diffToStart);
        if (end <= endOfPhase && end >= startPos) {
            SUMOReal fac = def.fac;
            SUMOReal actualfac = fac / facSum;
            facSum = facSum - fac;
            StretchTimeOfPhase = TIME2STEPS(int(STEPS2TIME(remainingStretchTime) * actualfac + 0.5));
            remainingStretchTime = allStretchTime - StretchTimeOfPhase;
        }
    }
    if (facSum == 0) {
        WRITE_WARNING("The computed factor sum in WAUT '" + myWAUT.id + "' at time '" + toString(STEPS2TIME(step)) + "' equals zero;\n assuming an error in WAUT definition.");
        return;
    }
    durOfPhase = durOfPhase - diffToStart + StretchTimeOfPhase;
    myTo->changeStepAndDuration(myControl, step, currStep, durOfPhase);

    currStep = (currStep + 1) % (int)myTo->getPhases().size();
    // stretch all other phases, if there is a "bereich"
    while (remainingStretchTime > 0) {
        for (unsigned int i = currStep; i < myTo->getPhases().size() && remainingStretchTime > 0; i++) {
            durOfPhase = myTo->getPhase(i).duration;
            SUMOTime beginOfPhase = myTo->getOffsetFromIndex(i);
            SUMOTime endOfPhase = beginOfPhase + durOfPhase;
            for (int j = 0; j < areasNo && remainingStretchTime > 0; j++) {
                StretchBereichDef def = getStretchBereichDef(myTo, j + 1);
                SUMOTime end = TIME2STEPS(def.end);
                SUMOReal fac = def.fac;
                if ((beginOfPhase <= end) && (endOfPhase >= end)) {
                    SUMOReal actualfac = fac / facSum;
                    StretchTimeOfPhase = TIME2STEPS(int(STEPS2TIME(remainingStretchTime) * actualfac + 0.5));
                    facSum -= fac;
                    durOfPhase += StretchTimeOfPhase;
                    remainingStretchTime -= StretchTimeOfPhase;
                }
            }
            myTo->addOverridingDuration(durOfPhase);
        }
        currStep = 0;
    }
}
void
MSTLLogicControl::WAUTSwitchProcedure_Stretch::adaptLogic(SUMOTime step) {
    SUMOTime gspTo = TIME2STEPS(getGSPValue(*myTo));
    SUMOTime cycleTime = myTo->getDefaultCycleTime();
    // the position, where the logic has to be after synchronisation
    SUMOTime posAfterSyn = myTo->getPhaseIndexAtTime(step);
    // calculate the difference, that has to be equalized
    SUMOTime deltaToCut = 0;
    if (posAfterSyn < gspTo) {
        deltaToCut = posAfterSyn + cycleTime - gspTo;
    } else {
        deltaToCut =  posAfterSyn - gspTo;
    }
    // test, wheter cutting of the Signalplan is possible
    SUMOTime deltaPossible = 0;
    int areasNo = getStretchAreaNo(myTo);
    for (int i = 0; i < areasNo; i++) {
        StretchBereichDef def = getStretchBereichDef(myTo, i + 1);
        assert(def.end >= def.begin);
        deltaPossible += TIME2STEPS(def.end - def.begin);
    }
    int stretchUmlaufAnz = (int) TplConvert::_2SUMOReal(myTo->getParameterValue("StretchUmlaufAnz").c_str());
    deltaPossible = stretchUmlaufAnz * deltaPossible;
    if ((deltaPossible > deltaToCut) && (deltaToCut < (cycleTime / 2))) {
        cutLogic(step, gspTo, deltaToCut);
    } else {
        SUMOTime deltaToStretch = (cycleTime - deltaToCut) % cycleTime;
        stretchLogic(step, gspTo, deltaToStretch);
    }
}
示例#3
0
void
NBLoadedSUMOTLDef::patchIfCrossingsAdded() {
    // XXX what to do if crossings are removed during network building?
    const unsigned int size = myTLLogic->getNumLinks();
    unsigned int noLinksAll = 0;
    for (NBConnectionVector::const_iterator it = myControlledLinks.begin(); it != myControlledLinks.end(); it++) {
        const NBConnection& c = *it;
        if (c.getTLIndex() != NBConnection::InvalidTlIndex) {
            noLinksAll = MAX2(noLinksAll, (unsigned int)c.getTLIndex() + 1);
        }
    }
    int oldCrossings = 0;
    // collect crossings
    std::vector<NBNode::Crossing> crossings;
    for (std::vector<NBNode*>::iterator i = myControlledNodes.begin(); i != myControlledNodes.end(); i++) {
        const std::vector<NBNode::Crossing>& c = (*i)->getCrossings();
        // set tl indices for crossings
        (*i)->setCrossingTLIndices(noLinksAll);
        copy(c.begin(), c.end(), std::back_inserter(crossings));
        noLinksAll += (unsigned int)c.size();
        oldCrossings += (*i)->numCrossingsFromSumoNet();
    }
    const int newCrossings = (int)crossings.size() - oldCrossings;
    if (newCrossings > 0) {
        const std::vector<NBTrafficLightLogic::PhaseDefinition> phases = myTLLogic->getPhases();
        if (phases.size() > 0) {
            if (phases.front().state.size() == noLinksAll - newCrossings) {
                // patch states for the newly added crossings

                // collect edges
                EdgeVector fromEdges(size, 0);
                EdgeVector toEdges(size, 0);
                std::vector<int> fromLanes(size, 0);
                collectEdgeVectors(fromEdges, toEdges, fromLanes);
                const std::string crossingDefaultState(newCrossings, 'r');

                // rebuild the logic (see NBOwnTLDef.cpp::myCompute)
                const std::vector<NBTrafficLightLogic::PhaseDefinition> phases = myTLLogic->getPhases();
                NBTrafficLightLogic* newLogic = new NBTrafficLightLogic(getID(), getProgramID(), 0, myOffset, myType);
                SUMOTime brakingTime = TIME2STEPS(3);
                //std::cout << "patchIfCrossingsAdded for " << getID() << " numPhases=" << phases.size() << "\n";
                for (std::vector<NBTrafficLightLogic::PhaseDefinition>::const_iterator it = phases.begin(); it != phases.end(); it++) {
                    if ((*it).state.find_first_of("yY") != std::string::npos) {
                        brakingTime = MAX2(brakingTime, it->duration);
                    }
                    NBOwnTLDef::addPedestrianPhases(newLogic, it->duration, it->state + crossingDefaultState, crossings, fromEdges, toEdges);
                }
                NBOwnTLDef::addPedestrianScramble(newLogic, noLinksAll, TIME2STEPS(10), brakingTime, crossings, fromEdges, toEdges);

                delete myTLLogic;
                myTLLogic = newLogic;
            } else if (phases.front().state.size() != noLinksAll) {
                WRITE_WARNING("Could not patch tlLogic " + getID() + "for new crossings");
            }
        }
    }
}
示例#4
0
// ===========================================================================
// method definitions
// ===========================================================================
MSRailCrossing::MSRailCrossing(MSTLLogicControl& tlcontrol,
                               const std::string& id, const std::string& subid,
                               const std::map<std::string, std::string>& parameters) :
    MSSimpleTrafficLightLogic(tlcontrol, id, subid, Phases(), 0, DELTA_T, parameters),
    // XXX make this configurable
    mySecurityGap(TIME2STEPS(15)),
    myMinGreenTime(TIME2STEPS(5)),
    /// XXX compute reasonable time depending on link length
    myYellowTime(TIME2STEPS(5)) {
    // dummy phase, used to avoid crashing in MSTrafficLightLogic::setTrafficLightSignals()
    myPhases.push_back(new MSPhaseDefinition(1, 1, 1, std::string(SUMO_MAX_CONNECTIONS, 'X')));
}
示例#5
0
void
ODMatrix::applyCurve(const Distribution_Points& ps, ODCell* cell, std::vector<ODCell*>& newCells) {
    const std::vector<double>& times = ps.getVals();
    for (int i = 0; i < (int)times.size() - 1; ++i) {
        ODCell* ncell = new ODCell();
        ncell->begin = TIME2STEPS(times[i]);
        ncell->end = TIME2STEPS(times[i + 1]);
        ncell->origin = cell->origin;
        ncell->destination = cell->destination;
        ncell->vehicleType = cell->vehicleType;
        ncell->vehicleNumber = cell->vehicleNumber * ps.getProbs()[i] / ps.getOverallProb();
        newCells.push_back(ncell);
    }
}
示例#6
0
SUMOTime
MESegment::newArrival(const MEVehicle* const v, SUMOReal newSpeed, SUMOTime currentTime) {
    // since speed is only an upper bound pos may be to optimistic
    const SUMOReal pos = MIN2(myLength, STEPS2TIME(currentTime - v->getLastEntryTime()) * v->getSpeed());
    // traveltime may not be 0
    return currentTime + MAX2(TIME2STEPS((myLength - pos) / newSpeed), SUMOTime(1));
}
long
GUIParameterTracker::onCmdChangeAggregation(FXObject*,FXSelector,void*) {
    int index = myAggregationInterval->getCurrentItem();
    size_t aggInt = 0;
    switch (index) {
    case 0:
        aggInt = 1;
        break;
    case 1:
        aggInt = 60;
        break;
    case 2:
        aggInt = 60 * 5;
        break;
    case 3:
        aggInt = 60 * 15;
        break;
    case 4:
        aggInt = 60 * 30;
        break;
    case 5:
        aggInt = 60 * 60;
        break;
    default:
        throw 1;
        break;
    }
    TrackedVarsVector::iterator i1;
    for (i1=myTracked.begin(); i1!=myTracked.end(); i1++) {
        (*i1)->setAggregationSpan(TIME2STEPS(aggInt));
    }
    return 1;
}
SUMOTime
MSPModel_NonInteracting::PState::computeWalkingTime(const MSEdge* prev, const MSPerson::MSPersonStage_Walking& stage, SUMOTime currentTime) {
    myLastEntryTime = currentTime;
    const MSEdge* edge = stage.getEdge();
    const MSEdge* next = stage.getNextRouteEdge();
    int dir = UNDEFINED_DIRECTION;
    if (prev == 0) {
        myCurrentBeginPos = stage.getDepartPos();
    } else {
        // default to FORWARD if not connected
        dir = (edge->getToJunction() == prev->getToJunction() || edge->getToJunction() == prev->getFromJunction()) ? BACKWARD : FORWARD;
        myCurrentBeginPos = dir == FORWARD ? 0 : edge->getLength();
    }
    if (next == 0) {
        myCurrentEndPos = stage.getArrivalPos();
    } else {
        if (dir == UNDEFINED_DIRECTION) {
            // default to FORWARD if not connected
            dir = (edge->getFromJunction() == next->getFromJunction() || edge->getFromJunction() == next->getToJunction()) ? BACKWARD : FORWARD;
        }
        myCurrentEndPos = dir == FORWARD ? edge->getLength() : 0;
    }
    // ensure that a result > 0 is returned even if the walk ends immediately
    myCurrentDuration = MAX2((SUMOTime)1, TIME2STEPS(fabs(myCurrentEndPos - myCurrentBeginPos) / stage.getMaxSpeed()));
    //std::cout << SIMTIME << " dir=" << dir << " curBeg=" << myCurrentBeginPos << " curEnd=" << myCurrentEndPos << " speed=" << stage.getMaxSpeed() << " dur=" << myCurrentDuration << "\n";
    return myCurrentDuration;
}
bool
MSTLLogicControl::WAUTSwitchProcedure::isPosAtGSP(SUMOTime currentTime, const MSTrafficLightLogic& logic) {
    SUMOTime gspTime = TIME2STEPS(getGSPValue(logic)) % logic.getDefaultCycleTime();
    SUMOTime programTime = logic.getOffsetFromIndex(logic.getCurrentPhaseIndex())
                           + (logic.getCurrentPhaseDef().duration - (logic.getNextSwitchTime() - currentTime));
    return gspTime == programTime;
}
// ===========================================================================
// method definitions
// ===========================================================================
TrackerValueDesc::TrackerValueDesc(const std::string& name,
                                   const RGBColor& col,
                                   SUMOTime recordBegin)
    : myName(name), myActiveCol(col), myInactiveCol(col),
      myMin(0), myMax(0),
      myAggregationInterval(TIME2STEPS(1) / DELTA_T), myInvalidValue(-1), myValidNo(0),
      myRecordingBegin(recordBegin), myTmpLastAggValue(0) {}
示例#11
0
void
Person::appendWalkingStage(const std::string& personID, const std::vector<std::string>& edgeIDs, double arrivalPos, double duration, double speed, const std::string& stopID) {
    MSTransportable* p = getPerson(personID);
    ConstMSEdgeVector edges;
    try {
        MSEdge::parseEdgesList(edgeIDs, edges, "<unknown>");
    } catch (ProcessError& e) {
        throw TraCIException(e.what());
    }
    if (edges.empty()) {
        throw TraCIException("Empty edge list for walking stage of person '" + personID + "'.");
    }
    if (fabs(arrivalPos) > edges.back()->getLength()) {
        throw TraCIException("Invalid arrivalPos for walking stage of person '" + personID + "'.");
    }
    if (arrivalPos < 0) {
        arrivalPos += edges.back()->getLength();
    }
    if (speed < 0) {
        speed = p->getVehicleType().getMaxSpeed();
    }
    MSStoppingPlace* bs = nullptr;
    if (stopID != "") {
        bs = MSNet::getInstance()->getStoppingPlace(stopID, SUMO_TAG_BUS_STOP);
        if (bs == nullptr) {
            throw TraCIException("Invalid stopping place id '" + stopID + "' for person: '" + personID + "'");
        }
    }
    p->appendStage(new MSPerson::MSPersonStage_Walking(p->getID(), edges, bs, TIME2STEPS(duration), speed, p->getArrivalPos(), arrivalPos, 0));
}
void
MSTLLogicControl::WAUTSwitchProcedure_Stretch::cutLogic(SUMOTime step, SUMOTime startPos, SUMOTime allCutTime) {
    unsigned int actStep = myTo->getIndexFromOffset(startPos);
    // switches to startPos and cuts this phase, if there is a "Bereich"
    int areasNo = getStretchAreaNo(myTo);
    SUMOTime toCut = 0;
    for (int i = 0; i < areasNo; i++) {
        StretchBereichDef def = getStretchBereichDef(myTo, i + 1);
        SUMOTime begin = TIME2STEPS(def.begin);
        unsigned int end = TIME2STEPS(def.end);
        size_t stepOfBegin = myTo->getIndexFromOffset(begin);
        if (stepOfBegin == actStep)	{
            if (begin < startPos) {
                toCut = end - startPos;
            } else {
                toCut = end - begin;
            }
            toCut = MIN2(allCutTime, toCut);
            allCutTime = allCutTime - toCut;
        }
    }
    SUMOTime remainingDur = myTo->getPhase(actStep).duration - getDiffToStartOfPhase(*myTo, startPos);
    SUMOTime newDur = remainingDur - toCut;
    myTo->changeStepAndDuration(myControl, step, actStep, newDur);

    // changes the duration of all other phases
    int currStep = (actStep + 1) % (int)myTo->getPhases().size();
    while (allCutTime > 0) {
        for (int i = currStep; i < (int) myTo->getPhases().size(); i++) {
            SUMOTime beginOfPhase = myTo->getOffsetFromIndex(i);
            SUMOTime durOfPhase = myTo->getPhase(i).duration;
            SUMOTime endOfPhase = beginOfPhase + durOfPhase;
            for (int i = 0; i < areasNo; i++) {
                StretchBereichDef def = getStretchBereichDef(myTo, i + 1);
                SUMOTime begin = TIME2STEPS(def.begin);
                SUMOTime end = TIME2STEPS(def.end);
                if ((beginOfPhase <= begin) && (endOfPhase >= end)) {
                    SUMOTime maxCutOfPhase = MIN2(end - begin, allCutTime);
                    allCutTime = allCutTime - maxCutOfPhase;
                    durOfPhase = durOfPhase - maxCutOfPhase;
                }
            }
            myTo->addOverridingDuration(durOfPhase);
        }
        currStep = 0;
    }
}
示例#13
0
SUMOTime
ODMatrix::parseSingleTime(const std::string& time) {
    if (time.find('.') == std::string::npos) {
        throw OutOfBoundsException();
    }
    std::string hours = time.substr(0, time.find('.'));
    std::string minutes = time.substr(time.find('.') + 1);
    return TIME2STEPS(TplConvert::_2int(hours.c_str()) * 3600 + TplConvert::_2int(minutes.c_str()) * 60);
}
示例#14
0
SUMOTime
MSCFModel::getMinimalArrivalTime(double dist, double currentSpeed, double arrivalSpeed) const {
    const double accel = (arrivalSpeed >= currentSpeed) ? getMaxAccel() : -getMaxDecel();
    const double accelTime = (arrivalSpeed - currentSpeed) / accel;
    const double accelWay = accelTime * (arrivalSpeed + currentSpeed) * 0.5;
    const double nonAccelWay = MAX2(0., dist - accelWay);
    // will either drive as fast as possible and decelerate as late as possible
    // or accelerate as fast as possible and then hold that speed
    const double nonAccelSpeed = MAX3(currentSpeed, arrivalSpeed, SUMO_const_haltingSpeed);
    return TIME2STEPS(accelTime + nonAccelWay / nonAccelSpeed);
}
// ===========================================================================
// method definitions
// ===========================================================================
SUMOTime
string2time(const std::string& r) throw(EmptyData, NumberFormatException, ProcessError) {
    double time;
    std::istringstream buf(r);
    buf >> time;
    if (buf.fail()) {
        throw ProcessError("Input string '" + r + "' cannot be parsed as a time");
    } else {
        return TIME2STEPS(time);
    }
}
示例#16
0
void
MSDevice_Tripinfo::notifyMoveInternal(const SUMOVehicle& veh,
                                      const double /* frontOnLane */,
                                      const double timeOnLane,
                                      const double /* meanSpeedFrontOnLane */,
                                      const double meanSpeedVehicleOnLane,
                                      const double /* travelledDistanceFrontOnLane */,
                                      const double /* travelledDistanceVehicleOnLane */,
                                      const double /* meanLengthOnLane */) {

    // called by meso
    const MEVehicle* mesoVeh = dynamic_cast<const MEVehicle*>(&veh);
    assert(mesoVeh);
    const double vmax = veh.getEdge()->getVehicleMaxSpeed(&veh);
    if (vmax > 0) {
        myMesoTimeLoss += TIME2STEPS(timeOnLane * (vmax - meanSpeedVehicleOnLane) / vmax);
    }
    myWaitingTime += veh.getWaitingTime();
    myStoppingTime += TIME2STEPS(mesoVeh->getCurrentStoppingTimeSeconds());
}
void
NIImporter_VISUM::parse_TrafficLights() {
    myCurrentID = NBHelpers::normalIDRepresentation(myLineParser.get("Nr"));
    SUMOTime cycleTime = (SUMOTime) getNamedFloat("Umlaufzeit", "UMLZEIT");
    SUMOTime intermediateTime = (SUMOTime) getNamedFloat("StdZwischenzeit", "STDZWZEIT");
    bool phaseBased = myLineParser.know("PhasenBasiert")
                      ? TplConvert::_2bool(myLineParser.get("PhasenBasiert").c_str())
                      : false;
    SUMOTime offset = myLineParser.know("ZEITVERSATZ") ? TIME2STEPS(getNamedFloat("ZEITVERSATZ")) : 0;
    // add to the list
    myTLS[myCurrentID] = new NIVisumTL(myCurrentID, cycleTime, offset, intermediateTime, phaseBased);
}
示例#18
0
// ===========================================================================
// method definitions
// ===========================================================================
MESegment::MESegment(const std::string& id,
                     const MSEdge& parent, MESegment* next,
                     SUMOReal length, SUMOReal speed,
                     unsigned int idx,
                     SUMOTime tauff, SUMOTime taufj,
                     SUMOTime taujf, SUMOTime taujj,
                     SUMOReal jamThresh, bool multiQueue, bool junctionControl,
                     SUMOReal lengthGeometryFactor) :
    Named(id), myEdge(parent), myNextSegment(next),
    myLength(length), myIndex(idx),
    myTau_ff((SUMOTime)(tauff / parent.getLanes().size())),
    myTau_fj((SUMOTime)(taufj / parent.getLanes().size())), // Eissfeldt p. 90 and 151 ff.
    myTau_jf((SUMOTime)(taujf / parent.getLanes().size())),
    myTau_jj((SUMOTime)(taujj / parent.getLanes().size())),
    myTau_length(MAX2(MESO_MIN_SPEED, speed) * parent.getLanes().size() / TIME2STEPS(1) ),
    myHeadwayCapacity(length / DEFAULT_VEH_LENGHT_WITH_GAP * parent.getLanes().size())/* Eissfeldt p. 69 */,
    myCapacity(length * parent.getLanes().size()),
    myOccupancy(0.f),
    myJunctionControl(junctionControl),
    myTLSPenalty(MSGlobals::gMesoTLSPenalty > 0 && myNextSegment == 0 && (
                     parent.getToJunction()->getType() == NODETYPE_TRAFFIC_LIGHT ||
                     parent.getToJunction()->getType() == NODETYPE_TRAFFIC_LIGHT_NOJUNCTION ||
                     parent.getToJunction()->getType() == NODETYPE_TRAFFIC_LIGHT_RIGHT_ON_RED)),
    myEntryBlockTime(SUMOTime_MIN),
    myLengthGeometryFactor(lengthGeometryFactor),
    myMeanSpeed(speed),
    myLastMeanSpeedUpdate(SUMOTime_MIN) {
    myCarQues.push_back(std::vector<MEVehicle*>());
    myBlockTimes.push_back(-1);
    const std::vector<MSLane*>& lanes = parent.getLanes();
    if (multiQueue && lanes.size() > 1) {
        unsigned int numFollower = parent.getNumSuccessors();
        if (numFollower > 1) {
            while (myCarQues.size() < lanes.size()) {
                myCarQues.push_back(std::vector<MEVehicle*>());
                myBlockTimes.push_back(-1);
            }
            for (unsigned int i = 0; i < numFollower; ++i) {
                const MSEdge* edge = parent.getSuccessors()[i];
                myFollowerMap[edge] = std::vector<size_t>();
                const std::vector<MSLane*>* allowed = parent.allowedLanes(*edge);
                assert(allowed != 0);
                assert(allowed->size() > 0);
                for (std::vector<MSLane*>::const_iterator j = allowed->begin(); j != allowed->end(); ++j) {
                    std::vector<MSLane*>::const_iterator it = find(lanes.begin(), lanes.end(), *j);
                    myFollowerMap[edge].push_back(distance(lanes.begin(), it));
                }
            }
        }
    }
    recomputeJamThreshold(jamThresh);
}
示例#19
0
NBTrafficLightLogic*
NBLoadedTLDef::myCompute(const NBEdgeCont& ec, unsigned int brakingTime) {
    MsgHandler::getWarningInstance()->clear(); // !!!
    NBLoadedTLDef::SignalGroupCont::const_iterator i;
    // compute the switching times
    std::set<SUMOReal> tmpSwitchTimes;
    for (i = mySignalGroups.begin(); i != mySignalGroups.end(); i++) {
        NBLoadedTLDef::SignalGroup* group = (*i).second;
        // needed later
        group->sortPhases();
        // patch the yellow time for this group
        group->patchTYellow(brakingTime, OptionsCont::getOptions().getBool("tls.yellow.patch-small"));
        // copy the now valid times into the container
        //  both the given red and green phases are added and also the
        //  yellow times
        std::vector<SUMOReal> gtimes = group->getTimes(myCycleDuration);
        for (std::vector<SUMOReal>::const_iterator k = gtimes.begin(); k != gtimes.end(); k++) {
            tmpSwitchTimes.insert(*k);
        }
    }
    std::vector<SUMOReal> switchTimes;
    copy(tmpSwitchTimes.begin(), tmpSwitchTimes.end(), back_inserter(switchTimes));
    sort(switchTimes.begin(), switchTimes.end());

    // count the signals
    unsigned int noSignals = 0;
    for (i = mySignalGroups.begin(); i != mySignalGroups.end(); i++) {
        noSignals += (*i).second->getLinkNo();
    }
    // build the phases
    NBTrafficLightLogic* logic = new NBTrafficLightLogic(getID(), getProgramID(), noSignals, myOffset, myType);
    for (std::vector<SUMOReal>::iterator l = switchTimes.begin(); l != switchTimes.end(); l++) {
        // compute the duration of the current phase
        unsigned int duration;
        if (l != switchTimes.end() - 1) {
            // get from the difference to the next switching time
            duration = (unsigned int)((*(l + 1)) - (*l));
        } else {
            // get from the differenc to the first switching time
            duration = (unsigned int)(myCycleDuration - (*l) + * (switchTimes.begin()));
        }
        // no information about yellow times will be generated
        assert((*l) >= 0);
        logic->addStep(TIME2STEPS(duration), buildPhaseState(ec, (unsigned int)(*l)));
    }
    // check whether any warnings were printed
    if (MsgHandler::getWarningInstance()->wasInformed()) {
        WRITE_WARNING("During computation of traffic light '" + getID() + "'.");
    }
    logic->closeBuilding();
    return logic;
}
示例#20
0
SUMOTime
MESegment::getNextInsertionTime(SUMOTime earliestEntry) const {
    // since we do not know which queue will be used we give a conservative estimate
    SUMOTime earliestLeave = earliestEntry;
    for (size_t i = 0; i < myCarQues.size(); ++i) {
        earliestLeave = MAX2(earliestLeave, myBlockTimes[i]);
    }
    if (myEdge.getSpeedLimit() == 0) {
        return MAX2(earliestEntry, myEntryBlockTime);    // FIXME: This line is just an adhoc-fix to avoid division by zero (Leo)
    } else {
        return MAX3(earliestEntry, earliestLeave - TIME2STEPS(myLength / myEdge.getSpeedLimit()), myEntryBlockTime);
    }
}
示例#21
0
SUMOTime
MESegment::getTimeHeadway(bool predecessorIsFree, SUMOReal leaderLength) {
    if (predecessorIsFree) {
        return (free() ? myTau_ff : myTau_fj) + (SUMOTime)(leaderLength / myTau_length);
    } else {
        if (free()) {
            return myTau_jf;
        } else {
            // the gap has to move from the start of the segment to its end
            // this allows jams to clear and move upstream
            return TIME2STEPS(myA * getCarNumber() + myB);
        }
    }
}
示例#22
0
void
NLBuilder::buildNet() {
    MSEdgeControl* edges = 0;
    MSJunctionControl* junctions = 0;
    SUMORouteLoaderControl* routeLoaders = 0;
    MSTLLogicControl* tlc = 0;
    std::vector<SUMOTime> stateDumpTimes;
    std::vector<std::string> stateDumpFiles;
    try {
        edges = myEdgeBuilder.build();
        junctions = myJunctionBuilder.build();
        routeLoaders = buildRouteLoaderControl(myOptions);
        tlc = myJunctionBuilder.buildTLLogics();
        MSFrame::buildStreams();
        const std::vector<int> times = myOptions.getIntVector("save-state.times");
        for (std::vector<int>::const_iterator i = times.begin(); i != times.end(); ++i) {
            stateDumpTimes.push_back(TIME2STEPS(*i));
        }
        if (myOptions.isSet("save-state.files")) {
            stateDumpFiles = myOptions.getStringVector("save-state.files");
            if (stateDumpFiles.size() != stateDumpTimes.size()) {
                WRITE_ERROR("Wrong number of state file names!");
            }
        } else {
            const std::string prefix = myOptions.getString("save-state.prefix");
            const std::string suffix = myOptions.getString("save-state.suffix");
            for (std::vector<SUMOTime>::iterator i = stateDumpTimes.begin(); i != stateDumpTimes.end(); ++i) {
                stateDumpFiles.push_back(prefix + "_" + time2string(*i) + suffix);
            }
        }
    } catch (IOError& e) {
        delete edges;
        delete junctions;
        delete routeLoaders;
        delete tlc;
        throw ProcessError(e.what());
    } catch (ProcessError&) {
        delete edges;
        delete junctions;
        delete routeLoaders;
        delete tlc;
        throw;
    }
    // if anthing goes wrong after this point, the net is responsible for cleaning up
    myNet.closeBuilding(myOptions, edges, junctions, routeLoaders, tlc, stateDumpTimes, stateDumpFiles,
                        myXMLHandler.haveSeenInternalEdge(),
                        myXMLHandler.haveSeenNeighs(),
                        myXMLHandler.lefthand(),
                        myXMLHandler.networkVersion());
}
示例#23
0
文件: MELoop.cpp 项目: cbrafter/sumo
void
MELoop::teleportVehicle(MEVehicle* veh, MESegment* const toSegment) {
    const SUMOTime leaveTime = veh->getEventTime();
    MESegment* const onSegment = veh->getSegment();
    const bool teleporting = (onSegment == 0); // is the vehicle already teleporting?
    // try to find a place on the current edge
    MESegment* teleSegment = toSegment->getNextSegment();
    while (teleSegment != 0 && !teleSegment->hasSpaceFor(veh, leaveTime)) {
        // @caution the time to get to the next segment here is ignored XXX
        teleSegment = teleSegment->getNextSegment();
    }
    if (teleSegment != 0) {
        if (!teleporting) {
            // we managed to teleport in a single jump
            WRITE_WARNING("Teleporting vehicle '" + veh->getID() + "'; waited too long, from edge '" + onSegment->getEdge().getID()
                          + "':" + toString(onSegment->getIndex())
                          + " to edge '" + teleSegment->getEdge().getID()
                          + "':" + toString(teleSegment->getIndex())
                          + ", time " + time2string(leaveTime) + ".");
            MSNet::getInstance()->getVehicleControl().registerTeleportJam();
        }
        changeSegment(veh, leaveTime, teleSegment, true);
        teleSegment->setEntryBlockTime(leaveTime); // teleports should not block normal flow
    } else {
        // teleport across the current edge and try insertion later
        if (!teleporting) {
            // announce start of multi-step teleport, arrival will be announced in changeSegment()
            WRITE_WARNING("Teleporting vehicle '" + veh->getID() + "'; waited too long, from edge '" + onSegment->getEdge().getID()
                          + "':" + toString(onSegment->getIndex()) + ", time " + time2string(leaveTime) + ".");
            MSNet::getInstance()->getVehicleControl().registerTeleportJam();
            // remove from current segment
            onSegment->send(veh, 0, leaveTime);
            // mark veh as teleporting
            veh->setSegment(0, 0);
        }
        // @caution microsim uses current travel time teleport duration
        const SUMOTime teleArrival = leaveTime + TIME2STEPS(veh->getEdge()->getLength() / veh->getEdge()->getSpeedLimit());
        const bool atDest = veh->moveRoutePointer();
        if (atDest) {
            // teleporting to end of route
            changeSegment(veh, teleArrival, 0, true);
        } else {
            veh->setEventTime(teleArrival);
            addLeaderCar(veh, 0);
            // teleporting vehicles must react to rerouters
            getSegmentForEdge(*veh->getEdge())->addReminders(veh);
            veh->activateReminders(MSMoveReminder::NOTIFICATION_JUNCTION);
        }
    }
}
void
MSOffTrafficLightLogic::rebuildPhase() {
    size_t no = getLinks().size();
    std::string state;
    for (unsigned int i = 0; i < no; ++i) {
        // !!! no brake mask!
        state += 'o';
    }
    for (MSTrafficLightLogic::Phases::const_iterator i = myPhaseDefinition.begin(); i != myPhaseDefinition.end(); ++i) {
        delete *i;
    }
    myPhaseDefinition.clear();
    myPhaseDefinition.push_back(new MSPhaseDefinition(TIME2STEPS(120), state));
}
示例#25
0
void
Person::appendWaitingStage(const std::string& personID, double duration, const std::string& description, const std::string& stopID) {
    MSTransportable* p = getPerson(personID);
    if (duration < 0) {
        throw TraCIException("Duration for person: '" + personID + "' must not be negative");
    }
    MSStoppingPlace* bs = nullptr;
    if (stopID != "") {
        bs = MSNet::getInstance()->getStoppingPlace(stopID, SUMO_TAG_BUS_STOP);
        if (bs == nullptr) {
            throw TraCIException("Invalid stopping place id '" + stopID + "' for person: '" + personID + "'");
        }
    }
    p->appendStage(new MSTransportable::Stage_Waiting(p->getArrivalEdge(), nullptr, TIME2STEPS(duration), 0, p->getArrivalPos(), description, false));
}
bool
MSTLLogicControl::WAUTSwitchProcedure_Stretch::trySwitch(SUMOTime step) {
    // switch to the next programm if the GSP is reached
    if (isPosAtGSP(step, *myFrom)) {
        // adapt program's state
        if (mySwitchSynchron) {
            adaptLogic(step);
        } else {
            switchToPos(step, *myTo, TIME2STEPS(getGSPValue(*myTo)));
        }
        // switch to destination program
        return true;
    }
    // do not switch, yet
    return false;
}
// ===========================================================================
// method definitions
// ===========================================================================
MSActuatedTrafficLightLogic::MSActuatedTrafficLightLogic(MSTLLogicControl& tlcontrol,
        const std::string& id, const std::string& programID,
        const Phases& phases,
        int step, SUMOTime delay,
        const std::map<std::string, std::string>& parameter,
        const std::string& basePath) :
    MSSimpleTrafficLightLogic(tlcontrol, id, programID, phases, step, delay, parameter) {

    myMaxGap = TplConvert::_2double(getParameter("max-gap", DEFAULT_MAX_GAP).c_str());
    myPassingTime = TplConvert::_2double(getParameter("passing-time", DEFAULT_PASSING_TIME).c_str()); // passing-time seems obsolete... (Leo)
    myDetectorGap = TplConvert::_2double(getParameter("detector-gap", DEFAULT_DETECTOR_GAP).c_str());
    myShowDetectors = TplConvert::_2bool(getParameter("show-detectors", "false").c_str());
    myFile = FileHelpers::checkForRelativity(getParameter("file", "NUL"), basePath);
    myFreq = TIME2STEPS(TplConvert::_2double(getParameter("freq", "300").c_str()));
    myVehicleTypes = getParameter("vTypes", "");
}
// ------------ "actuated" algorithm methods
SUMOTime
MSActuatedTrafficLightLogic::duration(const double detectionGap) const {
    assert(getCurrentPhaseDef().isGreenPhase());
    assert((int)myPhases.size() > myStep);
    const SUMOTime actDuration = MSNet::getInstance()->getCurrentTimeStep() - myPhases[myStep]->myLastSwitch;
    // ensure that minimum duration is kept
    SUMOTime newDuration = getCurrentPhaseDef().minDuration - actDuration;
    // try to let the last detected vehicle pass the intersection (duration must be positive)
    newDuration = MAX3(newDuration, TIME2STEPS(myDetectorGap - detectionGap), SUMOTime(1));
    // cut the decimal places to ensure that phases always have integer duration
    if (newDuration % 1000 != 0) {
        const SUMOTime totalDur = newDuration + actDuration;
        newDuration = (totalDur / 1000 + 1) * 1000 - actDuration;
    }
    // ensure that the maximum duration is not exceeded
    newDuration = MIN2(newDuration, getCurrentPhaseDef().maxDuration - actDuration);
    return newDuration;
}
示例#29
0
void
TrafficLight::setCompleteRedYellowGreenDefinition(const std::string& tlsID, const TraCILogic& logic) {
    MSTLLogicControl::TLSLogicVariants& vars = getTLS(tlsID);
    // make sure index and phaseNo are consistent
    if (logic.currentPhaseIndex >= (int)logic.phases.size()) {
        throw TraCIException("set program: parameter index must be less than parameter phase number.");
    }
    std::vector<MSPhaseDefinition*> phases;
    for (TraCIPhase phase : logic.phases) {
        phases.push_back(new MSPhaseDefinition(TIME2STEPS(phase.duration), phase.state, TIME2STEPS(phase.minDur), TIME2STEPS(phase.maxDur), phase.next, phase.name));
    }
    if (vars.getLogic(logic.programID) == nullptr) {
        MSTrafficLightLogic* mslogic = new MSSimpleTrafficLightLogic(MSNet::getInstance()->getTLSControl(), tlsID, logic.programID, TLTYPE_STATIC, phases, logic.currentPhaseIndex, 0, logic.subParameter);
        vars.addLogic(logic.programID, mslogic, true, true);
    } else {
        static_cast<MSSimpleTrafficLightLogic*>(vars.getLogic(logic.programID))->setPhases(phases, logic.currentPhaseIndex);
    }
}
NBLoadedSUMOTLDef*
NIXMLTrafficLightsHandler::initTrafficLightLogic(const SUMOSAXAttributes& attrs, NBLoadedSUMOTLDef* currentTL) {
    if (currentTL) {
        WRITE_ERROR("Definition of tl-logic '" + currentTL->getID() + "' was not finished.");
        return 0;
    }
    bool ok = true;
    std::string id = attrs.getStringReporting(SUMO_ATTR_ID, 0, ok);
    std::string programID = attrs.getOptStringReporting(SUMO_ATTR_PROGRAMID, id.c_str(), ok, "<unknown>");
    SUMOTime offset = attrs.hasAttribute(SUMO_ATTR_OFFSET) ? TIME2STEPS(attrs.getSUMORealReporting(SUMO_ATTR_OFFSET, id.c_str(), ok)) : 0;

    // there are two scenarios to consider
    // 1) the tll.xml is loaded to update traffic lights defined in a net.xml:
    //   simply retrieve the loaded definitions and update them
    // 2) the tll.xml is loaded to define new traffic lights
    //   nod.xml will have triggered building of NBOwnTLDef. Replace it with NBLoadedSUMOTLDef
    NBLoadedSUMOTLDef* loadedDef = dynamic_cast<NBLoadedSUMOTLDef*>(myTLLCont.getDefinition(id, programID));
    if (loadedDef == 0) {
        // case 2
        NBOwnTLDef* newDef = dynamic_cast<NBOwnTLDef*>(myTLLCont.getDefinition(
                                 id, NBTrafficLightDefinition::DefaultProgramID));
        assert(newDef != 0);
        loadedDef = new NBLoadedSUMOTLDef(id, programID, offset);
        std::vector<NBNode*> nodes = newDef->getControlledNodes();
        for (std::vector<NBNode*>::iterator it = nodes.begin(); it != nodes.end(); it++) {
            (*it)->removeTrafficLight(newDef);
            (*it)->addTrafficLight(loadedDef);
        }
        myTLLCont.removeProgram(id, NBTrafficLightDefinition::DefaultProgramID);
        myTLLCont.insert(loadedDef);

        std::string type = attrs.getOptStringReporting(SUMO_ATTR_TYPE, 0, ok, toString(TLTYPE_STATIC));
        if (type != toString(TLTYPE_STATIC)) {
            WRITE_WARNING("Traffic light '" + id + "' has unsupported type '" + type + "' and will be converted to '" + toString(TLTYPE_STATIC) + "'");
        }
    }
    if (ok) {
        myResetPhases = true;
        return loadedDef;
    } else {
        return 0;
    }
}